text string | label_name string | labels int64 |
|---|---|---|
ired, subject=subject, function=function, extra_kws=extra_kws, extra_args=extra_args)
if len(event) > 1:
self._nested_slot = self.register_disconnectable(MultiSlot(event=event[1:], listener=listener, function=function, extra_kws=extra_kws, extra_args=extra_args))
self._update_nested_subj... | Python | 1 |
28.0, 28.0]
# hO hO hO paw paw paw
true3_f0 = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
true_f0 = np.array(true1_f0 + true2_f0 + true3_f0, dtype=np.float32)
# Outputs
phoneme, f0 = _query_to_decoder_feature(query)
# Test
assert np.array_equal(phoneme, true_phoneme)
assert np.arr... | Python | 1 |
select any remaining non manifold edges and try again after subdividing and using a larger merge
bpy.context.scene.tool_settings.mesh_select_mode = [False, True, False]
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.subdivide()
bpy.context.scene.tool_settings.mesh_select_mode = ... | Python | 1 |
# User function template for Python
class Solution:
def findMagicalNumber(self, arr):
# code here
for i in range(len(arr)):
if arr[i]==i:
return arr[i]
return -1
| Python | 1 |
'{unit}', use m/h/d")
try:
value = int(user_input[:-1])
except ValueError:
raise ValueError(f"Invalid number in '{user_input}'")
seconds = value * units[unit]
return time.time() + seconds
def quote_if_needed(val: str, quote: str) -> str:
"""
Return the value, quoted with esca... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import numpy as np
import faiss
from faiss.contrib.ondisk import merge_ondisk
############################... | Python | 1 |
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
summ = 0
l = 0
for r, num in enumerate(nums):
summ += num
while summ * (r - l + 1) >= k:
summ -= nums[l]
l += 1
ans += r - l + 1
return ans
| Python | 1 |
from subprocess import PIPE, Popen
def install_pip(pipfile):
print(f"installing {pipfile}")
pip_cmd = ["pip", "install", f"{pipfile}"]
process = Popen(pip_cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
return stdout
| Python | 1 |
for (idx, embedding) in storage.view().outer_iter().enumerate() {
let reconstruction = quantized_storage.embedding(idx);
cosine_similarity_sum += cosine_similarity(embedding, reconstruction.view());
euclidean_distance_sum += euclidean_distance(embedding, reconstruction.view());
}
ep... | Rust | 0 |
t]
fn test_splice_forget() {
let mut v = v64![1, 2, 3, 4, 5];
let a = [10, 11, 12];
::std::mem::forget(v.splice(2..4, a.iter().cloned()));
assert_eq!(v, &[1, 2]);
}
#[test]
fn test_into_boxed_slice() {
let xs = v64![1, 2, 3];
let ys = xs.into_boxed_slice();
assert_eq!(&*ys, [1, 2, 3]);
... | Rust | 0 |
okeId']
# return str(response)
except:
print('命令执行失败')
OSSTools.show_message(ui, '命令执行失败')
def DescribeInvocationResults(AccessKeyID, AccessKeySecret, ZoneId, InvokeID):
client = AcsClient(AccessKeyID, AccessKeySecret, ZoneId)
request = DescribeInvocationResultsRequest()
reques... | Python | 1 |
: Char { terminated: true }, suffix_start: 3 }, len: 3 }
"#]],
)
}
#[test]
fn characters() {
check_lexing(
"'a' ' ' '\\n'",
expect![[r#"
Token { kind: Literal { kind: Char { terminated: true }, suffix_start: 3 }, len: 3 }
Token { kind: Whitespace, len: 1 }
... | Rust | 0 |
class Solution:
def countPrimes(self, n: int) -> int:
if n <= 2:
return 0
return sum(self._sieveEratosthenes(n))
def _sieveEratosthenes(self, n: int) -> List[bool]:
isPrime = [True] * n
isPrime[0] = False
isPrime[1] = False
for i in range(2, int(n**0.5) + 1):
if isPrime[i]:
... | Python | 1 |
_,
ptr::null(),
flags,
);
gl.BindBuffer(target, 0);
}
}
if let Err(err) = self.share.check() {
panic!("Error {:?} initializing buffer {:?}, memory {:?}",
err, unbound, memory.properties);
... | Rust | 0 |
"""
Example of connecting to RabbitMQ using a SSL Certificate.
"""
import logging
import ssl
from amqpstorm import Connection
logging.basicConfig(level=logging.INFO)
def on_message(message):
"""This function is called on message received.
:param message:
:return:
"""
print("Message:", message.b... | Python | 1 |
import torch
from torch.nn import functional as F
def cross_entropy(input, target, label_smooth=0, reduction="mean"):
"""Cross entropy loss.
Args:
input (torch.Tensor): logit matrix with shape of (batch, num_classes).
target (torch.LongTensor): int label matrix.
label_smooth (float, o... | Python | 1 |
omponent(NETWORK_CONTEXT_COMPONENT_NAME)],
})
.with_context(|| {
format!(
"error adding route offering capability '{}' to component '{}'",
fnet_tun::ControlMarker::SERVICE_NAME,
NETWORK_CONTEXT_COMPONENT_NAME
)
})?
.... | Rust | 0 |
range.end() + T::one()..=*self.ranges[isect_last-1].end();
(isect_first+1, isect_last-1)
};
// remove ranges, shift later ranges and truncate
for (i, index) in (remove_last..self.ranges.len()).enumerate() {
self.ranges[remove_first+i] = self.ranges[index].clone();
}
let new_len = self.... | Rust | 0 |
el próximo número de comprobante
tipo_cbte = 1
punto_vta = 4000
nro = wsmtxca.ConsultarUltimoComprobanteAutorizado(tipo_cbte, punto_vta)
cbte_nro = int(nro) + 1
# obtengo CAE (sin tributos)
wsmtxca.Reprocesar = True
self.test_autorizar_comprobante(tipo_cbte, cbte... | Python | 1 |
from bevyframe import *
def post(r: Request) -> (Response, Page):
resp = redirect(f'/SendSession.py')
email = r.form['email'] if '@' in r.form['email'] else f'{r.form["email"]}@hereus.net'
if resp.login(email, r.form['password']):
return resp
else:
return get(r, message='Credentials di... | Python | 1 |
(target_os = "macos",
target_os = "bitrig",
target_os = "openbsd",
target_os = "solaris"))]
pub unsafe fn current() -> Option<Guard> {
let stackaddr = get_stack_start()? as usize;
Some(stackaddr - PAGE_SIZE..stackaddr)
}
#[cfg(any(target_os = "andro... | Rust | 0 |
######################################## #
CORS_ALLOW_ALL_ORIGINS=True
# Load the default ones
CORS_ALLOWED_ORIGINS = ["http://localhost:3000", "http://127.0.0.1:3000"]
# Leaded from Environment
CORS_ALLOWED_ORIGINS_ENV = env("CORS_ALLOWED_ORIGINS", default=None)
if CORS_ALLOWED_ORIGINS_ENV:
CORS_ALLOWED_ORIGIN... | Python | 1 |
for doc in docs:
assert doc.price != 3
@pytest.mark.parametrize(
'find_limit, filter_limit, expected_docs', [(10, 3, 3), (5, 8, 5)]
)
def test_query_builder_limits(find_limit, filter_limit, expected_docs, doc_index):
q = (
doc_index.build_query()
.filter(filter_query={'price': {'$... | Python | 1 |
import threading
import time
from typing import List
from events.base_event import BaseEvent, Priority
from game.macro import MAX_HOTKEY
from service.config_file import ACTIVE, CONFIG_FILE, DELAY, DELAY_ACTIVE, KEY, KNIFE_KEY, MACRO, MOUSE_CLICK, VIOLIN_KEY
from service.keyboard import KEYBOARD
from service.mouse im... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from wtforms.fields import TextField, HiddenField, SubmitField, SelectField, FileField
from wtforms.widgets import HiddenInput
from wtforms.validators import Required
from flask.ext.wtf import Form
from guitarfan.utilities import validator
from guitarfan.mo... | Python | 1 |
def open_or_senior(data):
output = []
for person in data:
age, handicap = person
if age >= 55 and handicap > 7:
output.append("Senior")
else:
output.append("Open")
return output | Python | 1 |
3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4,
3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4,
3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4,
3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4,
3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 2, 1
... | Rust | 0 |
ype(b"multipart/form-data").unwrap()
);
assert_eq!(
Bstr::from("multipart/form-data"),
parse_content_type(b"multipart/form-data;boundary=X").unwrap()
);
assert_eq!(
Bstr::from("multipart/form-data"),
parse_content_type(b"multipart/form-data boundary=X").unwrap()
);
... | Rust | 0 |
'3', b'5', b'3', b'6', b'4', b'0', b'4', b'1', b'4', b'2', b'4', b'3',
b'4', b'4', b'4', b'5', b'4', b'6', b'5', b'0', b'5', b'1', b'5', b'2', b'5', b'3', b'5', b'4',
b'5', b'5', b'5', b'6', b'6', b'0', b'6', b'1', b'6', b'2', b'6', b'3', b'6', b'4', b'6', b'5',
b'6', b'6',
];
pub(crate) const DIGIT_TO_BASE... | Rust | 0 |
import torch
from colossalai.legacy.zero.gemini.stateful_tensor import StatefulTensor, TensorState
class ShardedTensor(StatefulTensor):
def __init__(self, tensor: torch.Tensor, state: TensorState = TensorState.HOLD) -> None:
r"""
A tensor sharded in multiple processes. Constructed from an existin... | Python | 1 |
['spatial'].keys())[0]
spatial_coords=spatial_coords*adata.uns['spatial'][spatial_key]['scalefactors'][f'tissue_{img_key}_scalef']
plot_data=pd.DataFrame()
for ct in cell_type_columns:
if ct in adata.obs.columns:
plot_data[ct] = adata.obs[ct]
elif ct in adata.var_names:
... | Python | 1 |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | Python | 1 |
let mut a: HashSet<i32> = vec![1i32, 2, 3].into_iter().collect();
let mut b: HashSet<i32> = vec![2i32, 4, 3].into_iter().collect();
assert!(a.insert(4));
assert!(a.contains(&4));
assert!(a.contains(&3));
assert!(!a.contains(&0));
// 既に存在する値を追加すると inster() は falseを返す
// assert!(b.insert(4), "Value 4 i... | Rust | 0 |
"""Shannon SDK - Python client for Shannon multi-agent AI platform."""
__version__ = "0.1.0a1"
from shannon.client import AsyncShannonClient, ShannonClient
from shannon.models import (
Event,
EventType,
PendingApproval,
Session,
SessionSummary,
TaskHandle,
TaskStatus,
TaskStatusEnum,
)... | Python | 1 |
".labels", "w+", "utf-8") as f:
for i in xrange(1, len(revlabels)+1):
f.write("%s %d \n" % (revlabels[i], i))
# if sys.argv[1] == "prep_gen":
# generated_input = sys.argv[2]
# dict_pfx = sys.argv[3]
# output_fi = sys.argv[4]
# if len(sys.argv) > 5:
# start_after = int(sys.a... | Python | 1 |
# TA_MAType enums
MA_SMA, MA_EMA, MA_WMA, MA_DEMA, MA_TEMA, MA_TRIMA, MA_KAMA, MA_MAMA, MA_T3 = range(9)
| Python | 1 |
tIteratorStreamer(pipe.tokenizer, skip_prompt=True, skip_special_tokens=True)
# Use Thread to run generation in background
# Otherwise, the process is blocked until generation is complete
# and no streaming effect can be observed.
generation_kwargs = dict(text_inputs=messages, max_new_tokens=512, strea... | Python | 1 |
if not img_metas[0]['prev_bev_exists']:
prev_bev = None
# feature maps with strides (8, 16, 32)
img_feats = self.extract_feat(img=img, img_metas=img_metas)
losses = dict()
losses_pts = self.forward_pts_train(img_feats, gt_occ, img_metas, prev_bev)
... | Python | 1 |
ata
msghash = sha256(bytes(sign_doc)).digest()
match backend:
case 'secp256k1':
from ...secp256k1.secp256k1 import verify_sig
if not verify_sig(sig, msghash, pubkey):
raise ValueError('signature verification failed')
case 'ecdsa':
# ecdsa.keys.VerifyingKey.verify_digest():
# raises Bad... | Python | 1 |
eaders(
ResponseStartLine('', 200, 'OK'),
HTTPHeaders())
request.connection.finish()
return
message = b"Hello world"
request.write(utf8("HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n\r\n" % len(... | Python | 1 |
the entry action
pub action: SimpleAction,
/// the step selector
pub select: Vec<RequestSelectorCondition>,
/// marker for the last step
pub is_last: bool,
}
impl FlowEntry {
fn convert(rawentry: RawFlowEntry) -> anyhow::Result<FlowEntry> {
let mkey: anyhow::Result<Vec<RequestSelector>>... | Rust | 0 |
where U: IntoFuture
{
Empty,
Future(U::Future),
Stream(S),
}
impl<I, E, S, F, U> Future for StreamForEach<S, F, U>
where S: Stream<Item = I, Error = E>,
F: FnMut(I, S) -> U,
U: IntoFuture<Item = (bool, S), Error = E>
{
type Item = Option<S>;
type Error = E;
fn poll(... | Rust | 0 |
nd in intervals:
for code_point in range(i_start, i_end + 1):
face = load_glyph(code_point)
bitmap = face.glyph.bitmap
pixels = []
px = 0
for i, v in enumerate(bitmap.buffer):
y = i / bitmap.width
x = i % bitmap.width
if x % 2 == 0:
... | Python | 1 |
r_to_examine = 'C:/DMTA/projects/SD4EO/chaotic-aggregation/Cat/T31TCG/'
# folder_to_examine = 'C:/DMTA/projects/SD4EO/chaotic-aggregation/Cat/T31TDG/'
for filename_i in list_files_with_extension(folder_to_examine, '.pickle'):
full_filename = folder_to_examine + filename_i
with open(full_filename... | Python | 1 |
;", "Error: Expected string."
);
use std::collections::VecDeque;
#[derive(Debug, Clone)]
pub struct RingBuffer<T> {
capacity: usize,
buff: VecDeque<T>,
}
impl<T> RingBuffer<T> {
pub fn new(capacity: usize) -> Self {
let buff = VecDeque::with_capacity(capacity);
Self { capacity, buff }
... | Rust | 0 |
lower, None) => self.media(&format!("@media (min-width:{}px)", lower)),
}
}
pub fn only_and_above<T>(self, bp: T) -> Style
where
T: BreakpointTheme + 'static,
{
let bp_pair = with_themes(ReturnBpTuple(bp));
match bp_pair {
(lower, Some(_higher)) => self.medi... | Rust | 0 |
llections::BTreeMap;
use std::cmp::Ordering;
use byteorder::{ReadBytesExt, BigEndian};
use num_traits::NumCast;
use Error;
use super::{Value, Integer, ValueRef, Hash, Identity, Lockbox, Timestamp};
use Marker;
use MarkerType;
fn not_shortest(len: usize) -> Error {
Error::BadEncode(len, "Not shortest possible enc... | Rust | 0 |
3RSEL_A::PULL24K
}
}
#[doc = "Write proxy for field `PAD43RSEL`"]
pub struct PAD43RSEL_W<'a> {
w: &'a mut W,
}
impl<'a> PAD43RSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PAD43RSEL_A) -> &'a mut W {
{
self.bits(variant.into... | Rust | 0 |
x",
"⦼": "circled anticlockwise-rotated division sign",
"⦾": "circled white bullet",
"⦿": "circled bullet",
"⧀": "circled less-than",
"⧁": "circled greater-than",
"⧂": "circle with circle to the right",
"⧃": "circle with two horizontal strokes to the right",
... | Python | 1 |
import sqlite3
DATABASE_URL = "main.db"
def get_db():
db = getattr(g, "_database", None )
if not db:
db = g._database = sqlite3.connect(DATABASE_URL)
return db | Python | 1 |
l: SocketPool,
}
impl Shared {
fn new() -> Self {
Self {
socket_pool: SocketPool::new(),
}
}
}
pub struct EsWifi<SPI, T, CS, READY, RESET, WAKEUP>
where
SPI: SpiBus<Word = u8> + 'static,
T: Delayer + 'static,
CS: OutputPin + 'static,
READY: InputPin + InterruptPin +... | Rust | 0 |
}", &req);
#[derive(Debug, Deserialize)]
struct Items {
items: Vec<VolumeInfo>,
}
#[derive(Debug, Deserialize)]
struct VolumeInfo {
#[serde(rename = "volumeInfo")]
volume_info: GoogleBooks,
}
let response = reqwest::get(req)
... | Rust | 0 |
from time import sleep
from gefyra.types import GefyraClient, GefyraClientState
import pytest
from pytest_kubernetes.providers import AClusterManager
def test_a_create_client(operator: AClusterManager):
k3d = operator
from gefyra.api.clients import add_clients
gclient = add_clients(
"client-a", k... | Python | 1 |
jWinPitchAndFamily: u8,
pub usWinWeight: u16,
pub flInfo: u32,
pub fsSelection: u16,
pub fsType: u16,
pub fwdUnitsPerEm: i16,
pub fwdLowestPPEm: i16,
pub fwdWinAscender: i16,
pub fwdWinDescender: i16,
pub fwdMacAscender: i16,
pub fwdMacDescender: i16,
pub fwdMacLineGap: i16,... | Rust | 0 |
= time.time()
print("Image {}/{} id: {} cost time {} ms".format(index, total_nums, image_id, (end - start) * 1000.))
# post-process
detections = merge_outputs(detections, eval_config.soft_nms)
# get prediction result
pred_json = convert_eval_format(detections, image_id)
... | Python | 1 |
,
PyFuncArgs {
args: vec![repr],
kwargs: vec![],
},
)
.unwrap();
}
}
None
}
... | Rust | 0 |
import torch
import numpy as np
from lib.test.utils.match import cal_Merge
from lib.utils.box_ops import clip_box
from lib.test.utils.cal_tracker import update_xywh, update_xyxy, update
from collections import deque
def getBox(offset_map, size_map, i, j, resize_factor): # 根据特征点的位置得到框的参数
box = [(j + of... | Python | 1 |
#!/usr/bin/python3
import os, socket, argparse, logging
from channel import ICMP_Channel_Server, Channel_Transport
description = '''Start server to receive exfiltrated messages on localhost:
\tpython3 server.py -b 127.0.0.1
Start server to receive key strokes inside any input field:
\tpython3 server.py freq_en.json -... | Python | 1 |
import curses
class Col:
RESET = '\033[0m'
BOLD = '\033[1m'
FAINT = '\033[2m'
BLACK = '\033[0;30m'
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
BLUE = '\033[0;34m'
MAGENTA = '\033[0;35m'
CYAN = '\033[0;36m'
WHITE = '\033[0;37m'
class BCol:
HEADER = '\0... | Python | 1 |
from setuptools import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext_modules = [
Extension('ffm', ['fastFM/ffm.pyx'],
libraries=['m', 'fastfm'],
library_dirs=['fastFM/', 'fastFM-core/bin/'],
include_dirs=['fastFM/',... | Python | 1 |
import json
import os.path
import sys
import requests
from bs4 import BeautifulSoup as bs
from requests.structures import CaseInsensitiveDict
from httpobs.conf import SCANNER_PINNED_DOMAINS
HSTS_URL = 'https://raw.githubusercontent.com/chromium/chromium/main/net/http/transport_security_state_static.json'
def parse... | Python | 1 |
licy.Fixed
)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.spinBox_simulation_steps.sizePolicy().hasHeightForWidth())
self.spinBox_simulation_steps.setSizePolicy(sizePolicy)
self.spinBox_simulation_steps.setBaseSize(... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchlibrosa as tl
from djtransgan.config import settings
class TorchlibrosaSTFT(nn.Module):
def __init__(self,
n_fft=settings.N_FFT,
hop_length=settings.HOP_LENGTH,
sr=settings.SR,
... | Python | 1 |
s RtActivatable<IEccCurveNamesStatics>>::get_activation_factory().get_wtls12()
}
#[inline] pub fn get_x962p192v1() -> Result<HString> {
<Self as RtActivatable<IEccCurveNamesStatics>>::get_activation_factory().get_x962p192v1()
}
#[inline] pub fn get_x962p192v2() -> Result<HString> {
<Self... | Rust | 0 |
let reelstrips: [&[S]; 2] = [
&[S(9), S(11), S(2), S(33), S(24), S(5)],
&[S(10), S(1), S(2), S(3), S(4), S(5), S(6), S(7), S(8), S(9)],
];
let result = vec![
vec![S(11), S(33), S(5), S(2)],
vec![S(7), S(8), S(9), S(10)],
];
assert_e... | Rust | 0 |
import cv2
import time
from camera_handler import CameraManager
from object_detector import ObjectDetector
def main():
"""Test the camera and object detection functionality."""
print("Initializing camera...")
camera = CameraManager() # Camera is initialized in the constructor
print("Initializing ... | Python | 1 |
[offset_base]
uint16 posFormat
Offset16(Coverage) markCoverage
Offset16(Coverage) baseCoverage
uint16 markClassCount
Offset16(MarkArray) markArray
Offset16(BaseArray) baseArray
}
BaseArray [nodeserialize] [default] {
[offset_base]
[embed]
Counted(BaseRecord) baseRecords
}... | Rust | 0 |
ig {
#[doc = "< true if lcore was detected"]
pub detected: ::std::os::raw::c_uint,
#[doc = "< pthread identifier"]
pub thread_id: pthread_t,
#[doc = "< communication pipe with master"]
pub pipe_master2slave: [::std::os::raw::c_int; 2usize],
#[doc = "< communication pipe with master"]
pub... | Rust | 0 |
benchmark.curve_y,
color=colors.blue_rgb,
linewidth=2,
label=benchmark.method + f" ({benchmark.value:0.3})",
)
ax = plt.gca()
ax.set_xlabel(xlabel_names[benchmark.metric], fontsize=13)
ax.set_ylabel("Model output", fontsize=13)
ax.xax... | Python | 1 |
d: 4,
Rn: 14,
immr: 0,
imms: 15
}
);
}
#[test]
fn test_sxtw() {
// sxtw x1, w1
assert_eq!(
decode_root_unwrap(0x93407C21),
InstructionKind::SBFM64MBitfield {
Rd: 1,
Rn: 1,
immr: 0,
imms: 31
}
... | Rust | 0 |
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
ImageCms.Intent.SATURATION = 2
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
see the pyCMS documentation for details on rendering intents and what
th... | Python | 1 |
'''
EJERCICIO:
* Muestra ejemplos de asignación de variables "por valor" y "por referencia", según
su tipo de dato.
* Muestra ejemplos de funciones con variables que se les pasan "por valor" y
"por referencia", y cómo se comportan en cada caso en el momento de ser modificadas.
(Entender estos conc... | Python | 1 |
);
}
None => {
parsed.target_insert(field, value).unwrap_or_else(
|error| warn!(message = "Error updating field value", field = %field, %error)
... | Rust | 0 |
use uuid::Uuid;
/// This enum represents various keys which should
/// exist in our database. They each have a namespace
/// parameter `ns`, which indicates a common "root"
/// shared by all data for this particular prawn grow.
#[derive(Serialize, Deserialize)]
pub enum Key {
Tank {
ns: Namespace,
... | Rust | 0 |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | Python | 1 |
output_dir / f"{current_time}_{args.model}_log.txt").open("a") as f:
f.write(json.dumps(log_stats) + "\n")
total_time = time.time() - start_time
total_time_str = str(timedelta(seconds=int(total_time)))
print('Training time {}'.format(total_time_str))
if __name__ == '__main__':
par... | Python | 1 |
import pytest
from spacy.lang.da.lex_attrs import like_num
def test_da_tokenizer_handles_long_text(da_tokenizer):
text = """Der var så dejligt ude på landet. Det var sommer, kornet stod gult, havren grøn,
høet var rejst i stakke nede i de grønne enge, og der gik storken på sine lange,
røde ben og snakkede ægypti... | Python | 1 |
d xhtml 1.0 frameset//u$ -//w3c//dtd xhtml 1.0 transitional//u limited quirksu
beforeHtml(7 u* +//silmaril//dtd html pro v0r11 19970101//u4 -//advasoft ltd//dtd html 3.0 aswedit + extensions//u* -//as//dtd html 3.0 aswedit + extensions//u -//ietf//dtd html 2.0 level 1//u -//ietf//dtd html 2.0 leve... | Python | 1 |
ipe -> indication_competitions_side'
@(yield from '')
def j4i10mxo3rx(i2drbid9ajn: c84vro6_132, jo5hxbfr0r8, wqwlryaoyfl, qcknq61mbq8: m5ie4mx5mju, b82wkw_utpa: x2g3r4sq0vc, swkwur97ep8, tlfk3wlp1lx, srvflk2e1vu: wzq8hvkahsi, v7gfc9on12u: fk51go5yuy0, xe5j3p1y9uj):
assert 0.0, db65mpfe4m1
raise False
'# kno... | Python | 1 |
from pyrogram.enums import ParseMode
from AarohiX import app
from AarohiX.utils.database import is_on_off
from config import LOGGER_ID
async def play_logs(message, streamtype):
if await is_on_off(2):
logger_text = f"""
<b>{app.mention} ᴘʟᴀʏ ʟᴏɢ</b>
<b>ᴄʜᴀᴛ ɪᴅ :</b> <code>{message.chat.id}</code>
<b>ᴄʜᴀᴛ... | Python | 1 |
0.0, 1.0), result.get(0, 2));
assert_eq!(Rgb::new(0.0, 0.0, 1.0), result.get(1, 2));
assert_eq!(Rgb::new(0.0, 0.0, 1.0), result.get(0, 3));
assert_eq!(Rgb::new(0.0, 0.0, 1.0), result.get(1, 3));
assert_eq!(Rgb::new(1.0, 0.0, 1.0), result.get(2, 2));
assert_eq!(Rgb::new(1.0, 0.0, 1.0), result.get(3, 2));
a... | Rust | 0 |
def solve(grid):
ev = [i for i in range(len(grid[0])) if grid[0][i] == 2 or grid[1][i] == 2]
h = len(ev)
w = h - 1
out = [[0] * w for _ in range(h)]
mid = w // 2
out[0][mid] = 3
x = mid
for j in range(1, h):
i = ev[j]
top = grid[0][i] == 2
bot = grid[1][i] == 2
... | Python | 1 |
PartialEq for RNode {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl IntoLisp<'_> for RNode {
fn into_lisp(self, env: &Env) -> Result<Value> {
RefCell::new(self).into_lisp(env)
}
}
impl RNode {
pub fn new<'e, F: FnOnce(&'e Tree) -> Node<'e>>(tree: Shared<T... | Rust | 0 |
used_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
# expat 1.2
raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover
def defused_external_entity_ref_handler(self, context, base, sysid, pubid):
raise ExternalReferenceForbidden(conte... | Python | 1 |
.http
.use_compression
.ok_or(ConfigError::MissingFieldOrEnvVar(
"http.use_compression",
argv::env::USE_COMPRESSION,
))?;
let gzip_level = raw
.http
.gzip_level
.ok_or(ConfigError::MissingFieldO... | Rust | 0 |
: String,
pub title: String,
pub description: String,
}
#[derive(Serialize, FromRow)]
pub struct Manuscripts {
pub entries: Vec<Entry>,
}
#[derive(Deserialize)]
pub struct Parameters {
pub category: Option<Category>,
pub sort: Option<Sort>,
}
impl Responder for Manuscripts {
type Error = Erro... | Rust | 0 |
in zip(text_similarities, distances, price_differences)]
# Sort places by composite similarity score
sorted_places = [place for _, place in sorted(zip(composite_scores, data['Place']), reverse=True)]
# Return the top 10 similar places as a list of dictionaries
recommendations = [{'place': place} for ... | Python | 1 |
th {
fn div_assign(&mut self, rhs: Self) {
self.0 /= rhs.0
}
}
mod repo_with_small_packs {
use git_odb::Find;
use crate::odb::{fixture_path, hex_to_id};
#[test]
fn all_packed_objects_can_be_found() {
let store = git_odb::at(fixture_path("repos/small-packs.git/objects")).unwrap(... | Rust | 0 |
Vec<usb_sys::usbdevfs_urb>,
pub buffer: Vec<u8>,
callback: Option<Box<dyn Fn(Transfer) + Send + Sync>>,
}
/// TransferHandle is a handle that allows cancellation of in-flight transfers
/// between submit_transfer() and get_completed_transfer().
/// Attempting to cancel a transfer that has already completed is... | Rust | 0 |
);
let c = ax.powf(2.) + ay.powf(2.) - circle.r_squared;
let discriminant = b.powf(2.) - 4. * a * c;
if discriminant < 0. {
return false;
}
let sqrt_discriminant = discriminant.sqrt();
let t1 = (-b + sqrt_discriminant) / (2. * a);
let t2 = (-b - sqrt_... | Rust | 0 |
f,
cx, span, substructure)
}
#[doc = "Reader of register MODER"]
pub type R = crate::R<u32, super::MODER>;
#[doc = "Writer for register MODER"]
pub type W = crate::W<u32, super::MODER>;
#[doc = "Register MODER `reset()`'s with value 0xa800_0000"]
impl crate::ResetValue for super::MODER {
type Type = u3... | Rust | 0 |
λότης", "adēlótēs | ad-ay-lot'-ace", "uncertainty"],
"G84":["ἀδήλως", "adḗlōs | ad-ay'-loce", "uncertainly"],
"G85":["ἀδημονέω", "adēmonéō | ad-ay-mon-eh'-o", "to be in distress (of mind)"],
"G86":["ᾅδης", "háidēs | hah'-dace", "properly, unseen, i.e. \"Hades\" or the place (state) of departed souls"],
"G87":["ἀδιάκριτ... | Python | 1 |
'''Crie uma tuplapreenchida com os 20
primeiro colocados da tabelas do campeonato Brasileiro
da Futebol, na ordem de colocação. Depois mostre:
A)Apenas os 5 primeiros colocados.
b)Os ultimos 4 colocados da tabela.
c)Uma lista com os times em ordem olfabetica.
d)Em que posção na tabela está o time da Chapecoense.
'''
pr... | Python | 1 |
::ast::{Map, MapField, MapUpdate};
pub(super) fn lower_map_update_expr(
ctx: &mut LowerCtx,
b: &mut FunctionBuilder,
mut block: IrBlock,
map: &MapUpdate,
) -> (IrBlock, IrValue) {
let entry_map_val = map_block!(block, lower_single(ctx, b, block, &map.map));
let mut map_builder = b.op_map_put_bu... | Rust | 0 |
#Name: Colin Opitz
#Class: 6th Hour
#Assignment: HW24
import random, time
#1. Copy over your class from HW23 and all the functions inside of it, and alter any functions to use self if applicable.
class Character:
def __init__(self, health, damage, speed, max_health, name):
self.health = health
sel... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import arrow
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django_th.models import Digest
class Command... | Python | 1 |
no_decay.append(param)
else:
decay.append(param)
# Build Parameter Groups
groups = [{"params": decay, "weight_decay": self.weight_decay}, {"params": no_decay, "weight_decay": 0.0}]
# Create Optimizer & LR Scheduler
self.optimizer = Ad... | Python | 1 |
result = await func()
else:
result = await loop.run_in_executor(None, func)
results.append((fut, result))
except Exception as e:
fut.set_exception(e)
del aqueue[fut]
for fu... | Python | 1 |
<'reg>);
impl Registry<'_> {
/// Creates a new templates registry.
pub fn new() -> Result<Self> {
let mut handlebars = Handlebars::new();
macro_rules! template {
($path:expr) => {
handlebars.register_template_string($path, include_str!(concat!($path, ".hbs")))
... | Rust | 0 |
};
ret.push_str(&add.show_rru(mb_rru));
} else if offset == 0 {
let mov = Inst::gen_move(rd, reg, I64);
ret.push_str(&mov.show_rru(mb_rru));
} else if let Some(imm12) = Imm12::maybe_from_u64(abs_offset) {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.