text string | label_name string | labels int64 |
|---|---|---|
import time
import numpy as np
import cv2
import rospy
from sensor_msgs.msg import Image as Image_msg
from sensor_msgs.msg import PointCloud2
from sensor_msgs.point_cloud2 import read_points_list,PointField
# path: /home/zhengxinyue/livox_ws/devel/lib/python2.7/dist-packages/livox_ros_driver/msg
from _CustomMsg impo... | Python | 1 |
print("Hello, Arewa Data Science!")
| Python | 1 |
import ast
asyncio_run_ast = ast.parse("asyncio.run(coro(arg))", "exec").body[0].value
print(ast.dump(asyncio_run_ast, indent=4))
await_coro_ast = ast.parse("await coro(arg)", "exec").body[0].value
print(ast.dump(await_coro_ast, indent=4))
def transform_asyncio_run(node):
return ast.Await(
value=node.arg... | Python | 1 |
for data in d])
tempID = np.asarray([data.item for data in d])
tempstage = torch.tensor([data.stage for data in d])
tempmeta = torch.tensor([data.mets_class for data in d])
out = model(d)
out = F.normalize(out, p=2, dim=0)
... | Python | 1 |
args,
unpacked_arg,
);
let ctor_annot = (env.ast_pos(ctor_pos), ctor_fty);
(
ty,
tast::Expr_::mk_new(class_id, targs, args, unpacked_arg, ctor_annot),
)
}
x => unimplemented!("{:#?}", x),
};
// TODO(h... | Rust | 0 |
KHR: u32 = 2;
pub const DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR: u32 = 4;
pub const DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR: u32 = 8;
pub type SurfaceTransformFlagsKHR = Flags;
pub type SurfaceTransformFlagBitsKHR = u32;
pub const SURFACE_TRANSFORM_IDENTITY_BIT_KHR: u32 = 1;
pub const SURFACE_TRANSFORM_ROTAT... | Rust | 0 |
the current structure 128 bytes long
* which is nicely 64 bit aligned but also has room
* for us to add more and keep ABI compatibility.
* For example, already we have the sctp_extrcvinfo
* when enabled which is 48 bytes.
*/
/*
* The assoc up needs a verfid
* all sendrcvinfo's need a verfid for SENDING only.
*... | Rust | 0 |
55,
50, 50, 50, 48, 50, 49, 50, 57, 50, 51, 55, 56, 54, 55, 57, 13, 10, 67, 111, 110, 116,
101, 110, 116, 45, 68, 105, 115, 112, 111, 115, 105, 116, 105, 111, 110, 58, 32, 102,
111, 114, 109, 45, 100, 97, 116, 97, 59, 32, 110, 97, 109, 101, 61, 34, 102, 105, 108,
101, 34... | Rust | 0 |
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
df1 = pd.read_csv('file.csv')
df1.drop(columns=['date'], inplace=True)
df1.drop(columns=['pc'], inplace=True)
df1.drop(columns=['id'], inplace=True)
df1.... | Python | 1 |
**********************
main_sizes = (
(2, 2),
(3, 3),
(4, 4),
(5, 5),
)
plugin_widget_factory(BaseVideoWidget,
'android',
'main',
'video',
main_sizes)
# ************************************************************... | Python | 1 |
&DataType::Uint8 => "uint8",
&DataType::Int8 => "int8",
&DataType::Uint16 => "uint16",
&DataType::Int16 => "int16",
&DataType::Uint32 => "uint32",
&DataType::Int32 => "int32",
&DataType::Uint64 => "uint64",
&DataType::Int64 => "int64",
&DataType::HalfFloat => "half... | Rust | 0 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.mail.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: Ge... | Python | 1 |
lse;
} else {
panic!("Released a peripheral which was not taken");
}
});
}
/// Unsafely steal EXTI
///
/// This function is similar to take() but forcibly takes the
/// Instance, marking it as taken irregardless of its previous
/// state.
#[cf... | Rust | 0 |
apters::fetch(request)?;
// --
if github_response.is_success() {
Ok(crate::adapters::to_json(github_response)?)
} else {
match github_response.status_code() {
code => Err(TeamsUpdateDiscussionLegacyError::Generic { code }),
}
}
}
... | Rust | 0 |
:\n{}",
err
);
}
NFLZError::RenameFailed(old, new, ioerror) => {
println!("Failure during renaming. File state might be inconsistent now.");
println!(
"Could not rename '{}' to '{} because of: {}'",
... | Rust | 0 |
ises(ValueError, match="reserved name"):
plt.color_sequences.register('tab10', ['r', 'g', 'b'])
with pytest.raises(ValueError, match="not a valid color specification"):
plt.color_sequences.register('invalid', ['not a color'])
rgb_colors = ['r', 'g', 'b']
plt.color_sequences.register('rgb', ... | Python | 1 |
from Task1 import Dual_SVM
import numpy as np
from cvxopt import solvers
solvers.options['show_progress'] = False
# 钓鱼岛坐标
FishingIsoland = [123.28,25.45]
FishingIsoland = np.array(FishingIsoland)[None, :]
# 仅仅使用沿海城市
China_coastal = [119.28,26.08,#福州
121.31,25.03,#台北
121.47,31.23,#上... | Python | 1 |
lfinder", "hepar2", "win95pts",
"andes"
]
bnlearn_path = 'tests/TestData/bnlearn_discrete_10000/data'
for bname in benchmark_names:
data = np.loadtxt(os.path.join(bnlearn_path, f'{bname}.txt'), skiprows=1)
G, edges = fci(data, chisq, 0.05, verbose=False)
... | Python | 1 |
nt know that they cannot send images if they
# attempted to send one
msg = None
act = {
'id': 'SYSTEM',
'text': 'Only text messages are supported at this time. '
'Please try with a text-only message.',
... | Python | 1 |
(
span::Column::new_zero_indexed(start),
span::Column::new_zero_indexed(end),
)
}
// TODO include workspace Cargo.tomls in watchers / relevant
/// Client file-watching request / filtering logic
/// We want to watch workspace 'Cargo.toml', root 'Cargo.lock' & the root 'target' dir
pub struct FileWat... | Rust | 0 |
was a problem: {:?}", e)
}
}
}
Err(error) => {
panic!("There was a problem opening the file: {:?}", error)
},
};
let f = File::open("hello2.txt").unwrap();
// エラーメッセージを指定可能
// let f = File::open("hello2.txt").expect("Failed to open hello2... | Rust | 0 |
want to send this file with a `Content-Disposition: attachment`
/// header. This will return `NotFound` if filepath is not one file.
pub fn send_file_range(filepath: &str, mimetype: Mime, as_attachment: bool, range: Option<&Range>)
-> PencilResult
{
let filepath = Path::new(filepath);
if !filepath.is_file... | Rust | 0 |
import config
import requests
import json
from datetime import datetime
#API_KEY = config.OUTLINE_API_KEY
def get_all_api_keys():
return json.loads(requests.get(f"{API_KEY}/access-keys/", verify=False).text)
def get_count_active_keys(API_KEY):
return json.loads(requests.get(f"{API_KEY}/access-keys/", veri... | Python | 1 |
alidStartingPointYouSillyPerson,
}
pub fn collatz(n: u64) -> Result<u64, CollatzError> {
if n == 0 {
Err(CollatzError::ZeroIsNotAValidStartingPointYouSillyPerson)
} else {
let mut m: u64 = n;
let mut c: u64 = 0;
while m > 1 {
c += 1;
m = if m & 1 == 0 { m... | Rust | 0 |
.trim_start().to_owned()))
})
.filter(|v| v.is_some())
.map(|v| v.unwrap())
.collect();
let body = match body_lines {
Some(b) => b.join("\n"),
None => "".to_owned(),
};
Ok(HttpRequest {
method,
path... | Rust | 0 |
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Add something to the end of a list or table",
example: "echo [1 2 3] | append 4",
result: Some(vec![
UntaggedValue::int(1).into(),
UntaggedValue::int(2).into(),
... | Rust | 0 |
for (i, layer) in structure.iter().enumerate() {
match (i, layer) {
// First, we are interested in signatures over the
// data, i.e. level 0 signatures.
(0, MessageLayer::SignatureGroup { ref results }) => {
// Finally, given a Ver... | Rust | 0 |
if m:
if intport(m.group(2)) in portreplacement.keys():
newline = line.replace(m.group(2),portreplacement[intport(m.group(2))],1)
elif OldLines:
newline = "# "+line
else:
newline = ""
m = re.search(r'enable sharing ([0-9... | Python | 1 |
"""Test edge cases in host handling."""
# Test with subdomain wildcard
mock_settings.ALLOWED_HOSTS = [".api.example.com"]
mock_app = Mock()
mock_response = Mock()
mock_response.status_code = 200
mock_app.get_response.return_value = mock_response
wsgi_heal... | Python | 1 |
# Generated by Django 4.2 on 2024-08-14 10:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Notification', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='customernotification',
name='data',
... | Python | 1 |
as u32, 115);
assert_eq!(svg.inner_bbox().height.round() as u32, 25);
}
}
<filename>src/utils/time.rs<gh_stars>1-10
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) fn make_timestamp() -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("internal error: current ... | Rust | 0 |
&m.original_media_type },
|m: &mut RecognitionMetadata| { &mut m.original_media_type },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<RecognitionMetadata_RecordingDeviceType>>(
"recording_device... | Rust | 0 |
1260) = &input.http_protocol_ipv6 {
scope_1259.string(var_1260.as_str());
}
#[allow(unused_mut)]
let mut scope_1261 = writer.prefix("InstanceMetadataTags");
if let Some(var_1262) = &input.instance_metadata_tags {
scope_1261.string(var_1262.as_str());
}
Ok(())
}
#[allow(unused_mu... | Rust | 0 |
Inner>);
//#[derive(Debug, Clone)]
//struct Inner {
// format: Format,
// exclude: HashSet<String>,
// exclude_regex: RegexSet,
//}
//impl Logger {
// /// Create `Logger` middleware with the specified `format`.
// pub fn new(format: &str) -> Logger {
// Logger(Rc::new(Inner {
// forma... | Rust | 0 |
let netaddr: Netv6Addr = Netv6Addr {
mask: "ffff:ffff:ffff:7fc00:e968:6179::de52:7100".parse().unwrap(),
addr: "::".parse().unwrap(),
};
assert!(!netaddr.is_cidr());
}
#[test]
fn cidr_returns_true() {
let netaddr: Netv6Addr = Netv6Addr {
mask: "ffff:ffff:ffff:fffc::0".parse().unwrap(),
... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
import torch
from mmocr.models.common.layers.transformer_layers import (TFDecoderLayer,
TFEncoderLayer)
class TestTFEncoderLayer(TestCase):
def test_forward(self):
en... | Python | 1 |
end_array.push(&self.coordinates.end.longitude().into());
end_array.push(&self.coordinates.end.latitude().into());
let coordinate_array = Array::new();
coordinate_array.push(&start_array);
coordinate_array.push(&end_array);
coordinate_array
}
/// Usable length... | Rust | 0 |
# model settings
# Voxel size for voxel encoder
# Usually voxel size is changed consistently with the point cloud range
# If point cloud range is modified, do remember to change all related
# keys in the config.
voxel_size = [0.25, 0.25, 8]
model = dict(
type='MVXFasterRCNN',
pts_voxel_layer=dict(
max_n... | Python | 1 |
# The match-case statement is used to match a variable against a list of patterns. It is more
# readable than a long set of if/elif statements
# When checking many possible values, it is much easier to maintain.
# The wildcard "_" should always be used as the default for when there are unmatched cases.
# It follows th... | Python | 1 |
s_empty() {
Err(HealthchecksConfigError::EmptyApiUrl)
} else {
let user_agent = user_agent.unwrap_or_else(|| default_user_agent().to_owned());
Ok(ManageClient {
api_key,
user_agent,
api_url,
})
}
}
/// When creating a new check, it's possible... | Rust | 0 |
;
#[cfg(feature = "sqlx-mssql")]
fetch_by_where!(sqlx::Mssql,fetch_one_by_where,"SELECT TOP 1 {} FROM {}","SELECT TOP 1 {} FROM {} WHERE {}", query_as, fetch_one, M);
#[cfg(feature = "sqlx-mysql")]
fetch_by_where_call!(sqlx::MySql,fetch_all_by_where_call,"SELECT {} FROM {} WHERE {}", query_as, fetch_all, Vec<M>);
#... | Rust | 0 |
expected_output = {
'isakmp_stats': {
'IPv4':{
1:{
'c_id': 29609,
'local_ip': '100.0.10.2',
'remote_ip': '100.13.220.2',
'ivrf': 'RED',
'status': 'ACTIVE',
'encr_al... | 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 |
"""Helpers for reading compute profile settings."""
from __future__ import annotations
import os
_COMPUTE_ENV_VARS = ("AMI_COMPUTE_PROFILE", "AMI_COMPUTE_TARGET", "COMPUTE_PROFILE")
_ALIASES: dict[str, str] = {
"cpu": "cpu",
"nvidia": "nvidia",
"gpu": "nvidia",
"cuda": "nvidia",
"intel": "intel",... | Python | 1 |
dict1 = {'month': [1, 2, 3], 'name': ['Jan', 'Feb', 'March']}
res1 = dict(zip(dict1['month'], dict1['name']))
res2 = {dict1['month'][i]: dict1['name'][i] for i in range(len(dict1['month']))}
res3 = {}
for i in range(len(dict1['month'])):
res3[dict1['month'][i]] = dict1['name'][i]
print('Flattened dictionary:\n'... | Python | 1 |
(|_| TreasuryError::InvalidTreasuryFundAccount)?;
// authority owner checks
if !authority_info.is_signer {
return Err(TreasuryError::MissingAuthoritySignature.into());
}
if treasury.authority != *authority_info.key {
return Err(TreasuryError::InvalidTreasuryOwne... | Rust | 0 |
task_id)}\\s+"
f"status\\s*=\\s*OK\\s+"
f"(?:answer|result)\\s*=\\s*([\\d\\.\\-]+)"
)
success, match = wait_for_token(pane_id, eot_pattern, timeout=30)
if not success:
raise TimeoutError(f"EOT timeout for task {task_id}")
result = match[0] if isinstance(match, tuple) else ma... | Python | 1 |
Auth(models.Model):
class Meta:
constraints = (
models.UniqueConstraint(
fields=("user", "name"),
name="lava_scheduler_app_remote_artifact_user_and_name_uniq",
),
)
ordering = ["name"]
user = models.ForeignKey(
User,
... | Python | 1 |
dp, logger)
model.cuda()
acc1, loss = validate(config, data_loader, model)
logger.info(f"Accuracy of the network on the test images: {acc1:.1f}%")
else:
raise ValueError("No path to pretrained model given, please consider passing such a path as an argument (--resume or --pretrained)... | Python | 1 |
,
alias,
settings.clone(),
block0_file.as_path(),
working_directory,
&version,
)
.unwrap();
Ok(vit_station.controller())
}
pub fn spawn_wallet_proxy_custom(
&self,
controller: &mut Controller,
params: &m... | Rust | 0 |
;
assert!(!it.had_comments());
assert_eq!(unwrap_token_value(it.next()), TokenValue::Hash);
assert!(it.had_comments());
assert_eq!(
unwrap_token_value(it.next()),
TokenValue::Ident("version".to_string())
);
assert!(it.had_comments());
expect_lexer_end(&mut it);
}
// TODO tes... | Rust | 0 |
v, must do it ourselves
self.conv = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=4,
stride=2,
padding=1)
def forward(self, x, scale_fa... | Python | 1 |
from typing import Optional
from pydantic import BaseModel, EmailStr, Field
from datetime import datetime
from sympy import O
class UserBase(BaseModel):
email: EmailStr = Field(None, min_length=9, max_length=50)
full_name: str = Field(None, min_length=3, max_length=50)
image: Optional[str] = None
rol... | Python | 1 |
x1 = fdot6::from_f32(pts[1].x);
let y1 = fdot6::from_f32(pts[1].y);
if let Some(clip) = clip {
let left = x0.min(x1);
let top = y0.min(y1);
let right = x0.max(x1);
let bottom = y0.max(y1);
let ir = IntRect::from_ltrb(
fdot6::... | Rust | 0 |
rs,
&Neighbor {
id: from_id,
last_updated: time
}
);
}
}
pub struct RandomRouting {
nodes: Vec<Node>,
time: u32,
}
impl RandomRouting {
pub fn new() -> Self {
Self {
nodes: vec![Node::new(); 42],
time: 0
}
}
}
impl RoutingAlgorithm for RandomRouting
{
fn get(&self, key: &str, out: &mu... | Rust | 0 |
emit('stream_end', {
"prompt": user_prompt,
"message_id": get_message_context()
})
emit("update_workflow", {
"status": "finished",
"duration": job_duration
})
def stream_response(response_stream, message_uuid: str) -... | Python | 1 |
#!/usr/bin/env python3
import unittest
from gpytorch.kernels import PeriodicKernel as GPeriodicKernel
from gpytorch.kernels.keops import PeriodicKernel
from gpytorch.priors import NormalPrior
from gpytorch.test.base_keops_test_case import BaseKeOpsTestCase
from gpytorch.test.base_kernel_test_case import BaseKernelTes... | Python | 1 |
logger.debug("PDF download failed for %s: %s", url, exc)
break # move to next URL pattern
# All patterns exhausted
logger.debug("No PDF available for %s", pmcid)
return None
# --------------------------------------------------------------------------- #
# Public API
# -... | Python | 1 |
unches `-n` games with a random starting player and count victories for the first policy.
use ggpf::game;
use ggpf::game::breakthrough::*;
use ggpf::game::meta::with_history::*;
use ggpf::game::*;
use ggpf::policies::{get_multi, mcts::muz::*, mcts::puct::*, DynMultiplayerPolicyBuilder};
use ggpf::settings::{self, Conf... | Rust | 0 |
e}.pt"
if not Path(file).is_file():
from ultralytics import download
download(f"https://docs-assets.developer.apple.com/ml-research/datasets/mobileclip/{file}")
self.model = mobileclip.create_model_and_transforms(f"mobileclip_{config}", pretrained=file, device=device)[0]
... | Python | 1 |
= client.get("https://hyper.rs")
.send()
.map_err(|e| Error::from(e))
.and_then(|mut res| {
println!("{}", res.status());
let body = mem::replace(res.body_mut(), Decoder::empty());
body.concat2().map_err(Into::into)
})
.and_then(|body| {
... | Rust | 0 |
# - compute (pyTree) -
# - Monobloc laminar flat plate -
import Converter.PyTree as C
import Fast.PyTree as Fast
import FastS.PyTree as FastS
import Converter.Internal as Internal
import KCore.test as test
test.TOLERANCE=1.e-9
t = C.convertFile2PyTree('Pplane_136_96.cgns')
t = C.addState(t, MInf=0.2, ReInf=25.e6, MutS... | Python | 1 |
from flask import Blueprint
from controllers.productController import save, find_all, search_product
product_blueprint = Blueprint("product_bp", __name__)
#where we put our url_endpoints
product_blueprint.route('/', methods=['POST'])(save)
product_blueprint.route('/', methods=['GET'])(find_all)
product_blueprint.rou... | Python | 1 |
from collections import deque
print('Implementing stack using list')
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stac... | Python | 1 |
let proof = prover.prove(&bp_gens).unwrap();
let end = start.elapsed();
println!("Proving time is {:?}", end);
(proof, (com_leaf, leaf_index_comms, proof_comms))
};
let mut verifier_transcript = Transcript::new(b"VSMT");
let mut verifier = Verifier... | Rust | 0 |
checkedTree};
use unproven_tree::{UnprovenLeaf, UnprovenSchnorr};
use self::challenge::Challenge;
use self::unchecked_tree::UncheckedSchnorr;
use derive_more::From;
use derive_more::TryInto;
/** The message sent by a prover to its associated verifier as part of a sigma protocol interaction. */
pub(crate) trait Prove... | Rust | 0 |
from browser import document as doc
from browser.html import *
trans_menu = {
'menu_console':{'en':'Console','es':'Consola','fr':'Console', 'pt':'Console'},
'menu_editor':{'en':'Editor','es':'Editor','fr':'Editeur', 'pt':'Editor'},
'menu_gallery':{'en':'Gallery','es':'Galería','fr':'Galerie', 'pt':'Galeri... | Python | 1 |
きません**。これは、マルチスレッドアプリケーションにおいて、複数のスレッドが同時にPythonのコードを実行することを妨げます。
# ---
# ### なぜGILは存在するのか?
# GILの主な目的は、**メモリ管理を単純化し、スレッドセーフなPythonコードを簡単に書けるようにすること**です。
# - **単純なメモリ管理:** Pythonのオブジェクトは参照カウントという方法でメモリ管理をしています。これは、オブジェクトへの参照の数を数えることで、不要になったオブジェクトを自動的に解放する仕組みです。複数のスレッドが同時に参照カウントを操作すると、競合状態が発生し、メモリリークやクラッシュにつながる可能性があ... | Python | 1 |
ttle_time: DateTime) -> crate::Result {
self.lags
.push((Utc::now() - last_battle_time).num_seconds().try_into()?);
Ok(())
}
pub fn add_batch(&mut self, batch_len: usize, matched_len: usize) {
let batch_len = batch_len as f64;
self.average_batch_size.push(batch_len);... | Rust | 0 |
n_nudge, on_increase_size, on_decrease_size):
super().__init__(daemon=True)
self.on_opacity_delta = on_opacity_delta
self.on_nudge = on_nudge
self.on_increase_size = on_increase_size
self.on_decrease_size = on_decrease_size
self.running = True
def run(self):
... | Python | 1 |
import pygame
# Inicialización de Pygame
pygame.init()
import os #Para poder buscar en el sistema
ANCHO_PANTALLA, ALTO_PANTALLA = 1200, 680
PANTALLA = pygame.display.set_mode((ANCHO_PANTALLA, ALTO_PANTALLA))
pygame.display.set_caption("Paintxel")
FPS = 120
# Crear una fuente para mostrar el número
font = pygame.fon... | Python | 1 |
* \file flow-rs/src/graph/debug.rs
* MegFlow is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2019-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASI... | Rust | 0 |
pdf::content::Content::decode(&data),
Err(_) => lopdf::content::Content::decode(&content_stream.content),
})
};
if debug_depth > 0 {
// println!("Finding text operators in: {:?}", content);
indent!(debug_depth, "Will visit {} ops.", content.operations.len());
}
let mu... | Rust | 0 |
xbb\xe0\x18\xd5;\xa7\xfb\
#\x93\x08\x1a\x03i\xde3\xed\x0e\xc49\xb3?\xdc\xa0\
qtG\x0e\xb8\x07\xd6\xb5q:\xae\x08C\xb4D\x9e\
\xe8u\xe3\xf8\xdc\xbb\xb1Z\xd8\xefw\xb8&\xf2\xbc'\
\xed\xf6l1\xfdl\x8d\xfa\x99\xaf\xf9\x8c/\xff\xc7\x97\
\x02p\xc1\xbf\x82o\xf9\x93_\x18^x8\xbcm\x1f\
y\x92\xd6_\x1fC\xb8\x15@\xdc\xf1V\x10\x1dLw\
\xc... | Python | 1 |
from typing import List, Tuple
from collections import defaultdict
def sparse_similarity(docs_raw: List[Tuple[int, List[int]]]) -> None:
doc_dict = dict(docs_raw)
rev_index = defaultdict(set)
for doc_id, doc_words in doc_dict.items():
for word in doc_words:
rev_index[word].add(doc_id)... | Python | 1 |
{
fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
join_all(iter)
}
}
/**
* Holo-REA satisfaction zome I/O data structures
*
* Required by packages wishing to interact with the zome via its standard RPC interface,
* and by the zome API handlers accepting these parameters.
*
* @package H... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Target, Minimums, Maximums
class MinimumInlineAdmin(admin.TabularInline):
model = Minimums
fk_name = "of_target"
fields = (
('kilojoules','protein','fibre','carbohydrate','fat','sugar',... | Python | 1 |
fix situations like copying a row and getting a different order in the cells,
// or copying a sorted table and getting a weird order in the copied cells.
indexes_sorted.sort_unstable_by(|a, b| {
let cmp = a.row().cmp(&b.row());
match cmp {
Ordering::Equal => if a.column() < b.column... | Rust | 0 |
print("Toto je task 14")
print("konec úkolu 14") | Python | 1 |
(a + b + c))
# Both values are in range. Since they're not ndarrays (but lists),
# they will be converted, and their value checked.
assert numpy.all(f([3], [6], 1) == 10)
# Values are in range, but a dtype too large has explicitly been given
# For perfor... | Python | 1 |
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2009-2010 Ars Aperta, Itaapy, Pierlis, Talend.
#
# Authors: David Versmisse <david.versmisse@itaapy.com>
# Hervé Cauwelier <herve@itaapy.com>
#
# This file is part of Lpod (see: http://lpod-project.net).
# Lpod is free software; you can redistribute it and/or modify it... | Python | 1 |
inal::TokenDefinitions => write!(f, r"TokenDefinitions"),
}
}
}
impl lalr1_plus::Parser<AATerminal, AANonTerminal, AttributeData> for Specification {
fn lexical_analyzer(&self) -> &lexan::LexicalAnalyzer<AATerminal> {
&AALEXAN
}
fn viable_error_recovery_states(token: &AATerminal) -> BT... | Rust | 0 |
field_element(&group_size, rng),
base_x: random_field_element(&modulus, rng),
base_y: random_field_element(&modulus, rng),
result_x: BigUint::from(0u64),
result_y: BigUint::from(0u64),
};
let g2 = JsonG2PointScalarMultiplicationPair {
scalar: ... | Rust | 0 |
sig.signature),
"Verification of a valid signature failed!");
assert!(good != bad, "good == bad");
assert!(good_sig.signature != bad_sig.signature, "good sig == bad sig");
assert!(!keypair.public.verify(good, &bad_sig.signature),
"Verification of a signature on a different ... | Rust | 0 |
nset (<127)",
));
}
if bytes[0] & 0xf0 != 0xf0 {
return MpkMidiMessage::parse_channel_msg(bytes);
}
match bytes[0] {
MIDI_SYSEX => MpkMidiMessage::parse_sysex(bytes),
MIDI_RESET => Ok(MpkMidiMessage::Reset),
_ => Ok(MpkMidiMes... | Rust | 0 |
::Client,
sink: String,
}
impl DownstreamSender {
pub fn new() -> anyhow::Result<Self> {
let sink = std::env::var("K_SINK").context("Missing variable 'K_SINK'")?;
Ok(DownstreamSender {
client: reqwest::ClientBuilder::new().build()?,
sink,
})
}
pub async... | Rust | 0 |
= &input.reserved_instances_listing_id {
scope_2918.string(var_2919);
}
writer.finish();
Ok(aws_smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_crate_operation_describe_reserved_instances_modifications(
input: &crate::input::DescribeReservedInstancesModificationsInput,
) ->... | Rust | 0 |
try!(NameParser::new().parse_stream(input));
if name == String::from("on")
{
let mut errors = ParseError::empty(position);
errors.add_error(Error::Unexpected(From::from(name.clone())));
errors.add_error(Error::Expected(From::from("name")));
Err(Consumed::Empty(errors))
... | Rust | 0 |
mporterState {
id: Option<AssetUuid>,
}
/// Wrapper struct to be able to impl Importer for any `SimpleFormat`
pub struct SimpleImporter<A: 'static, T: Format<A> + TypeUuid>(
pub T,
::std::marker::PhantomData<A>,
);
impl<A: 'static, T: Format<A> + TypeUuid + 'static> From<T> for SimpleImporter<A, T> {
... | Rust | 0 |
it is not on a char boundary.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::{RString,RVec};
///
/// let mut str=RString::from("Galileo");
///
/// assert_eq!(str.remove(3),'i');
/// assert_eq!(str.as_str(),"Galleo");
///
/// assert_eq!(str.remove(4),'e');
... | Rust | 0 |
r:
raise
except Exception as e:
raise TransportConnectionFailed(str(e)) from e
finally:
if upload_files:
close_files(list(self.files.values()))
async def execute_batch(
self,
reqs: List[GraphQLRequest],
extra_args: Optional... | Python | 1 |
es().to(input.dtype)
col = out.col_indices().to(input.dtype)
edge_index = paddle.convert_indices_from_csr_to_coo(
rowptr, col, out_int32=rowptr.dtype != paddle.int64)
elif out.layout == paddle.sparse.coo:
edge_index = out.indices()
edge_index = EdgeIndex(edge_index)
edg... | Python | 1 |
#!/usr/bin/env python3
"""
使用正确的API端点测试Tu-zi.com
"""
import os
from openai import OpenAI
def test_tuzi_with_correct_endpoint():
"""使用正确的端点测试Tu-zi"""
api_key = "sk-w7jb5s5hSWwwG93CBwodiwBqsQiVsGn671xqPAU5ZZk85huu"
base_url = "https://api.tu-zi.com/v1"
client = OpenAI(api_key=api_key, base_url... | Python | 1 |
self.0[1] = code as u8;
}
unsafe fn set_len(&mut self, new_length: u16) {
NE::write_u16(&mut self.0[4..], new_length)
}
pub fn clear_payload(&mut self) {
unsafe { self.set_len(0) };
}
pub fn clear_eol(&mut self) {
if Some(tag::Tag::EndOfList) == self.tags().last... | Rust | 0 |
import heapq
def shortest_path(matrix, start, end):
rows, cols = len(matrix), len(matrix[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up
# Convert the matrix into a graph
graph = {(i, j): {} for i in range(rows) for j in range(cols) if matrix[i][j] != 'x'}
for i in ra... | Python | 1 |
if boxes:
for box in boxes:
gt_boxes.append(torch.tensor([box.center.tolist(), box.dimensions.tolist()]))
gt_boxes = torch.stack(gt_boxes)
else:
gt_boxes = torch.zeros(0, 2, 3)
pred_boxes = torch.tensor(prediction["predicted_boxes"])
# if pr... | Python | 1 |
t<(), EvalError> {
let value = self.memory[self.memory_pointer]
.checked_sub(1)
.unwrap_or(std::u8::MAX);
self.memory[self.memory_pointer] = value;
Ok(())
}
fn put_char(&mut self) -> Result<(), EvalError> {
let c = self.memory[self.memory_pointer];
... | Rust | 0 |
< 1 << MAX_VIRT_BITS.load(Ordering::Acquire),
"virtual address {:#018x} overflows address space", end_virt);
let mut addr_virt = virt_base;
let mut addr_phys = phys_base;
while addr_virt < end_virt {
let index = (addr_virt - bigger... | Rust | 0 |
ookie = parseCookieValue(value, true);
value = &cookie.0;
let ok = &cookie.1;
if !ok {
continue;
}
let mut c = Cookie::default();
c.Name = name.to_string();
c.Value = value.to_string();
c.Raw = line.to_string();
for i in 1..len!(parts)... | Rust | 0 |
"""
Copyright 2023 Man Group Operations Limited
Use of this software is governed by the Business Source License 1.1 included in the file licenses/BSL.txt.
As of the Change Date specified in that file, in accordance with the Business Source License, use of this software will be governed by the Apache License, version ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.