text string | label_name string | labels int64 |
|---|---|---|
c.asm
.pop_and_jump_if_not(c.scopes.local_var_count(span)?, false_label, span);
Ok(true)
}
/// Assemble an [ast::Condition].
#[instrument]
fn condition(
condition: &ast::Condition,
c: &mut Assembler<'_>,
then_label: Label,
) -> CompileResult<Scope> {
match condition {
ast::Condi... | Rust | 0 |
&self) -> std::option::Option<&str> {
self.media_type.as_deref()
}
}
impl std::fmt::Debug for Layer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Layer");
formatter.field("layer_digest", &self.layer_digest);
formatter.f... | Rust | 0 |
sg.Spin([x for x in range(1, 100000)], size=(5, 1), key='-PARSER.DELAY_BETWEEN_CLICKS-',
initial_value=config.parser.delay_between_clicks,
tooltip='Задержка между кликами по записям (миллисекунд)'),
... | Python | 1 |
TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
// Definition for an interval.
#[derive(Debug, PartialEq, Eq)]
pub struct Interval {
pub start: i32... | Rust | 0 |
this
// crate's concerns. The timeout is here just to prevent the tests from
// stalling forever if a developer makes a mistake locally in this
// crate. Tests of Zircon behavior or virtualization behavior should be
// covered elsewhere. See fxbug.dev/31235.
p1.call_etc(Time::aft... | Rust | 0 |
info!("Submitted habit deletion {:?}", habit_id);
let result = repo.remove_habit(habit_id.to_string());
if let Err(err) = result {
warn!("Encountered error {:?}", err);
return Status::InternalServerError;
}
Status::Ok
}
#[get("/users/<user_id>/habits")]
pub fn get_habits(
repo: S... | Rust | 0 |
");
set("TEST_EXPAND_UNIX_WITH_VALUES3", "test3");
set("TEST_EXPAND_UNIX_WITH_VALUES4", "test4");
set("TEST_EXPAND_UNIX_WITH_VALUES5", "test5");
let mut options = ExpandOptions::new();
options.default_to_empty = false;
options.expansion_type = Some(ExpansionType::Unix);
let output = expand... | Rust | 0 |
val * 2 + 1,
);
Self::scan(
&mut root.as_ref().unwrap().borrow_mut().right,
v,
val * 2 + 2,
);
}
}
fn find(&self, target: i32) -> bool {
self.v.get(&target).is_some()
}
}
#![allow(non_snake_case)]
#
#[macro_export]
macro_rules! assert_snapshot_matches {
($value:expr, @$snapshot:literal) => {
$crate::_assert_snapshot_matches!(
$crate::_macro_supp... | Rust | 0 |
!("Invalid seek mode: {}", whence)));
}
};
Ok((rid, seek_from))
}
fn op_seek_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> {
let (rid, seek_from) = seek_helper(args)?;
let pos = std_file_resource(state, rid, |r| match r {
Ok(std_file) => std... | Rust | 0 |
nd::thread_rng().gen_range(0, max) + 1
}
}
impl Rollable for u32 {
fn roll(max: u32) -> u32 {
rand::thread_rng().gen_range(0, max) + 1
}
}
impl Rollable for u64 {
fn roll(max: u64) -> u64 {
rand::thread_rng().gen_range(0, max) + 1
}
}
impl Rollable for u128 {
fn roll(max: u128) -... | Rust | 0 |
***********************************************/
///Common types and definitions for the [vt6/foundation](https://vt6.io/std/foundation/) and
///[vt6/core](https://vt6.io/std/core/) modules.
pub mod core;
use cosmwasm_std::{Decimal, StdResult, Storage, Uint128};
use cosmwasm_storage::{ReadonlySingleton, Singleton};
us... | Rust | 0 |
dden_states).sample
lr = self.trainer.optimizers[0].param_groups[0]["lr"]
loss_weights = (1 - batch['mask']) * 0.6 + torch.ones_like(batch['mask'])
loss = F.mse_loss(noise_pred, noise, reduction="none")*loss_weights
loss = loss.mean([1, 2, 3]).mean()
self.log("train_loss", loss.... | Python | 1 |
for Variable {
type Output = Formula;
fn $fn(self, rhs: Formula) -> Formula {
Formula::from(self).$fn(rhs)
}
}
impl $($trait)::+<Formula> for &Variable {
type Output = Formula;
fn $fn(self, rhs: Formula) -> Formula... | Rust | 0 |
aste::paste;
use sqlx::migrate::MigrateDatabase;
use tokio::sync::OnceCell;
static SHARED_CLIENT: OnceCell<Client> = OnceCell::const_new();
async fn get_client() -> Result<&'static Client> {
async fn init_client() -> Result<Client> {
let url = "sqlite:ransaq.test.sqlite";
... | Rust | 0 |
"check that your learning rate isn't too high"
)
TRICYCLE_CONTEXT.loss_scale_factor /= 2
self.logger.warn(
f"New scaling factor: {TRICYCLE_CONTEXT.loss_scale_factor}"
)
return tensor
if (combined_grad == 0).sum() > combined_grad.siz... | Python | 1 |
crate::query::{QueryCacheStore, QueryContext, QueryState};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_errors::DiagnosticBuilder;
use std::fmt::Debug;
use std::hash::Hash;
pub trait QueryConfig {
const NAME: &'static str;
type Key: Eq + Hash + Clone + Debug;
type Value;
type Store... | Rust | 0 |
en_includes_DECL_RUNTIME_APIS::sp_api::ApiError,
> {
let runtime_api_impl_params_encoded =
self::sp_api_hidden_includes_DECL_RUNTIME_APIS::sp_api::Encode::encode(&(
&equivocation_proof,
&key_owner_proof,
));
self . GrandpaApi_submit_report_equi... | Rust | 0 |
if l < len(waiting) - 1:
waiting[l + 1].extend(waiting[l][:i + 1])
del waiting[l][:i + 1]
break
return mapping
def perm_invert(p):
"""
Return the inverse of the permutation `p`.
INPUT:
a permutation of {0,..,n-1} given by a list of... | Python | 1 |
from __future__ import print_function
from __future__ import absolute_import
__author__ = 'Taneem Jan, taneemishere.github.io'
from argparse import ArgumentParser
from Evaluator import *
def build_parser():
parser = ArgumentParser()
parser.add_argument('--original_gui_filepath', type=str,
... | Python | 1 |
Fraction.get_price_at_tick(weth_token_kovan, usdc_token_kovan, weth_usdc_kovan_pool.tick_current)
print("current pool tick", weth_usdc_kovan_pool.tick_current)
print("current pool price", current_pool_price.float_quotient())
desired_price = PriceFraction(weth_token_kovan, usdc_token_kovan, Wad.from_num... | Python | 1 |
# Write a program to print the 4th element from first and 4th element from last in a tuple.
touple = (10, 20, 30, 40, 50, 60, 70, 80, 90)
print("4th element from first:", touple[3])
print("4th element from last:", touple[-4])
# Write a program to check whether an element exists in a tuple or not.
element = int(inpu... | Python | 1 |
,
{
// Need to assigned owned a fixed location, so do not move it from here for the duration of the poll.
let internals = Internals::new(&**shared as *const Shared, index);
let waker = RawWaker::new(&internals as *const _ as *const (), INTERNALS_VTABLE);
let waker = mem::ManuallyDrop::new(unsafe { Wake... | Rust | 0 |
pdate": self._last_successful_update,
"consecutive_failures": self._consecutive_failures,
"is_healthy": self.is_healthy(),
"source_names": list(self._sources.keys()),
}
async def refresh_source_configs(self) -> None:
"""Refresh configurations for all sources from... | Python | 1 |
e.low,
"high": env.full_action_spec_unbatched[("agents", "action")].space.high,
},
return_log_prob=True,
)
# Load checkpoint
checkpoint_path = cfg.eval.checkpoint_path
load_checkpoint(policy, checkpoint_path)
# Evaluation rollouts
policy.eval()
env.frames = []
... | Python | 1 |
off'" % bits[0])
else:
use_tz = bits[1] == "on"
nodelist = parser.parse(("endlocaltime",))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
@register.tag("timezone")
def timezone_tag(parser, token):
"""
Enable a given time zone just for this block.
The ``timezone... | Python | 1 |
not "reader objects", but the actual value
// of the registers at time of assignment :))
let intstat_r = intstat.read();
// First handle endpoint 0 (the only control endpoint)
if intstat_r.ep0out().bit_is_set() {
if devcmdstat.read().setup().bit_is_set() ... | Rust | 0 |
Some(Value::Currency(v, c)) => {
xml_out.attr("office:value-type", "currency")?;
xml_out.attr_esc("office:currency", String::from_utf8_lossy(c))?;
let value = v.to_string();
xml_out.attr("office:value", value.as_str())?;
xml_out.elem("text:p")?;
... | Rust | 0 |
ig` with the ones in `_vision_config_dict`.
vision_config.update(_vision_config_dict)
if text_config is None:
text_config = {}
logger.info("`text_config` is `None`. Initializing the `GroupViTTextConfig` with default values.")
if vision_config is None:
vi... | Python | 1 |
lease add the 'repo' scope to the token.",
)
return None, None
def recce_pr_information(github_token=None) -> Tuple[Optional[type(PullRequest)], Optional[str]]:
branch = current_branch()
repo = hosting_repo()
if not repo:
return None, "This is not a git repository."
if "/" no... | Python | 1 |
sender.clone(),
};
WriteLogger::init(LevelFilter::Debug, Config::default(), target).unwrap();
log::info!("Running the microphone playback example");
/*
* Then, setup the audio graph. It has two modes: record audio and playback audio.
*/
let mut audio_thread = AudioThread::new();
/*
... | Rust | 0 |
grel(%ebx, %ecx, 4), %eax")
craftCoff("relocs.obj.coff-x86_64", "x86_64-pc-win32", Relocs_Coff_X86_64.entries(), "mov foo@imgrel(%ebx, %ecx, 4), %eax")
#craftCoff("relocs.obj.coff-arm", "arm-pc-win32", Relocs_Coff_ARM.entries(), "...")
craftMacho("relocs.obj.macho-i386", "i386-apple-darwin9", Relocs_Macho_i386... | Python | 1 |
let error_msg = uv::ll::get_last_err_info(loop_ptr);
fail ~"timer::delayed_send() start failed: " +
error_msg;
}
}
else {
let error_msg = uv::ll::get_last_err_info(loop_ptr)... | Rust | 0 |
*mut SLwchar_Type,
num: c_uint,
) -> c_int;
}
extern "C" {
pub fn SLuchar_apply_char_map(
map: *mut SLwchar_Map_Type,
str_: *mut SLuchar_Type,
) -> *mut SLuchar_Type;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct SLang_Name_Type {
pub name: *mut c_char,
pub next: *mu... | Rust | 0 |
from typing import List, Dict, Any
# 这是我们不变的“骨架”,是所有导师共有的教学哲学。
# 使用.jinja2模板是更高级的做法,但为了第一阶段的清晰性,我们先用f-string。
MASTER_PROMPT_TEMPLATE = """
{persona_description}
你的教学目标:以苏格拉底式问答法的方式,引导一位学生,独立思考并完成“{topic_name}”的学习。
**Instruction:** Your response must be in language:**{{output_language}}**.
### 核心原则
1. 禁止直接给出答案。你的回答永... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Python | 1 |
Bookmark,
user_id: int = Header(None, alias="x-user-id"),
session=Depends(get_session)):
check_user(user_id, session)
# проверяем наличие полки
check_shelf = (
select(Shelf).where(Shelf.id == new_bookmark.shelf_id)
)
result = session.execute(check_shelf)
... | Python | 1 |
: {}", guild.name);
ensure_guild(&ctx, guild.id);
let channel_ids: Vec<_> = guild
.channels
.values()
.map(|c| c.read().id.0 as i64)
.collect();
let is_blocked: bool = with_pool(&ctx, |pool| {
use schema::blocked_guilds_channels::dsl... | Rust | 0 |
import os
from dotenv import load_dotenv
import anthropic
import json
import logging
import time
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
class AnthropicClient:
# Constants
MODEL_NAME = "cla... | Python | 1 |
ter', {}).get('imageUrl'),
'duration': int_or_none(content.get('dataDuration')),
}
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
article = self._parse_json(self._search_regex(
r'window\.\$REAC... | Python | 1 |
while left_index <= parent.as_ref().borrow().num_keys
&& ByAddress(parent.as_ref().borrow().pointers[left_index].as_ref().unwrap().as_ref().borrow())
!= ByAddress(left.as_ref().borrow()){
left_index += 1;
}
left_index
}
fn insert_into_leaf(leaf: NodeType, key: isize, ptr_record: No... | Rust | 0 |
ys:
* reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling, if not specified.
"""
ref = {
'exchange': 'role-updated',
'name': 'roleUpdated',
'routingKey': [
... | Python | 1 |
"""
app\ez_calendar\__init__.py
This module handles analytical init for the blueprint.
"""
from flask import Blueprint
# Create the blueprint
calendar_bp = Blueprint('calendar', __name__)
from . import routes | Python | 1 |
class RuntimeTypeHandle(object,ISerializable):
""" Represents a type using an internal metadata token. """
def Equals(self,*__args):
"""
Equals(self: RuntimeTypeHandle,handle: RuntimeTypeHandle) -> bool
Indicates whether the specified System.RuntimeTypeHandle structure is equal to the current
System... | Python | 1 |
s:List[dict] = response['IdentityDocuments'][0]['IdentityDocumentFields']
for field in document_fields:
key = field['Type']['Text']
value = field['ValueDetection']['Text']
properties[key] = value
if len(result["Blocks"]) > 2 :
document_fields:List[dict] = result['Blocks']
for field in docum... | Python | 1 |
Bids) -> Result<(), Error>
where
P: StorageProvider + RuntimeProvider + ?Sized,
{
for (_, bid) in validators.into_iter() {
let account_hash = AccountHash::from(bid.validator_public_key());
provider.write_bid(account_hash, bid)?;
}
Ok(())
}
pub fn get_unbonding_purses<P>(provider: &mut ... | Rust | 0 |
l_uniforms: &Self::GlUniforms) {}
}
impl GlUniforms for EmptyUniformsGl {
fn new(_context: &GlContext, _program: GlProgramId) -> Self {
EmptyUniformsGl {}
}
}
<filename>src/process.rs
use std::convert::TryFrom;
use std::ffi;
use std::io;
use std::os::unix::prelude::*;
use std::path::Path;
use crate::e... | Rust | 0 |
""" Ejemplo: Gestión deInventario deProductos
Considerando elenunciado anterior, realicemos lo siguiente:
1.
Cree un diccionario llamado inventario que representará el inventario
dela tienda. El inventario deberá contener nombre, cantidad y precio
detres productos.
2. Actualizar la cantidad de un producto solici... | Python | 1 |
_end_1: Option<u32>,
storage_start_2: Option<u32>,
storage_end_2: Option<u32>,
}
pub type SplitRange = (u32, u32);
pub fn split_arc(arc: &DhtArc) -> (Option<SplitRange>, Option<SplitRange>) {
let mut storage_1 = None;
let mut storage_2 = None;
use std::ops::{Bound, RangeBounds};
let r = arc.ra... | Rust | 0 |
.finish()
}
}
<filename>src/event.rs
// Copyright (c) 2019 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
use cmd::Result;
pub enum Event {
OutputUpdate(Result),
Input(i32),
Signal(i32),
Exit,
}
<reponame>talklittle... | Rust | 0 |
Gpt2Config, Gpt2ConfigResources, Gpt2MergesResources, Gpt2ModelResources,
Gpt2VocabResources,
};
use crate::marian::MarianForConditionalGeneration;
use crate::openai_gpt::{
OpenAIGPTLMHeadModel, OpenAiGptConfigResources, OpenAiGptMergesResources,
OpenAiGptModelResources, OpenAiGptVocabResources,
};
use cra... | Rust | 0 |
::from(CROSS_DOMAIN_XML),
));
}
None
}
extern crate aura;
extern crate message_handler;
extern crate utils;
use aura::aura_interface;
use futures::channel::mpsc::*;
use message_handler::messages::MessageTypes;
use poa::poa_interface;
use std::sync::{Arc, Mutex};
use utils::configreader::Configuration;
... | Rust | 0 |
let depthtexture = DepthTexture2d::empty_with_format(display, DepthFormat::F32, MipmapsOption::NoMipmap, res.0, res.1).unwrap();
let area_tex = Texture2d::empty_with_format(display, UncompressedFloatFormat::F32F32F32F32, MipmapsOption::NoMipmap, res.0, res.1).unwrap();
{
... | Rust | 0 |
# Author: wangxy
# Emial: 1393196999@qq.com
import copy, math
import numpy as np
from scipy.spatial import ConvexHull
PI = np.pi
TWO_PI = 2 * np.pi
from typing import Tuple
def iou_2d(boxA, boxB):
boxA = [int(x) for x in boxA]
boxB = [int(x) for x in boxB]
xA = max(boxA[0], boxB[0])
yA = max(boxA[1],... | Python | 1 |
comp = parse_frac(v).unwrap();
updated_base = true;
}
if let Some(v) = subm.value_of("report") {
args.report = if v.len() == 0 {
None
} else {
Some(v.to_owned())
... | Rust | 0 |
self.dirty_state.dirty_bitmap[idx] |= 1 << bit;
}
}
Some(())
}
/// Get the maximum size of guest memory
#[inline]
pub fn len(&self) -> usize {
self.memory.len()
}
/// Get the dirty list length
#[inline]
pub fn dirty_len(&self) -> usize... | Rust | 0 |
IF_0_MANUAL_SPEC>,
#[doc = "0x10 - ef_if_0_status."]
pub ef_if_0_status: crate::Reg<ef_if_0_status::EF_IF_0_STATUS_SPEC>,
#[doc = "0x14 - ef_if_cfg_0."]
pub ef_if_cfg_0: crate::Reg<ef_if_cfg_0::EF_IF_CFG_0_SPEC>,
#[doc = "0x18 - ef_sw_cfg_0."]
pub ef_sw_cfg_0: crate::Reg<ef_sw_cfg_0::EF_SW_CFG_0... | Rust | 0 |
gressor policies are deterministic.
del key
apply_fn = (
ensemble.apply_round_robin if use_round_robin else ensemble.apply_mean)
return apply_fn(
policy_prior_network.apply,
params,
observation_t=observation_t,
action_tm1=action_tm1)
dummy_action = utils.zeros_like... | Python | 1 |
\x98\xbd:;\xee\xd3\x17)-\xbb\xd6g0R\x03\xc9\
[\xcf`\xa4\x09\x9eJ4f\xb0\x15(,\xd2\xa5\
\xb1\x11\xees\xd9\x00\x07Z\x978H\x03XK\x9f\xcb\
Hui\xf7}:\x22e\xb0\x08\xb1\xf5lFR\xc0\
3\x84\xeeAmX\xac\xcc\xb6\xaf/\xd6\x14\x98\xba\x9e\
\xceH\xa4\xb9\x0bF\xd7+\x91G#\xf8q\x0d\xee\x13\
\xdb\x00\xa3\x17ZOl$\x0aJ\xea:f\xb6e\x0f\
r\xe... | Python | 1 |
();
let distance_colour = *GREEN;
let wall_colour = *BLUE;
canvas.set_draw_color(wall_colour);
let cell_size_pixels = options.cell_side_pixels_length as usize;
// Font creation
let font_path: &Path = Path::new("resources/Roboto-Regular.ttf");
let font_px_size = ((cell_size_pixels as f32) ... | Rust | 0 |
0x46, 0x66, 0x33, 0x13, 0x0B, 0x0B, 0x1F, 0x0F, 0x0F, 0x1E, 0x1E, 0x1C,
0x30, 0x00, 0xF0, 0x0C, 0x46, 0x66, 0x33, 0x13, 0x0B, 0x0B, 0x1F, 0x0F,
0x0F, 0x1E, 0x1E, 0x1C, 0x30, 0x00, 0x3F, 0x3F, 0x3F, 0x3C, 0x3C, 0x3C,
0x3C, 0x3C, 0x3C, 0x3C, 0x3C... | Rust | 0 |
sign_0 || (zero_0 && sign_1)
}
pub fn fp2_is_square(x: Fp2) -> bool {
let c1 = Fp::from_byte_seq_be(&P_1_2.to_be_bytes()); // (p - 1) / 2
let (x1, x2) = x;
let tv1 = x1 * x1;
let tv2 = x2 * x2;
let tv1 = tv1 + tv2;
let tv1 = tv1.pow_self(c1);
let neg1 = Fp::ZERO() - Fp::ONE();
tv1 !... | Rust | 0 |
import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
comEnergy = cms.double(13000.0),
crossSection = cms.untracked.double(2.172e+01),
filterEfficie... | Python | 1 |
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
def heston_char(u, S0, r, gam0, kappa, lamb, sig_tild, T):
## Compute characteristic function of log-stock price in the Heston model, cf. equation (4.8) with t = 0
d = np.sqrt(lamb ** 2 + sig_tild ** 2 * (u * 1j + u ** 2... | Python | 1 |
pwm_pdmacap4_5: crate::Reg<pwm_pdmacap4_5::PWM_PDMACAP4_5_SPEC>,
_reserved63: [u8; 0x04],
#[doc = "0x250 - PWM Capture Interrupt Enable Register"]
pub pwm_capien: crate::Reg<pwm_capien::PWM_CAPIEN_SPEC>,
#[doc = "0x254 - PWM Capture Interrupt Flag Register"]
pub pwm_capif: crate::Reg<pwm_capif::PWM... | Rust | 0 |
_many("GRAPH".len())?;
skip_whitespace(&mut parser.inner.read)?;
let graph_name = parse_label_or_subject(
&mut parser.inner.read,
&mut parser.graph_name_buf,
&mut parser.inner.temp_buf,
&parser.inner.base_iri,
&parser.inner.namespaces,
... | Rust | 0 |
center=False
)
self.save_rewards = BaseCheckBox(
"save_rewards", None,
QT_TRANSLATE_NOOP("BaseCheckBox", "保存困牢奖励"),
tips=QT_TRANSLATE_NOOP("BaseCheckBox", "仅在进行困难镜牢时生效,普通难度不生效"),
center=False
)
self.hard_mirror_single_bonuses = B... | Python | 1 |
server.
These can include options like `show`, `start`, `dev`, `autoreload`,
and `websocket_origin`.
"""
if port == 0:
port = find_free_port()
print(f"Found available port: {port}")
if address == "auto-ip":
address = get_local_ip()
# Set websocket_origin automat... | Python | 1 |
})
);
// query pot
let msg = QueryMsg::GetPot { id: Uint64::new(1) };
let res = query(deps.as_ref(), mock_env(), msg).unwrap();
let pot: Pot = from_binary(&res).unwrap();
assert_eq!(
pot,
Pot {
target_addr: Addr::uncheck... | Rust | 0 |