text string | label_name string | labels int64 |
|---|---|---|
(), ".");
assert_eq!(config.to_ascii("...xn--").unwrap(), "...");
assert_eq!(config.to_ascii("xn--.xn--").unwrap(), ".");
assert_eq!(config.to_ascii("xn--.example.org").unwrap(), ".example.org");
}
#[test]
fn test_v5() {
let config = idna::Config::default()
.verify_dns_length(true)
.use... | Rust | 0 |
# -*- coding: UTF-8 -*-
#/usr/bin/python
import os
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
merge = lambda l: string.join(l, '\n')
def manual():
print """
usage:
python remote_ssh.py [port] [user] [ppk] [host_file] [cmds_file]
sample:
python remote_ssh.py 22 jo... | Python | 1 |
be true if you want to use signature based authentication for the
/// REST API calls.
pub sign_based_auth: bool,
/// REST API version to be used.
pub api_version: ApiVersion,
}
/// Client is responsible for preparing requests and making http calls.
pub struct Client {
set_auth_header: Box<dyn Fn(&... | Rust | 0 |
(Error::SysError(SysErr::EAGAIN))
}
// Fast path when no control message nor name buffers are provided.
if msg.msgControlLen == 0 && msg.nameLen == 0 {
let (n, mut mflags, _ , cms) = sock.RecvMsg(task, &mut dst, flags, deadline, false, 0)?;
if !cms.Empty() {
mflags |= MsgType::... | Rust | 0 |
int")
.arg(
Arg::new("lint")
.help("The lint to enable")
.required(true)
.multiple_values(true)
.min_values(1)
.possible_values(lint_names)
.clone(),
)
}
pub fn run_on_match(matches: &ArgMatches)... | Rust | 0 |
get(pixels);
img.save(path).unwrap();
}
pub fn draw_spatial_tree_sprites(tree: &mut SpatialTree<(PathBuf, image::RgbaImage)>, path: &Path) {
let region = tree.region().clone();
let mut pixels = vec![Rgba::new(255, 255, 255, 255); ((region.width+1)*(region.height+1)) as usize];
for node in tree.iter_nod... | Rust | 0 |
consts::TAU;
fn sample_surface_inside(sphere: &Sphere, sample: Vec2) -> SurfaceSample {
let mut normal = sample_unit_sphere(sample);
let point = sphere.center + sphere.radius * normal;
if sphere.inverse {
normal = -normal;
}
SurfaceSample::new(point, normal)
}
#[typetag::serde]
impl Sampl... | Rust | 0 |
te::{
encode::{
event::EncodeAuthTicketEvent, infra::EncodeAuthTicketInfra, method::encode_auth_ticket,
},
validate::{
event::ValidateAuthTokenEvent, infra::ValidateAuthTokenInfra, method::validate_auth_token,
},
};
use crate::auth::user::remote::kernel::data::RequireAuthRoles;
pub enu... | Rust | 0 |
videos.append(video)
# =======================================
except:
pass
result = {'list': videos}
result['page'] = pg
result['pagecount'] = 9999
result['limit'] = 90
result['total'] = 999999
return result
def detailContent(self,... | Python | 1 |
列
source_seq = source_x.permute(0, 2, 3, 1).reshape(B, H*W, C)
target_seq = target_x.permute(0, 2, 3, 1).reshape(B, H1*W1, C)
# 根据不同模式组合序列
if self.combine_mode == CombineMode.CONCAT:
combined_seq = self.combine_sequences_concat(source_seq, target_seq)
elif se... | Python | 1 |
'day': train_day_norm,
'recent': train_recent_norm,
'target': train_target,
},
'val': {
'week': val_week_norm,
'day': val_day_norm,
'recent': val_recent_norm,
'target': val_target
},
'test': {
... | Python | 1 |
NFOW {
pub SizeOfStruct: u32,
pub DeviceId: u32,
pub State: u32,
pub Flags: u32,
pub Rings: u32,
pub Priority: u32,
pub DeviceName: ::windows_sys::core::PCWSTR,
pub Tsid: ::windows_sys::core::PCWSTR,
pub Csid: ::windows_sys::core::PCWSTR,
}
impl ::core::marker::Copy for FAX_PORT_INFO... | Rust | 0 |
c words from the sentence
"""
# Get word frequency dataframe for the sentence
word_frequency_df = create_word_frequency_df(sentence)
# print(f"word_frequency_df {word_frequency_df}")
# Calculate weirdness scores
weirdness_df = self.Weirdness(word_frequency_df)
# p... | Python | 1 |
ild()?)
};
let fence = FenceCheck::new(vertices_promise)?;
let prop_manager = PropCollection::new(renderer)?;
let state = ToolGunState {
scroll: 0.0,
tools: get_all_tools(),
tool_id: 0,
menu_pos: None,
render_tool: false,
};
Ok(ToolGun {
inner: ComponentInner::f... | Rust | 0 |
let preprocessed_table = table.preprocess(&prover_key, 2usize.pow(8));
let mut lookup = LookUp::new(table);
// Adds 1 to the rangeproof
lookup.read(&(Fr::from(1u8), Fr::from(1u8)));
// Adds 2 to the rangeproof
lookup.read(&(Fr::from(2u8), Fr::from(2u8)));
// Adds 10 to the rangeproof
loo... | Rust | 0 |
ed as a `BitSlice` at the
point of use.
# Examples
```rust
use bitvec::prelude::*;
use core::cell::Cell;
radium::if_atomic! { if atomic(16) {
use core::sync::atomic::AtomicU32;
} }
let a: &BitSlice = bits![0, 1, 0, 1, 2];
assert_eq!(a.count_ones(), 3);
let b: &mut BitSlice = bits![mut 2; 5];
assert!(b.all());
as... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from detectron2.config import CfgNode as CN
def add_ubteacher_config(cfg):
"""
Add config for semisupnet.
"""
_C = cfg
_C.TEST.VAL_LOSS = True
_C.MODEL.RPN.UNSUP_LOSS_WEIGHT = 1.0
_C.MODEL.RPN.LOSS = "CrossEntropy"
... | Python | 1 |
nstant_(m.weight, 1)
# # init.constant_(m.bias, 0)
# # elif isinstance(m, nn.BatchNorm1d):
# # init.constant_(m.weight, 1)
# # init.constant_(m.bias, 0)
# # elif isinstance(m, nn.Linear):
# # init.normal_(m.weight, std=0.001)
# # ... | Python | 1 |
* (Original author: <NAME>)
* converted into portable ITL format by <NAME>.
*
* Copyright 2013-2015 <NAME> (<EMAIL>)
* Copyright 2015-2017 <NAME> (<EMAIL>)
*
* 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 c... | Rust | 0 |
xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6,
0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569,
0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69,
0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, ... | Rust | 0 |
fn set_output(&mut self, pin: usize, state: bool) -> Result<(), Error> {
if pin >= CHAIN_LENGTH * 8 {
return Err(Error::PinOutOfRange);
}
self.set_output_unchecked(pin, state);
Ok(())
}
/// Sets the output state for a pin without pin boundary checks.
///
... | Rust | 0 |
create_temp_dir().unwrap();
let tmp_dir_path: &std::path::Path = tmp_dir.as_ref();
let manifest_path = tmp_dir_path.join(MANIFEST_FILE_NAME);
let mut file = File::create(&manifest_path).unwrap();
let wapm_toml = toml! {
[package]
name = "_/test"
versi... | Rust | 0 |
# Encryption Function
# Iterate through each character in the message and encrypt it using its ASCII value and the shift value.
def encryption():
print("Encrypted Message is: \n")
for a in message.lower():
if a == ' ':
print(' ', end='')
else:
x = ord(a) #converting the l... | Python | 1 |
0.1.1-alpine3.9 as base-image
‾‾‾‾‾
"""
self.__version = self.tag
if self.__version and "-" in self.__version:
self.__version, _, _ = self.tag.partition("-")
return self.__version
@property
... | Python | 1 |
("ERROR: Please accept the trust dialog on the screen of device")
{
println!("Please accept the trust dialog on the screen of your device");
paired_failed(&mount_dir);
}
Ok(())
}
None => {
pri... | Rust | 0 |
rror"
if len(elems) != 1:
raise SCons.Errors.UserError("{} : Elems List size needs to be 1".format(msg_context))
return elems[0]
def root_dir():
"Returns the root of driver_stack tree"
return os.path.realpath(os.path.join(__file__, "..", ".."))
def add_padding(align):
"""
Return a fu... | Python | 1 |
from collections import OrderedDict
from czsc.analyze import CZSC
from czsc.signals.tas import update_ma_cache
from czsc.utils import create_single_signal
def tas_dma_bs_V240608(c: CZSC, **kwargs) -> OrderedDict:
"""双均线多头排列下的回调买点
参数模板:"{freq}_N{n}双均线{t1}#{t2}顺势_BS辅助V240608"
**信号逻辑:**
参考链接:https://m... | Python | 1 |
texte = input("Entrez un texte : ")
voyelles = "aeiouyAEIOUY"
for char in texte:
if char.isalpha() and char not in voyelles:
print(char, end=" ") | Python | 1 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
import os
from db import db_connect
from db_models import user_data, client_data, config
from routers import user_endpoints, client_endpoints, config_endpoints
from old_db import old_db_endpoints
from old_db.ol... | Python | 1 |
(((kcu::table_name, kcu::table_schema), kcu::column_name))
.first::<(TableName, _)>(connection)?;
let (mut primary_key_table, primary_key_column) = kcu::table
.filter(kcu::constraint_schema.eq(primary_key_schema))
.filter(kcu::constraint_name.e... | Rust | 0 |
import brukva
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
from brukva import adisp
import logging
from functools import partial
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('app')
c = brukva.Client()
c.connect()
def on_set(result):
(error, d... | Python | 1 |
from xml.parsers import expat
from HTMLParser import HTMLParser
from django import template
register = template.Library()
parser = HTMLParser()
def unescape(s):
want_unicode = False
if isinstance(s, unicode):
s = s.encode("utf-8")
want_unicode = True
# the rest of this assumes that `s` ... | Python | 1 |
stributed
// except according to those terms.
// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
#![allow(missing_docs, non_upper_case_globals, non_snake_case)]
/// The version of [Unicode](http://www.unicode.org/)
/// that this version of unicode-width is based on.
pub const UNI... | Rust | 0 |
import os
import random
import sys
import asyncio
import contextlib
from config import *
from translation import BATCH
from plugins.database import add_file
from config import ADMINS
from pyrogram import Client, filters
from pyrogram.errors.exceptions.forbidden_403 import ChatWriteForbidden
from pyrogram.types import ... | Python | 1 |
e[sort_order]
return dict(
time=time,
value=value,
interpolation_mode=interpolation_mode,
is_bool_param=is_bool_param,
)
@functools.cached_property
def _get_cached_interpolated_param(
self,
) -> interpolated_param.InterpolatedVarSingleAxis:
"""Interpolates the in... | Python | 1 |
})
}
}
impl Writer for UdpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let connected_to = self.connected_to;
self.as_socket(|sock| sock.sendto(buf, connected_to))
}
}
#[cfg(test)]
#[allow(experimental)]
mod test {
use super::*;
use io::net::ip::{SocketAddr};
... | Rust | 0 |
rds_png_paths = []
for index, row in df_pos.iterrows():
record = []
coord_x = row["coord_x"]
coord_y = row["coord_y"]
coord_z = row["coord_z"]
nodule_chance = float(row["nodule_chance"])
box_label = row["box_label"]
# 绘制可视化
... | Python | 1 |
import os
import sys
import screen_watermark_tkinter
import screen_watermark_qt5
import screen_watermark_qt5_oblique
def qt5_effect():
# 检查文件是否存在
Desktop_dir = os.path.join(os.path.expanduser("~"), "Desktop")
current_dir = os.path.join(Desktop_dir, "no_screen_mark.ini")
exists = os.path.exists(curren... | Python | 1 |
from test.fabricas.leilao import fabricar_leilao, fabricar_lance
def test_sem_lances(con, client):
with con.cursor() as cur:
fabricar_leilao(cur, id_=-1, criador='cfb795dc-7c3d-406e-8cac-ae310e82e1b2')
resp = client.get('/leiloes/-1')
assert resp.status_code == 200
json = resp.json
assert json['criador'... | Python | 1 |
ode = mode
self.transform = transform
self.mask_path = ""
else:
self.names = data["name"]
self.ids = data["id"]
self.image_path = data["img_path"]
self.mask_path = data["mask_path"]
self.mode = mode
self.transform = ... | Python | 1 |
import pyautogui as pg
import numpy as np
from ScreenShoot import get_image
from pynput.keyboard import *
BaseDelay = 0.02
triggerK = KeyCode.from_char('z')
exitK = KeyCode.from_char('q')
porK = KeyCode.from_char('x')
paused = True; runing = True
cliclPorK = True
cliclPor = 1
def on_pressK(key):
global paused, ru... | Python | 1 |
# Dictionary of common atom types and their masses (in atomic mass units, u)
atom_masses = {
"H": 1.008,
"He": 4.0026,
"Li": 6.94,
"Be": 9.0122,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.31,
"Al": 26.98,
"Si": 2... | Python | 1 |
Cell::new(None),
new_colln_btn: new_colln_btn,
load_colln_btn: load_colln_btn,
save_colln_btn: save_colln_btn,
save_as_colln_btn: save_as_colln_btn,
file_path_text: gtk::Label::new(None),
file_status_btn: file_status_btn,
});
bpe.fi... | Rust | 0 |
];
let (usize, _socket_address) = self.socket.recv_from(&mut buff)?;
Ok(String::from_utf8(Vec::from(&buff[0..usize]))?)
}
}
mod render;
mod layers;
mod path;
// Renders an SVG to pixmap.
// If fit_to size differs from tree.svg_node.size, SVG would be scaled accordingly.
pub fn render(
tree: &usv... | Rust | 0 |
=== 判断标准 ===
1. **DATABASE类型** - 需要查询数据库:
- 涉及上述业务实体和指标的查询、统计、分析、报表
- 包含业务相关的时间查询
- 例如:业务数据统计、收入排行、流量分析、占比分析等
2. **CHAT类型** - 不需要查询数据库:
- 生活常识:水果蔬菜上市时间、动植物知识、天气等
- 身份询问:你是谁、什么模型、AI助手等
- 技术概念:人工智能、编程、算法等
- 平台使用:功能介绍、操作帮助、使用教程等
- 旅游出行:旅游景点、酒店、机票、高铁、的士等
- 情绪:开心、伤心、无聊、生气、孤独、累了、烦恼、心情、难过、抑郁
- 商... | Python | 1 |
the following sentence if you were to substitute it:
///
/// ```text
/// error attempting to <operation>.
/// ```
fn operation(&self) -> &'static str;
/// Returns `true` if there is an expected value.
fn has_expected(&self) -> bool;
/// The expected value.
///
/// # Errors
... | Rust | 0 |
nown(self, node):
"""Ignores unknown tags in YAML"""
return node.value[0].value
_SafeLoaderIgnoreUnknown.add_constructor(
None, _SafeLoaderIgnoreUnknown.ignore_unknown
)
storage_options = default_signer() if ObjectStorageDetails.is_oci_path(uri) else {}
with fsspec.ope... | Python | 1 |
from keras.utils import Sequence
import numpy as np
class DataWrapper():
"""
The N2V_DataWrapper extracts random sub-patches from the given data and manipulates 'num_pix' pixels in the
input.
Parameters
----------
X : array(floats)
The noisy input data. ('SZYXC' or ... | Python | 1 |
n == 'SSS':
parts['microsecond'] = int(value) * 1000
elif token == 'SS':
parts['microsecond'] = int(value) * 10000
elif token == 'S':
parts['microsecond'] = int(value) * 100000
elif token == 'X':
parts['timestamp'] = int(value)
elif token... | Python | 1 |
2_admin"]);
enforcer.add_grouping_policy(&["bob", "data1_admin"]);
enforcer.add_grouping_policy(&["eve", "data3_admin"]);
assert_eq!(enforcer.get_roles_for_user("alice", None), Vec::<String>::new());
assert_eq!(enforcer.get_roles_for_user("bob", None), ["data1_admin"]);
assert_e... | Rust | 0 |
"""
run_fast.py - Versão rápida sem download do OSM
Script otimizado para:
- usar apenas distâncias haversine (sem grafo OSM)
- calcular rotas com 4 heurísticas rapidamente
- produzir programação semanal
Autor: Gabriel (versão otimizada)
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import pa... | Python | 1 |
push(grid[row + 1][col]);
entrance.row += 1;
exit.row += 2;
}
ParseState::BelowMaze | ParseState::InnerTop => {
portal_name.push(grid[row + 1][col]);
exit.row -= 1;
}
_ => {
portal_name.push(grid[row][col + 1]);
matc... | Rust | 0 |
vec![JobType::default()],
EnergyConsumptionModel::SimplifiedLinear(hash_map(&[(
DEFAULT_KEY.to_string(),
SimplifiedLinearEnergyConsumptionModel { phi_max: 1. },
)])),
EnergyCostModel::Linear(hash_map(&[(
DEFAULT_KEY.to_string(),
LinearEnergyCostMod... | Rust | 0 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from gammapy.scripts.main import cli
from gammapy.utils.testing import requires_dependency, run_cli
@pytest.fixture(scope="session")
def config():
return {
"release": "0.20",
"notebook": "overview",
"envfilename"... | Python | 1 |
pass
else:
raise
else:
raise AssertionError("addProto must raise an exception for bad protocols")
def testAddingBadProtos_TooSmall(self) -> None:
"""Adding a protocol with a negative number raises an exception."""
e = rawudp.RawUDPProtoco... | Python | 1 |
\
intervals_a[i][start] <= intervals_b[j][end]
# check if intervals overlap and intervals_a[j]'s start time lies within the other intervals_b[i]
b_overlaps_a = intervals_b[j][start] >= intervals_a[i][start] and \
intervals_b[j][start] <= intervals_a[i][end]
# store t... | Rust | 0 |
,
node: tuple_decl,
});
Some(CtorDecl {
name_opt,
tuple_decl_opt,
node,
})
}
fn gen_stmt(node: Rc<NodeData>) -> Option<Stmt> {
match node.node() {
Node::MatchStmt => gen_match_stmt(node).map(Stmt::Match),
Node::EnumDecl => gen_enum_decl(node).map... | Rust | 0 |
rams for the original image
for i in range(3):
plt.subplot(2, 3, i+1)
plt.hist(rgb_values[:,:,i].flatten(), bins=256, range=(0,1),
color=colors[i], alpha=0.7)
plt.title(f"Original - {channels[i]} Channel")
plt.xlabel("Pixel Value")
plt.ylabel("Frequency")
... | Python | 1 |
import torch
from torch.utils.data import Dataset
from pymj.botzone.action import *
from pymj.botzone.GameData import GameData
class SLDataset(Dataset):
ALL_TILES = {i: 4 for i in range(34)}
DRAW_SOURCE = {
Play: 0,
Chi: 1,
Peng: 2,
Gang: 3,
BuGang: 4,
AnGang: ... | Python | 1 |
from llama_index.core.indices.managed.base import BaseManagedIndex
from llama_index.core.base.base_retriever import BaseRetriever
from llama_index.indices.managed.postgresml import PostgresMLIndex
from llama_index.indices.managed.postgresml import PostgresMLRetriever
def test_class():
names_of_base_classes = [b._... | Python | 1 |
ecause we are not
# in an interactive framework.
ax = fig_test.add_subplot()
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1, 1)
x = np.linspace(0, 2 * np.pi, 100)
line, = ax.plot([], [])
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(x, n... | Python | 1 |
import random
import sys
print('Камень, ножницы, бумага')
# В этих переменных накапливается количество
# побед, поражений и ничьих
wins = 0
losses = 0
ties = 0
while True: # главный цикл игры
print('%s побед, %s поражений, %s ничьих' % (wins, losses, ties))
while True: # цикл выбора хода
print('Вы... | Python | 1 |
}
fn files<F>(&self, resource_modules: Option<bool>) -> Result<Vec<F>>
where F: PtrContainer<_FileStream>
{
let p = self.ptr_mut();
let mut pfiles: *mut SAFEARRAY = ptr::null_mut();
let hr = match resource_modules {
Some(get_modules) => unsafe {
... | Rust | 0 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
def batch_norm(inputs, name_scope, is_training, epsilon=1e-3, decay=0.99):
with tf.variable_scope(name_scope):
size = inputs.get_shape().as_list()[1]
gamma = tf.get_variable(
'gamma', [size], initializer=tf.consta... | Python | 1 |
e.
/*
* generated from files in cras/src/common in adhd:
* cras_audio_format.h
* cras_iodev_info.h
* cras_messages.h
* cras_shm.h
* cras_types.h
* cras_util.h
* packet_status_logger.h
*/
#![allow(clippy::unreadable_literal)]
#![allow(clippy::cognitive_complexity)]
";
let mut output_file = File::create(o... | Rust | 0 |
# From: Bayesian Models for Astrophysical Data, Cambridge Univ. Press
# (c) 2017, Joseph M. Hilbe, Rafael S. de Souza and Emille E. O. Ishida
#
# you are kindly asked to include the complete citation if you used this
# material in a publication
# Code 5.11 - Inverse Gaussian model in Python using Stan
# 1 response... | Python | 1 |
nge proposal is can remain in a pending state until deleted.
type DeleteExpiredChangesPeriod: Get<Self::BlockNumber>;
}
decl_error! {
pub enum Error for Module<T: Trait> {
/// Space owners was not found by id
SpaceOwnersNotFound,
/// Change was not found by id
ChangeNotFound,
/// Space owners a... | Rust | 0 |
ck(pady=5, fill="x")
last_name_label = customtkinter.CTkLabel(search_frame, text="Last Name:")
last_name_label.pack(pady=5, anchor="w")
last_name_entry = customtkinter.CTkEntry(search_frame, placeholder_text="Enter Last Name")
last_name_entry.pack(pady=5, fill="x")
search_button = customtkinter.CT... | Python | 1 |
from django.test.client import RequestFactory
from nose.tools import eq_
import mkt
import mkt.site.tests
from mkt.account.utils import purchase_list
from mkt.constants import apps
from mkt.site.fixtures import fixture
from mkt.site.utils import app_factory
from mkt.users.models import UserProfile
from mkt.webapps.mo... | Python | 1 |
::Pair(root.clone()));
hs.force_gc();
// After GC, the root object should be unchanged.
assert_eq!(root.head(), Value::Pair(root.clone()));
assert_eq!(root.tail(), Value::Pair(root.clone()));
});
}
<filename>packages/rhoas-kafka-instance-sdk/src/models/acl_binding_list.rs
/*
* Kaf... | Rust | 0 |
from typing import Optional, List
from extract_block_mutator.SpecialInstInputUtil.SpecialOpVal import SpecialOpVal
from extract_block_mutator.SpecialInstInputUtil.insts_for_reset_op_util import generate_insts_for_byop, reverse_op_idxs
from ..InstModel.PHEnv import PHEnv
from extract_block_mutator.Context import Conte... | Python | 1 |
, statuses)
def get_funcs_keys_all(parms):
"""Получаем список ключей из вложенных словарей "settings".
:param parms: Словарь из "settings".
:type parms: dict
:return: Список ключей с названиями функций.
"""
funcs_keys_all = []
if isinstance(parms, dict):
for f_key in list(parms.k... | Python | 1 |
;
interpret_results(resp.status())?;
let props = resp
.headers()
.get(crate::servicebus::brokeredmessage::BROKER_PROPERTIES_HEADER)
.and_then(|header| serde_json::from_str::<BrokerProperties>(header.to_str().ok()?).ok())
.unwrap_or(Default::default());
... | Rust | 0 |
# Copyright 2018 Rackspace, US Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | Python | 1 |
import numpy as np
import numba as nb
from numpy.random import PCG64
from timeit import timeit
bit_gen = PCG64()
next_d = bit_gen.cffi.next_double
state_addr = bit_gen.cffi.state_address
def normals(n, state):
out = np.empty(n)
for i in range((n + 1) // 2):
x1 = 2.0 * next_d(state) - 1.0
x2 =... | Python | 1 |
}.svg
)
FILE_FORMAT = (TYPE = 'CSV' FIELD_DELIMITER = NONE RECORD_DELIMITER = NONE);
-- View the content directly
SELECT * FROM svg_files WHERE filename = '{filename}.svg';
""", language="sql")
else:
st.error("Failed to generate SVG content")
... | Python | 1 |
verse::from(vec![item1.clone(), item2.clone()]);
let tree = universe.empty_tree();
assert_eq!(
vec![
ItemStatus::Excluded(item1.clone()),
ItemStatus::Excluded(item2.clone()),
],
tree.summarize(&[], &[])
);
}
#[test]
... | Rust | 0 |
ert_eq!(0xFF000000 & value, 0, "value: {} is too big", value);
Self { value }
}
}
trait ToHexCode {
fn to_hex_code(&self) -> HexCode;
}
impl ToHexCode for Rgb<u8> {
fn to_hex_code(&self) -> HexCode {
HexCode {
value: (self[0] as u32) << 16 | (self[1] as u32) << 8 | (self[2] as u... | Rust | 0 |
import mindtorch.torch as torch
import mindtorch.torch.nn.functional as F
from mindtorch.torchaudio.transforms import Resample
from .constants import * # noqa: F403
from .model import E2E0
from .spec import MelSpectrogram
from .utils import to_local_average_cents, to_viterbi_cents
class RMVPE:
def __init__(self... | Python | 1 |
117939,
'tm_trap': 'RXPDR_J_COUNTER_OVERFLOW',
'trap_id': '29',
},
'trap_2_asic_0': {
'asic': '0',
'current': 4333278472,
'delta': 4214818838,
'prev': 118459634,
'tm_trap': 'STATISTICAL_METER_PACKET_GOT_DROPPED_DUE_TO_ST... | Python | 1 |
from_git("01452d761e", "testdata/en.json").unwrap();
assert_eq!(branch, tag);
assert_eq!(branch, commit);
}
#[test]
fn decode_parse_encodings() {
crate::config::init_test();
let utf8 = include_bytes!("../../testdata/en-utf8.json");
let utf8bom = include_bytes!("../..... | Rust | 0 |
from typing import List
from pandas import DataFrame
from consensus_economics.utils.date_format import DateFormatUtils
from consensus_economics.paths import Paths
from openpyxl import load_workbook
class BaseWorksheet:
"""
Base class for handling consensus economics worksheet operations.
Args:
... | Python | 1 |
.service(unconfirmed_op)
.service(unconfirmed_ops)
.service(unconfirmed_deposits)
})
.bind(&config.bind_addr())
.expect("failed to bind")
.run()
.await
})
}... | Rust | 0 |
();
// you will have to keep track of the input geometry. it will be referenced as
// input geometry indices in the output.
vb.with_vertices(p.iter())?;
vb.with_segments(s.iter())?;
// this will generate the list of cells, edges and circle events (aka vertices)
let result = vb.build()?;
prin... | Rust | 0 |
res.touch("crypto_file");
chmod.args(&["u-r", "crypto_file"]).succeeds();
ucmd.args(&["!", "-r", "crypto_file"]).succeeds();
}
#[test]
#[cfg(not(windows))] // FIXME: implement on Windows
fn test_file_is_writable() {
new_ucmd!().args(&["-w", "regular_file"]).succeeds();
}
#[test]
#[cfg(not(windows))] // F... | Rust | 0 |
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
ans = 1
increasing = 1
decreasing = 1
for i in range(1, len(arr)):
if arr[i] > arr[i - 1]:
increasing = decreasing + 1
decreasing = 1
elif arr[i] < arr[i - 1]:
decreasing = increasing + 1
i... | Python | 1 |
///
/// Must be significantly (e.g. four times) smaller than `protocol_period`.
pub ack_timeout: u8,
/// Maximum number of members selected for indirect probing.
///
/// When probed member does not respond in `ack_timeout`, `num_indirect` other members are asked to check
/// the probed mem... | Rust | 0 |
u8; 32], &p));
}
}
<filename>examples/vendored/complicated_cargo_library/cargo/vendor/winapi-0.3.7/src/um/dxva2api.rs
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your... | Rust | 0 |
theses = |is_left| {
let mut new_item = v.clone();
let (c, index) = if is_left {
('(', &mut new_item.1)
} else {
(')', &mut new_item.2)
};
new_item.0.push(c);
*index += 1;
next.push(new_item);
};
let (left, right) = (v.1, v.2);
... | Rust | 0 |
unsafe {
let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(PointerVal));
let min = llvm::LLVMConstInt(t, lo, signed);
let max = llvm::LLVMConstInt(t, hi, signed);
do [min, max].as_imm_buf |ptr, len| {
llvm::LLVMSetMetadata(value, lib::llvm::MD_range as c_uint,
... | Rust | 0 |
globals)] pub const COLOR_ATTACHMENT9: types::GLenum = 0x8CE9;
#[allow(dead_code, non_upper_case_globals)] pub const COLOR_BUFFER_BIT: types::GLenum = 0x00004000;
#[allow(dead_code, non_upper_case_globals)] pub const COLOR_CLEAR_VALUE: types::GLenum = 0x0C22;
#[allow(dead_code, non_upper_case_globals)] pub const COLOR_... | Rust | 0 |
se {
Err(self.int_to_err(result))
}
}
fn set_filter_cstr(&mut self, filter: &CStr) -> Result<(), Error> {
let result = unsafe { self.dll.pfring_set_bpf_filter(self.handle, filter.as_ptr() as *mut i8) };
if result == SUCCESS {
Ok(())
} else {
E... | Rust | 0 |
collect::<Vec<_>>();
// Even though we don't care about the number of bags, we still need
// to try and parse a count to distinguish between a number and "no
// bags".
if subparts[0].parse::<usize>().is_ok() {
let name = subparts[1]
.t... | Rust | 0 |
may not be copied, modified, or distributed
// except according to those terms.
//! Trencadis Display Server
//!
//! This is an experimental display server for rendering user interfaces
//! built with the Trencadis frameworks. It uses the [WebRender][webrender]
//! library from [Mozilla][mozilla]'s [Servo][servo] pro... | Rust | 0 |
()),
in_app: entry.in_app,
in_element: entry.in_element,
in_mock: entry.in_mock,
};
let res = api_with_auth::<CreateEntryResponse, EmptyError, CreateEntryRequest>(
endpoints::locale::entry::Create::PATH,
endpoints::locale::entry::Create::METHOD,
Some(body),
)... | Rust | 0 |
"""
Example Usage:
python test_faiss_perf.py \
--query-embedding-file ../data/datasets/wikipedia-en/09_wikipedia-en.embeddings.npy \
--index-file ../data/datasets/indexes_wikipedia/wikipedia_chunk_0_to_8/IVF1024,PQ32_populated.index \
--num-neighbours 100 \
--nprobe 32 \
--use-gpu 1 \
--num-quer... | Python | 1 |
"Megapixel",
"%/K",
"mm/m",
"cSt",
"c/min",
"c/h",
"1/min",
"l/min",
"kBit/s",
"Mbyte",
"kByte",
"kOhm",
"l/h",
"mAh",
"opm",
"W/m",
"Bd",
"DPI",
"lm/W",
"µH",
"µF",
"AX",
"nm",
"°",
"%",
"ml",
"kg/m",
"GHz",
... | Python | 1 |
from typing import Literal, Optional
from ..._utilities.dataclass_maker import build_model, FormatType
from ..bases.baseitem import BaseItem
@build_model(format_type=FormatType.camel_case)
class GameMedia(BaseItem):
asset_type_id: Literal[1]
asset_type: Literal["Image"]
image_id: str
video_hash: Opti... | Python | 1 |
/// ```
/// use stellar_client::endpoint::ledger;
///
/// let payments = ledger::Payments::new(123);
/// ```
pub fn new(sequence: u32) -> Payments {
Payments {
sequence,
cursor: None,
order: None,
limit: None,
}
}
fn has_quer... | Rust | 0 |
y()
"""
## Create evaluation Callback
This callback will compute the exact match score using the validation data
after every epoch.
"""
def normalize_text(text):
text = text.lower()
# Remove punctuations
exclude = set(string.punctuation)
text = "".join(ch for ch in text if ch not in exclude)
#... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.