text string | label_name string | labels int64 |
|---|---|---|
# YOLOv6l model
model = dict(
type='YOLOv6l_mbla',
pretrained=None,
depth_multiple=0.5,
width_multiple=1.0,
backbone=dict(
type='CSPBepBackbone',
num_repeats=[1, 4, 8, 8, 4],
out_channels=[64, 128, 256, 512, 1024],
csp_e=float(1)/2,
fuse_P2=True,
stage... | Python | 1 |
que subsaharienne', 'ga': 'an Afraic fho-Shahárach', 'gd': 'Afraga Deas air an t-Sathara', 'gl': 'África subsahariana', 'gu': 'સબ-સહારન આફ્રિકા', 'ha': 'Afirka ta Kudancin Sahara', 'he': 'אפריקה שמדרום לסהרה', 'hi': 'उप-सहारा अफ़्रीका', 'hi-Latn': 'Sub-Saharan Africa', 'hr': 'Subsaharska Afrika', 'hsb': 'subsaharaska A... | Python | 1 |
canvas = &mut self.canvas;
canvas.combine();
let clamped = Clamped(canvas.buffer());
let img = ImageData::new_with_u8_clamped_array_and_sh(clamped,width,height)?;
ctx.put_image_data(&img,0_f64,0_f64)
} else {
if self.append_can... | Rust | 0 |
shift;
ranges.push(e1..e2);
}
}
let result = HpxRanges::<u64>::new_from(ranges);
Ok(result)
}
/// Serializes a spatial coverage to a JSON format
///
/// # Arguments
///
/// * ``coverage`` - The spatial coverage ranges to serialize.
pub fn to_json(py: Python, coverage: HpxRanges<u64>)... | Rust | 0 |
# Copyright 2024 MIT Han Lab
#
# 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, ... | Python | 1 |
{
/// The east is positive direction.
x: i32,
/// The south is positive direction.
y: i32,
/// Z means the level of power if supported it.
z: i32,
},
/// A spherical coordinate system (3-axis haptic device).
Spherical {
/// The direction in degrees ti... | Rust | 0 |
fication(caller_origin, old_certification);
let _hospital = Hospitals::<T>::hospital_by_account_id(caller.clone())
.unwrap();
let new_certification = HospitalCertificationInfo {
title: "DeBio certificate 2".as_bytes().to_vec(),
issuer: "DeBio 2".as_bytes().to_vec(),
month: "September".as_bytes().to_vec... | Rust | 0 |
import threading
import numpy as np
from numba import cuda
from numba.cuda.testing import CUDATestCase, skip_unless_cudasim
import numba.cuda.simulator as simulator
import unittest
class TestCudaSimIssues(CUDATestCase):
def test_record_access(self):
backyard_type = [('statue', np.float64),
... | Python | 1 |
from prowler.lib.check.models import Check, Check_Report_AWS
from prowler.providers.aws.services.cloudtrail.cloudtrail_client import (
cloudtrail_client,
)
from prowler.providers.aws.services.cloudwatch.cloudwatch_client import (
cloudwatch_client,
)
from prowler.providers.aws.services.cloudwatch.lib.metric_fil... | Python | 1 |
r, converted_size.unwrap());
let bytes_written = callbacks.write(slice_buffer);
bytes_written as i32
}
}
#[allow(non_snake_case)]
#[allow(unused_variables)]
unsafe extern "C" fn cb_close(pvContext: *mut c_void) {
let pushstream = &mut *(pvContext as *mut PushAudi... | Rust | 0 |
sor;
solana_sdk::declare_id!("ownab1e111111111111111111111111111111111111");
<filename>src/tools/clippy/tests/ui/blacklisted_name.rs
#![allow(
dead_code,
clippy::similar_names,
clippy::single_match,
clippy::toplevel_ref_arg,
unused_mut,
unused_variables
)]
#![warn(clippy::blacklisted_name)]
fn... | Rust | 0 |
tan1': '#ffa54f',
'tan2': '#ee9a49',
'tan3': '#cd853f',
'tan4': '#8b5a2b',
'thistle': '#d8bfd8',
'thistle1': '#ffe1ff',
'thistle2': '#eed2ee',
'thistle3': '#cdb5cd',
'thistle4': '#8b7b8b',
'tomato': '#ff6347',
'tomato1': '#ff6347',
'tomato2': '#ee5c42',
'tomato3': '#cd4f3... | Python | 1 |
from enum import Enum
from typing import Any
import mugen.video.detection as detection
from mugen.mixins.Filterable import ContextFilter, Filter
from mugen.video.segments import Segment
def is_repeat(segment: Segment, memory: Any) -> bool:
return detection.video_segment_is_repeat(segment, video_segments_used=mem... | Python | 1 |
/rfc792#page-16)
TimestampRequest(IcmpTimestamp),
/// Described in [RFC 792 Pg 16](https://tools.ietf.org/html/rfc792#page-16)
TimestampReply(IcmpTimestamp),
/// Described in [RFC 792 Pg 16](https://tools.ietf.org/html/rfc792#page-18)
InformationRequest(IcmpCommon),
//... | Rust | 0 |
_base_ = '../htc/htc_x101_64x4d_fpn_16x1_20e_coco.py'
# learning policy
lr_config = dict(step=[24, 27])
runner = dict(type='EpochBasedRunner', max_epochs=28)
| Python | 1 |
dir = HorizDir::Left
}
if self.y == 0 {
self.vert_dir = VertDir::Up
} else if self.y == frame.height - 1 {
self.vert_dir = VertDir::Down
}
}
fn mv(&mut self) {
match self.horiz_dir {
HorizDir::Left => self.x -= 1,
HorizDir... | Rust | 0 |
exists = False
filepath_or_buffer = stringify_path(filepath_or_buffer)
if not isinstance(filepath_or_buffer, str):
return exists
try:
exists = os.path.exists(filepath_or_buffer)
# gh-5874: if the filepath is too long will raise here
except (TypeError, ValueError):
pas... | Python | 1 |
session_token {
json.insert(
"session_certificates_enabled".to_owned(),
with_session_token.into(),
);
}
let json: Value = json.into();
admin_rest_request(self.client.patch(&url).json(&json)).await?;
Ok(())
}
fn make_url(&s... | Rust | 0 |
Set the appropriate read delay for flash
cx.device.MSC.readctrl.write(|reg| reg.mode().ws2());
// Switch to high frequency oscillator
cx.device.CMU.hfclksel.write(|reg| reg.hf().hfxo());
// Use the high frequency clock for the ITM
cx.device.CMU.dbgclksel.write(|reg| reg.dbg().... | Rust | 0 |
use crate::{event::*, Easing};
#[test]
fn to_line_static() {
let movex_event: MoveX = (0, 320).into();
assert_eq!(movex_event.to_line(), " MX,0,0,,320");
let mut movex_event_depth: MoveX = (0, 320).into();
movex_event_depth.set_depth(2);
assert_eq!(movex_event_depth.to_... | Rust | 0 |
awn_local(async {
if let Err(err) = future.await {
nuts::publish(err);
}
});
}
<reponame>kjn-void/advent-of-code-2019<filename>src/day7/mod.rs
use permutohedron::LexicalPermutation;
use std::sync::mpsc::*;
use super::intcode::*;
use super::Solution;
const NUM_AMPS: usize = 5;
fn amplif... | Rust | 0 |
adraticModelStructureError):
sampler.sample_qubo(Q).resolve()
def test_problem_labelling(self):
sampler = self.qpu
h, J = self.nonzero_ising_problem(sampler)
label = 'problem label'
# label set
sampleset = sampler.sample_ising(h, J, label=label)
self.ass... | Python | 1 |
eturn schema_data
normalized_schema_data = {}
if "name" in schema_data:
normalized_schema_data["name"] = schema_data["name"]
del schema_data["name"]
last_mapping = None
node = None
current_node = normalized_schema_data
for node in self._insertion... | Python | 1 |
>= Ipv4Addr::from(LE::read_u32(&buf[row_size..])),
IpAddr::V6(addr) => addr >= Ipv6Addr::from(LE::read_u128(&buf[row_size..])),
};
if below {
high_row = mid_row.checked_sub(1).ok_or_else(|| {
io::Error::new(ErrorKind::Inva... | Rust | 0 |
ter {
first: bool,
board: Board,
stack: Vec<(usize, usize, BitIter<u16>)>,
}
impl SolutionIter {
/// Construct a `SolutionIter` value from a [`Board`].
///
/// ## Example
///
/// ```rust
/// # fn main() {
/// # use sudoku_solver::*;
/// let board = Board::from(&[
/// ... | Rust | 0 |
# -- coding: utf-8 --
# @Time : 2023/7/31 0031 9:52
# @Author : TangKai
# @Team : ZheChengData
import pandas as pd
import geopandas as gpd
from itertools import chain
from ...GlobalVal import NetField
from shapely.geometry import LineString
from ....WrapsFunc import function_time_cost
net_field = NetField()
#... | Python | 1 |
Assign(VarAssign),
ForLoop(ForLoop),
WhileLoop(WhileLoop),
IfElse(IfElse),
Break(Break),
Continue(Continue),
Expr(ExprStatement),
Return(Return),
}
impl Spannable for Statement {
#[inline]
fn span(&self) -> Span {
match self {
Self::VarDeclaration(v) => v.span(),... | Rust | 0 |
IPlayer,
type_: alt_IBlip_BlipType,
pos: *mut alt_Vector_float_3_PointLayout,
_returnValue: *mut alt_RefBase_RefStore_IBlip,
);
}
extern "C" {
pub fn alt_ICore_CreateBlip_CAPI_Heap(
_instance: *mut alt_ICore,
target: *mut alt_RefBase_RefStore_IPlayer,
type_: alt_I... | Rust | 0 |
# -*- coding:utf-8 -*-
"""
通联数据
Created on 2015/08/24
@author: Jimmy Liu
@group : waditu
@contact: jimmysoa@sina.cn
"""
from pandas.compat import StringIO
import pandas as pd
from tushare.util import vars as vs
from tushare.util.common import Client
from tushare.util import upass as up
class Market():
def _... | Python | 1 |
#########################################
def get_k8s_manifest_dict(self) -> Optional[Dict[str, Any]]:
"""Returns the K8s Manifest for this Object as a dict"""
from itertools import chain
k8s_manifest: Dict[str, Any] = {}
all_attributes: Dict[str, Any] = self.model_dump(exclude_de... | Python | 1 |
aphQLSchema(), plugin_manager=mocked_plugin_manager
)
generator.generate()
assert mocked_plugin_manager.generate_enums_module.called
def test_generate_triggers_generate_enum_hook_for_every_definition(
mocked_plugin_manager,
):
schema_str = """
enum TestEnumAB {
A
B
}
... | Python | 1 |
[1] = -waypoint_pos_tmp[1];
}
270 => {
let waypoint_pos_tmp = waypoint_pos.clone();
waypoint_pos[0] = -waypoint_pos_tmp[1];
waypoint_pos[1] = waypoint_pos_tmp[0];
}
_ => panic!(),
},
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. 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 requir... | Python | 1 |
xmlParserInputDeallocate,
pub encoding: *const xmlChar,
pub version: *const xmlChar,
pub standalone: ::std::os::raw::c_int,
pub id: ::std::os::raw::c_int,
}
/// xmlParserNodeInfo:
///
/// The parser can be asked to collect Node informations, i.e. at what
/// place in the file they were detected.
/// NOTE: Thi... | Rust | 0 |
.triggered.connect(self.underline_text)
# Fonksiyonlar
def new_file(self):
self.ui.textEdit.clear()
def open_file(self):
filename, _ = QFileDialog.getOpenFileName(self, "Dosya Aç", "", "Text Files (*.txt)")
if filename:
with open(filename, 'r', encoding='utf-8') as file... | Python | 1 |
# Listas en Python
"""Para generar una lista, primero definimos el nombre, dentro de [corchetes] colocamos cada valor separado por una coma """
nombres = ["Pedro", "Luisa", "Ana"]
print(nombres)
print(type(nombres))
mis_datos = ["Juancho", 46, "juancho.designs@icloud.com", 1.78]
print(mis_datos)
edad = 48
hobbies = ... | Python | 1 |
,
sae: false,
mask: None,
broadcast: None,
},
&[72, 171],
OperandSize::Qword,
)
}
<reponame>HristoKolev/xdxd-backup
use std::collections::HashMap;
use time::Duration;
use clap::Arg;
use crate::global::prelude::*;
use crate::archive_type::*;
use crate::ar... | Rust | 0 |
from models import OmniESI
from time import time
from utils import set_seed, graph_collate_func, mkdir
from configs import get_cfg_defaults
from dataloader import ESIDataset
from torch.utils.data import DataLoader
import torch
import argparse
import warnings, os
import pandas as pd
from run.tester import Tester
from ru... | Python | 1 |
}
fn evaluate_opcode_constraints(&mut self, frame: &MainEvaluationFrame<E>) {
let curr = frame.current();
let one: E = Felt::ONE.into();
self[MUL_1] = curr.mul() - (curr.op0() * curr.op1());
self[MUL_2] = curr.f_res_add() * (curr.op0() + curr.op1())
+ curr.f_res_mul() *... | Rust | 0 |
import os
from errors import BadRequestError
from app import logger
import sqlite3
import json
import healpy
import astropy.units as u
from astropy.coordinates import SkyCoord
import svgwrite
from .skyframe import SkyFrame
from .marker import Marker
from .star import Star
from .svg import SVG
SQLITE_PATH = os.pat... | Python | 1 |
execute("select id from number order by id desc limit 1")
row = cur.fetchone()
if row is None:
id = 0
else:
id = row[0] + 1
insert_db(con, cur, "insert into number values (?, ?, ?)", (id, number, avg_length))
cur.execute("select * from status order by id desc limit 1")
row = cur.... | Python | 1 |
}
},
Err(e) => {
let err = format!("{:?}", e);
assert_eq!(err, "")
}
}
}
#[test]
fn res_native_1_1() {
let bid_price = 1.0;
let jd = &mut serde_json::Deserializer::from_str(&NATIVE_1_1);
let ortb_res_result: Result<BidResponse, serde_path_to_error:... | Rust | 0 |
r_hc,
'r2_all': r2_all, 'r_all': r_all})
f = open(os.path.join(opt.model_file,'ACC_SPE_SEN_each_epoch.txt'),'a')
f.write('\n model:{}'.format(str(model)))
f.write('\n parameter:{}'.format(str(opt)))
# f.write('\n r2_hc:{}, r2... | Python | 1 |
from auto_regex.regex_tree import Node
from auto_regex.config.conf import RegexFlavour
from auto_regex.regex_tree import RegexContext
class Constant(Node):
allowed_classes = {"\\w", "\\d", ".", "\\b", "\\s"}
def __init__(self, value: str):
super().__init__()
self.__value = value
self.i... | Python | 1 |
from typing import Tuple
from srl.base.rl.config import RLConfig
from tests.algorithms_.common_long_case import CommonLongCase
from tests.algorithms_.common_quick_case import CommonQuickCase
class QuickCase(CommonQuickCase):
def create_rl_config(self, rl_param) -> Tuple[RLConfig, dict]:
from srl.algorith... | Python | 1 |
from polars.series.series import Series
__all__ = [
"Series",
]
| Python | 1 |
rom(disc.disconnect_reason));
}
}
error!("[DECODE ERR]: {}", err);
return Err(ReasonCode::BuffError);
}
if (packet.fixed_header & 0x06)
== <QualityOfService as Into<u8>>::into(QualityOfService::QoS1)
{
let mut puback = ... | Rust | 0 |
ght.map(|right| ParIterProducer { iter: right });
(left, right)
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold_with<F>(self, folder: F) -> F
where
F: Folder<Self::Item>,
{
folder.consume_iter(self.iter)
}
}
/// Parallel iterator which consumes a table and return... | Rust | 0 |
and tx_out:
output.append(" z:{} {:#066x} {}".format(' ' if i else '', sig_hash,
network.annotate.sighash_type_to_string(sig_type)))
def dump_footer(network, output, tx, missing_unspents):
if not missing_unspents:
output.append("Total input %12.5f m%s" % (sato... | Python | 1 |
let t = TryTemplate { a: Err(Error) };
assert!(t.call().is_err());
let t = TryTemplate { a: Ok(1) };
assert_eq!("1", t.call().unwrap());
}
#[derive(Template)]
#[template(path = "expr-trymethod")]
struct TryMethodTemplate {
some: bool,
}
impl TryMethodTemplate {
fn not_is(&self, some: bool) -... | Rust | 0 |
import aiounittest
from laozy import settings
from laozy.connectors.wx import wxkf_connector
def create_wxkf():
wxkf_token = settings.get('WXKF_TOKEN', '')
wxkf_encoding_aes_key = settings.get('WXKF_ENCODING_AES_KEY', '')
wxkf_company_id = settings.get('WXKF_COMPANY_ID', '')
wxkf_secret = settings.get... | Python | 1 |
import cv2
import img2pdf
from PIL import Image
import io
def save_outputs2pdf(image_list, pdf_path):
"""
Convertit une liste d'images en un fichier PDF et le sauvegarde à un chemin spécifié.
Args:
image_list (list): Liste d'images en format OpenCV (BGR).
pdf_path (str): Chemin complet où ... | Python | 1 |
import os
from typing import Tuple, Union
from netrc import netrc, NetrcParseError
class ConflictError(Exception):
"""
netrc machine creds already exist in the file, but aren't to be overwritten.
"""
pass
def _get_user_netrc_path() -> str:
"""
Return:
(str): the absolute path to the ... | Python | 1 |
&handle.join()[..]).expect("Failed to decode result") && result
}
<gh_stars>100-1000
use std::iter::FromIterator;
use crate::{
join,
merge,
treefrog::{self, Leapers},
};
/// A static, ordered list of key-value pairs.
///
/// A relation represents a fixed set of key-value pairs. In many places in a
/// Da... | Rust | 0 |
concat!(
"Offset of field: ",
stringify!(vaccel_tf_saved_model),
"::",
stringify!(var_index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<vaccel_tf_saved_model>())).priv_ as *const _ as usize },
112usize,
concat!(
... | Rust | 0 |
MagnitudePruningParamsScorer(params)
def _get_mask_creator(
self, param_names: List[str], params: List[Parameter]
) -> PruningMaskCreator:
"""
:param names: full names of parameters to be pruned
:param params: list of Parameters to be masked
:return: mask creator object ... | Python | 1 |
from stats import word_count, char_count
import sys
def main():
if len(sys.argv) != 2:
print("Usage: python3 main.py <path_to_book>")
sys.exit(1)
path = sys.argv[1]
def get_book_text(filepath):
with open(filepath) as f:
return f.read()
input_text = get_book_text(pa... | Python | 1 |
# DON'T add anything here just add in render's secret or env section
from os import environ
API_ID = int(environ.get("API_ID", "26231033"))
API_HASH = environ.get("API_HASH", "23905191485be2fb424e89d503e9d80c")
BOT_TOKEN = environ.get("BOT_TOKEN", "")
| Python | 1 |
w);
pdf_release_obj(contents);
return 0 as *mut pdf_obj;
} else {
if pdf_concat_stream(content_new, content_seg) < 0i32 {
dpx_warning(
b"Could not handle content stream with multiple segments.... | Rust | 0 |
api_request.to_owned())
.expect("request builder failed");
E::fetch::<_, _>(request)
}
use clap::Parser;
use lazy_static::lazy_static;
use super::options::Options;
lazy_static! {
static ref DEFAULT_DIR: String = default_dir();
}
pub fn default_dir() -> String {
let home = dirs::home_dir();
ma... | Rust | 0 |
}
impl SegmentTreeAllocator {
fn update_node(&mut self, mut index: usize, value: bool) {
self.tree[index]= value;
while index > 1 {
index /= 2;
let v = self.tree[index * 2] && self.tree[index * 2 + 1];
self.tree[index]= v;
}
}
}
<reponame>zhangpanrobo... | Rust | 0 |
(
(x - d, x + d),
(y - d, y + d),
color='k',
lw=self.linewidth
)
l2 = Line2D(
(x - d, x + d),
(y + d, y - d),
color='k',
lw=self.linewidth
)
self._axes.add_line(l1)
self._axes.add_line... | Python | 1 |
data + index.
"""
storage = [float(x) for x in self.evalf().to_storage()]
return {"storage": storage, "index": self.index()}
def __setstate__(self, d: T.Dict[str, T.Any]) -> None:
"""
Called when unpickling a Values object. Rebuilds the Values object using the storage data
... | Python | 1 |
"""Type definitions for XAI Diagnostic Toolkit"""
from typing import Dict, List, Optional, Union, Any, Callable, Protocol
import numpy as np
from numpy.typing import NDArray
# Type aliases
FeatureImportanceDict = Dict[str, float]
FeatureList = List[str]
ProgressCallback = Callable[[float], None]
ModelWeights = NDArra... | Python | 1 |
,
/// Region ID - identifier of a NEM region included in this requirement
pub regionid: String,
/// Coefficient for the region in this reserve requirement
pub coef: Option<rust_decimal::Decimal>,
#[serde(with = "crate::mms_datetime_opt")]
pub lastchanged: Option<chrono::NaiveDateTime>,
}
impl cr... | Rust | 0 |
from lle import World, Action
from src.adversarial_search import expectimax
from src.competitive_world import CompetitiveWorld
from .competitive_graph import GraphMDP
def test_raise_value_error():
mdp = GraphMDP.parse("tests/graphs/vary-depth.graph")
s0 = mdp.reset()
s = mdp.step(s0, "Right")
try:
... | Python | 1 |
import os
import pytest
import medperf.config as config
from medperf.tests.mocks.cube import TestCube
from medperf.commands.mlcube.submit import SubmitCube
PATCH_MLCUBE = "medperf.commands.mlcube.submit.{}"
@pytest.fixture
def cube(mocker):
mocker.patch(PATCH_MLCUBE.format("Cube.download_config_files"))
moc... | Python | 1 |
tree.add(b"hello.txt", 0o100644, blob.id)
repo.object_store.add_object(tree)
commit = Commit()
commit.tree = tree.id
commit.message = b"Initial commit"
commit.author = commit.committer = b"Test User <test@example.com>"
commit.commit_time = commit.author_time = 1234... | Python | 1 |
fn get_cvterm(cvterm_map: &mut HashMap<i32, Rc<Cvterm>>, cvterm_id: i32) -> Rc<Cvterm> {
cvterm_map.get(&cvterm_id)
.unwrap_or_else(|| panic!("can't find {:?} in map", cvterm_id)).clone()
}
fn get_feature(feature_map: &mut HashMap<i32, Rc<Feature>>, feature_id: i32) -> Rc<F... | Rust | 0 |
import regex
KWIK_PARAMS_RE = regex.compile(r'\("(\w+)",\d+,"(\w+)",(\d+),(\d+),\d+\)')
KWIK_D_URL = regex.compile(r'action="(.+?)"')
KWIK_D_TOKEN = regex.compile(r'value="(.+?)"')
KWIK_REDIRECTION_RE = regex.compile(r'<a href="(.+?)" .+?>Redirect me</a>')
CHARACTER_MAP = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFG... | Python | 1 |
# 让鼠标随机往下移动一段距离
webdriver.ActionChains(self.browser).move_by_offset(xoffset=0, yoffset=100).perform()
time.sleep(0.15)
for item in tracks:
webdriver.ActionChains(self.browser).move_by_offset(xoffset=item,
... | Python | 1 |
:`DetDataSample`]): The Data
# Samples. It usually includes information such as
# `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`.
# rescale (bool): Whether to rescale the results.
# Defaults to True.
# Returns:
# list[:obj:`DetDataSampl... | Python | 1 |
convert::TryFrom;
use ::renamed::{IntoPrimitive, TryFromPrimitive, UnsafeFromPrimitive};
#[derive(Debug, PartialEq, Eq, IntoPrimitive, TryFromPrimitive, UnsafeFromPrimitive)]
#[repr(u8)]
enum Number {
Zero,
One,
}
pub fn test() {
assert_eq!(u8::from(Number::Zero), 0);
assert_eq!(u8::from(Number::One)... | Rust | 0 |
0x72, 0x64, 0x70, 0x64, 0x72, 0x00, 0x00, 0x00, // channel 1::name
0x00, 0x00, 0x80, 0x80, // channel 1::options
0x63, 0x6c, 0x69, 0x70, 0x72, 0x64, 0x72, 0x00, // channel 2::name
0x00, 0x00, 0xa0, 0xc0, // channel 2::options
0x72, 0x64, 0x70, 0x73, 0x6e, 0x64, 0x00, 0x00, // channel 3::name
0x0... | Rust | 0 |
b64("tests/assets", "image/gif", "gif"),
vec![to_base64("tests/assets/test_002.gif", "image/gif")]
);
}
#[test]
fn ut_to_base64() {
assert_eq!(to_base64("tests/assets/test_003mini.png", "image/png"), "data:image/image/png;base64,iVBORw0KGgoAAAANSUh\
EUgAAAAoAAAAKCAYAAACN... | Rust | 0 |
class Student:
""" This is a simple class to model a student"""
def __init__(self,name,roll_number):
self.name=name
self.roll_number=roll_number
self.institution="St. Stephen's"
def describe(self):
""" A simple method to describe a student."""
print(f"Name: {self.name}"... | Python | 1 |
/rust-fatfs
fn split_path(path: &str) -> (&str, Option<&str>) {
println!("Splitting path : {:?}", path);
let mut path_split = path.trim_matches('/').splitn(2, "/");
let comp = path_split.next().unwrap_or("");
let rest_opt = path_split.next();
println!("Split Result: {:?}", (comp, rest_opt));
(co... | Rust | 0 |
tor for Prims {
/// Builds a valid, "solvable" maze using a randomized version of Prim's
/// algorithm.
///
/// Reference: `https://en.wikipedia.org/wiki/Maze_generation_algorithm`
fn build(&self, map: &mut Map) {
let mut rng = rand::thread_rng();
let mut current = map.get_random_gri... | Rust | 0 |
inue
tmpl, klass = line.strip().split(':')
mappings[tmpl] = (os.path.join(scriptdir, tmpl),
os.path.join(srcdir, *klass.split('.')) + '.java')
return mappings
def usage():
print """Usage: python %s [--lazy|--help] <template> <outfile>
If lazy is given, a template is only processed if ... | Python | 1 |
default_app_config = 'core.apps.CoreConfig'
| Python | 1 |
ref())?;
let reader = BufReader::new(file);
match reader.lines().next() {
Some(Ok(line)) => Ok(line.starts_with("#!") && line.trim().ends_with("sh")),
Some(Err(e)) => match e.kind() {
// not a UTF-8 file: can't be a shell script
ErrorKind::InvalidData => Ok(false),
... | Rust | 0 |
aram'] = value
elif key == '-s':
user['speed_limit_per_con'] = int(value)
elif key == '-S':
user['speed_limit_per_user'] = int(value)
elif key == '-m':
if value in fast_set_method:
user['method'] = fast_set_method[value]
else:
user['method'] = value
elif key == '-f':
user['forb... | Python | 1 |
== event.target && state.mouse.left.pressed == entity {
state.release(entity);
entity.set_active(state, false);
if !entity.is_disabled(state) {
if state.hovered == entity {
if let Some(ca... | Rust | 0 |
// if the option returned is 'None', the array has been fully read.
fn next(&mut self) -> Option<Result<T>> {
if !self.failed && self.read_elems < self.n_elems {
Some({
let res = self.read.load();
// if ok, increment the iterator
// if not ok,... | Rust | 0 |
(row)
}
pub(crate) fn decode_range_partition_key(
schema: &Schema,
range_partition_schema: &RangePartitionSchema,
mut key: &[u8],
) -> Result<Row<'static>> {
let mut row = schema.new_row();
if range_partition_schema.columns().is_empty() {
return Ok(row);
}
let last_idx = *range_part... | Rust | 0 |
#create class
class Phone():
price=40000
Brand="Sony"
Model="Xperia"
features=['camera','speaker','call']
#create object
my_phone=Phone()
print(my_phone.Brand)
print(my_phone.Model)
print(my_phone.price)
print(my_phone.features)
| Python | 1 |
se crate::TokenKind;
use crate::processors::ProcessedText;
use super::TokenStream;
use super::Tokenizer;
pub struct LegacyMeilisearch;
impl Tokenizer for LegacyMeilisearch {
fn tokenize<'a>(&self, s: &'a ProcessedText<'a>) -> super::TokenStream<'a> {
TokenStream {
inner: Box::new(LegacyTokeniz... | Rust | 0 |
it is.
# lightning still takes care of proper multiprocessing though
data.prepare_data()
data.setup()
print("#### Data #####")
for k in data.datasets:
print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
# configure learning rate
bs, base_lr = config.data.p... | Python | 1 |
from addict import Dict
from sklearn.base import BaseEstimator
from jamboree.middleware.procedures import ModelProcedureAbstract
from sklearn.datasets import make_friedman2
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
from loguru impo... | Python | 1 |
}
} else if e.binding.command == DETAIL_COMMAND {
if bar_i3.is_detailed() { continue; }
bar_i3.set_detailed(true);
} else if e.binding.command == HIDE_DETAIL_COMMAND {
if !bar_i3.is_detailed() { continue; }
... | Rust | 0 |
OnceBox<Box<dyn RandomSource + Send + Sync>> = OnceBox::new();
/// A supplier of Randomness used for different hashers.
/// See [RandomState.set_random_source].
pub trait RandomSource {
fn get_fixed_seeds(&self) -> &'static [[u64; 4]; 2];
fn gen_hasher_seed(&self) -> usize;
}
pub(crate) const PI: [u64; 4]... | Rust | 0 |
/ after 2 steps
assert_eq!(uni.moons[0].pos, (5, -3, -1));
assert_eq!(uni.moons[0].vel, (3, -2, -2));
assert_eq!(uni.moons[1].pos, (1, -2, 2));
assert_eq!(uni.moons[1].vel, (-2, 5, 6));
assert_eq!(uni.moons[2].pos, (1, -4, -1));
assert_eq!(uni.moons[2].vel, (0, 3, -6));
assert_eq!(uni.moo... | Rust | 0 |
println!("CL_DEVICE_MAX_WORK_ITEM_SIZES: {:?}", value);
assert!(0 < value.len());
let value = device.max_preferred_vector_width_char().unwrap();
println!("CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR: {}", value);
assert!(0 < value);
let value = device.max_preferred_vector_wi... | Rust | 0 |
import numpy as np
#from PINN_Inverse import PINN
from PINNs_Inverse_Parameters import PINN
if __name__ == "__main__":
layers_u = [3, 30,30,30, 1]
#layers_Diff = [2, 32, 32, 1]
lb = -2.5
rb = 2.5
bb = -2.5
tb = 2.5
tf = 2.5
nx = 51
ny = 51
t = np.arange(0, tf + 0.01, 0.01)
x... | Python | 1 |
index,
symbol,
})
}
}
/// An iterator over the symbols of an `ElfFile32`.
pub type ElfSymbolIterator32<'data, 'file, Endian = Endianness, R = &'data [u8]> =
ElfSymbolIterator<'data, 'file, elf::FileHeader32<Endian>, R>;
/// An iterator over the symbols of an `ElfFile64`.
pub type ElfSymbolI... | Rust | 0 |
"""
Find Kth Node From End ( ** Interview Question)
Implement the find_kth_from_end function, which takes the LinkedList (ll) and an integer k as input, and returns the k-th node from the end of the linked list WITHOUT USING LENGTH.
Given this LinkedList:
1 -> 2 -> 3 -> 4
If k=1 then return the first node from the e... | Python | 1 |
#[derive(Copy, Debug, Eq)]
pub struct Coord {
pub x: i64,
pub y: i64,
pub vx: i64,
pub vy: i64,
}
impl Clone for Coord {
fn clone(&self) -> Coord { *self }
}
impl PartialEq for Coord {
fn eq(&self, other: &Coord) -> bool {
self.x == other.x && self.y == other.y && self.vx == other.vx &... | Rust | 0 |
pub(crate) async fn connect(&self, url: Url) -> anyhow::Result<Arc<VideoStream>> {
let mut video_streams = self.video_streams.video_streams.write().await;
match video_streams.entry(url.host().ok_or(anyhow!("no host in url"))?.to_owned()) {
Entry::Occupied(entry) => Ok(Arc::clone(entry.get... | Rust | 0 |
let _ = write!(&mut out_file, "{}", out_string);
Ok(svt_objs.len())
}
pub fn print_debug(&self) {
println!("\n[svt] DEBUG all_objs:");
let mut uni_count = 0;
let mut inh_count = 0;
let mut snp_count = 0;
let mut hit_count = 0;
for map_obj in self.all_objs.iter() {
match map... | Rust | 0 |
import enum
# Sync with touch designer code
@enum.unique
class BufferStates(enum.IntEnum):
SERVER = 0
CLIENT = 1
SERVER_ALIVE = 2
@enum.unique
class States(bytes, enum.Enum):
NULL_STATE = b'0'
READY_SERVER_MESSAGE = b'1'
READY_CLIENT_MESSAGE = b'2'
IS_SERVER_ALIVE = b'3'
@enum.unique
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.