text string | label_name string | labels int64 |
|---|---|---|
from .base import DyGraphTask
import numpy as np
import re
class DyGraphTaskNumEdge(DyGraphTask):
def generate_qa(self, info, *args, **kwargs):
context = info['edge_index']
context = np.array(context)
time = np.max(context[:, 2]) + 1
answer = [int(sum(context[:, 2] == t)) for t in r... | Python | 1 |
u64, index: TrieIndex, storage: SkeensMultiStorage, t: T, id: Uuid},
ReplicatedSenti{max_timestamp: u64, index: TrieIndex, storage: SkeensMultiStorage, t: T, id: Uuid},
ReplicatedSnap{max_timestamp: u64, index: TrieIndex, storage: SkeensMultiStorage, t: T, id: Uuid},
ReplicatedSingle{max_timestamp: u64, in... | Rust | 0 |
print("[epoch %d][%d/%d]%s, || Loss: %.4f || Conf Loss: %.4f"
" || Loc Loss: %.4f" % (
epoch, batch_id + 1, batch_len, suffix,
total_loss, cls_loss, reg_loss))
if not writer is None:
writer.add_scalar('Regression_los... | Python | 1 |
Ordering::Equal => {
#![cold]
return trial;
},
}
}
debug_assert!(lo == hi);
lo
}
fn swap_ends<T>(s: &mut [T], k: usize) {
// Swap front k items of sequence with back k items
debug_assert!(k > 0);
debug_assert!(k <= s.len() / 2);
let b... | Rust | 0 |
use chrono::NaiveDate;
use serde::{self, de::Error, Deserialize, Deserializer};
pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
NaiveDate::parse_from_str(&s, "%Y.%m.%d.").map... | Rust | 0 |
[(i3 + 2)..i4].parse()?,
h: s[(i4 + 1)..].parse()?,
})
}
fn interset(&self, other: &Rect) -> bool {
let x = max(self.x, other.x);
let y = max(self.y, other.y);
let w = min(self.x + self.w - x, other.x + other.w - x);
let h = min(self.y + self.h - y, other.y +... | Rust | 0 |
ttention_mask.size() != (bsz, 1, q_len, kv_seq_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights + attention_mask
# upcast at... | Python | 1 |
apitools_client.http,
batch_url=client.batch_url)
if not errors:
for invalidation_operation in resources:
log.status.write('Invalidation pending for [{0}]\n'.format(
invalidation_operation.targetLink))
log.status.write('Monitor its progress at [{0}]\n'.format(
i... | Python | 1 |
erialize(bytes)
}
// unrevised
pub fn serialized_size<T: ?Sized>(value: &T) -> Result<u64>
where
T: serde::Serialize,
{
config().serialized_size(value)
}
// unrevised
#[doc(hidden)]
pub fn with_deserializer<'a, A, R>(reader: R, acceptor: A) -> A::Output
where
A: DeserializerAcceptor<'a>,
R: BincodeRea... | Rust | 0 |
otectedContainerImportResultVtbl): IInspectable [IID_IProtectedContainerImportResult] {
fn get_Status(&self, out: *mut ProtectedImportExportStatus) -> HRESULT,
#[cfg(feature="windows-storage")] fn get_File(&self, out: *mut <super::super::storage::StorageFile as RtType>::Abi) -> HRESULT
}}
impl IProtectedContain... | Rust | 0 |
()?,
roles
))),
_ => {
println!("{:?}", response.as_str());
unimplemented!()
}
}
}
}
use crate::{CookTrait, CuisineTrait, ShanDongCook};
#[derive(Clone)]
pub struct ShanDongCuisine {
cook: ShanDongCook,
}
impl ShanDong... | Rust | 0 |
et listener = TcpListener::bind("127.0.0.1:0").unwrap();
println!("Server will listening on: {}", listener.local_addr().unwrap());
let client = SecureClient::new(
TcpStream::connect(("127.0.0.1", listener.local_addr().unwrap().port())).unwrap(),
mac_key,
ROOT_CERT,
);
let serve... | Rust | 0 |
f) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `SPI_MEM_PES_END_INT_EN... | Rust | 0 |
sockaddr_in6)).sin6_addr as *mut in6_addr
as caddr_t
}
2 => {
/* copy IPv4 address */
(*lookup_0).ph.param_type = htons(0x5u16);
p_size_0 = ::std::mem::size_of::<sctp_ipv4addr_param>() as uint16_t;
... | Rust | 0 |
#Copyright (C) 2017 Paolo Galeone <nessuno@nerdz.eu>
#
#This Source Code Form is subject to the terms of the Mozilla Public
#License, v. 2.0. If a copy of the MPL was not distributed with this
#file, you can obtain one at http://mozilla.org/MPL/2.0/.
#Exhibit B is not attached; this software is compatible with the
#lic... | Python | 1 |
multiplier = params.get("atr_multiplier", 2.0)
min_stop = params.get("min_stop_percent", 0.01)
max_stop = params.get("max_stop_percent", 0.08)
if atr > 0:
stop_distance = atr * multiplier
stop_percent ... | Python | 1 |
otides.as_slice()
}
}
#[deriving(PartialEq, Eq, Show)]
pub struct DeoxyribonucleicAcid {
nucleotides: String
}
fn transcribe_dna_rna(c: char) -> char {
match c {
'C' => 'G',
'G' => 'C',
'A' => 'U',
'T' => 'A',
_ => c
}
}
impl DeoxyribonucleicAcid {
pub fn... | Rust | 0 |
failed = true;
}
rsDebug("broken", 'y');
temp_sc2 = min( rand_sc2_0, rand_sc2_1 );
if (temp_sc2.x != min_rand_sc2_sc2.x
|| temp_sc2.y != min_rand_sc2_sc2.y) {
failed = true;
}
return failed;
}
void bug_char_test() {
bool failed = false;
failed |= test_bug... | Rust | 0 |
}
}
/// Return the `x` coordinate of this window relative to its parent window.
pub fn getparx(handle: WINDOW) -> result!(i32) {
let x = unsafe { ncurses::getparx(handle) };
if x.is_negative() {
Err(ncurses_function_error_with_rc!("getparx", x))
} else {
Ok(x)
}
}
/// Return the `... | Rust | 0 |
from path_finder import PathFinder
from PIL import Image
from pathlib import Path
#전체 이미지 크기 4056x3040
# PathFinder 인스턴스 생성
path_finder = PathFinder()
# 경로를 Path 객체로 변환
original_image_dir = Path(path_finder.tcx_image_dir_path)
# 원본 이미지 파일 경로
input_image_path = original_image_dir / 'test.jpg'
# 크롭된 이미지를 저장할 파일 경로
# ou... | Python | 1 |
";
<filename>graph-builder/tests/mod.rs<gh_stars>0
#[cfg(feature = "test-e2e")]
mod e2e;
// Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
use dyn_clone::DynClone;
use crate::cmds::Writer;
use crate::error::Result;
pub trait Command: DynClone {
fn name(&self) -> &str;
fn... | Rust | 0 |
ename"), field.get::<&str, LuaString>("data"))
{
let data = data.as_bytes().to_owned();
settings.attachments.push((filename, data));
}
}
}
}
Ok(settings)
}
pub fn bot_flags(state: &Lua, bot_tbl: &LuaTable) -> Result<()... | Rust | 0 |
let guard = x.lock().unwrap();
*guard += 1;
}
bar.await;
}
let _1 = 1; //VIOLAZ
let __22_1 = 1; //VIOLAZ
let __1___2 = 11; //VIOLAZ
let _ = mutex.lock(); //VIOLAZ
let _lock = mutex.lock(); //OK
#[macro_use] //VIOLAZ
use some_macro;
fn main() {
main(); //VIOLAZ
}
fn main() {
#!... | Rust | 0 |
&self.contacts
}
}
#[doc(hidden)]
pub struct RTDChangeImportedContactsBuilder {
inner: ChangeImportedContacts,
}
impl RTDChangeImportedContactsBuilder {
pub fn build(&self) -> ChangeImportedContacts {
self.inner.clone()
}
pub fn contacts(&mut self, contacts: Vec<Contact>) -> &mut ... | Rust | 0 |
now
if python_version >= '2.6':
base_modules += ['json', 'multiprocessing']
base_modules = list(set(base_modules).difference(set(py26_deprecated)))
if python_version >= '2.7':
base_modules += ['argparse']
base_modules = list(set(base_modules).difference(set(py27_deprecated)))
# Now iterate in the bas... | Python | 1 |
ADDR_HIGH0_R {
MAC_ADDR_HIGH0_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15"]
#[inline(always)]
pub fn mac_addr_high0(&mut self) -> MAC_ADDR_HIGH0_W {
MAC_ADDR_HIGH0_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub un... | Rust | 0 |
account_moves._post()
def out5(self):
Product = self.env['product.product']
# For store to supplier
move_vals_list = []
in_stock_valuation_layers = self.env['stock.valuation.layer'].search([('stock_move_id', '!=', False), ('description', 'like', 'COI/LI/22/00007%')])
move... | Python | 1 |
PROP_JAM_DETECT_HISTORY_BITMAP: ::std::os::raw::c_uint = 4613;
#[doc = " Channel monitoring sample interval"]
#[doc = "** Format: `L` (read-only)"]
#[doc = "* Units: Milliseconds"]
#[doc = "*"]
#[doc = "* Required capability: SPINEL_CAP_CHANNEL_MONITOR"]
#[doc = "*"]
#[doc = "* If channel monitoring is enabled and act... | Rust | 0 |
if status[i]:
prevPoints.append(self.prevKeyPoints[i])
currPoints.append(matchedKeypoints[i])
prevPoints = np.array(prevPoints)
currPoints = np.array(currPoints)
# Find rigid matrix
if (prevPoints.shape[0] > 4) and (prevPoints.shape[0] == currPoints.shap... | Python | 1 |
use tokio::task;
// MQTT related
use librumqttd::async_locallink::construct_broker;
// Error
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("{source}")]
SendError {
#[from]
source: flume::SendError<Event>,
},
// #[error("{source}")]
// TokioError {
// ... | Rust | 0 |
# -*- coding: utf-8 -*-
from odoo import models
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
def session_info(self):
result = super(IrHttp, self).session_info()
result['is_quick_edit_mode_enabled'] = self.env.user._is_internal() and self.env.company.quick_edit_mode
return ... | Python | 1 |
#!/usr/bin/env python
import numpy as np
from scipy.io import loadmat
from numpy import savez_compressed
def _mean(a, axis=None, *args, **kwargs):
"""Equivalent to numpy.mean except that the axis along which the mean is taken is not removed."""
rv = np.mean(a, axis=axis, *args, **kwargs)
if axis is not ... | Python | 1 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
curr = head
prev = None
while curr:
temp ... | Python | 1 |
apacity': 1800,
'max_egg_capacity': 3000,
'max_delivery_distance': 3000,
'min_hub_cost': 3000,
'max_hub_cost': 10000,
'min_link_cost': 1225,
'max_link_cost': 3000,
'min_hub_capacity': 562,
'max_hub_capacity': 750,
}
optimizer = MoreComplexEggDistr... | Python | 1 |
0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
// }}}
// {{{ 4. Process Message in 16-Word Blocks
let mut rdr = Cursor::new(buf);
// Process each 16-word block.
while rdr.position() < buf_len {
let mut x : [u32; 16] = unsafe { mem::uninitialized() };
... | Rust | 0 |
# inactive_bg = colors[1],
# inactive_fg = colors[0],
# padding_left = 8,
# padding_x = 8,
# padding_y = 6,
# sections = ["ONE", "TWO", "THREE"],
# section_fontsize = 10,
# section_fg = colors[7],
# section_top = 15,
# section_bottom = 15,
... | Python | 1 |
o| &o.raw as *const _).unwrap_or(ptr::null());
unsafe {
try_call!(raw::git_describe_format(buf.raw(), self.raw, opts));
}
Ok(String::from_utf8(buf.to_vec()).unwrap())
}
}
impl<'repo> Binding for Describe<'repo> {
type Raw = *mut raw::git_describe_result;
unsafe fn from_... | Rust | 0 |
from __future__ import absolute_import
import os
import sys
import json
from todo.commands.base import Command
from todo.utils.styles import Fore, Style
class RenameCommand(Command):
def rename_project(self, data):
"""Returns the project with the new name"""
data_copy = data.copy()
new_n... | Python | 1 |
# coding:陈小斌
# GitHub:doFighter
import numpy as np
def VPSO(N, dim, x_min, x_max, iterate_max, fitness):
"""
VPSO算法:带有收缩因子的粒子群优化算法(DOI:10.1109/CEC.2002.1004493)
:param N: 粒子数目
:param dim: 问题维度
:param x_min: 搜索空间下限
:param x_max: 搜索空间上限
:param iterate_max: 最大迭代次数
:param fitness: 评价函数
... | Python | 1 |
or is_rule_suboption_set(rule, "xbits", "isnotset")
)
):
issues.append(
Issue(
code="S521",
message="""\
The rule (un)sets a xbit but does not use the noalert option.
Consider using the noalert option to prevent unnecessary alert... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Union
from .base import TelegramMethod
class EditForumTopic(TelegramMethod[bool]):
"""
Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to wor... | Python | 1 |
# parol = input()
# parol_2 = input()
#
#
# if parol == parol_2:
# print("Пароль принят")
# else:
# print("Пароль не принят")
# a = int(input())
#
# div, mod = divmod(a, 2)
# if mod > 0:
# print("Нечетное")
# else:
# print("Четное")
#
# s = int(input())
# t = n // 1000
# s = (n % 1000) // 100
# d = (n %... | Python | 1 |
txt is an existing logical file"
)]
fn copy_should_reject_conflicting_files() {
let root = TempDir::new().unwrap();
let temp = TempDir::new().unwrap();
let repo = default_repo(root.path());
let object_id = "conflicting";
repo.create_object(object_id, DigestAlgorithm::Sha512, "content", 0)
... | Rust | 0 |
ail.
fn test_file_truncate_for_nonwritable_file() {
let filename = "file.txt";
let mut memnode =
MemNode::new(1, filename, FileModes::S_IRUSR.into(), FileType::File).unwrap();
assert_eq!(memnode.file_truncate(), Err(KError::PermissionError));
}
}
use anyhow::{Error, Result};
... | Rust | 0 |
up_event(&mut self, ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) {
self.scene_manager.on_key_up(ctx, keycode, keymod, repeat);
}
fn controller_button_down_event(&mut self, ctx: &mut Context, btn: Button, ctrl_id: i32) {
self.scene_manager
.on_controller_button_dow... | Rust | 0 |
ef().map(|x|{
_fbb.create_string(x)
});
let position_tmp = self.position.as_ref().map(|x| x.pack());
let position = position_tmp.as_ref();
let world_name = self.world_name.as_ref().map(|x|{
_fbb.create_string(x)
});
let data = self.data.as_ref().map(|x|{
_fbb.create_string(x)
... | Rust | 0 |
if len(labels) == 0:
print(f"Skipping ROC for {file}: No labels collected.")
continue
fpr, tpr, thresholds = roc_curve(labels, predictions)
eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0.0, 1.0)
export["File"].append(os.path.basename(file))
... | Python | 1 |
nviron.get('TEST_RERANKER_ID', '3'))
def assert_response_shape(
response: dict | None,
*,
require_status: int | None = 200,
require_code: str | None = "SUCCESS",
custom_shape: Type["T"] | None = None
) -> "T":
"""
Assert the response shape is correct
:param respons... | Python | 1 |
, s: &str) -> core::fmt::Result {
for b in s.bytes() {
if self.offs < self.buf.len() {
self.buf[self.offs] = b;
self.offs += 1;
} else {
break;
}
}
Ok(())
}
}
<filename>src/uhm.rs
/*
.uhm files consist of 1... | Rust | 0 |
"""
Этот модуль реализует функцию, которая запрашивает локальную языковую модель с целью получения ответов на вопросы.
Он использует библиотеку `loguru` для логирования процесса, отслеживая этапы выполнения
и результаты промежуточных вычислений.
Модуль сконфигурирован на работу с моделью обработки естественного языка и... | Python | 1 |
able](index.html) module"]
pub struct WAYENABLE_SPEC;
impl crate::RegisterSpec for WAYENABLE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [wayenable::R](R) reader structure"]
impl crate::Readable for WAYENABLE_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [wayenable::W](W) writer s... | Rust | 0 |
# Pablo Gainza 2019 - Assign the raw data from Intpred's webserver to each PDB's b factor column.
# Also, verify the data.
import numpy
from Bio.PDB import *
from IPython.core.debugger import set_trace
def parse_psiver_raw(pdbid, filename):
pvfile = open(filename)
lines = pvfile.readlines()
line_ix = ... | Python | 1 |
)]
pub fn variant(self, variant: THSEL4_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "1 ADC clock cycle."]
#[inline(always)]
pub fn _1_adc_clk(self) -> &'a mut W {
self.variant(THSEL4_A::_1_ADC_CLK)
}
#[doc = "2 ADC clock cycles."]
#[inlin... | Rust | 0 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
##declare dictionary to store ... | Python | 1 |
import pytest
import os
@pytest.fixture(scope='session')
def datafile():
pwd = os.path.dirname(os.path.abspath(__file__))
def fullpath(fn):
return os.path.join(pwd, "data", fn)
return fullpath
@pytest.fixture
def show():
def __show__(name, arr):
print(name + ": [" + ", ".... | Python | 1 |
}
if let Phase::Fly(_) = b.phase {
panic!("{} should be resting.", b.name);
}
}
#[test]
fn part_two() {
let mut reindeers = Vec::new();
let a = Reindeer::new(&"Comet".to_string(), 14, 10, 127);
let b = Reindeer::new(&"Dancer".to_string(), 16, 11, 162);
reindeers.push(a);
rein... | Rust | 0 |
# factorial = 4
# num = 3
# for i in factorial:
# factorial = factorial * num
# num = num - 1
# print("The factorial of the number is ", factorial)
factorial = 3
num = 4
for i in range(1, num + 1):
factorial *= i
print("The factorial of the number is", factorial)
| Python | 1 |
from unittest import TestCase, main
import sys
sys.path.append("src")
sys.path.append("../src")
from utils import bits_le_with_width, pow_2, is_power_of_two, next_power_of_two, log_2
class TestUtils(TestCase):
def test_bits_le_with_width(self):
self.assertEqual(bits_le_with_width(5, 4), [1, 0, 1, 0])
... | Python | 1 |
listener.incoming().next().unwrap()?;
println!("Incoming...");
let mut line = String::new();
let mut reader = BufReader::new(stream.try_clone().unwrap());
reader.read_line(&mut line).unwrap();
Ok(line)
}()));
// Wait fot the listener
... | Rust | 0 |
XMM22
| Reg::YMM22
| Reg::ZMM22
| Reg::XMM23
| Reg::YMM23
| Reg::ZMM23
| Reg::XMM24
| Reg::YMM24
| Reg::ZMM24
| Reg::XMM25
| Reg::YMM25
| Reg::ZMM25
| Reg::XMM26
| ... | Rust | 0 |
_independent_resources: DeviceIndependentResources,
device_dependent_resources: DeviceDependentResources,
) -> Self {
Self {
dpi,
device_independent_resources,
device_dependent_resources,
}
}
fn render(&mut self) {
unsafe { self.device_dep... | Rust | 0 |
reading Send Error: {0:?}")]
SendError(String),
#[error("DF Transforms Error")]
TransformError(#[from] crate::transforms::TransformError),
#[error("DF Augmentation Error")]
AugmentationError(#[from] crate::augmentations::AugmentationError),
#[error("DF Utils Error")]
UtilsError(#[from] crate... | Rust | 0 |
art()
audio_input_thread.start()
video_thread.start()
audio_thread.start()
text_thread.start()
# wait for threads to finish executing
audio_callback_thread.join()
audio_input_thread.join()
video_thread.join()
audio_thread.join()
text_thread.join()
logger.info('Waiting for f... | Python | 1 |
output: &::I16x64,
definition: Named("llvm.hexagon.V6.vunpackb")
},
"Wuh_vunpack_Vub64" => Intrinsic {
inputs: { static INPUTS: [&'static Type; 1] = [&::U8x64]; &INPUTS },
output: &::U16x64,
definition: Named("llvm.hexagon.V6.vunpackub")
... | Rust | 0 |
Floor {
let width = input.find('\n').unwrap();
let heightmap = input
.lines()
.flat_map(|l| l.chars())
.map(|c| c.to_digit(10).unwrap())
.collect();
Floor { heightmap, width }
}
pub fn part_1(floor: &Floor) -> u32 {
(0..floor.heightmap.len()).fold(0, |risk, i| risk + f... | Rust | 0 |
::{Rejection, Reply};
// Handles GET endpoint documented at https://docs.docker.com/registry/spec/api/#manifest
pub async fn handle_get_manifests(name: String, tag: String) -> Result<impl Reply, Rejection> {
let colon = tag.find(':');
let mut hash = String::from(&tag);
if colon == None {
let manife... | Rust | 0 |
uct KeyInfoJson(#[serde(with = "self")] pub KeyInfo);
/// Wrapper for serializing a SignedMessage reference to JSON.
#[derive(Serialize)]
#[serde(transparent)]
pub struct KeyInfoJsonRef<'a>(#[serde(with = "self")] pub &'a KeyInfo);
impl From<KeyInfoJson> for KeyInfo {
fn from(key: KeyInfoJ... | Rust | 0 |
each(|cap, data| {
data.swap(&mut buffer);
count += buffer.len();
output.session(&cap).give_vec(&mut buffer);
});
if let Some(f) = input.frontier.frontier().get(0) {
println!("{}|{}|{}|{}", index, f.first, t... | Rust | 0 |
np.int64)
edge_attr = edge_attr.astype(np.float64)
hit_ids = hit_ids.astype(np.int64)
numba_edges = Dict.empty(key_type=types.int64, value_type=inner_dict_type)
for i in range(len(edge_index_src)):
src = hit_ids[edge_index_src[i]]
dst = hit_ids[edge_index_dst[i]]
attr = edge_at... | Python | 1 |
imal>
<leadingDecimalPoint>0.8675309</leadingDecimalPoint>
<andTrailing>8675309</andTrailing>
<positiveSign>1</positiveSign>
<trailingComma>in objects</trailingComma>
<andIn>arrays</andIn>
<andIn>arrays-2</andIn>
<backwardsCompatible>with JSON</backwardsCompatible>
</MyStruct>"#;
// Content... | Rust | 0 |
import pytest
from pyknow.matchers.rete import utils
def test_prepare_rule_is_dnf():
from pyknow import Rule, NOT, AND, OR, Fact
from pyknow.matchers.rete.dnf import dnf
rule = Rule(AND(Fact(0), NOT(OR(Fact(1), Fact(2)))))(lambda:None)
assert list(utils.prepare_rule(rule)) == [Fact(0),
... | Python | 1 |
import os
import argparse
def encode_label(label, num_sm, bits):
num_steps = (2**bits) -1
if num_steps == 0:
return 0
step = num_sm // num_steps
return label * step
def create_label_files(bin_file_path, output_dir, bits_list, num_sm):
# read bin file and create label using given bits list
... | Python | 1 |
inish_impl(&self, for_twitter: bool) -> OAuthAuthorizationHeader {
let tmp_timestamp = self.timestamp.unwrap_or_else(gen_timestamp).to_string();
let tmp_nonce;
let oauth_params = {
let mut p = Vec::with_capacity(8);
p.push(("oauth_consumer_key", self.consumer_key.borrow(... | Rust | 0 |
min >= i32::MIN as f64 && max <= i32::MAX as f64 => {
let arr: PrimitiveArray<Int32Type> = arr
.into_iter()
.map(|v| v.map(|v| transcoder.encode(v)))
.collect();
let enc: Box<dyn ScalarEncoding<f64>> = if rle {
Box::new(RLE::new_fro... | Rust | 0 |
});
let actual =
check_sender_or_receiver(&data_decoded, "0x1230B3d59858296A31053C1b8562Ecf89A2f888b");
assert!(actual);
}
#[test]
fn check_sender_or_receiver_data_decoded_none() {
let data_decoded: Option<DataDecoded> = Option::None;
let actual = check_sender_or_receiver(&data_decoded, "");
... | Rust | 0 |
let ptr = addresses_ptr.offset(i as isize);
ffi::CString::from_raw(*ptr);
};
}
}
// Copyright 2020 <NAME>
// SPDX-License-Identifier: Apache-2.0
// (Re-)generated by schema tool
// >>>> DO NOT CHANGE THIS FILE! <<<<
// Change the json schema instead
#![allow(dead_code)]
#![allow(unused_im... | Rust | 0 |
ry(
key_properties=unique_constraints,
metadata=metadata,
replication_method=REPLICATION_METHOD_FULL_TABLE,
schema=schema,
stream=stream_id,
tap_stream_id=stream_id,
unique_conflict_method=UNIQUE_CONFLICT_MET... | Python | 1 |
id, _)| id.0);
for (key,value) in &a {
writeln!(f, "{} := {},", key.0, value).ok();
}
Ok(())
}
}
use std::convert::TryFrom;
/// Represents either the constant *zero clock* or a *clock variable*.
#[derive(Clone, Eq, PartialEq, Hash, Copy, Debug)]
#[repr(transparent)]
pub struct ... | Rust | 0 |
"id": rand::random_string(20)
}).to_string()
}
#[inline]
pub fn with_storage(storage: &str) -> String {
json!({
"id": rand::random_string(20),
"storage_type": storage,
}).to_string()
}
#[inline]
pub fn with_custom_path<P: AsRef<Path>>... | Rust | 0 |
[1] as i8) - 50,
key_scaling: (data[2] as i8) - 50,
}
}
fn to_bytes(&self) -> Vec<u8> {
vec![
(self.attack_velocity + 50).try_into().unwrap(),
(self.release_velocity + 50).try_into().unwrap(),
(self.key_scaling + 50).try_into().unwrap(),
]... | Rust | 0 |
dexedIndirect {}
impl ANDAddressMode for IndirectIndexed {}
pub(crate) struct AND<T: ANDAddressMode>(pub T);
impl<T: ANDAddressMode> Instruction for AND<T>
where
AND<T>: Renderable,
{
fn evaluate(&self, memory: &mut Memory, registers: &mut Registers) {
let value = self.0.read(memory, registers);
registers... | Rust | 0 |
path,
extras: bone_name,
}
}
}//! Support for the `r2d2` connection pool.
#[cfg(feature = "mysql-16")]
pub mod mysql;
#[cfg(feature = "postgresql-0_16")]
pub mod postgres;
#[cfg(feature = "rusqlite-0_19")]
pub mod sqlite;
use std::path::PathBuf;
/// An `r2d2::ManageConnection` for all ... | Rust | 0 |
from django import forms
from .models import Contact
class NameForm(forms.Form):
your_name = forms.CharField(label="Seu nome", max_length=100)
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = "__all__"
| Python | 1 |
# dispatches to _socket for actual implementation
from _socket import (
socket, error, herror, gaierror, timeout, has_ipv6,
create_connection,
getdefaulttimeout,
setdefaulttimeout,
getfqdn,
gethostbyaddr,
gethostbyname,
gethostbyname_ex,
gethostname,
getprotobyname,
g... | Python | 1 |
020}\u{043A}\u{0430}\u{0442}\u{0443}\u{0443}\u{0020}\u{0442}\
\u{0430}\u{043B}\u{043A}\u{0443}\u{0443}\u{0020}\u{0436}\u{04AF}\u{0440}\u{04AF}\
\u{043F}\u{002C}\u{0020}\u{0031}\u{0039}\u{0034}\u{0030}\u{0020}\u{0436}\u{044B}\
\u{043B}\u{0434}\u{0430}\u{043D}\u{0020}\u{043A}\u{0438}\u... | Rust | 0 |
ble ICMP messages must be generated:
// "If no Neighbor Advertisement is received after MAX_MULTICAST_SOLICIT
// solicitations, address resolution has failed. The sender MUST return
// ICMP destination unreachable indications with code 3
// (Address Unreachable) for each packet queued awaiting addre... | Rust | 0 |
Clone)]
pub struct FinalizedDiagMapWasm {
inner: Box<[u8]>,
generated_history: Box<[usize]>,
expanded_history: Box<[usize]>,
num_generated_history: Box<[u8]>,
}
#[wasm_bindgen]
impl FinalizedDiagMapWasm {
pub fn inner(&self) -> Box<[u8]> {
self.inner.clone()
}
pub fn generated_history(&self... | Rust | 0 |
import unittest
import torch
from PIL import Image
from app.models.machine_learning import Model
class TestModel(unittest.TestCase):
def setUp(self):
self.model = Model()
def test_process_image(self):
img = Image.open("tests/test_images/binoculars.png")
img_t = self.model.process_im... | Python | 1 |
CommittedCandidateReceipt` pending availability for the para provided, if any.
pub(crate) fn candidate_pending_availability(
para: ParaId,
) -> Option<CommittedCandidateReceipt<T::Hash>> {
<PendingAvailability<T>>::get(¶)
.map(|p| p.descriptor)
.and_then(|d| <PendingAvailabilityCommitments<T>>::get(&par... | Rust | 0 |
# compare diffs between .svg files
import os
import sys
import glob
import subprocess
if (len(sys.argv) < 3):
usage_str = "Usage: %s <dir1> <dir2>" % (sys.argv[0])
print(usage_str)
print("e.g.: python test_diff_svg.py ~/blah1 ~/blah2")
exit(1)
else:
dir1 = sys.argv[1]
dir2 = sys.argv[2]
svg_files = gl... | Python | 1 |
"""
This example shows how to get the standings of a tournament.
In this case, we get the standings of the last season of the UEFA Champions League.
The tournament id is 7 and the last season id is 61644.
Example output:
1. Liverpool 21 points
Matches: 8 Wins: 7 Draws: 0 Losses: 1
2. Barcelona 19 points
Matches: 8 W... | Python | 1 |
from . import waveform_extractor
| Python | 1 |
, safe, addition: neither `self` nor `other` can be the neutral
/// element, and other != ±self.
pub fn double_and_add<CS: ConstraintSystemAbstract<ConstraintF>>(
&self,
cs: CS,
other: &Self,
) -> Result<Self, SynthesisError> {
self.double_and_add_internal(cs, other, true)
... | Rust | 0 |
tempdisk).unwrap();
assert_eq!(h.signature, new_primary.signature);
assert_eq!(h.revision, new_primary.revision);
assert_eq!(h.header_size_le, new_primary.header_size_le);
assert_eq!(h.reserved, new_primary.reserved);
assert_eq!(h.current_lba, new_primary.current_lba);
assert_eq!(h.backup_lba, ... | Rust | 0 |
refactor to get rid of the redundant fields.
#[derive(Clone, Debug)]
pub enum Bundle {
Read { source: Source, input: Input },
Parsed { source: Source, line_map: LineMap, node_id_generator: NodeIdGenerator, tree: Located<Root> },
Prenamed { source: Source, line_map: LineMap, node_id_generator: NodeIdGenerat... | Rust | 0 |
--------------------------------
/// Trait for checking whether a point is on the curve.
///
/// This trait is only for debugging/testing, since it should be
/// impossible for a `curve25519-dalek` user to construct an invalid
/// point.
pub(crate) trait ValidityCheck {
/// Checks whether the point is on the curve... | Rust | 0 |
### Escaneador de usuarios en red Wifi ###
from scapy.all import ARP, Ether, srp
import socket
def obtener_nombre(ip):
try:
# se realiza una búsqueda inversa de DNS para obtener el nombre del dispositivo
nombre = socket.gethostbyaddr(ip)[0]
except socket.herror:
nombre = "Nombre descon... | Python | 1 |
_PKEY_get_bits(key: *const EVP_PKEY) -> c_int;
}
#[inline]
pub unsafe fn EVP_PKEY_id(pkey: *const EVP_PKEY) -> c_int {
EVP_PKEY_get_id(pkey)
}
#[inline]
pub unsafe fn EVP_PKEY_bits(pkey: *const EVP_PKEY) -> c_int {
EVP_PKEY_get_bits(pkey)
... | Rust | 0 |
# scripts/visualization.py
# # Lighter Phase
# # # # # Analyzes the transcript chunks and returns the analysis results.
# # # # # The analysis results include the sentiment scores and keyword counts.
# # # # # The analysis results are saved to a JSON file.
import os, json, time
from datetime import datetime
import ma... | Python | 1 |
from rest_framework import serializers
from .models import Examen
class ExamenSerializer(serializers.ModelSerializer):
class Meta:
model = Examen
fields = ['id','paciente_id','archivo']
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.