text string | label_name string | labels int64 |
|---|---|---|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from erpnext.controllers.print_settings import print_settings_for_item_table
class PurchaseRe... | Python | 1 |
/// Creates a ```FirebaseParams``` instance, a Firebase struct that only
/// knows how to GET data, and limits the number of entries returned
/// on each request to the first ```count```. Often used with ```order_by```.
pub fn limit_to_first(&self, count: u32) -> FirebaseParams {
self.params(LIMIT_T... | Rust | 0 |
So you put Tkinter in it's own process.
# Now why is Pystray in another process too?!
# A: Because if I don't, MPV and GNOME Appindicator
# try to access the same resources and cause the
# entire application to segfault.
#
# I suppose this means I can put the Tkinter GUI back
# into the main process. This is ... | Python | 1 |
_inputs,
&proof,
extra_transcript_init_msg,
)
.is_ok());
Ok(())
}
fn compose_proof_of_quintic_equ_root<F>(
circuit: &mut PlonkCircuit<F>,
x_var: Variable,
) -> Result<Variable, PlonkError>
where
F: PrimeField
{
let x2_var = circuit.mul(x_var, x_var)?;
let x3_var = circu... | Rust | 0 |
#!/usr/bin/python2.5
#
# Copyright 2014 Emilie Gillet.
#
# Author: Emilie Gillet (emilie.o.gillet@gmail.com)
#
# 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 without restriction, including w... | Python | 1 |
() {
Err(ExitError::expected_error(format!("{:#?}", e)))
} else {
Err(ExitError::temporary(format!("{:?}", e)))
}
}
}
}
fn main_run_forever(project: Project) -> OpResult {
let (tx, rx) = chan::unbounded();
let build_thread = {
thread::... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Vitamins Colorscheme
~~~~~~~~~~~~~~~~~~~~
Converted by Vim Colorscheme Converter
"""
from pygments.style import Style
from pygments.token import Token, String, Keyword, Generic, Comment, Operator, Name, Number
class VitaminsStyle(Style):
background_color = '#242424'
st... | Python | 1 |
# Basic Dictionary Operations
# Create an empty dictionary
my_dict = {}
# Add key-value pairs to the dictionary
my_dict["name"] = "Alice"
my_dict["age"] = 25
my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Access a value using a key
print(my_dict["name"]) # ... | Python | 1 |
SIZE: usize = 32;
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct ConnectionToken([u8; CONNECTION_TOKEN_SIZE]);
impl ConnectionToken {
pub fn from_slice(slice: &[u8]) -> Result<Self, ()> {
if slice.len() != CONNECTION_TOKEN_SIZE {
// TODO proper error
return Err(());
... | Rust | 0 |
, time: {:.3f}, eta: {}'.format(
it, np.mean(outs[-1]), logs, time_cost, eta)
logger.info(strs)
if (it > 0 and it == cfg.max_iters - 1) and (not FLAGS.dist or
trainer_id == 0):
save_name = str(
... | Python | 1 |
constraints: self.constraints,
constraints: constraints,
subsumeds: vec![false; len],
//graph: Arc::new(graph.finalize()),
graph: Arc::new(BipartiteGraphBuilder::new().finalize()),
})
}
}
*/
#[derive(Clone)]
pub struct DefaultConstraintsHandler<H: VariablesHa... | Rust | 0 |
2")
.timestamp()
.field("data", DataType::Int32)
.build()
.unwrap();
let batch = RecordBatch::try_new(
schema.as_arrow(),
vec![
Arc::new(tag1),
Arc::new(tag2),
Arc::new(time),
... | Rust | 0 |
'''
InSAR tools go in here
Diego Melgar
University of Oregon
'''
def quadtree2mudpy(home,project_name,quadtree_file,gflist_file,prefix):
'''
Convert quadtree Matlab generated file into a .sta file with station codes
and locations. Also generate individaul .neu files for each los displacement
'''
... | Python | 1 |
: sf::Session,
}
impl sf::IObject for SystemDisplayService {
fn get_session(&mut self) -> &mut sf::Session {
&mut self.session
}
fn get_command_table(&self) -> sf::CommandMetadataTable {
vec![
ipc_cmif_interface_make_command_meta!(get_z_order_count_min: 1200),
ipc_c... | Rust | 0 |
"""
===========================================
Create a 3 panel plot using GridMapDisplay
===========================================
An example that creates a 3 panel plot of a PPI, latitude slice,
and longitude slice using xarray and a cartopy background.
"""
print(__doc__)
# Author: Jason Hemedinger
# License: ... | Python | 1 |
isize, f32, f64, bool, char, &str,
String, Uuid
);
impl ToHtml for Html {
fn to_html(&self) -> Html {
self.clone()
}
}
impl<T> ToHtml for Option<T>
where
T: ToHtml,
{
fn to_html(&self) -> Html {
self.as_ref().map(ToHtml::to_html).unwrap_or_default()
}
}
impl<T, E> ToHtml for R... | Rust | 0 |
fn polymesh_example() -> PolyMesh<f32> {
let pts = make_positions();
let faces = make_polygons();
let faces_flat: Vec<_> = faces
.into_iter()
.flat_map(|poly| std::iter::once(poly.len()).chain(poly.into_iter()))
.collect();
let mut polymesh = Pol... | Rust | 0 |
<usize> {
self.check_self_state()?;
let rv = self.recv_frames();
debug!(
"[{}] StreamHandle.read() recv_frames() => {:?}, state: {:?}",
self.id, rv, self.state
);
self.check_self_state()?;
let n = ::std::cmp::min(buf.len(), self.read_buf.len());... | Rust | 0 |
{
Merges(Merges),
Filename(&'a str),
}
#[pymethods]
impl PyBPE {
#[getter]
fn get_dropout(self_: PyRef<Self>) -> Option<f32> {
getter!(self_, BPE, dropout)
}
#[setter]
fn set_dropout(self_: PyRef<Self>, dropout: Option<f32>) {
setter!(self_, BPE, dropout, dropout);
}
... | Rust | 0 |
logger::init();
let matches = App::new("ruugle_crawler")
.version("0.0.1")
.author("<NAME> <<EMAIL>>")
.about("A Crawler for ruugle engine")
.arg(Arg::with_name("kvs_path")
.short("k")
.long("kvs_path")
.default_value("kvs.json")
.help... | Rust | 0 |
obs_space,
act_space,
nbatch_act=,
nbatch_train=,
nsteps=,
ent_coef=,
vf_coef=,
max_grad_norm=,
nenvs=1,
nsteps=args.max_episode_... | Python | 1 |
_size=16, embed_dim=768, depth=12, num_heads=12, qkv_bias=False, **kwargs)
model = _create_vision_transformer('vit_base_patch16_224_miil_in21k', pretrained=pretrained, **model_kwargs)
return model
@register_model
def vit_base_patch16_224_miil(pretrained=False, **kwargs):
""" ViT-Base (ViT-B/16) from origi... | Python | 1 |
m.output("o8", i15 >> i16_);
let i17 = m.input("i17", 128);
let i18 = m.input("i18", 1);
m.output("o9", i17 >> i18);
m
}
fn shr_arithmetic_test_module<'a>(p: &'a impl ModuleParent<'a>) -> &Module<'a> {
let m = p.module("shr_arithmetic_test_module", "ShrArithmeticTestModule");
let i1 = m.... | Rust | 0 |
iangle meshes.
///
#[derive(Default, Debug)]
pub struct CPUMesh {
pub name: String,
pub material_name: Option<String>,
pub positions: Vec<f32>,
pub indices: Option<Vec<u32>>,
pub normals: Option<Vec<f32>>,
pub uvs: Option<Vec<f32>>,
pub colors: Option<Vec<u8>>,
}
impl CPUMesh {
pub fn s... | Rust | 0 |
.0));
bez
}
fn measure_path() -> BezPath {
let mut bez = BezPath::new();
bez.move_to((0.0, 500.0));
bez.line_to((140.0, 500.0));
bez.line_to((140.0, 0.0));
bez.line_to((0.0, 0.0));
bez.line_to((0.0, 500.0));
bez.close_path();
bez.move_to((190.0, 0.0));
bez.line_to((330.0, 0.0)... | Rust | 0 |
rn an absolute path, but was {}",
orig.display()
)
})
.join(name);
Ok(if path.as_path().is_file() {
Some(path)
} else {
None
})
}
#[cfg(test)]
mod tests {
use lorri::AbsPathBuf;
use super::*;
use std::path::{Path, PathBuf};
/// T... | Rust | 0 |
# Возвращаемся в главное меню
if hasattr(self.menu_manager, "go_to_main_menu"):
self.menu_manager.go_to_main_menu()
elif hasattr(self.menu_manager, "go_back"):
# Возможно, нужно вернуться несколько раз
while self.menu_manager.cu... | Python | 1 |
"""Utils for spline evaluation."""
import chex
import jax.numpy as jnp
def compute_knots(n: int, degree: int = 3) -> chex.Array:
"""Get the knot vector for a given number of points.
Args:
n: Number of evaluation points.
degree: Degree of the B-spline.
Returns:
chex.Array: Knot v... | Python | 1 |
__doc_##n1##_##n2##_##n3
#define __DOC4(n1, n2, n3, n4) __doc_##n1##_##n2##_##n3##_##n4
#define __DOC5(n1, n2, n3, n4, n5) __doc_##n1##_##n2##_##n3##_##n4##_##n5
#define __DOC6(n1, n2, n3, n4, n5, n6) __doc_##n1##_##n2##_##n3#... | Python | 1 |
Arc::new(aevent::Event::new());
(
TxBusyHandle {
tx_done: Arc::clone(&ev),
is_busy_lock: Arc::clone(&is_busy_lock),
},
RxBusyHandle {
rx_done: ev,
is_busy_lock,
},
)
}
pub const U64_BITS_AMOUNT: usize = 64;
<gh_stars>1-10
// This f... | Rust | 0 |
map_location=torch.device('cpu'))
scale_factor = checkpoint["scale_factor"]
print(f"Scaling factor set to {scale_factor}")
scheduler = DDIMScheduler(
num_train_timesteps=1000,
beta_start=0.0015,
beta_end=0.0205,
schedule="scaled_linear_beta",
pr... | Python | 1 |
# %%
import sys
sys.path.append('../..')
from app import ModelApp, GemmaModel, QwenModel, OpenRouterApp
with open('free_response_queries.txt') as f:
queries = f.readlines()
novice_system_prompt = """
You are an assistant for a Japanese learning course, at the novice level. Respond as normal, but use words, phras... | Python | 1 |
from pydantic import BaseModel
from datetime import datetime
from .ticket_type import TicketType
from .ticket_state import TicketState
__authors__ = [
"Ajay Gandecha",
"Sadie Amato",
"Bailey DeSouza",
"Meghan Sun",
"Maddy Andrews",
]
__copyright__ = "Copyright 2024"
__license__ = "MIT"
class New... | Python | 1 |
#
# This file is part of the Chemical Data Processing Toolkit
#
# Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# versi... | Python | 1 |
method
def trailer(title_date):
''' Gets trailer embed ID from Youtube.
title_date (str): movie title and date ('Movie Title 2016')
Attempts to connect 3 times in case Youtube is down or not responding
Can fail if no response is received.
Returns str
'''
lo... | Python | 1 |
'''
Shorten URL v1.1
Github: https://github.com/hzlzh/Alfred-Workflows
Author: hzlzh (hzlzh.dev@gmail.com)
Twitter: @hzlzh
Blog: https://zlz.im/Alfred-Workflows/
'''
from feedback import Feedback
import urllib
import urllib2
import json
import sys
query = sys.argv[1]
api = {
'goo.gl' : {'api_url':'https://www.googl... | Python | 1 |
// Regression test for #70934
fn f() {
const C: [S2; 1] = [S2];
let _ = S1(C[0]).clone();
//~^ ERROR cannot move out of type `[S2; 1]`
}
#[derive(Clone)]
struct S1(S2);
#[derive(Clone)]
struct S2;
fn main() {
f();
}
<filename>src/helpers/utils.rs<gh_stars>0
use std::time::Duration;
use futures::fu... | Rust | 0 |
import numpy as np
from functools import reduce
import matplotlib.pyplot as plt
n_samples = 20
xTrainRaw = np.random.randn(n_samples, 1)
Ntrain = len(xTrainRaw)
xTrain = np.hstack((np.ones((Ntrain,1)), xTrainRaw))
wtrue = [1, 1]
sigma = 1
yTrain = wtrue[0] + wtrue[1]*xTrainRaw + sigma*np.random.randn(Ntrain, 1)
X = xT... | Python | 1 |
dht::DhtConfig;
use crate::discovery::mdns::MdnsConfig;
#[derive(Debug, Default)]
pub struct Config {
pub mdns: Option<MdnsConfig>,
pub dht: Option<DhtConfig>,
pub local_addr: Option<SocketAddr>,
}
impl Config {
pub fn new() -> Self {
Self::default()
}
pub fn all() -> Self {
S... | Rust | 0 |
"""Functions for reading data."""
from polars.io.avro import read_avro
from polars.io.clipboard import read_clipboard
from polars.io.csv import read_csv, read_csv_batched, scan_csv
from polars.io.database import read_database, read_database_uri
from polars.io.delta import read_delta, scan_delta
from polars.io.iceberg ... | Python | 1 |
rgumentParser("X-LLM-X Chat Demo")
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--gpu_ids",
type=int,
nargs="+",
help="A list of space-separated gpu ids to run the model on. "
"The model will span across GPUs in tensor-parallel mode.",
)
grou... | Python | 1 |
{
#[allow(unused_mut)]
let mut builder = update_http_builder(input, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"appl... | Rust | 0 |
pub struct Config {
pub http: HttpCfg,
pub routers: Vec<RouterAddr>,
pub github: GitHubCfg,
pub ui: UiCfg,
}
impl ConfigFile for Config {
type Error = Error;
}
impl GitHubOAuth for Config {
fn github_url(&self) -> &str {
&self.github.url
}
fn github_client_id(&self) -> &str {
... | Rust | 0 |
ly use the low-level bindings directly, although it's recommended to
/// use the high-level Rust idiomatic API to ensure safety. The low-level bindings are
/// quite unsafe to use because there are a lot of unsafe pointers, unsafe blocks, etc...
#[test]
fn should_create_a_pipeline() {
spawn(pro... | Rust | 0 |
material;
mod mesh;
mod mesh_part;
mod mesh_pass;
mod mesh_pipeline;
pub use geometry::{MeshPartGeometry, Vertex};
pub use material::{Material, MaterialData, MaterialFactors, MaterialKind};
pub use mesh::Mesh;
pub use mesh_part::{MeshPart, MeshPartData, mesh_parts_bbox};
pub use mesh_pass::MeshPass;
<reponame>viktorch... | Rust | 0 |
_(optimizer)
# grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.optim.max_norm)
# update
scaler.step(optimizer)
scale = scaler.get_scale()
scaler.update()
optimizer.zero_grad()
step += 1
writer.add_sc... | Python | 1 |
pending, set budgets, and monitor progress. Choose an app that fits your needs and integrates with your financial accounts.",
"What should I include in a financial plan?": "A financial plan should include your financial goals, income, expenses, debt, savings, investments, insurance, and retirement planning."
}
# S... | Python | 1 |
import pytest
import httpx
BASE_URL = "/api/pros"
EXPECTED_FIELDS = ["created_at", "created_by", "updated_at", "url", "id"]
@pytest.mark.asyncio(scope="session")
async def test_upload_download_storage(
test_client,
user_project,
cookies_admin,
):
key = "test/file_0.txt"
file_content = "this is so... | Python | 1 |
rs scaled to maintain a desired false-
/// positive rate for an unbounded number of items.
///
/// * Proper tests.
///
/// For my current purposes I ended up just using the write log idea - 16 bytes
/// per entry was sufficient and the implementation was dead simple.
use std::convert::TryInto;
use std::fs::OpenOption... | Rust | 0 |
or backwards compatibility
return vit_base_r50_s16_224_in21k(pretrained=pretrained, **kwargs)
@register_model
def vit_large_r50_s32_224_in21k(pretrained=False, **kwargs):
""" R50+ViT-L/S32 hybrid. ImageNet-21k.
"""
backbone = _resnetv2((3, 4, 6, 3), **kwargs)
model_kwargs = dict(embed_dim=1024, de... | Python | 1 |
# Importamos la biblioteca requests, que nos permite enviar solicitudes HTTP de forma sencilla.
import requests
# Manejo de Respuesta
# --------------------
# Enviamos una solicitud GET a una URL específica. Esta URL se espera que devuelva datos en formato JSON.
response = requests.get('https://jsonplaceholder.typico... | Python | 1 |
stats} for month, stats in monthly_totals.items()]
history.sort(key=lambda x: x['date'])
return history
def get_yearly_history(uid: str) -> list[dict]:
"""Gets yearly usage for all time by aggregating hourly data."""
user_ref = db.collection('users').document(uid)
hourly_usage_collection = user_re... | Python | 1 |
ect2, box)
action.pick(object0, box)
action.place(object0, box)
# Fourth, after making all actions, provide your reasoning based on the given rules.
# The sequence starts with placing non-plastic objects (object1 and object2) into the box,
# as they have no constraints. Once these are placed, objec... | Python | 1 |
};
pub(crate) use nu_parser::ParserScope;
pub(crate) use nu_protocol::{out, row};
pub(crate) use nu_source::{AnchorLocation, PrettyDebug, Span, SpannedItem, Tag, TaggedItem, Text};
pub(crate) use nu_stream::ToInputStream;
pub(crate) use nu_stream::{InputStream, Interruptible, OutputStream};
pub(crate) use nu_value_ext:... | Rust | 0 |
pub caret: i32,
pub description: String,
#[serde(rename = "completionStart")]
pub completion_start: i32,
#[serde(rename = "completionEnd")]
pub completion_end: i32,
#[serde(rename = "matchingStart")]
pub matching_start: i32,
#[serde(rename = "matchingEnd")]
pub matching_end: i32... | Rust | 0 |
mod client;
mod error;
mod retry;
mod state;
pub mod defaults;
pub use client::{Client, Request, Response};
pub use error::{Error, UnexpectedError, WaitForTransactionError};
pub use libra_json_rpc_types::{errors::JsonRpcError, proto::types, response::JsonRpcResponse};
pub use retry::{Retry, RetryStrategy};
pub use sta... | Rust | 0 |
SupervisionSegment("ut1", "c1", start=1.5, duration=7.13, text="greetings, assistant", speaker="user"),
SupervisionSegment("at1", "c1", start=10.2, duration=8.49, text="welcome, user", speaker="assistant"),
SupervisionSegment(
"ut2", "c1", start=21.3, duration=15.2, tex... | Python | 1 |
}
Err(why) => {
log::info!("Failed to get compatible FourCC: {}", why.to_string())
}
}
camera
.set_camera_format(CameraFormat::new(
Resolution::new(1280, 720),
FrameFormat::MJPEG,
30,
))
.unwrap();
camera.open_stream().... | Rust | 0 |
structs a ResNet-RS-420 model
Paper: Revisiting ResNets - https://arxiv.org/abs/2103.07579
Pretrained weights from https://github.com/tensorflow/tpu/tree/bee9c4f6/models/official/resnet/resnet_rs
"""
attn_layer = partial(get_attn('se'), rd_ratio=0.25)
model_args = dict(
block=Bottleneck, lay... | Python | 1 |
"""Test configuration.
These allow the mocking of various Python modules
that might otherwise have runtime side-effects.
"""
import sys
import mock
import pytest
@pytest.fixture(scope='function', autouse=False)
def FanShim():
import fanshim
yield fanshim.FanShim
del sys.modules['fanshim']
@pytest.fixtur... | Python | 1 |
pe = f"{imitate_type}_{model_name}"
for model_idx in range(n_imitate_shadows):
model_dir = os.path.join(shadow_dir, str(model_idx))
nonpivot_arr = np.load(os.path.join(model_dir, f"adapt_nonpivot_{model_name}.npy"))
logits_arr = np.load(os.path.join(model_dir, f"adapt_{model_type}_confs_on_... | Python | 1 |
esult: Result<(), crate::errors::ErrorKind>,
call_count: Arc<AtomicU64>,
}
impl FakeUpdateApplier {
pub fn new_success() -> Self {
Self { result: Ok(()), call_count: Arc::new(AtomicU64::new(0)) }
}
pub fn new_error() -> Self {
Self {
result... | Rust | 0 |
merged_conf = rel.clone().parsed_config().unwrap();
rt.eval(
"<app config>",
&format!(
"window.fly.app = {{ config: {}, version: {} }};",
merged_conf, rel.version
),
);
// load external libraries... | Rust | 0 |
.values_of(cli::ARG_BA_ARG)
.unwrap_or_default()
.map(str::to_string)
.collect();
let block_assembler_hash_type = matches
.value_of(cli::ARG_BA_HASH_TYPE)
.and_then(|hash_type| serde_plain::from_str::<ScriptHashType>(hash_type).ok())
... | Rust | 0 |
'''
Função J
Considere a seguinte função f(x):
⎧ −1
⎪ ________ , se −1000 ≤ x < −2
⎪ (x + 2)
⎪
f(x) =⎨
⎪ 1
⎪ ________ , se 2 <x ≤ 1000
⎪ (X - 2)
⎩
Faça um programa que leia o valor de x e retorne o valor de f(x) baseado na definição acima.
Imprima ... | Python | 1 |
_tree,
};
serde_json::to_writer(&mut writer, &raw)?;
writeln!(&mut writer)?;
}
Ok(())
}
pub fn write(accession_file: &Path, metadata_file: &Path, output_file: &Path) -> Result<()> {
let mut writer = rnc_utils::buf_writer(output_file)?;
let metadata = JsonlIterator::from_path(... | Rust | 0 |
60 - Invalidate JTAG result register"]
pub set_invalidate_jtag: crate::Reg<set_invalidate_jtag::SET_INVALIDATE_JTAG_SPEC>,
#[doc = "0x64 - Invalidate digital signature result register"]
pub set_invalidate_ds: crate::Reg<set_invalidate_ds::SET_INVALIDATE_DS_SPEC>,
#[doc = "0x68 - The matching result betw... | Rust | 0 |
from datetime import datetime, timezone, timedelta
import json
import os
from googletrans import Translator
import asyncio
class MarkdownReporter:
def __init__(self, items):
self.items = items
self.timezone = timezone(timedelta(hours=8)) # UTC+8 for Shanghai
self.now = datetime.now(self.ti... | Python | 1 |
_action_mock
fc.services = create_fc_services(fc_services_capabilities["HostNumberOfEntries"])
# Act 1
fd = FritzDevice(FritzCredentials("somehost", "someuser", "password"), "FritzMock", host_info=False)
donate_data(fd, upload=True)
# Check 1
assert (
"Data ... | Python | 1 |
(
grafs,
|_| false,
|ef| {
!util::is_workspace(ef.source)
&& (ef.kind == krates::DepKind::Build || ef.kind == krates::DepKind::Dev)
},
);
}
// Just workspace crates
{
let mut kb = krates::Builder::new();
... | Rust | 0 |
ial;
pub use self::cd::cd;
pub use self::echo::echo;
pub use self::pwd::pwd;
pub use self::shift::shift;
pub use self::trivial::{colon, false_cmd, true_cmd};
pub(crate) async fn generate_and_print_output<E, F, ERR>(
builtin_name: &str,
env: &mut E,
generate_bytes: F,
) -> BoxFuture<'static, ExitStatus>
wh... | Rust | 0 |
5], [-0.2, -0.5], [0, -0.5], [0, 0], [L, 0], [L, 0.5],
# [L + 0.2 * np.cos(phi), 0.5 + 0.2 * np.sin(phi)],
# [L - 0.2 * np.cos(phi), 0.5 - 0.2 * np.sin(phi)], [L, 0.5], [L, -0.5],
# [L + 0.2 * np.cos(phi), -0.5 + 0.2 * np.sin(phi)],
# [L - ... | Python | 1 |
from __future__ import annotations
from abqpy.decorators import abaqus_class_doc
from ..UtilityAndView.abaqusConstants import SymbolicConstant
from .InteractionState import InteractionState
@abaqus_class_doc
class SelfContactExpState(InteractionState):
"""The SelfContactExpState object stores the propagating da... | Python | 1 |
"""
TODO: it would be nice if the open grounding dino pipeline worked in the same
way as the huggingface official grounding dino stuff, but alas it doesn't, and
this pipeline runs a the separate variant on a repo that is not setup properly
as a python package, so we have to do some hacks.
"""
from geowatch.mlops.pipeli... | Python | 1 |
from rest_framework.serializers import ModelSerializer
from main import models
class UserSerializer(ModelSerializer):
class Meta:
model = models.User
fields = ['code', 'username', 'email', 'first_name', 'last_name', 'avatar', 'last_login']
class UserRealtionSerializer(ModelSerializer):
... | Python | 1 |
== "M3":
self.tool.tool_on()
elif cmd == "M5":
self.tool.tool_off()
def main():
# Replace 'COM1' and 'COM2' with your actual port names
global tool_head
tool_head = Tool(sn="3423931353535120B1E0")
long_motor_sn = '209D3077484E'
long_motor = ... | Python | 1 |
pub trait DynIterateeImpl: Deref {
type Item: ?Sized;
fn as_ref(&self) -> &dyn Iteratee<Self::Item>;
}
macro_rules! impl_dyn_iteratee_impl {
($(
$ty:ty
),*$(,)?) => {$(
impl<'a, T: ?Sized> DynIterateeImpl for &'a $ty {
type Item = T;
fn as_ref(&self) -> &dyn Iteratee<Self::Item> {
*self... | Rust | 0 |
ceiv(&self) -> CEIV_R {
CEIV_R::new((self.bits & 0xffff) as u16)
}
}
fn main() {
let minidump = std::fs::read("PoC.gif").unwrap();
print!("vec!{:#x?};", minidump);
}
<reponame>raphaelcohn/olympus-xmp
// This file is part of olympus-xmp. It is subject to the license terms in the COPYRIGHT file found... | Rust | 0 |
Aligned,
iq_controller : pid::PidController::new(&i_settings),
id_controller : pid::PidController::new(&i_settings),
last_t : 0.0,
motor_pole_pairs : pole_pairs,
}
}
pub fn initialize_foc(&mut self, initial_time : f32) -> Result<(), FocResult>{
... | Rust | 0 |
= text +"\n" + str;
elm.set_inner_text(&text);
return Ok(None)
}
}
}
}
log(str);
Ok(None)
}
pub(crate) fn flush_log() -> Result<Option<CallbackResponse>,Error> {
if web_sys::window().is_some() {
let window = web_sys::w... | Rust | 0 |
end_dict['zhanming']:
tw.cellWidget(r, 1).setValue(end_stop_sec // 60)
tw.cellWidget(r, 2).setValue(end_stop_sec % 60)
break
def _paint_ok(self, anTrain: Train):
"""
铺画结束。
"""
print("ChangeTrainIntervalDialog::paint_ok")
self.... | Python | 1 |
from typing import Optional, List
import numbers
import dynet as dy
import numpy as np
from xnmt import expression_seqs, param_collections, param_initializers, tensor_tools as tt
from xnmt.transducers import base as transducers
from xnmt.persistence import Serializable, serializable_init, Ref, bare
class FixedSizeAt... | Python | 1 |
_sprites.push(s.clone());
(self.dyn_sprites.len() as i32) - 1
}
pub fn map(&mut self, cel_x: u32, cel_y: u32, sx: i32, sy: i32, cel_w: u32, cel_h: u32, layer: u8) {
let mut idx_x: i32 = 0;
let mut idx_y: i32 = 0;
let mut cel_w = cel_w;
if cel_w > SCREEN_WIDTH as u32 {
... | Rust | 0 |
"""Main loop which requests new commands and publish them on the Robotiq2FGripperRobotOutput topic."""
rospy.init_node('Robotiq2FGripperSimpleController')
pub = rospy.Publisher('Robotiq2FGripperRobotOutput', outputMsg.Robotiq2FGripper_robot_output)
command = outputMsg.Robotiq2FGripper_robot_output(... | Python | 1 |
Self {
box_x: 24,
box_y: 16,
velocity_x: 1,
velocity_y: 1,
}
}
/// Update the `World` internal state; bounce the box around the screen.
fn update(&mut self) {
if self.box_x <= 0 || self.box_x + BOX_SIZE > WIDTH as i16 {
self.veloc... | Rust | 0 |
::Morning)))
);
b.rule_1_terminal("end of morning",
b.reg(r#"[uúù]ltima hora de la mañana|la mañana a [uúù]ltima hora"#)?,
|_| Ok(helpers::hour(10, false)?
.span_to(&helpers::hour(12, false)?, false)?
.latent()
... | Rust | 0 |
候,客户端会接收到一条关于被订阅频道的反馈消息。
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '0'} # 这些结构就是我们在遍历pubsub.listen()函数时得到的元素。
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '1'} #
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '2'} #
{'pattern': None, 'type': 'unsubscrib... | Python | 1 |
lf.load_uncompressed_chunk17(x, z, new, skylight, mask, mask_add, &mut chunk_data)?;
}
Ok(())
}
pub fn load_chunk17(
&self,
x: i32,
z: i32,
new: bool,
mask: u16,
mask_add: u16,
compressed_data: Vec<u8>,
) -> Result<(), protocol::Error... | Rust | 0 |
=> hm_shape_expr(env, e2),
Let(_, _, e2) => hm_shape_expr(env, e2),
App(e1, _) => {
if let TFun(_, _, rtype) = hm_shape_imm(env, e1) {
*rtype
} else {
panic!("app for non-fun: {:?}", e1);
}
}
Op(op) => hm_shape_op(env, ... | Rust | 0 |
ffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
/// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff... | Rust | 0 |
ryptor,
plaintext_buffer: Buffer,
signature_key: *mut Ed25519PrivateKey,
) -> *mut message::Message {
let encryptor = &mut *encryptor;
let data = plaintext_buffer.to_bytes();
let signature_key = signature_key.as_ref();
let message = encryptor.encrypt(&data[..], signature_key);
Box::into_raw(... | Rust | 0 |
pub enum CaffePoolKind {
Avg,
Max,
}
pub trait CaffePoolKernel {
fn kind() -> CaffePoolKind;
}
impl CaffePoolKernel for AvgPool {
fn kind() -> CaffePoolKind {
CaffePoolKind::Avg
}
}
impl CaffePoolKernel for MaxPool {
fn kind() -> CaffePoolKind {
CaffePoolKind::Max
}
}
pub struct CaffePoolGPUBa... | Rust | 0 |
noisy_data.shape[1]) # 转换为(1,288,288)
noise_level = estimate_sigma(noise_im_np) * 2
noise_level = 5
with open(result_root + 'result.txt', 'w') as f:
_, lowest_loss = denoising(noise_im_np, LR=LR, sigma=sigma, rho=rho, eta=eta,
total_step=total... | Python | 1 |
nfo.load_exchange_info(),
GateioExchangeInfo.load_exchange_info(),
HyperliquidExchangeInfo.load_exchange_info(),
MexcExchangeInfo.load_exchange_info(),
OkxExchangeInfo.load_exchange_info(),
)
async def start_exchanges_info(parse_interval_seconds: int = 60 * 60) -> None:
"""Запу... | Python | 1 |
"""Unit tests for AWS client authentication and session management."""
import pytest
import boto3
from unittest.mock import patch, MagicMock
from ecsctl.aws_client import AWSClient
from ecsctl.exceptions import AuthenticationError
@pytest.fixture
def aws_client():
"""Create AWSClient instance for testing."""
... | Python | 1 |
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped
class GoalListenerAndSender(Node):
def __init__(self):
super().__init__('goal_listener_and_sender')
self.subscription = self.create_subscription(
PoseStamped,
'/tb1/goa... | Python | 1 |
: [0xfe, 0x3e] : "i64.atomic.rmw8.xor_u",
I64AtomicRmw16XorU(MemArg<2>) : [0xfe, 0x3f] : "i64.atomic.rmw16.xor_u",
I64AtomicRmw32XorU(MemArg<4>) : [0xfe, 0x40] : "i64.atomic.rmw32.xor_u",
I32AtomicRmwXchg(MemArg<4>) : [0xfe, 0x41] : "i32.atomic.rmw.xchg",
I64AtomicRmwXchg(MemArg<8>) : ... | Rust | 0 |
rt("Fxch_st0_sti_DDC8", Code::Fxch_st0_sti_DDC8);
h.insert("Fst_sti", Code::Fst_sti);
h.insert("Fstp_sti", Code::Fstp_sti);
h.insert("Fucom_st0_sti", Code::Fucom_st0_sti);
h.insert("Fucomp_st0_sti", Code::Fucomp_st0_sti);
h.insert("Fiadd_m16int", Code::Fiadd_m16int);
h.insert("Fimul_m16int", Code::Fimul_m16... | Rust | 0 |
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.models import User, Account, Transaction
from backend.extensions import db
from backend.schemas import TransactionSchema, TransactionResponseSchema
transaction_bp = Blueprint('transactions', __name_... | Python | 1 |
y][x] = BingoCell::Marked(drawn_number);
}
}
}
if has_bingo(&input.boards[board_num]) {
wins.push((input.boards[board_num].clone(), drawn_number));
}
}
}
wins
}
fn part_one(s: &str) -> String {
let wins = wins... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.