text string | label_name string | labels int64 |
|---|---|---|
import pkgutil
from scattertext.Common import SEMIOTIC_SQUARE_HTML_PATH
class ClickableTerms:
@staticmethod
def get_clickable_lexicon(lexicon, plot_interface='plotInterface'):
out = []
for term in lexicon:
clickable_term = ClickableTerms.get_clickable_term(term, plot_interface)
out.append(clickable_term)... | Python | 1 |
DateTime, Local};
const PROC_CONFIG_GZ: &str = "/proc/config.gz";
const BOOT_CONFIG: &str = "/boot/config";
trait IntoOption<T> {
fn into_option(t: Self) -> Option<T>;
}
impl<T> IntoOption<T> for Option<T> {
fn into_option(t: Option<T>) -> Option<T> {
t
}
}
impl<T, R> IntoOption<T> for Result<T,... | Rust | 0 |
from datetime import datetime, timedelta, timezone
import pytest
from bs4 import BeautifulSoup
from app import create_app, db
from app.models.game import Game
from app.models.user import User
@pytest.fixture
def app():
app = create_app({
"TESTING": True,
"WTF_CSRF_ENABLED": False,
"SQLAL... | Python | 1 |
to serialize");
let mut expected = TimeBalance::new();
expected.insert(utc_dt, dur);
assert_eq!(balance, expected);
}
#[test]
fn to_json_works() {
let mut balance = TimeBalance::new();
let naive = NaiveDate::from_ymd(2021, 1, 27).and_hms(14, 19, 21);
let utc... | Rust | 0 |
= eutils::to_complex(&eutils::sin(&t, f0));
// apply FFT using multi-threading
let mut planner = FFTplanner::<f32>::new(false);
let fft: Arc<dyn FFT<f32>> = planner.plan_fft(size);
let x_arc = Arc::new(Mutex::new(x));
let x_f_arc = Arc::new(Mutex::new(Vec::<Vec<Complex32>>::new()));
l... | Rust | 0 |
ort time
from mpi4py_fft import generate_xdmf
t0 = time()
N = (128, 32, 4)
config['optimization']['mode'] = 'cython'
d = {
'N': N,
'Re': 8000.,
'dt': 0.001,
'filename': f'KMM_OS_{N[0]}_{N[1]}_{N[2]}',
'conv': 0,
'modplot': 100,
'modsave': 1000,... | Python | 1 |
# SPDX-FileCopyrightText: 2020 Jim Bennet for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`quote`
================================================================================
The quote function %-escapes all characters that are neither in the
unreserved chars ("always safe") nor the additional chars ... | Python | 1 |
milyName)
if thisFont.filepath:
print(thisFont.filepath)
else:
print("⚠️ The font file has not been saved yet.")
print()
# read out user settings:
particle = self.pref("particle")
shouldAddParticle = self.pref("subtractOrAdd")
elidablePart = self.pref("elidablePart")
includeIn... | Python | 1 |
ould
be taken into accout according to the `max_history` setting. If all events
should be taken into account, the return value is `None`.
"""
if not max_history:
return None
num_events = 0
num_actions = 0
for event in reversed(tracker.applied_events()):
num_events += ... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from ..builder import ARCHITECTURES
from .base import BaseArchitecture
@ARCHITECTURES.register_module()
class MMClsArchitecture(BaseArchitecture):
"""Architecture based on MMCls."""
def __init__(self, **kwargs):
super(MMClsArchitecture, self).__init__(**... | Python | 1 |
#!/usr/bin/env python3
"""
Test walk generation starting FROM a repeater to ensure cycles complete.
"""
import sys
from pathlib import Path
# Add GraphVerse to path
sys.path.insert(0, str(Path(__file__).parent))
from graphverse.graph.base import Graph
from graphverse.graph.rules import RepeaterRule
from graphverse.g... | Python | 1 |
import requests
class URLFetcher:
def __init__(self, base_url, user_agent):
"""
Initializes the URLFetcher with a base URL and user-agent.
Parameters:
base_url (str): The base URL for the API.
user_agent (str): The user-agent string to be used for the requests.
"""
... | Python | 1 |
# Convert image tensor to latent space
latent = image_tensor * 2 - 1 # Scale to [-1, 1]
# Ensure the latent is in the shape [B, C, H, W]
if latent.dim() == 3:
latent = latent.unsqueeze(0)
# If we have 3 channels, repeat one channel to get 4
... | Python | 1 |
the differential coding/decoding\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MODE2_DIFF_CODING_A {
#[doc = "0: `0`"]
MODE2_DIFF_CODING_DEFAULT = 0,
}
impl From<MODE2_DIFF_CODING_A> for bool {
#[inline(always)]
fn from(variant: MODE2_DIFF_CODING_A) -> Self {
variant ... | Rust | 0 |
效选择,请重新输入")
continue
# 询问是否继续
if choice in ['1', '2']:
again = input("\n🔄 是否尝试其他模式?(y/n): ")
if again.lower() != 'y':
print("\n👋 感谢体验AI思维可视化演示!")
break
except KeyboardInterrupt... | Python | 1 |
# <additional-imports>
from pathlib import Path
import pandas as pd
import rio
from . import data_models, persistence
# </additional-imports>
# <additional-code>
def on_app_start(app: rio.App) -> None:
"""
A function that runs when the app is started.
"""
# Create a persistence instance. This clas... | Python | 1 |
the initial trusted state to initialize the node with"
)]
pub height: u64,
#[options(
free,
help = "hash of the initial subjectively trusted header to initialize the node with"
)]
pub header_hash: String,
}
impl Runnable for InitCmd {
fn run(&self) {
let subjective_hea... | Rust | 0 |
hema_description = "instance 2"
live_storage.save_schema(schema_2)
assert live_storage.is_live_schema_committed("simple")
# content replaces in place
assert schema._schema_description == "instance 2"
assert mod_hash in schema.previous_hashes
def test_live_schema_getter_when_committed(live_storage:... | Python | 1 |
def __init__(self, model, schedule='linear', **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
| Python | 1 |
import os
from unittest import TestCase
from unittest import mock
from .test_s3_blobstore import S3_STORAGE_VCAP_EXAMPLE
from buildpack import util
from buildpack.infrastructure import storage
from lib.m2ee.version import MXVersion
class M2EEMock:
class ConfigMock:
def __init__(self):
self._c... | Python | 1 |
inline]
fn value(&self) -> Result<Self::Value, SynthesisError> {
match (self.c0.value(), self.c1.value()) {
(Ok(c0), Ok(c1)) => Ok(QuadExtField::new(c0, c1)),
(..) => Err(SynthesisError::AssignmentMissing),
}
}
}
impl<BF, P> From<Boolean<P::BasePrimeField>> for QuadExtVa... | Rust | 0 |
import functools
from scipy._lib._array_api import (
is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API
)
import numpy as np
from ._ndimage_api import * # noqa: F403
from . import _ndimage_api
from . import _delegators
__all__ = _ndimage_api.__all__
MODULE_NAME = 'ndimage'
def _maybe_convert_arg(arg, xp):... | Python | 1 |
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.security import verify_token
from app.models import User
security = HTTPBearer()
async def get_curre... | Python | 1 |
class A(object):
_test = '1'
__test = '2'
class B(A):
def _print(self):
print(self._test)
def __print(self):
print(self)
a = A()
a._
print(a._test)
print(a._A__test)
b = B()
b.print_()
b.print__() | Python | 1 |
DOTALL | MULTILINE)
value = compile(r"(PK_[A-Z_]+_ENUM_[A-Z0-9_]+),\s+\"([^\"]+)\"")
enum_c_name = sys.argv[2]
inp = pathlib.Path(enum_c_name).read_text()
for (name, data) in enum.findall(inp):
for (enum_name, string) in value.findall(data):
enum_to_string[enum_name]... | Python | 1 |
self.CLKT.modify(CLKT::TOUT.val(0)); //Turn off clock stretching since it's buggy.
self.C.write (
C::I2CEN::SET + //Enable I2C
C::CLEAR::SET //Clear the FIFO.
);
self.S.modify (
S::CLKT::SET + //Reset clock timeout.
S::ERR::SET + //Reset... | Rust | 0 |
# memory_manager.py
import chromadb
from sentence_transformers import SentenceTransformer, CrossEncoder
from typing import List, Dict
class MemoryManager:
def __init__(self):
"""
初始化MemoryManager。
这个过程会在服务器启动时执行一次。
"""
print("正在初始化MemoryManager...")
# 1. 加载嵌入模型 (用于召... | Python | 1 |
0_0011
/// 0x4b6 = 0000_0000_0000__0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0100_1011_0110
/// thus we have 1_1010_0011.0100_1011_0110p1
/// which simplifies to 1.1010_0011_0100_1011_0110p9
/// ...and we drop the integer part to leave the power (because the integral part is always 1)
/// ...so 1010_0011_0100_1... | Rust | 0 |
bug!("Connecting to SAFE Network...");
if bootstrap_config.is_some() {
self.bootstrap_config = bootstrap_config;
}
debug!(
"Client to be instantiated with specific pk?: {:?}",
app_keypair
);
debug!(
"Bootstrap contacts list set to:... | Rust | 0 |
import numpy as np
import adi
import matplotlib.pyplot as plt
sample_rate = 1e6 # Hz
center_freq = 915e6 # Hz
num_samps = 100000 # number of samples per call to rx()
sdr = adi.Pluto("ip:192.168.2.1")
sdr.sample_rate = int(sample_rate)
# Config Tx
sdr.tx_rf_bandwidth = int(sample_rate) # filter cutoff, just set it to... | Python | 1 |
eq.append(X_dict[county][i])
Y_seq.append(Y_dict[county][i])
X_seqs.append(X_seq)
Y_seqs.append(Y_seq)
counties.append(county)
X_seqs, Y_seqs, counties = torch.tensor(X_seqs), torch.tensor(Y_seqs), torch.tensor(counties)
year_XY[year] = (X_seqs, Y_seqs... | Python | 1 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup
description = """SMAC - StarCraft Multi-Agent Challenge
SMAC offers a diverse set of decentralised micromanagement challenges based on
StarCraft II game. In these challenges, each... | Python | 1 |
i in 0..1000 {
dbg!(i);
let input = vec![i as u8; i];
let my_hash = sha256(&input);
let mut standard_hasher = Sha256::new();
standard_hasher.update(&input);
let expected = standard_hasher.finalize();
assert_eq!(my_hash[..], expected[..]);
}
}
fn recover_stat... | Rust | 0 |
#!/usr/bin/env python
"""
ZetCode wxPython tutorial
In this example we create buttons with standard ids.
author: Jan Bodnar
website: www.zetcode.com
last modified: July 2020
"""
import wx
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
... | Python | 1 |
from io import StringIO
import pytest
from pandas import DataFrame
from graphdatascience.call_parameters import CallParameters
from graphdatascience.query_runner.protocol.status import Status
from graphdatascience.query_runner.protocol.write_protocols import RemoteWriteBackV3
from graphdatascience.query_runner.termin... | Python | 1 |
and their location within the cache.
pub cache: text::GlyphCache<'static>,
/// The buffer used to store the pixels of the glyphs.
pub pixel_buffer: Vec<u8>,
/// Will be set to `true` after the cache has been updated if the texture requires re-uploading.
pub requires_upload: bool,
}
/// A top-level... | Rust | 0 |
import logging
import os
from contextlib import contextmanager
from dataclasses import dataclass
from functools import lru_cache
import torch
import torch.distributed as dist
logger = logging.getLogger(__name__)
@dataclass
class DistributedContext:
is_distributed: bool
rank: int
local_rank: int
worl... | Python | 1 |
bias=False,
)
self.up_projection_ca = Dense(
emb_size_bilinear,
emb_size_edge,
activation=activation,
bias=False,
)
self.up_projection_ac = Dense(
emb_size_bilinear,
emb_size_edge,
activation=act... | Python | 1 |
#"
[target.'cfg(target_os="android")'.dependencies]
my_crate = "0.1"
"#,
Ok(FoundCrate::Name(name)) if name == "my_crate"
}
create_test! {
target_dependency2,
r#"
[target.x86_64-pc-windows-gnu.dependencies]
my_crate = "0.1"
... | Rust | 0 |
_packet_number(VarInt::from_u8(1));
let end = PacketNumberSpace::Handshake.new_packet_number(VarInt::from_u8(10));
let mut range = PacketNumberRange::new(start, end);
assert_eq!(start, range.start());
assert_eq!(end, range.end());
while let Some(packet_number) = range.next_back... | Rust | 0 |
q_ts) values(1630360000000, 1246868406, 8440235059780981684, 17929, -72, -179883228781.260010, 74775.726422, 0, 'binary.AdgnDiCLdBHvjVsUEUlA', 'nchar.福建省张家港市怀柔唐街k座 206637', 1630000000024)")
tdSql.execute(f"insert into nested.stable_1_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_boo... | Python | 1 |
)),
|(head, tail)| {
let mut m = vec![head];
m.extend(tail);
Query::new(m)
},
),
)(i)
}
#[cfg(test)]
pub mod gens {
use itertools::Itertools;
use prop_check_rs::gen::{Gen, Gens};
use crate::parser::parsers::basic_parsers::gens::*;
fn sub_delims_without_char_gen... | Rust | 0 |
}
mcread_impl_primitive!(
u8 => ReadMinecraftExt::read_u8,
u16 => ReadMinecraftExt::read_u16,
u32 => ReadMinecraftExt::read_u32,
u64 => ReadMinecraftExt::read_u64,
u128 => ReadMinecraftExt::read_u128,
i8 => ReadMinecraftExt::read_i8,
i16 => ReadMinecraftExt::read_i16,
i128 => ReadMinec... | Rust | 0 |
import getpass
from abc import abstractmethod
from typing import Any, Dict, List, Tuple
from mmengine.config import Config, ConfigDict
from opencompass.utils import LarkReporter, get_logger
class BaseRunner:
"""Base class for all runners. A runner is responsible for launching
multiple tasks.
Args:
... | Python | 1 |
_baldrdash_reg(call_conv: isa::CallConv, param: &ir::AbiParam) -> Option<ABIArg> {
if call_conv.extends_baldrdash() {
match ¶m.purpose {
&ir::ArgumentPurpose::VMContext => {
// This is SpiderMonkey's `WasmTlsReg`.
Some(ABIArg::Reg(
xreg(BAL... | Rust | 0 |
from rdflib import Graph
import json
graph = Graph()
graph.parse('data-lex2kg.ttl')
query = "select distinct ?x { ?a lex2kg-o:disahkanOleh ?x . }"
result = graph.query(query)
for x in result:
print(x) | Python | 1 |
matrix: [[Complex { re: 1.0, im: 0.0 }, Complex { re: 0.0, im: 0.0 }],
[Complex { re: 0.0, im: 0.0 }, Complex { re: 0.0, im: 0.0 }]], shape=[2, 2], strides=[2, 1], layout=Cc (0x5), const ndim=2 }"
);
// Test Clone trait
assert_eq!(pragma.clone(), pragma);
// Test PartialEq trait
let pragma_0 = Pr... | Rust | 0 |
-> &str {
self.0.as_ref()
}
}
impl std::fmt::Display for EncodedChannelsList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_ref())
}
}
<filename>src/events.rs
use utils;
#[derive(Debug)]
pub enum MetaEventType {
SequenceNumber = 0x00,
Text = 0... | Rust | 0 |
# Alex just got a new hula hoop, he loves it but feels discouraged
# because his little brother is better than him
# Write a program where Alex can input (n) how many times the hoop
# goes round and it will return him an encouraging message :)
# If Alex gets 10 or more hoops, return the string "Great, now move on t... | Python | 1 |
Rectangle {\x0a \
id: timeS\
liderHead\x0a \
width: parent.\
width\x0a he\
ight: parent.wid\
th\x0a radiu\
s: parent.width \
/ 2\x0a\x0a col\
or: parent.color\
\x0a\x0a MouseA\
rea {\x0a \
anchors.fill: \
parent\x0a\x0a \
drag {\x0a \
targ... | Python | 1 |
let mut inner = quote! {true};
for (bi, bi_rhs) in v.bindings().iter().zip(v_rhs.bindings().iter()) {
inner = quote! { #inner && #bi.eq_modulo_pos(#bi_rhs) }
}
quote!(
match rhs {
#arm => { #inner }
_ => false,
}
)
}... | Rust | 0 |
.as_str(),
_ => ""
};
let date = match time::Date::parse(data, "%F") {
Ok(x) => x,
Err(x) => {
println!("Failed to parse date {}!\n{}", data, x);
return
}
};
match System::fetch_from_horizons(list.as_slice(),... | Rust | 0 |
!(
index.saturating_add(mem::size_of::<T>()) <= self.size,
"Frame buffer accessed out of bounds"
);
(self.base.add(index) as *mut T).write_volatile(value)
}
}
use std::f64::consts::PI;
use std::collections::{ HashMap, HashSet };
fn main()
{
let asteroids = coords(include... | Rust | 0 |
"fill",
(x, y, x + xtile, y + ytile),
i32(s, i) + 28,
(self.rawmode, s[12:16]),
)
)
elif compression == 2:
internal_color_conversion = s[14]
jpeg_tables = s[15]
... | Python | 1 |
crate::flat::AB_BUTTON_BLOOD_TYPE as &crate::Emoji),
("abacus" , &crate::flat::ABACUS as &crate::Emoji),
("abc" , &crate::flat::INPUT_LATIN_LETTERS as &crate::Emoji),
("abcd" , &crate::flat::INPUT_LATIN_LOWERCASE as &crate::Emoji),
("accept" , &crate::flat::JAPANESE_ACCEPTABLE_BUTTON as &crate::Emoji),
("accordion" , &... | Rust | 0 |
import os
import torch
from sklearn.metrics import accuracy_score, balanced_accuracy_score, roc_auc_score, f1_score, cohen_kappa_score, confusion_matrix
from torch.nn import functional as F
import numpy as np
def planar_metrics(logits, labels, num_classes): # logits:[batch_size, num_classes] labels:[batch_siz... | Python | 1 |
ity:.3f} ({primary_method})"
)
except (SQLAlchemyError, ValueError, TypeError, AttributeError) as e:
logger.warning(f"사용자 {other_profile.user_id}와의 유사도 계산 실패: {e}")
continue
await session.commit()
# 4. 추천 생성 태스크 큐에 추가
if similari... | Python | 1 |
k
noise = torch.randn(dr.size(0), 2, dr.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
z_q = noise
# posterior encoder
logdet_tot_q = 0.0
for idx, flow in enumerate(self.post_flows):
z_q, logdet_q = flow(z_q, x_mask, g=(x + h))
... | Python | 1 |
ive_union_test() {
let _ = generator_no_clone_test!(Union::gen());
}
<filename>src/units.rs
//! Partially re-exported [uom](https://crates.io/crates/uom) quantities and measurement units
//! used in the library public interface.
//!
//! Public methods for [Battery](struct.Battery.html) are returning these types.\
/... | Rust | 0 |
import argparse
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument("--input_embedding_1", type=str, required=True)
parser.add_argument("--input_embedding_2", type=str, required=True)
parser.add_argument("--input_embedding_3", type=str)
parser.add_argument("--output_path", type=str, required=Tr... | Python | 1 |
to generate an `Iterator` over all `GridIdx2D` in `GridBounds`
pub fn grid_idx_iter_2d<B>(bounds: &B) -> impl Iterator<Item = GridIdx2D>
where
B: GridBounds<IndexArray = [isize; 2]>,
{
let GridIdx([y_s, x_s]) = bounds.min_index();
let GridIdx([y_e, x_e]) = bounds.max_index();
(y_s..=y_e).flat_map(move... | Rust | 0 |
ntGroup', verbose_name='Recipients')),
('test_lists', models.ForeignKey(blank=True, help_text='Select which group of Test Lists this notification should be limited to. Leave blank to include all Test Lists.', null=True, on_delete=django.db.models.deletion.PROTECT, to='notifications.TestListGroup', verbo... | Python | 1 |
,
CameraRotationUpdater::new(&mut window_events),
"cursor input handler",
&[],
);
builder = attach_system(builder, PlayerController, "player controller", &[]);
builder = attach_system(builder, Physics::new(), "physics", &[]);
builder = attach_system(
builder,
Bloc... | Rust | 0 |
nylon = int(input()) + 2
paint = int(input())
thinner = int(input())
hours = int(input())
paint = paint + paint * 0.10
nylon_price = nylon * 1.50
paint_price = paint * 14.50
thinner_price = thinner * 5
bags_price = 0.40
materials_price = nylon_price + paint_price + thinner_price + bags_price
one_hour_pay = material... | Python | 1 |
ls_over_maximum.set_attributes(reader, e);
}
_ => (),
},
Ok(Event::End(ref e)) => match e.name() {
b"c:chart" => return,
_ => (),
},
Ok(Event::Eof) => panic!("Error not find {}... | Rust | 0 |
# Scenario: University Enrollment System
# A university is developing a student enrollment system that manages student information using sets, logic,
# and relations. The system should be able to:
# • Store and manipulate student data using sets.
# • Implement logical operations to filter students based on conditions.
... | Python | 1 |
.map_err(|e| BrokerError::Internal(format!("cache write failed: {}", e)))
.map(|_| data)
})
});
Box::new(f)
};
let f = f.and_then(move |data| {
json::from_str(&data)
.map_err(|e| BrokerError::Provider(format!("fetch failed (... | Rust | 0 |
&recommendations, &actual_next_items);
assert_eq!(0.3333333333333333, mymetric.result());
assert_eq!("Mrr@20", mymetric.get_name());
}
}
pub trait Optimizer {
/// Initiates the gradient descent.
///
/// Adjusts each parameter by its gradient.
fn step(&mut self);
}
<reponame>david-sot... | Rust | 0 |
# coding: utf-8
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License'). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'lice... | Python | 1 |
# log_utils.py
#
# Copyright 2025 sepehr-rs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distri... | Python | 1 |
s:
if not (bdf in serial2BDF.values()):
rc = run_driver_check_fingerprint(bdf, parsed_args.driver)
if rc == 0:
serial2BDF[serial] = bdf
break
if not (serial in serial2BDF):
print(f":ERROR: Unable to determine BDF fo... | Python | 1 |
r_id.clone(), ());
known_addresses.push((peer_id, address));
}
for ((peer_id, address), _) in config.reserved_nodes {
reserved_nodes.insert(peer_id.clone(), ());
known_addresses.push((peer_id, address));
}
// peer manager
let peer_manager_config = PeerManagerConfig {
max_in_peers: config.max_in_p... | Rust | 0 |
/test_dependency_code'
for i in range(batch_size):
_path = f'{path}/{i}'
res = test_dependency_code(_path, False)
if res != 1:
fail_path.append(_path)
count += res
total += batch_size
for i in range(batch_size):
_path = f'{path}/{i}_f'
res = test_dependency_code(_path, True)
i... | Python | 1 |
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
def execute():
accounting_dimensions = frappe.db.get_all(
"Accounting Dimension", fields=["fieldname", "label", "document_type", "disabled"]
)
if not accounting_dimensions:
return
doctype = "Asset Capitalization"
... | Python | 1 |
reboot_csr: CSR::new(reboot_csr.as_mut_ptr() as *mut u32),
crg_csr: CSR::new(crg_csr.as_mut_ptr() as *mut u32),
gpio_csr: CSR::new(gpio_csr.as_mut_ptr() as *mut u32),
info_csr: CSR::new(info_csr.as_mut_ptr() as *mut u32),
identifier_csr: CS... | Rust | 0 |
DESCRIPTOR_HEAP_DESC
) -> *mut ::D3D12_DESCRIPTOR_HEAP_DESC,
fn GetCPUDescriptorHandleForHeapStart(
&mut self, __ret_val: *mut ::D3D12_CPU_DESCRIPTOR_HANDLE
) -> *mut ::D3D12_CPU_DESCRIPTOR_HANDLE,
fn GetGPUDescriptorHandleForHeapStart(
&mut self, __ret_val: *mut ::D3D12_GPU_DESCRIPTOR_H... | Rust | 0 |
ੱਧ ਐਟਲਸ ਤਮਾਜ਼ਿਤ', 'pcm': 'Mídúl Atlás Támazígt Lángwej', 'pl': 'tamazight (Atlas Środkowy)', 'ps': 'مرکزی اطلس تمازائيٹ', 'pt': 'tamazight do Atlas Central', 'qu': 'Tamazight Simi', 'rm': 'tamazight', 'ro': 'tamazight din Atlasul Central', 'ru': 'среднеатласский тамазигхтский', 'sc': 'tamazight de s’Atlànte tzentrale',... | Python | 1 |
#
# @lc app=leetcode id=28 lang=python3
#
# [28] Find the Index of the First Occurrence in a String
#
# @lc code=start
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(len(haystack)):
if haystack[i:i+len(needle)]==needle:
return i
... | Python | 1 |
astScope::OrganizationLocal),
14 => Some(Ipv6MulticastScope::Global),
_ => None,
}
} else {
None
}
}
/// Converts string in format X:X::X/Y (CIDR notation) to `Ipv6Network`, but truncating host bits.
///
/// # Examples
///
... | Rust | 0 |
nt<C>
where
C: aws_hyper::SmithyConnector,
{
pub fn delete_report_definition(&self) -> fluent_builders::DeleteReportDefinition<C> {
fluent_builders::DeleteReportDefinition::new(self.handle.clone())
}
pub fn get_report_definition(&self) -> fluent_builders::GetReportDefinition<C> {
fluent_... | Rust | 0 |
",
&expect![[r#"
Root@0..37
Whitespace@0..1 "\n"
InfixExpr@1..37
InfixExpr@1..22
Literal@1..5
Number@1..2 "1"
Whitespace@2..5 "\n "
Plus@5..6 "+"
Whitespace@6..7 " "
Literal@7..22
Number@7..8 "1"
Whi... | Rust | 0 |
"INSERT INTO Maquina "
"(imagem, loja, modelo, preco, mes_fabricacao, ano_fabricacao, quantidade) "
"VALUES (?, ?, ?, ?, ?, ?, ?)", params, imagem_conteudo, nome_imagem)
try:
# tenta inserir os dados
self.conn_db.send_dict(mensagem)
except:
... | Python | 1 |
ck(PipelineStageOutput { output: Some(data) })),
pipeline,
};
let _res = res_tx.send(msg).await;
}
/// Respond to the server with an `nack` over the given channel.
#[tracing::instrument(level = "debug", skip(res_tx, pipeline, err))]
async fn nack(res_tx: mpsc::Sender<Pipelin... | Rust | 0 |
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, QoSDurabilityPolicy
from std_msgs.msg import String
import serial
import time
#be able to write to the arduino serial port
#create an instance of the serial, open up a serial.write, and then write whatever the message being published is
class T... | Python | 1 |
2, 3, 2, 0)
verify_conv2d_NCHWc(1, 1280, 8, 320, 1, 1, 0)
verify_conv2d_NCHWc(1, 1280, 8, 384, 1, 1, 0)
verify_conv2d_NCHWc(1, 384, 8, 384, 1, 1, 0)
verify_conv2d_NCHWc(1, 384, 8, 384, 3, 1, 1)
verify_conv2d_NCHWc(1, 1280, 8, 448, 1, 1, 0)
verify_conv2d_NCHWc(1, 448, 8, 384, 3, 1, 1)
verify_... | Python | 1 |
#coding:utf-8
from __future__ import division
import re
import csv
import sys
from subprocess import call
str2bin = {'0': 52, '1': 53, '2': 54, '3': 55, '4': 56, '5': 57, '6': 58, '7': 59, '8': 60, '9': 61, '+': 62, '/': 63,
'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'I': 8, 'H': 7, 'K': 10, 'J... | Python | 1 |
e. Defaults to PREFIX.
suffix: The suffix to use. Defaults to SUFFIX.
format_instructions: The format instructions to use.
Defaults to FORMAT_INSTRUCTIONS.
input_variables: The input variables to use. Defaults to None.
kwargs: Additional parameters to pass... | Python | 1 |
query_sent = one_hop[1] + f"?x ns:people.person.gender ns:m.02zsn ." # 男性
# is_use_entity_cons = False
# """实体约束"""
# if is_use_entity_cons:
# # 这里一跳的实体约束还可以再改进一下按照中间实体约束那样搞(后面再弄)
# one_hop_entity_constrains = from_id_path_get_2hop_po_oName(question, topicEntityID, one_hop[1]) # ... | Python | 1 |
v.log(10f64).floor().abs() + 1f64) as usize;
f = if i > prec { 0 } else {
usize::min(prec - i, MAX_FRAC)
};
} else {
i = 1;
f = MAX_FRAC;
}
Some(format!("{v:i$.f$}", v=... | Rust | 0 |
HT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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
// option. This f... | Rust | 0 |
nst EXTI_PR_PR18: u32 = 262144;
pub const EXTI_PR_PR19_Pos: u32 = 19;
pub const EXTI_PR_PR19_Msk: u32 = 524288;
pub const EXTI_PR_PR19: u32 = 524288;
pub const EXTI_PR_PR20_Pos: u32 = 20;
pub const EXTI_PR_PR20_Msk: u32 = 1048576;
pub const EXTI_PR_PR20: u32 = 1048576;
pub const EXTI_PR_PR21_Pos: u32 = 21;
pub const EX... | Rust | 0 |
"""Test RevNotificationRecord."""
import pytest
import pytest_asyncio
from ......storage.error import StorageDuplicateError, StorageNotFoundError
from ......utils.testing import create_test_profile
from ...messages.revoke import Revoke
from ..rev_notification_record import RevNotificationRecord
@pytest_asyncio.fixt... | Python | 1 |
resource owner username.
password
REQUIRED. The resource owner password.
scope
OPTIONAL. The scope of the access request. (UNUSED)
Example successful response:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
... | Python | 1 |
session.query(DataShard)
.filter_by(table_name=table_class.__tablename__)
.order_by(DataShard.end_date.desc())
.first()
)
if latest_shard and latest_shard.end_date:
start_date = latest_shard.end_date + timedelta(days=1)
... | Python | 1 |
NTO_AVAILABLE', True)
@patch('lumibot.tools.databento_helper.get_price_data_from_databento')
def test_prefetch_handles_no_data(self, mock_get_data):
"""Test prefetch handling when no data is returned"""
# Mock DataBento to return None (no data)
mock_get_data.return_value = None
... | Python | 1 |
=> return Error::err(format!("Unsupported at-rule '{}'", name)),
},
_ => {}
}
i += 1;
}
Ok(())
}
fn parse_sass_value(value: &Value) -> Result<PropertyValue> {
match value {
Value::Literal(s) => {
if let Some(s) = s.single_raw() {
... | Rust | 0 |
/// A::deserialize(&p).unwrap(),
/// A { x: 1, y: 2 }
/// );
///
/// #[derive(Debug, Clone, PartialEq, Deserialize)]
/// #[serde(rename = "ANOTHER_KEYWORD")] // keyword does not match
/// struct B {
/// x: i32,
/// y: i32,
/// }
/// assert!(B::deserialize(&p).is_err());
/// ```
///
/// - Otherwise, it i... | Rust | 0 |
# Python program to impleament cycle sort
def cycleSort(array):
writes = 0
# Loop through the array to find cycles to rotate.
for cycleStart in range(0, len(array) - 1):
item = array[cycleStart]
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1,... | Python | 1 |
page = Rc::clone(&frame.buffer);
self.page_table.remove(&evict_page_id);
self.page_table.insert(page_id, buffer_id);
Ok(page)
}
}
use std::io;
use std::io::prelude::*;
pub fn print_progress(percent: usize) -> io::Result<()> {
let num_bars = percent / 5;
let num_spaces = 20 - num_bars;
... | Rust | 0 |
uest_union::create_request(ref v) => {
os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?;
os.write_raw_varint32(v.get_cached_size())?;
v.write_to_with_cached_sizes(os)?;
},
&WatchRequest_oneof_request_union::can... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.