text string | label_name string | labels int64 |
|---|---|---|
or change in changes {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
let result = sqlx::query("INSERT INTO events (timestamp, guild, channel, source, target, reason) VALUES (?, ?... | Rust | 0 |
"""Visitor classes pulled out from different tests
These are here because we don't currently support having interpreted
classes subtype compiled ones but pytest grabs the python file
even if the test was compiled.
"""
from __future__ import annotations
from mypy.nodes import AssignmentStmt, CallExpr, Expression, In... | Python | 1 |
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd.
# 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/LI... | Python | 1 |
if state.cl_buf.len() != 0 {
let buf = state.cl_buf.clone();
if let SshKeyStatus::Searching(_) = state.ssh_key_status {
if let AsyncSink::Ready = state.cl_tx.start_send(ServerMessage::SshData(buf))? {
state.cl_buf.clear();
}
}
... | Rust | 0 |
s` or `rustls-tls` feature to be enabled.
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
Certificate(ClientCertificate),
/// An id and api_key to use for API key authentication
ApiKey(String, String),
/// AWS credentials used for AWS SigV4 request signing.
///
/// # Optional
... | Rust | 0 |
37: Button = Button(740u32);
#[doc(alias = "BTN_TRIGGER_HAPPY38")]
pub const TRIGGER_HAPPY38: Button = Button(741u32);
#[doc(alias = "BTN_TRIGGER_HAPPY39")]
pub const TRIGGER_HAPPY39: Button = Button(742u32);
#[doc(alias = "BTN_TRIGGER_HAPPY40")]
pub const TRIGGER_HAPPY40: Button = Button(743u32... | Rust | 0 |
# simple program to print if else
n = int(input("enter any number:"))
if n<0:
print("given number is positive")
else:
print("given number is Negative") | Python | 1 |
_min_contig = Some(250);
vdj_asm(args.clone()).unwrap();
let mut bam = bam::Reader::from_path(Path::new(&"test/outputs/asm/test_asm.bam")).ok().expect("Error reading test_asm.bam");
let (_, unmapped) = count_records(&mut bam);
assert_eq!(unmapped, 18);
// W... | Rust | 0 |
.state
}
}
pub struct Server {
config: Arc<RwLock<Config>>,
router: RouteConn,
be_sock: zmq::Socket,
}
impl Server {
pub fn new(config: Config) -> Result<Self> {
let router = try!(RouteConn::new(Self::net_ident(), (**ZMQ_CONTEXT).as_mut()));
let be = try!((**ZMQ_CONTEXT).as_mut().s... | Rust | 0 |
: vec![],
node_type: NodeType::Text(TextData { text: text.into() }),
}
}
pub fn elem<S: Into<String>>(tag_name: S, attrs: AttrMap, children: Vec<Node>) -> Self {
Self {
children: children
.into_iter()
.map(|n| Arc::new(RefCell::new(n)))
.collect(),
node_type: NodeT... | Rust | 0 |
from machine import Pin
from neopixel import NeoPixel
from time import sleep
pi = 8
sw1 = Pin(13, Pin.IN, Pin.PULL_DOWN)
sw3 = Pin(5, Pin.IN, Pin.PULL_DOWN)
sw2 = Pin(4, Pin.IN, Pin.PULL_DOWN)
pixels1 = NeoPixel(Pin(14), pi)
pixels2 = NeoPixel(Pin(12), pi)
rainbow = [
(126 , 1 , 0),(114 , 13 , 0),(102 , 25 , 0),(... | Python | 1 |
print("hello hyeonseo") | Python | 1 |
::new(&name);
let stdout = stdout();
let mut writer = csv::Writer::from_writer(stdout.lock());
checkpoint(&mut file_result, &start, &mut writer)?;
file_result.progress = Step::Read;
let data = match std::fs::read(&file_path) {
Ok(data) => data,
Err(e) => {
file_result.... | Rust | 0 |
/// Updates the `motion` value at `channel` to `new_motion`.
///
/// # Notes
///
/// Returns the previous motion value if the operation was successful, and `Err(_)` if
/// the operation was out of bounds.
pub fn try_set_motion<I>(&mut self, index: I, new_motion: f32) -> Result<f32, SetMoti... | Rust | 0 |
{
*self == RTCR::DIV8
}
#[doc = "Checks if the value of the field is `DIV16`"]
#[inline]
pub fn is_div16(&self) -> bool {
*self == RTCR::DIV16
}
#[doc = "Checks if the value of the field is `DIV32`"]
#[inline]
pub fn is_div32(&self) -> bool {
*self == RTCR::DIV32... | Rust | 0 |
ret_status = self.INVALID
message = _l('parameter edge must be list. ')
return ret_status, message
return self.VALID, 'success'
def get_subgraph_list(self, params_json):
ret_status = self.VALID
# check parameter graph_id
graph_id = p... | Python | 1 |
)^n || ... || z^(m-1) * \vec(2)^n
let powers_of_2: Vec<Scalar> = util::exp_iter(Scalar::from(2u64)).take(n).collect();
let concat_z_and_2: Vec<Scalar> = util::exp_iter(z)
.take(m)
.flat_map(|exp_z| powers_of_2.iter().map(move |exp_2| exp_2 * exp_z))
.collect();
... | Rust | 0 |
formatter.field("backup_plan", &self.backup_plan);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UntagResourceInput {
/// <p>An ARN that uniquely identifies a resource. The format of the ARN depends on the type of
/// the tagged resourc... | Rust | 0 |
-> Option<PathBuf> {
dirs_sys_next::user_dir("PUBLICSHARE")
}
pub fn template_dir() -> Option<PathBuf> {
dirs_sys_next::user_dir("TEMPLATES")
}
pub fn video_dir() -> Option<PathBuf> {
dirs_sys_next::user_dir("VIDEOS")
}
#[cfg(test)]
mod tests {
#[test]
fn test_file_user_dirs_exists() {
let... | Rust | 0 |
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
ans = 0
maxDefense = 0
# Sort properties by attack descendingly, then by defense ascendingly
for _, defense in sorted(properties, key=lambda x: (-x[0], x[1])):
if defense < maxDefense:
ans += 1
m... | Python | 1 |
name, warehouse, stock_value_difference, valuation_rate,
voucher_detail_no, item_code, posting_date, posting_time,
actual_qty, qty_after_transaction
from
`tabStock Ledger Entry`
where
voucher_type=%s ... | Python | 1 |
let attenuation =
directional.intensity * lambertian(directional.direction, *normal);
(directional.color, attenuation)
}
LightDefinition::Spot(spot) => {
let d = spot.position - *... | Rust | 0 |
bles_initializer()
config = tf.ConfigProto(intra_op_parallelism_threads=4, inter_op_parallelism_threads=4)
with tf.train.MonitoredTrainingSession(master=server.target,
is_chief=(FLAGS.task_index==0),
checkpoint_dir... | Python | 1 |
tx`.
/// * `csprng` - Cryptographically secure random number generator.
pub fn validate<R: RngCore + CryptoRng>(
tx: &Tx,
current_block_index: u64,
root_proofs: &[TxOutMembershipProof],
minimum_fee: u64,
csprng: &mut R,
) -> TransactionValidationResult<()> {
validate_number_of_inputs(&tx.prefix,... | Rust | 0 |
oncurrency_limit: Some(limit),
..self
}
}
/// Set a timeout on for all request handlers.
///
/// # Example
///
/// ```
/// # use tonic::transport::Server;
/// # use tower_service::Service;
/// # use std::time::Duration;
/// # let mut builder = Server::builder... | Rust | 0 |
l).
#[derive(Debug, Clone)]
pub struct VkBindVertexBufferIndirectCommand {
pub buffer_address: u64,
pub size: usize,
pub stride: usize,
}
#[doc(hidden)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct RawVkBindVertexBufferIndirectCommand {
pub buffer_address: u64,
pub size: u32,
pub stride:... | Rust | 0 |
from decimal import Decimal
from graphql import GraphQLError
import strawberry
def test_decimal():
@strawberry.type
class Query:
@strawberry.field
def example_decimal(self) -> Decimal:
return Decimal("3.14159")
schema = strawberry.Schema(Query)
result = schema.execute_s... | Python | 1 |
r.
///
/// This `struct` is created by the [`chain`] method on [`Stream`]. See its
/// documentation for more.
///
/// [`chain`]: trait.Stream.html#method.chain
/// [`Stream`]: trait.Stream.html
#[derive(Debug)]
pub struct Chain<S, U> {
#[pin]
first: Fuse<S>,
#[pi... | Rust | 0 |
parent:
mat = np.dot(poseMats[bone.parent.index], np.dot(bone.matRestRelative, mat))
else:
mat = np.dot(self.matRestGlobal, mat)
poseMats[boneIdx] = mat
for boneIdx in sorted(mats.keys()):
bone = skel.boneslist[boneIdx]
poseMat... | Python | 1 |
for line in data.lines() {
let mut orig_prog: Vec<usize> = line.unwrap().split(',').map(|x| x.parse::<usize>().unwrap()).collect();
for noun in 0..99 {
for verb in 0..99 {
let mut prog:Vec<usize> = orig_prog.to_vec();
// Adjust input
... | Rust | 0 |
);
pub fn ScrollBox_GetClientRect(AObj: usize, Result: *mut TRect);
pub fn ScrollBox_GetClientWidth(AObj: usize) -> i32;
pub fn ScrollBox_SetClientWidth(AObj: usize, AValue: i32);
pub fn ScrollBox_GetControlState(AObj: usize) -> TControlState;
pub fn ScrollBox_SetControlState(AObj: usize, AValue: TControlStat... | Rust | 0 |
on_on_fe_side(|v|x2_y3_z_int(v), x, fe4, back_side),
0.);
assert_approx(rmesh3x4x5.intg_global_fn_x_facerel_mon_on_fe_side(|v|x2_y3_z_int(v), x*z, fe4, front_side),
0.);
assert_approx(rmesh3x4x5.intg_global_fn_x_facerel_mon_on_fe_side(|v|x2_y3_z_int(v), x*y, fe4, front_side),
... | Rust | 0 |
2.MCU_ACTIVE"]
MCU_ACTIVE,
#[doc = "AUX_EVCTL:EVSTAT2.PWR_DWN"]
PWR_DWN,
#[doc = "AUX_EVCTL:EVSTAT2.SCLK_LF"]
SCLK_LF,
#[doc = "AUX_EVCTL:EVSTAT2.AON_BATMON_TEMP_UPD"]
AON_BATMON_TEMP_UPD,
#[doc = "AUX_EVCTL:EVSTAT2.AON_BATMON_BAT_UPD"]
AON_BATMON_BAT_UPD,
#[doc = "AUX_EVCTL:EVST... | Rust | 0 |
#!/usr/bin/env python3
"""
Parse the SQL db and print a dictionary for every kernel.
"""
import sys
import argparse
from tqdm import tqdm
from .db import DB
from .kernel import Kernel
from .nvvp import NVVP
def parseArgs():
parser = argparse.ArgumentParser(prog=sys.argv[0], description="Parse SQL (nvvp) db.")
par... | Python | 1 |
DFExtractor() # Initialize PDF extractor
content = pdf_extractor.extract_header_from_pdf(request.keywords, request.prompt, file_path)
# Return extracted header information
return JSONResponse(content={"header_info": content}, status_code=200)
except Exception as e:
# Log and return... | Python | 1 |
shot()
.subnets()
.find(|s| s.subnet_type() == SubnetType::System)
.unwrap();
let subnet_app = env
.topology_snapshot()
.subnets()
.find(|s| s.subnet_type() == SubnetType::Application)
.unwrap();
let canister_nns = subnet_nns
.nodes()
.next... | Rust | 0 |
nums = [1,1,1,2,2,3]
nums = [-1,-1]
nums = [4,1,-1,2,-1,2,3]
k = 2
def characterCount(nums):
counter = {}
for number in nums:
counter[number] = counter.get(number,0) + 1
return counter
def topKFrequent(nums,k):
counter = characterCount(nums)
counter = list(sorted(counter.items(),key=lambda... | Python | 1 |
ype.__name__, "value": obj.tolist()}
elif _type is set:
return {"__type": _type.__name__, "value": list(obj)}
elif _type is torch.Tensor:
return tensor_to_dict(obj=obj)
elif _type.__module__ == "torch":
# Torch does not support saving to string, so save to buffer first
return... | Python | 1 |
::c_int
}
return retval;
}
unsafe extern "C" fn getSubsamp(mut dinfo: crate::jpeglib_h::j_decompress_ptr) -> libc::c_int {
let mut retval: libc::c_int = -(1 as libc::c_int);
let mut i: libc::c_int = 0;
let mut k: libc::c_int = 0;
/* The sampling factors actually have no meaning with grayscale J... | Rust | 0 |
return True
interval1 = expression1
interval2 = expression2
if interval1 == interval2:
return True
else:
inter_list1 = interval1.split("\\cup")
inter_list2 = interval2.split("\\cup")
if len(inter_list1) != len(inter_list2):
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on 2018-08-28 17:38:43
---------
@summary: 创建项目
---------
@author: Boris
@email: boris_liu@foxmail.com
"""
import getpass
import os
import shutil
import feapder.utils.tools as tools
def deal_file_info(file):
file = file.replace("{DATE}", tools.get_current_date())
file = ... | Python | 1 |
any task switching or changing of the current page table register (e.g., cr3).
pub fn with<F>(&mut self,
other_table: &mut PageTable,
mut temporary_page: temporary_page::TemporaryPage,
f: F)
-> Result<(), &'static str>
where F: FnOnce(&mut Ma... | Rust | 0 |
logger.error(f"保存執行記錄失敗: {e}")
def daily_update_task(self):
"""每日數據更新任務"""
task_name = "daily_update"
start_time = datetime.now()
logger.info("🚀 開始執行每日數據更新任務")
try:
# 獲取配置
config = self.config['daily_update']
... | Python | 1 |
# Copyright(C) 2010-2013 Christophe Benz, Romain Bignon, Julien Hebert
#
# This file is part of woob.
#
# woob 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 version 3 of the License, or
# (at y... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
n = 100
VX = np.linspace(-1.0, 2.0, n)
VY = np.linspace(-1.5, 1.5, n)
X,Y = np.meshgrid(VX, VY)
def f(x,y):
z = 2*x**3 - y**4 -3*x**2
return z
Z = f(X,Y)
#
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.set_xlabe... | Python | 1 |
ches.opt_present("immed"),
hold: matches.opt_present("hold"),
eot: matches.opt_present("eot"),
reten: matches.opt_present("reten"),
load: matches.opt_present("load"),
};
println!("Issuing: {:#?}", cmd);
let result = device.issue_cmd(&cmd);
print_status_or_return_error!(result, cmd);
}
fn loc... | Rust | 0 |
import pyjd # dummy in pyjs
from pyjamas import Window, DOM
from pyjamas.ui.FlexTable import FlexTable
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HTML import HTML
from RegexTextBox import RegexTextBox
def display_ok(obj):
obj.setStyleName("gwt-te... | Python | 1 |
assert (
age
- (
timezone.now() - test_run_1_failed_but_outdated.timestamp
).total_seconds()
<= 2
)
assert response_json == {
"failed": 1,
"status": "outdated",
... | Python | 1 |
/ `NP 0F 5E /r`
///
/// `SSE`
///
/// `16/32/64-bit`
Divps_xmm_xmmm128 = 1447,
/// `VDIVPS xmm1, xmm2, xmm3/m128`
///
/// `VEX.128.0F.WIG 5E /r`
///
/// `AVX`
///
/// `16/32/64-bit`
VEX_Vdivps_xmm_xmm_xmmm128 = 1448,
/// `VDIVPS ymm1, ymm2, ymm3/m256`
///
/// `VEX.256.0F.WIG 5E /r`
///
/// `AVX`
///
... | Rust | 0 |
;
use proc_macro::TokenStream as TokenStream1;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned, ToTokens};
use std::{mem, ops::Deref};
use syn::{
parenthesized,
parse::{Parse, ParseStream},
parse2, parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
visit_mut::{self... | Rust | 0 |
import re
INCOMPLETE_TASK_RE = re.compile(r'<li>\[ \] (.*?)(<ul.*?>|</li>)', re.DOTALL)
INCOMPLETE_TASK_SUB = (r'<li class="task-list-item">'
r'<input type="checkbox" '
r'class="task-list-item-checkbox" disabled=""> \1\2')
COMPLETE_TASK_RE = re.compile(r'<li>\[x\] (.*?)(<... | Python | 1 |
tui.add_privmsg(
"osa1",
&format!("a long line {}", i),
ts,
&target,
false,
false,
);
}
tui.draw();
#[rustfmt::skip]
let screen1 =
"|osa1: a long |
|line 11 |
|osa1: a long |
... | Rust | 0 |
lo as u64 | (hi as u64) << 32
}
/// Read two hardware performance counters at once (see `rdpmc`).
///
/// Should be more efficient/accurate than two `rdpmc` calls, as it
/// only requires one "serializing instruction", rather than two.
#[inline(always)]
fn rdpmc_pair(a_reg_idx: u32, b_reg_i... | Rust | 0 |
from laia.nn.adaptive_pool_2d import AdaptiveAvgPool2d, AdaptiveMaxPool2d
from laia.nn.image_pooling_sequencer import ImagePoolingSequencer
from laia.nn.image_to_sequence import ImageToSequence
from laia.nn.pyramid_maxpool_2d import PyramidMaxPool2d
from laia.nn.temporal_pyramid_maxpool_2d import TemporalPyramidMaxPool... | Python | 1 |
&mut sync_writer,
// out_shares_bits.as_slice(),
// rng,
// )
// .unwrap();
// let inp_bits = mpc
// .private_inputs(
// &mut sync_reader,
// &mut sync_writer,
// inp_rands_bits.as_slice(),
// rng,
// )
// .unwrap();... | Rust | 0 |
import uuid
from typing import List
from sqlalchemy import (
create_engine, Column, String, Float,
Integer, ForeignKey, UniqueConstraint,
Table, UUID, Text,
)
from sqlalchemy.orm import relationship, registry
from assimilator.core.database import BaseModel
from assimilator.mongo.database import MongoModel... | Python | 1 |
id = MENU_ITEMS_ID as UINT;
// MF_SEPARATOR ignore the lpNewItem and uIDNewItem parameters, so they must be set using SetMenuItemInfo
AppendMenuW(menu, MF_SEPARATOR, 0, ptr::null());
// Set the unique id of the separator
let pos = GetMenuItemCount(menu) - 1;
let mut info = MENUITEMINFOW {
... | Rust | 0 |
if !revoked.contains(&id) {
self.acl.add_rule(id, actor, perm, path)?;
}
}
self.acl.revoke_rules(revoked)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Backend, Keypair};
use std::pin::Pin;
use Permission::*;
#[async_std::te... | Rust | 0 |
combo_box.addItem(
WhisperModelSize.LUMII.value.title()
)
self.whisper_model_size_combo_box.setCurrentText(
self.transcription_options.model.whisper_model_size.value.title()
)
self.form_layout.setRowVisible(
self.whisper_model_size_combo_box,... | Python | 1 |
se offchain_utils::offchain_core::ethers;
use ethers::contract::{abigen, ContractFactory};
use ethers::core::utils::{Geth, GethInstance};
use ethers::providers::{Http, Middleware, Provider};
use hex;
use std::convert::TryFrom;
use std::sync::Arc;
abigen!(TestContract, "./tests/common/contract/TestContract.abi",);
p... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the GNU General Public License version 3.
from peft import PeftModel
from transformers import MixtralForCausalLM, MixtralConfig
# Function to load the main model for text generation
def load_mode... | Python | 1 |
} else if fld < 85.0 { // blue->cyan
[0, b, 255]
} else if fld < 127.5 { // cyan->green
[0, 255, 255 - c]
} else if fld < 170.0 { // green->yellow
[d, 255, 0]
} else if fld < 212.5 { // yellow->red
[255, 255 - e, 0]
} else { // red->white
[255, f, f]
}
}
#[allow(dead_code)]
pub fn viridi... | Rust | 0 |
s_id = header('ticket', ticket)
if this_id == ticket:
if callback:
callback(body)
responses.append(body)
else:
unclaimed[this_id].append(body)
consumer.register_callback(on_message)
try:
with consume... | Python | 1 |
Hash) {
self.credentials.insert(
username.clone(),
password_hash.clone(),
);
}
pub fn add_permission(self: &mut Self, username: &Username, prefix: &Path) {
self.permissions
.insert(username.clone(), prefix.clone());
}
}
#[cfg(test)]
impl Storage ... | Rust | 0 |
import logging
from .DescriptorGenerator import *
from .rdDescriptors import *
from .rdNormalizedDescriptors import *
| Python | 1 |
]:
tran.unknown_proper_noun = cache_dict[cache_key]["unknown_proper_noun"]
if tran.proofread_zh != "":
tran.post_zh = tran.proofread_zh
else:
tran.post_zh = tran.pre_zh
# 校对模式下,未校对的
if proofread and tran.proofread_zh == "":
translist_unhi... | Python | 1 |
for the prefix would be nice for socketcan
// otherwise i can't use this for can/vcan
mc.add_adapter(net_config.id, Box::new(SocketCanNetwork::new(net_config.id, "vcan")));
}
#[cfg(windows)]
{
panic!("Can't use SocketCAN on Windows");
}
} e... | Rust | 0 |
cv_PtrOfERFilter_get_inner_ptr
}
impl PtrOfERFilter {
pub fn as_raw_PtrOfERFilter(&self) -> *const c_void { self.as_raw() }
pub fn as_raw_mut_PtrOfERFilter(&mut self) -> *mut c_void { self.as_raw_mut() }
}
impl core::AlgorithmTrait for PtrOfERFilter {
fn as_raw_Algorithm(&self) -> *const c_void { self.inn... | Rust | 0 |
cur_token, &mut addr_spec);
if r != MAILIMF_NO_ERROR as libc::c_int {
return r;
}
r = mailimf_greater_parse(message, length, &mut cur_token);
if r != MAILIMF_NO_ERROR as libc::c_int {
free(addr_spec as *mut libc::c_void);
return r;
}
*result = addr_spec;
*indx = cur_... | Rust | 0 |
p.get_task_on_node_api)
app.post('/query/task/artifact/get')(at_exp.get_task_artifact_mapping)
app.post('/query/task/artifact/list')(at_exp.get_all_task_artifact_mapping)
app.post('/query/user/artifact/get')(au_user.get_user_artifact)
app.post('/query/service_task/list')(aq_optimized_service_task.data... | Python | 1 |
Hierarchical", {
let mut row_packer = repr::RowPacker::new();
move |key, source, target| {
// Should negative accumulations reach us, we should loudly complain.
if source.iter().any(|(_val, cnt)| cnt <= &0) {
for (val, cnt) in source.iter() {
... | Rust | 0 |
ServiceKind::Algolia))?;
let jigs: Vec<_> =
db::jig::get_by_ids(db.as_ref(), &ids, PrivacyLevel::Public, DraftOrLive::Live).await?;
Ok(Json(JigSearchResponse {
jigs,
pages,
total_jig_count: total_hits,
}))
}
async fn count(db: Data<PgPool>) -> Result<Json<<jig::Count as Ap... | Rust | 0 |
# roblem Statement
# There are times where you are working with lots of different data within a function that you want to return. While generally, we want to keep functions to have a precise purpose, sometimes that purpose just deals with multiple bits of data.
# To practice this, imagine we are working on a program w... | Python | 1 |
{
pub(crate) influx_type: InfluxColumnType,
pub(crate) valid: BitSet,
pub(crate) data: ColumnData,
}
/// The data for a column
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum ColumnData {
F64(Vec<f64>, StatValues<f64>),
I64(Vec<i64>, StatValues<i64>),
U64(Vec<u64>, StatValues<u64>),
... | Rust | 0 |
# ------------------------------------------------------------------
# Copyright (c) 2020 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE, distributed with
# this software.
#
# SPDX-Licens... | Python | 1 |
(arr_scaled, verbose=0)
# Inverse transform prediksi
try:
pred_original = loaded_scaler_y.inverse_transform(pred_scaled)
except Exception as e:
logging.error(f"Gagal melakukan inverse scaling output Y pada API: {e}", exc_info=True)
return jsonify({'error': ... | Python | 1 |
pub fn get_forced_recalibration_value(&mut self) -> Result<u16, E> {
let mut buf = [0u8; 2];
let mut vec: Vec<u8, 5> = Vec::new();
vec.extend_from_slice(&(Command::ForcedRecalibrationValue as u16).to_be_bytes()).expect(EXPECT_MSG);
self.comm.read(self.address, &mut buf)?;
Ok(... | Rust | 0 |
MySubscriber {
/// # fn new() -> Self { Self { }}
/// # }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// # impl tracing_core::Subscriber for MySubscriber {
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
/// # fn record(&self, _: &Id, _: &R... | Rust | 0 |
.7),
(0.4959, 2.17, 1.98),
(0.6199, 2.35, 2.47),
(0.8266, 2.73, 2.92),
(1.2399, 3.19, 3.66)
);
pub const LITHIUM_SAMPLES: &[SampledRefractiveIndex] = &refractive_index_samples!(
(0.32627, 0.34301, 1.38479),
(0.33062, 0.3382, 1.41929),
(0.33509, 0.33429, 1.43588),
(0.33968, 0.33051, 1.452... | Rust | 0 |
: 0 !important;
height: 1px;
flex-grow: 1;
width: 100%;
"#
.into()
}
}
use std::{
collections::HashMap,
cell::RefCell,
rc::Rc,
};
use super::{
rlox_class::RloxClass,
rlox_type::RloxType,
rlox_errors::RloxError,
token::Token,
};
#[derive(Clone, Debug, PartialEq)... | Rust | 0 |
le)
x = axis_angle[0] / mag
y = axis_angle[1] / mag
z = axis_angle[2] / mag
sn = sin(mag / 2.0)
return quatnormalize([cos(mag / 2.0), sn * x, sn * y, sn * z])
@cg.generate_code(axis_angle = 3)
def axisangle2euler(axis_angle):
return quattoeuler(axisangle2quat(axis_angle))
def apply_ang_velo... | Python | 1 |
ntinue
# Remote tunnel name is 100.1.1.1
match = p3.match(line)
if match and current_tunnel_id is not None:
tunnel_dict['remote_tunnel_name'] = match.group('remote_tunnel_name')
continue
# Local tunnel name is PG2
... | Python | 1 |
z = z.mul(&m);
x = h.clone();
let mut x_neg = h.clone();
x_neg.neg();
i.zero();
while BigNum::comp(&i, &m) <= 0 {
// positive solution
match table.get(&x.tostring()) {
Some(value) => {
let mut temp = BigNum::modmul(&i, &m, &CURVE_ORDER);
... | Rust | 0 |
// BACKGROUND ENTITY
parent_store
.insert(display_entities.background, display_parent.clone())
.unwrap();
transform_store
.insert(display_entities.background, bg_transform)
.unwrap();
sprite_render_store
... | Rust | 0 |
of::<mapDef>() as u64) as u32) as *mut mapDef;
for c in 0..256 {
(*t.offset(c as isize)).flag = 0i32 | 0i32;
let ref mut fresh4 = (*t.offset(c as isize)).code;
*fresh4 = 0 as *mut u8;
let ref mut fresh5 = (*t.offset(c as isize)).next;
*fresh5 = 0 as *mut mapDef;
}
t
}... | Rust | 0 |
import csv, re
from package import Package
def import_packages(packages_list):
# read csv and add packages to hash table: O(n)
with open('./package_file.csv', mode='r') as file:
packages_csv = csv.reader(file)
for row in packages_csv:
package_id = int(re.search(r'\d+', row[0]).group... | Python | 1 |
1_musig_nonce_agg(
*secp.ctx(),
aggnonce.as_mut_ptr(),
nonce_ptrs.as_ptr(),
nonce_ptrs.len(),
) == 0
{
Err(Error::InvalidMusigPubNonce)
} else {
Ok(aggnonce)
}
}
}
... | Rust | 0 |
rt_allclose(res[0], 0.024083, rtol=1e-4, atol=1e-4)
assert_allclose(res[1], 0.943151, rtol=1e-4, atol=1e-4)
assert res[2] == 3
def test_sp500_results(self):
mdl_file = os.path.join(self.run_dir, "SP500.csv")
mdl = np.asarray(pd.read_csv(mdl_file))
res = leybourne(mdl, arlags... | Python | 1 |
WordBoundary,
WordBoundary,
WordBoundary,
NotWordBoundary,
WordBoundary,
NotWordBoundary,
NotWordBoundary,
NotWordBoundary,
NotWordBoundary,
NotWordBoundary,
No... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import choose_delivery_package
from . import choose_delivery_carrier
| Python | 1 |
_name)
yield _lexer_cache[name]
for lexer in find_plugin_lexers():
yield lexer
def guess_lexer_for_filename(_fn, _text, **options):
"""
Lookup all lexers that handle those filenames primary (``filenames``)
or secondary (``alias_filenames``). Then run a text analysis for those
lexer... | Python | 1 |
erved1: Option<unsafe extern "C" fn()>,
pub _webkit_reserved2: Option<unsafe extern "C" fn()>,
pub _webkit_reserved3: Option<unsafe extern "C" fn()>,
}
impl ::std::fmt::Debug for WebKitEditorStateClass {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "WebKitEditorSta... | Rust | 0 |
name_class, true));
} else {
accounts.push(AccountMeta::new_readonly(Pubkey::default(), false));
}
if let Some(name_parent) = name_parent_opt {
accounts.push(AccountMeta::new_readonly(name_parent, false));
} else {
accounts.push(AccountMeta::new_readonly(Pubkey::default(), false)... | Rust | 0 |
s long.")
client_id = input("Enter client id: ").strip()
client_secret = input("Enter client secret: ").strip()
while len(client_secret) != 42:
print("Client secrets are exactly 42 characters long.")
client_secret = input("Enter client secret: ").strip()
conf... | Python | 1 |
from typing import Optional
import jax.numpy as jnp
from numpy.typing import ArrayLike
from tensorflow_probability.substrates import jax as tfp
from bmi.samplers._splitmultinormal import SplitMultinormal
from bmi.samplers._tfp._core import JointDistribution
jtf = tfp.tf2jax
tfd = tfp.distributions
def construct_mu... | Python | 1 |
game_version =
read_game_version(&opt_assets_dir).context("Failed to read the game version")?;
info!("Game version is {}", game_version);
info!("Finding all JSON files");
let all_json_files = json_file_finder::find_all_in_assets_dir(&opt_assets_dir)
.context("Failed to find all JSON files in t... | Rust | 0 |
<= rva;
self.last_rva = rva;
}
pub fn finalize(&mut self, sym_rva: u32, sym_len: u32, address_map: &AddressMap) {
self.compute_len(sym_rva, sym_len);
self.compute_rva(address_map);
}
fn compute_len(&mut self, sym_rva: u32, sym_len: u32) {
// The length (in the binary) ... | Rust | 0 |
theta)
# Run GD with square loss.
square_nsteps = 5000
square_learning_rate = 0.01
print('Running GD with square loss for {0} steps, learning_rate={1}'.format(
square_nsteps, square_learning_rate))
theta_square = run_gradient_descent_search(
X_train_augmented,
y_train,
... | Python | 1 |
dyn Cache>> = HashMap::new();
map.insert(255, Arc::new(cnc));
let s = Self {
addr,
entries: map,
};
(rx, s)
}
/// Adds a new managed cache
///
/// # Params
///
/// * `name` - Name of the cache, this must implement Into<u8>
/// *... | Rust | 0 |
# Atividade 06:
# Soma de Números Positivos:
# Escreva um programa que solicite números ao usuário até
# que ele digite um número negativo, somando apenas os
# números positivos inseridos.
soma = 0
n = 1
while n >= 0:
n = int(input('Digite um numero: '))
if n >= 0:
print('Tente novamente!')
NameError = n + ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.