text string | label_name string | labels int64 |
|---|---|---|
all_handles.append(P2POp(op=isend, tensor=dk_delta, peer=maybe_send_rank, group=seq_group))
all_handles.append(P2POp(op=isend, tensor=dv_delta, peer=maybe_send_rank, group=seq_group))
if debug:
_bwd_send_volume += torch.numel(dk_delta) * dk_delta.element_size()
... | Python | 1 |
Poly):
"""Fourier coefficinets of the polar coordinates
"""
def __init__(self,
eps=1,
x_cent=0,
y_cent=0,
f_as=np.array([0.]),
f_bs=np.array([]),
npts=100):
"""Create a shape defined by its Fourier... | Python | 1 |
_strlst, avahi_entry_group_commit, avahi_entry_group_free,
avahi_entry_group_is_empty, avahi_entry_group_new, avahi_entry_group_reset, AvahiClient,
AvahiEntryGroup, AvahiEntryGroupCallback, AvahiIfIndex, AvahiProtocol, AvahiPublishFlags,
};
use libc::{c_char, c_void};
/// Wraps the `AvahiEntryGroup` type from ... | Rust | 0 |
=self.stride, bias=qkv_bias)
self.kv = nn.Conv2d(dim, self.dim_qk + self.dim_v, 1, bias=qkv_bias)
self.pos_embed = PosEmbedRel(
block_size=block_size // self.stride, win_size=self.win_size, dim_head=self.dim_head, scale=self.scale)
def reset_parameters(self):
std = self.q.weigh... | Python | 1 |
# coding=utf-8
import unittest
from urllib.parse import quote
from bugsnag.event import Event
from bugsnag.configuration import (Configuration, RequestConfiguration)
class PathEncodingTest(unittest.TestCase):
environ = {
'SCRIPT_NAME': '',
'SERVER_NAME': 'localhost',
'SERVER_PORT': '80',... | Python | 1 |
ln!("No item to remove"),
}
}
"rcc" => {
// Response cache clear
let host = match words.next() {
Some(word) => word,
None =>... | Rust | 0 |
pdated_at",
"name",
"my_number",
"__class__"]
self.assertCountEqual(d.keys(), expected_attrs)
self.assertEqual(d['__class__'], 'BaseModel')
self.assertEqual(d['name'], "Holberton")
self.assertEqual(d['my_number... | Python | 1 |
9c,0x9c,0x9c,0x9c,0x9c,],
pt: [0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,0x9c,],
ct: [0xa0,0xc4,0xa6,0x13,0x19,0xf5,0x00,0x16,0x0a,0x21,0x96,0x41,0x2e,0x15,0x5a,0xb6,]
},
Aes128Test {
key: [0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,0x9d,... | Rust | 0 |
min_py.max(0) as isize;
let buf_width = (bound_max_px.min(src_width as isize)
- bound_min_px.max(0)) as usize;
let buf_height = (bound_max_py.min(src_height as isize)
- bound_min_py.max(0)) as usize;
let dst_x_offset = (0 - bound_min_px).max(0) as isize;
let dst_y_offset = (0 - bound_... | Rust | 0 |
# ======================================================================= #
# Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> #
# #
# This file is part of KIAUH - Klipper Installation And Update Helper #
# https://githu... | Python | 1 |
LE_CFG | USB_LE_CTR | USB_CFG_WR;
const USB_CMD_WR: usize = USB_LE_CFG | USB_LE_CTR | USB_CFG_WR | USB_CFG_ACT;
struct PiRegs {
ram_addr: *mut c_void,
pi_addr: *mut c_void,
read_len: usize,
write_len: usize,
status: usize,
}
/// we need the registers at this specific address
const PIR: *mut PiRegs... | Rust | 0 |
ured that n*k elements will go into the heap
# (in the worst case, otherwise less > n and < n*k),
# until you are at the last element of one of the lists.
# So this will take O(n*k*log(k)) time.
while not heap.is_empty():
# extract the minimum value out of the heap.
# No need to do mini... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright 2007 Doug Hellmann.
#
"""Data for use with difflib examples.
"""
#end_pymotw_header
text1 = """Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Integer eu lacus accumsan arcu fermentum euismod. Donec
pulvinar porttitor tellus. Aliquam venenatis. Donec facilisis
pharetra t... | Python | 1 |
ter=color_jitter,
auto_augment=auto_augment,
interpolation=interpolation,
use_prefetcher=use_prefetcher,
mean=mean,
std=std,
re_prob=re_prob,
re_mode=re_mode,
re_count=re_count,
... | Python | 1 |
element_tag == 'section':
return 'Sect'
elif element_tag == 'blockquote':
return 'BlockQuote'
elif element_tag == 'p':
return 'P'
elif element_tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
return element_tag.upper()
elif element_tag in ('dl'... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import json
from datetime import datetime
def extract_article_details(url, headers):
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# Title extraction
title = soup.find('h1', class_... | Python | 1 |
er_map(|path| {
match path {
CompoundPathElement::PathI32(path) => {
if let Some(path) = path.reduce(tolerance)
{ Some(CompoundPathElement::PathI32(path)) } else { None }
},
CompoundPathElement::P... | Rust | 0 |
ue and df.at[pid,"time"]==0:
person=dicname[pid]
x=df.at[pid,'x']
y=df.at[pid,'y']
print("player "+person+" time\n手头现金:",\
df.at[pid,"cash"],"\n银行存款:",df.at[pid,"bank"])
print("你所处位置:","("+str(x)+","+str(y)+")")
dices=ra.randint(1,6)
print("骰子点数为",di... | 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 |
ndInterface/api/js/get'
headers = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh - CN, zh; q = 0.9, en; q = 0.8 ',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/... | Python | 1 |
")]
#[serde(deserialize_with = "fix_common::workarounds::from_opt_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(default)]
#[serde(rename = "2432")]
pub tot_no_order_entries: Option<i32>,
/// Indicates whether this is the last fragment in a sequence of message fragments. Only required where message... | Rust | 0 |
ender
#new
}
impl #ident {
#helpers
}
};
Ok(tokens)
}
fn do_slider_as_input_helpers(data: &ast::Data<darling::util::Ignored, FieldOpts>) -> TokenStream {
let fields = data.as_ref().take_struct().unwrap();
let slider_input_fields = fields
.iter(... | Rust | 0 |
equests.get(url2019)
precipitation_data2019 = precipitation2019.json()
return precipitation_data2019
def precip_sum2020():
url2020 = 'https://archive-api.open-meteo.com/v1/archive?latitude=46.8083&longitude=-100.7837&start_date=2020-05-22&end_date=2020-05-22&daily=precipitation_sum&temperat... | Python | 1 |
Example {"),
],
)
}
#[test]
fn many_files() {
let result = run_thrift_expect(
&["one.thrift", "two.thrift"],
Some(
r#"one crate
two crate
"#,
),
&[
(
"one.thrift",
r#"struct Example {
1: i64 field,
}
"#,
... | Rust | 0 |
#!/usr/bin/env -S python3 -m pytest
import decompyle3
from reassembler import full_reassemble
from contextlib import redirect_stdout
from itertools import zip_longest
from glob import glob
import py_compile
import dis
import io
import re
def disassemble(code):
"""Capture dis.dis() output as a string."""
f = i... | Python | 1 |
teBeta.detailed_help = UpdateGA.detailed_help
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
"""Update a Compute Engine managed instance group."""
@classmethod
def Args(cls, parser):
super(UpdateAlpha, cls).Args(parser)
def _CreateInstanceGroupManagerPatch(
self, args,... | Python | 1 |
readControlBlock;
assert!(!tcb.is_null(), "Don't have TCB available?");
&mut *tcb
}
}
// TODO(correctness): this needs some hardending to avoid aliasing of ThreadState!
pub fn scheduler<'a>() -> &'a SchedulerControlBlock {
unsafe {
let scb = arch::get_scb... | Rust | 0 |
command(&self, cmd_num: usize, arg1: usize, arg2: usize, appid: ProcessId) -> CommandReturn {
if let Some(cmd) = Cmd::from_usize(cmd_num) {
match cmd {
Cmd::Ping => CommandReturn::success(),
Cmd::Write => self
.apps
.enter(appi... | Rust | 0 |
)
for name, value in vars(self).items():
property_name = name[1:]
if property_name in memeber_set:
memeber_set.remove(property_name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyProtect... | Python | 1 |
move |i| {
let (i, name) = ws(op_ident(line))(i)?;
let (i, fields) = opt(ws(defty_fields(line)))(i)?;
Ok((i, Variant { name, fields }))
}
}
fn defty_fields(line: &Line) -> impl Fn(&str) -> IResult<&str, Vec<Field>, ParsingError> + '_ {
move |i| delimited(char('{'), many0(ws(defty_field... | Rust | 0 |
import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Union
import streamlit as st
def login_input() -> Union[str, str]:
"""
Adiciona o input de usuário e senha para login.
Returns
-------
user, password: Union[str, str]
O usuário e a senha inserid... | Python | 1 |
))
}
}
}
Ok(vec![keybinding])
}
Value::List { vals, .. } => {
let res = vals
.iter()
.map(|inner_value| create_keybindings(inner_value, config))
.collect::<Result<Vec<Vec<Parsed... | Rust | 0 |
}
}
}
impl HeaderProcessor<Header> for Consensus {
type UncleProcessResult = UncleResult;
fn process_header(&self, header: &Header) -> Result<(), Box<Error>> {
if header.previous_hash.len() == 0 {
self.block_db
.lock()
.map_err(|_e| Exception::new("Poison... | Rust | 0 |
,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a1... | Rust | 0 |
0 / (bbox.y2 - bbox.y1),
0.0,
0.0,
]);
let mut resources = xobject.resources();
ctx.pop(&mut resources);
ctx.alloc_ref()
}
/// Calculates the bounding box and size conversions for an usvg tree.
fn get_sizings(tree: &Tree, options: &Options) -> (CoordToPdf, Rect) {
let native_size ... | Rust | 0 |
# -*- coding: utf-8 -*-
import os.path
from outwiker.api.gui.defines import TOOLBAR_PLUGINS
from outwiker.api.pages.wiki.defines import MENU_WIKI_COMMANDS, PAGE_TYPE_STRING
from outwiker.api.gui.actions import ActionsGUIController, ActionGUIInfo, ButtonInfo
from .commandspoiler import SpoilerCommand
from .actions im... | Python | 1 |
from faker import Faker
# make faker
faker = Faker()
print(f'name: {faker.name()}')
print(f'address: {faker.address()}')
print(f'text: {faker.text()}')
| Python | 1 |
"
contract test {
function foo() public returns (int64) {
return -7e3;
}
}",
);
runtime.function("foo", Vec::new());
assert_eq!(runtime.vm.output, Foo64Return(-7000).encode());
// parse
let mut runtime = build_solidity(
"
con... | Rust | 0 |
ibv_context_ops>()))._compat_async_event as *const _ as usize
},
248usize,
concat!(
"Offset of field: ",
stringify!(ibv_context_ops),
"::",
stringify!(_compat_async_event)
)
);
}
#[repr(C)]
pub struct ibv_context {
pub device: *mut ... | Rust | 0 |
None => {
i += 1;
continue;
}
},
None => break,
};
debug!(
"Reinterpreting as Skybox Texture {:?}: format: {:?}, len: {}, extents: {:?}",
handle,
texture.format,
... | Rust | 0 |
timize_memory_usage" in hyperparams:
kwargs.update(optimize_memory_usage=False)
# Check if we are running python 3.8+
# we need to patch saved model under python 3.6/3.7 to load them
newer_python_version = sys.version_info.major == 3 and sys.version_info.minor >= 8
custom_objects = {}
... | Python | 1 |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
"""
@Time : 2023/9/6 23:11:27
@Author : Stitch-z
@File : test_tutorial_assistant.py
"""
import aiofiles
import pytest
from metagpt.const import TUTORIAL_PATH
from metagpt.roles.tutorial_assistant import TutorialAssistant
@pytest.mark.asyncio
@pytest.mark.paramet... | Python | 1 |
TANT_BUFFER, D3D11_BIND_SHADER_RESOURCE, D3D11_BIND_UNORDERED_ACCESS,
D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD,
D3D11_FILTER_MIN_MAG_MIP_LINEAR,
};
const DENSITY_RESOLUTION: (u32, u32, u32) = (512, 512, 512);
const DIRECTIONAL_SHADOW_RESOLUTION: (u32, u32, u32) = (128, 128, 128);
const PO... | Rust | 0 |
import numpy as np
from stable_baselines3.common.env_checker import check_env
from quantrl_lab.custom_envs.core.trading_env import TradingEnvProtocol
def test_env_creation(standard_env: TradingEnvProtocol):
"""Test that environment can be created without errors."""
assert standard_env is not None
assert ... | Python | 1 |
in last_page, "Last page should have images"
# assert isinstance(last_page["images"], list), "images should be a list"
# assert len(last_page["images"]) > 0, "Should have at least one image"
# # Check if the driver's license number is in the processed content
# license_found = ... | Python | 1 |
"""
决策算子 - 基于Agent状态和用户感知进行决策
"""
from typing import Dict, Any, List
from .base_operator import BaseConceptOperator
from persona.knowledge_graph_agent import RuntimeState, ConceptGraph
class DecisionOperator(BaseConceptOperator):
"""决策算子 - 基于Agent状态和用户感知进行决策"""
def __init__(self, name: str = "DecisionO... | Python | 1 |
last stop, so the target value
// should be the maximum to make the reader's job easier.
self.max
} else if level == self.last_level() {
self.skips[skip_index].value
} else {
// Parent skips would like to index a value equivalent to the
// max... | Rust | 0 |
in_tracking_confidence.
"""
super().__init__(
binary_graph_path=_BINARYPB_FILE_PATH,
side_inputs={
'model_complexity': model_complexity,
'num_hands': max_num_hands,
'use_prev_landmarks': not static_image_mode,
},
calculator_params={
... | Python | 1 |
EceError::CryptoError)
}
}
<reponame>chertov/onnxruntime-rs
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/generated/linux/x86_64/bindings.rs"
));
#[cfg(all(target_os = "macos"))]
include!("./macos/bindings.rs");
#[cfg(all(target_os = "windows"... | Rust | 0 |
deprecated]
pub unsafe fn luaL_optlong(L: *mut lua_State, n: c_int, d: c_long) -> c_long {
luaL_optinteger(L, n, d as lua_Integer) as c_long
}
#[inline(always)]
pub unsafe fn luaL_typename(L: *mut lua_State, i: c_int) -> *const c_char {
lua::lua_typename(L, lua::lua_type(L, i))
}
#[inline(always)]
pub unsafe ... | Rust | 0 |
; 24],
/// Shifter Buffer N Half Word Swapped Register
pub SHIFTBUFHWS0: RWRegister<u32>,
/// Shifter Buffer N Half Word Swapped Register
pub SHIFTBUFHWS1: RWRegister<u32>,
/// Shifter Buffer N Half Word Swapped Register
pub SHIFTBUFHWS2: RWRegister<u32>,
/// Shifter Buffer N Half Word S... | Rust | 0 |
request: Request,
request_id: RequestId,
},
/// Send a successful Response to the libp2p service.
SendResponse {
peer_id: PeerId,
response: Response,
index: u8,
},
/// Publish a message.
Publish {
topic: GossipTopic,
message: Vec<u8>,
},
... | Rust | 0 |
le("WingGeom", "XSec_2", "Root_Chord", scaledStep=False)
self.geometry.nom_addVSPVariable("WingGeom", "XSec_3", "Root_Chord", scaledStep=False)
self.geometry.nom_addVSPVariable("WingGeom", "XSec_4", "Root_Chord", scaledStep=False)
self.geometry.nom_addVSPVariable("WingGeom", "XSec_4", "Tip_Chord... | Python | 1 |
, 48, 51, 163, 143, 146, 56, 144, 147, 64, 131, 148, 226, 154, 195, 122, 23, 82, 234],
xPub: & [ 131, 151, 117, 164, 24, 118, 227, 40, 152, 106, 162, 97, 104, 149, 139, 186, 17, 118, 230, 120, 25, 179, 87, 238, 168, 74, 252, 234, 184, 177, 219, 120, 65, 105, 162, 163, 46, 54, 24, 169, 3, 233, 48, 189, 26, 113, ... | Rust | 0 |
"""
Calculate and View Aerosol Percentages
--------------------------------------
Calculate the percentages of different aerosols in a Aerosol
Chemical Speciation (AOS) monitor dataset and view the percentages
in a pie chart.
Written: Zach Sherman
"""
from arm_test_data import DATASETS
import matplotlib.pyplot as p... | Python | 1 |
import autogen
config_list = autogen.config_list_from_json(
env_or_file="OAI_CONFIG_LIST.json",
filter_dict={
"model": ["gpt-3.5-turbo"]
},
)
llm_config = {
"config_list": config_list,
"timeout": 120,
}
assistant_quote1 = autogen.AssistantAgent(
name="assistant1",
system_message="... | Python | 1 |
col (str): The column to use.
ext (str): The HDF group name to use. (default: '/')
Returns:
The number of rows
"""
return self._group(ext)[col].size
def names(self, *, ext=None):
"""Return a list of the names of all the columns in an extension
... | Python | 1 |
uted shocks. If None, figure will not show the confidence
interval.
ax : AxesSubplot
matplotlib Axes instance to use
**predict_kwargs
Any additional keyword arguments to pass to ``result.get_prediction``.
Returns
-------
Figure
matplotlib Figure containing the predic... | Python | 1 |
t(obj)
print("список Lect's")
for obj in gc.get_objects():
if isinstance(obj, Lecturer):
print(obj)
print("список Std's")
for obj in gc.get_objects():
if isinstance(obj, Student):
print(obj)
print('Сравнение людей по средним оценкам:')
print('student_01 < student_02 ', student_01 < student_02... | Python | 1 |
n(i32) -> i32>(const_cstr!("rust_fun_add_one").as_cstr())
}.unwrap();
assert_eq!(rust_fun_add_one(5), 6);
let c_fun_print_something_else = unsafe {
lib.symbol_cstr::<unsafe extern "C" fn()>(
const_cstr!("c_fun_print_something_else").as_cstr(),
)
}.unwrap();
unsafe { c_fu... | Rust | 0 |
[[0.56067896, 0.36310029, 0.33273944],
[0.73811269, 0.28137168, 0.67521429]]])
>>> # Ellipsis batch matrix multiplication
>>> print(paddle.einsum('...jk, ...kl->...jl', A,B))
Tensor(shape=[2, 3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
... | Python | 1 |
import sys
import subprocess
import gzip
f = sys.argv[1]
lines = ["EMPTY"] + [x.strip() for x in gzip.open(f).readlines()]
print "checking indexing at bounds:"
def check(gzname, start, end=None):
run = subprocess.check_output
exp = lines[start:start+1] if end is None else lines[start:end + 1]
obs = run("... | Python | 1 |
se):
server_name = None
image_name = 'aler9/rtsp-simple-server'
command = ['docker', 'pull', image_name]
run_command(command)
command = ['docker', 'run', '--rm', '--network=host', '--name', rtsp_container_name, image_name ]
if verbose:
Popen(command)
else:
Popen(command, stderr=DEVNULL, stdout=D... | Python | 1 |
# coding: utf8
# @Author: 郭 璞
# @File: 判断一棵二叉树是否为另一棵的子结构.py
# @Time: 2017/4/16
# @Contact: 1064319632@qq.com
# @blog: http://blog.csdn.net/marksinoberg
# @Description: 判断一棵二叉树是否为另一棵的子结构,即子树。我的做法:遍历获取层次序列,判断序列是否在大树的序列中即可... | Python | 1 |
depth
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_max_depth() {
run_tests(max_depth);
}
#[test]
fn test_max_depth_iterative() {
run_tests(max_depth_iterative);
}
fn run_tests<F: Fn(Option<Rc<RefCell<TreeNode>>>) -> i32>(fun: F) {
assert_eq!(fun(... | Rust | 0 |
card_url)
card_info = {product_id: {"short_name": card_name,
"full_name": full_name,
"description": description,
"url": product_url,
"rating": rating,
... | 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 |
from pyteal.ast.expr import Expr
class LeafExpr(Expr):
"""Leaf expression base class."""
def has_return(self):
return False
LeafExpr.__module__ = "pyteal"
| Python | 1 |
let mut vga = Vga::new();
mem.write(&mut vga, 0x0000, 0x35);
let mut initial: cpu::CpuState = Default::default();
initial.source_index = Word::MAX;
let mut expected: cpu::CpuState = Default::default();
expected.program_counter = Word::new(0x0003);
expected.source_index = Word::ZERO;
cpu:... | Rust | 0 |
] && x[j].len() == 1 && s.ends_with("- main") {
to_delete[j] = true;
}
// Don't allow blocklets whose first line has the form ... main(...).
let m = " main (";
if s.contains(&m) && s.after(m).contains(')') && !s.between(m, ")").contains('(') {
... | Rust | 0 |
from genicam import CNodeMapRef, GenericException, IsReadable
import sys
def main():
try:
XMLFileName = "HelloWorld.xml"
Camera = CNodeMapRef()
Camera._LoadXMLFromFile(XMLFileName)
theNode = Camera._GetNode("TheNode")
print(type(theNode))
theInt = Camera.GetNode(... | Python | 1 |
from functions import crop_sprite
# Save the cropped sprite to a file
start_x = 0
start_y = 0
width = 32
height = 32
# specify specific rows where the sprite is doing a different motion
for row in range(0,9):
for column in range(0,8):
x = start_x + (32 * column)
y = start_y + (32 * row)
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# ... | Python | 1 |
# Adapted from DiT
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# DiT: https://github.com/facebookresearch/DiT/tree/main
# GLIDE: https://github.com/openai/glide-text2im... | Python | 1 |
#
prob_over_seq = prob_over_seq_over_type.reshape(
(new_shape_0, new_shape_1)
)[
tensor.arange(new_shape_0),
target_type.flatten()
].reshape(
(back_shape_0, back_shape_1)
)
log_prob_over_seq = tensor.log(
prob_o... | Python | 1 |
import matplotlib.pyplot as plt
import pickle
import matplotlib
import fire
import numpy as np
def main(
save_dir: str='pics/four_minus.png',
data_paths: list=[
'../cos_sims/all_cos_llama3.pkl',
'../cos_sims/all_cos_llama2.pkl',
'../cos_sims/all_cos_phi-3.pkl',
'../cos_sims/all_... | Python | 1 |
let height = BALL_DIAMMETER * ROD_LENGTH;
let mut cylinder = node.add_cylinder(0.07f32, height);
cylinder.append_translation(&Translation3::new(
(i as f32) - 1.5,
height / 2.0,
(j as f32) - 1.5,
));
cylinder.set... | Rust | 0 |
#[doc = "TIMG_T0HI\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [t0hi](t0hi) module"]
pub type T0HI = crate::Reg<u32, _T0HI>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _T0HI;
#[doc = "`re... | Rust | 0 |
(rkhaitan): this schema intentionally omits the data_collections field
// that is typically present in Debezium transaction metadata topics. See
// https://debezium.io/documentation/reference/connectors/postgresql.html#postgresql-transaction-metadata
// for more information. We chose to omit this field beca... | Rust | 0 |
ure if needed
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {"accuracy": acc}
@staticmethod
def get_device(device_num: int = 0):
"""Get a device (GPU or CPU) for the torch model"""
# If there's a GPU availa... | Python | 1 |
println!("Unexpected Object/hashmap Atom found?");
}
}
}
println!("expr stack {:?} ", expr_stack);
// Assert - only one value on expr stack
return expr_stack.pop().unwrap();
}
// pub fn init_runtime_input(runtime: &mut Runtime, input: &Option<AvHttpRequest>) {
// if le... | Rust | 0 |
}
// f32 wrappers below were not part of Skia.
macro_rules! impl_debug_display {
($t:ident) => {
impl core::fmt::Debug for $t {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{}", self.get())
}
}
impl core::fmt::Disp... | Rust | 0 |
thread::sleep(std::time::Duration::from_millis(250));
tx.send(42u32).unwrap();
println!("sent");
});
async_std::task::block_on(async {
println!("receiving...");
let x = rx.stream().next().await;
println!("received");
assert_eq!(x, Some(42));
});
t.join()... | Rust | 0 |
-0o7043275, -0o3641101,
),
[
I32(-2147483648), I32(-1853117), I32(-1000001),
I32(-2147483648), I32(-1853117), I32(-1000001),
I32(-2147483648), I32(-1853117), I32(-1000001),
]
);
}
#[test]
fn i32_suffixed() {
assert_bytify_eq!(
bytify!(
... | Rust | 0 |
import datetime
import decimal
from typing import Dict, Iterable, List, Tuple
class MyUDTFWithTypeHints:
def process(
self,
int_: int,
float_: float,
bool_: bool,
decimal_: decimal.Decimal,
str_: str,
bytes_: bytes,
byte_array_: bytearray,
) -> L... | Python | 1 |
();
fn try_from(nr: NodeResult) -> Result<Self, ()> {
Ok(nr)
}
}
impl TryFrom<NodeResult> for () {
type Err = ();
fn try_from(nr: NodeResult) -> Result<Self, ()> {
match nr {
NodeResult::Unit => Ok(()),
_ => Err(()),
}
}
}
impl TryFrom<NodeResult> for Value {
type Err = ();
f... | Rust | 0 |
hite Square Bracket", ']'),
('❴', "Medium Left Curly Bracket Ornament", '{'),
('❵', "Medium Right Curly Bracket Ornament", '}'),
('⁎', "Low Asterisk", '*'),
('٭', "Arabic Five Pointed Star", '*'),
('∗', "Asterisk Operator", '*'),
('᜵', "Philippine Single Punctuation", '/'),
('⁁', "Caret Inse... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import locale
from psychopy import localization
from psychopy.localization import _translate
welcome = u'Welcome to PsychoPy3!'
trans = {'en': welcome,
'ja': u'PsychoPy3へようこそ!'
}
### needs rewriting since localization.init() no longer sets... | Python | 1 |
_MM_SHUFFLE(2, 0, 3, 1));
vTemp3 = XM_PERMUTE_PS!(V3, _MM_SHUFFLE(0, 3, 0, 3));
vTemp3 = _mm_mul_ps(vTemp3, vTemp2);
// - V2wxwx * V3ywxz
vTemp2 = XM_PERMUTE_PS!(vTemp2, _MM_SHUFFLE(2, 1, 2, 1));
vTemp1 = XM_PERMUTE_PS!(V3, _MM_SHUFFLE(2, 0, 3, 1));
vTemp3 = XM_FNMADD_PS!... | Rust | 0 |
_owned());
let extensions = request.extensions_mut();
extensions.insert(jet_token);
extensions.insert(raw_token);
chain.next(ctx).await
}
Err(e) => {
error!("Invalid authorization token: {:#}", e);
let response = ResponseBuilder::ne... | Rust | 0 |
Delta(time) => write!(f, "{}ms", time.num_milliseconds()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TimeUnit {
Millisecond,
Second,
Minute,
Hour,
Day,
Week,
}
macro_rules! register_time_units {
(
$($($unit_str:literal)|+ => $unit:iden... | Rust | 0 |
#!/usr/bin/env python3
from cfg import *
class CurrentPair(object):
def __init__(self, cfg = None, working = None):
self.cfg = cfg
self.working = working
@property
def cfg(self):
return self._cfg
@cfg.setter
def cfg(self, cfg):
assert (not cfg) or isinstance(cfg, CFG)
self._cfg = cfg
@property
def... | Python | 1 |
from rest_framework import serializers
from .models import Medication, MedicationLog
class MedicationSerializer(serializers.ModelSerializer):
dose_times = serializers.ListField(
child=serializers.CharField(),
required=False,
allow_empty=True,
default=list
)
class Meta:
... | Python | 1 |
32, n_segments: i32, x: f32, y: f32, color: Hsl) {
// TODO: explore having a random radians_per_segment
let radians_per_segment = (2. * PI) / n_segments as f32;
for n in 0..n_segments {
let start_theta = n as f32 * radians_per_segment;
let end_theta = (n + 1) as f32 * radians_per_segment;
let min = r... | Rust | 0 |
ary connectives.
pub const PREALLOCATED_HANDLE_TYPE_UNARY_CONNECTIVE: Handle<tags::Type> =
Handle {
handle: 7,
marker: PhantomData,
};
/// A pre-allocated handle used to refer to the type of binary connectives.
pub const PREALLOCATED_HANDLE_TYPE_BINARY_CONNECTIVE: Handle<tags::Type> =
Handle... | Rust | 0 |
/// [`Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let input = "<!-- comments will be stripped -->This is an Ammonia example.";
/// let output = "This is an Ammonia example.";
///
/// let document = Builder::new()
/// ... | Rust | 0 |
from Class_endereco import Endereco
from Abstract_funcionario import Funcionario
class Medico(Funcionario):
def __init__(self, nome: str, telefone: str, email: str, crm: str, endereco: Endereco) -> None:
super().__init__(nome, telefone, email, endereco)
self.crm = crm
def calcular_salario(sel... | Python | 1 |
provider.Contacts.DATABASE_CREATED";
/// public static final [EXTRA_CREATE_DESCRIPTION](https://developer.android.com/reference/android/provider/ContactsContract.Intents.html#EXTRA_CREATE_DESCRIPTION)
pub const EXTRA_CREATE_DESCRIPTION : &'static str = "com.android.contacts.action.CREATE_DESCRIPTION";
... | Rust | 0 |
from google.adk import Agent
from travel_planner.subagents.flight_agent import flight_agent
from travel_planner.subagents.hotel_agent import hotel_agent
from datetime import datetime, timedelta
from google.adk import Agent
from google.adk.agents import LlmAgent
from google.adk.models.lite_llm import LiteLlm... | Python | 1 |
import os
from datetime import datetime
from string import Template
from formatters.file_formatter import save_problems_by_type
class ExerciseFileHandler:
def __init__(self, template_dir="templates", output_dir="output"):
self.template_dir = template_dir
self.output_dir = output_dir
self.e... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.