text string | label_name string | labels int64 |
|---|---|---|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Base import module',
'description': """
Import a custom data module
===========================
This module allows authorized users to import a custom data module (.xml files and static assests)
for cu... | Python | 1 |
u' = LATIN SMALL LETTER U
LatinSmallLetterV, // Char 118 'v' = LATIN SMALL LETTER V
LatinSmallLetterW, // Char 119 'w' = LATIN SMALL LETTER W
LatinSmallLetterX, // Char 120 'x' = LATIN SMALL LETTER X
LatinSmallLetterY, /... | Rust | 0 |
def scheduling(charlas):
if not charlas:
return []
charlas.sort(key=lambda x: x[1])
n = len(charlas)
opt = [0] * n
selected = [[] for _ in range(n)]
opt[0] = charlas[0][2] # inicializo la ganancia de la primer charla como el optimo
selected[0] = [charlas[0]]
for i in ... | Python | 1 |
import importlib.util
import sys
import logging
import gremlin.event_handler
import gremlin.joystick_handling
from vigem import vigem_gamepad as vg
from vigem.vigem_client import VigemClient as vc
import gremlin.config
from enum import Enum, auto
syslog = logging.getLogger("system")
_gamepad_available = False
_gamep... | Python | 1 |
# -*- coding: utf-8 -*-
# Scrapy settings for manmanbuy project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/top... | Python | 1 |
rawing operation
/// the display driver uses and framebuffer to store the pixel data in memory. This way all drawing
/// operations can be executed in local memory and the actual display is only updated on demand
/// by calling the `flush` method.
///
/// Because all drawing operations are using a local framebuffer no ... | Rust | 0 |
from .shift_kmeans import shift_kmeans | Python | 1 |
state.PC);
self.state.PC = self.state.PC.wrapping_add(1);
let (_, byte3) = self.read(self.state.PC);
self.state.PC = self.state.PC.wrapping_add(1);
instructions::decode3bytes(byte1, byte2, byte3)
}
x => panic... | Rust | 0 |
*const u8, in_size as usize) };
let output= unsafe { std::slice::from_raw_parts_mut(out_pointer as *mut u8, out_size as usize) };
impl_calculate_blake3(input, output);
}
#[no_mangle]
pub extern fn calculate_unsafe_blake3(
in_size: libc::size_t,
in_pointer: *const u8,
out_size: libc::size_t,
out_pointer: *... | Rust | 0 |
replace event will handle the update as a whole, preventing errors
# where the append handler deletes a meter on first append which is still needed
# in subsequent appends.
if initiator is not None and initiator.op is OP_BULK_REPLACE:
return
target.update_amount_and_currency(
[*target.s... | Python | 1 |
oadImageFromFile'),
# 截取
dict(type='CenterCrop', crop_size=(400, 450)),
# 缩放 到 统一的尺寸
dict(type='Resize', scale=(280, 315)), # original (280, 315)
dict(type='CChessPackInputs'),
]
data_root = 'data/cchess_multi_label_layout'
train_dataloader = dict(
batch_size=32,
num_workers=4,
datas... | Python | 1 |
assert_approx_eq!($affine3::IDENTITY, m_inv * m, 1.0e-5);
assert_approx_eq!(m_inv, trans_inv * rotz_inv * scale_inv, 1.0e-6);
// Make sure we can invert a shear matrix:
let m = $affine3::from_axis_angle($vec3::X, 0.5)
* $affine3::from_scale($vec3::new(1.0... | Rust | 0 |
from enum import Enum
class LatexPlacement(Enum):
fixed = "!h"
floating = None
class Formatter:
def document_class(dc: str) -> str:
template = "\\documentclass{{{}}}\n"
return template.format(dc)
def packages(pkgs: list[str]) -> str:
return "".join([Formatter.package(pkg) fo... | Python | 1 |
import click
import signal
import time
# logging
base = time.time()
ERROR = 0
PROGRESS = 1
INFO = 2
DETAIL = 3
DEBUG = 4
_verbosity = INFO
def log(verbosity, *args, **kwargs):
global _verbosity
if verbosity <= _verbosity:
click.echo(f"[{time.time()-base:.2f}] {' '.join(str(arg) for arg in args)}", **kw... | Python | 1 |
DWORD,
Timeout: ULONG,
Guid: GUID,
NumberOfStorages: DWORD,
Storage: ULONG,
}}
pub type PDFS_INFO_4_32 = *mut DFS_INFO_4_32;
pub type LPDFS_INFO_4_32 = *mut DFS_INFO_4_32;
}
STRUCT!{struct DFS_INFO_5 {
EntryPath: LPWSTR,
Comment: LPWSTR,
State: DWORD,
Timeout: ULONG,
Guid: GUID,
... | Rust | 0 |
from ...utils.maafw import Tasker, JobWithResult
from ...utils.datetime import datetime, timedelta, sleep
def maafw_run_ppl(tasker: Tasker, entry: str, pipeline_override: dict = {}, timeout: int = 10) -> tuple[bool, JobWithResult | None]:
# Deprecated 2025/04/18
"""Run a pipeline task with a timeout.
Args... | Python | 1 |
#!/usr/bin/env python
# simple smtp VRFY checker.. that works!
# by brad a.
import socket
import getopt
import sys
import re
def usage():
help = "Options:\n"
help += "\t-h <host>\t host\n"
help += "\t-p <port>\t port (Default: 25)\n"
help += "\t-u <filename>\t userlist\n"
help += "\t-v \t verbose\n"
return he... | Python | 1 |
counted in active
update_state(
peer_metadata_storage.clone(),
PeerNetworkId::new(network_id, peer_1),
PeerState::Disconnecting,
);
assert_eq!(2, interface.peers(network_id).len());
assert_eq!(1, interface.connected_peers(network_id).len());
// Removing a connection with a ... | Rust | 0 |
est_module.web.HTTPBadRequest):
await test_module.presentation_exchange_remove(self.request)
async def test_register(self):
mock_app = mock.MagicMock()
mock_app.add_routes = mock.MagicMock()
await test_module.register(mock_app)
mock_app.add_routes.assert_called_once... | Python | 1 |
#!/usr/bin/env python
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All ... | Python | 1 |
_SIZE: usize = 30000;
use std::num::Wrapping;
use std::io::{Read, Write, stdin, stdout};
let mut next_char = [0; 1];
let mut tape = [Wrapping(0u8); TAPE_SIZE];
let mut ptr = 0;
});
for token in tokens {
match token {
BrainToken::Add => code.push_str(st... | Rust | 0 |
pub generic_param: Option<GenericParm>,
/// Extends an existing type choice
pub is_type_choice_alternate: bool,
/// Type value
pub value: Type,
}
impl fmt::Display for TypeRule {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut tr_output = self.name.to_string();
if let Some(gp) = &se... | Rust | 0 |
Self { fft_space: None }
}
}
impl PowerCepstrum {
fn unscaled_spectrum(&self, bin_range: (usize, usize)) -> Box<dyn Iterator<Item = f64> + '_> {
if let Some(ref fft_space) = self.fft_space {
let (lower_limit, upper_limit) = bin_range;
Box::new(
fft_space
... | Rust | 0 |
am(cap)),
Err(err) => return Err(err),
}
let used = c.position() - pos;
if used > len as u64 {
len = 0;
} else {
len -= used as u8;
}
... | Rust | 0 |
henticator>>>;
fn main() {
let user = "user";
let password = "password";
let auth = StaticPasswordAuthenticator::new(&user, &password);
let node = NodeTcpConfigBuilder::new("127.0.0.1:9042", auth).build();
let cluster_config = ClusterTcpConfig(vec![node]);
let no_compression: CurrentSession =
... | Rust | 0 |
k.END, "\n")
data.append(rule['domain_sets'].strip())
self.cb1['values'] = data
self.cb1['values'] = list(set(data))
self.cb2['values'] = list(set(data))
else:
self.log_area.insert(tk.END, "未查询到任何防火墙规则信息。\n")
self.cb1['values'] = ()... | Python | 1 |
/// Address must be >= 0x2000_0000 and <= 0x2007_FFFC. Bit must be < 32.
fn ref_to_bitband(address: u32, bit: u8) -> *mut u32 {
let prefix = address & 0xF000_0000;
let byte_offset = address & 0x0FFF_FFFF;
let bit_word_offset = (byte_offset * 32) + (u32::from(bit) * 4);
let bit_word_addr = bit_word_offse... | Rust | 0 |
# Generated by Django 5.0.1 on 2024-02-16 12:05
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admissions', '0002_information_image'),
]
operations = [
migrations.AddField(
model_name='major... | Python | 1 |
import asyncio
import json
import os
import sys
import aiofiles
from src.config import MODEL_NAME, client
# The meta-prompt to instruct the AI
META_PROMPT_TEMPLATE = """
你是一位世界级的AI提示词工程大师。你的任务是根据用户提供的【购买需求】,模仿一个【参考范例】,为闲鱼监控机器人的AI分析模块(代号 EagleEye)生成一份全新的【分析标准】文本。
你的输出必须严格遵循【参考范例】的结构、语气和核心原则,但内容要完全针对用户的【购买需求】进行定制。最终生... | Python | 1 |
"""
Methods about time.
"""
import pprint
import time
import warnings
from collections import OrderedDict
from lumo.utils.fmt import strftime
class Timer:
"""
A class for timing the time cost in each part.
A global object is contained in lumo:
```python
from lumo.utils import timeit
timeit.... | Python | 1 |
6)
if results.get('analytical'):
residuals = y_noisy - spline.fitted_values
standardized_residuals = residuals / np.sqrt(spline.sigma2)
# Simple QQ plot
sorted_residuals = np.sort(standardized_residuals)
n = len(sorted_residuals)
theoretical_quantiles = np.linspace(... | Python | 1 |
Handle`]s are considered equal, if they refer to objects in the same
/// memory location.
#[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Handle<T> {
storage: Storage<T>,
}
impl<T> Handle<T> {
/// Access the object that the handle references
pub fn get(&self) -> Ref<T> {
self.stor... | Rust | 0 |
sRecord;
use catalog::mini_attribute::MiniAttributeRecord;
pub struct CatalogManager {
pub database_rm: RecordManeger<MiniDatabaseRecord>,
pub class_rm: RecordManeger<MiniClassRecord>,
pub attribute_rm: RecordManeger<MiniAttributeRecord>,
}
impl CatalogManager {
pub fn new(config: Rc<Config>) -> Catal... | Rust | 0 |
g {
use unicode_normalization::UnicodeNormalization;
let base = if preserve_capitalization && self.capitalized {
self.alphabet.to_cap()
} else {
self.alphabet.to_low()
};
let diacritics = self
.diacritics
.iter()
.map(|... | Rust | 0 |
1091569, 633147943970),
(1106446, 227991176130),
(1129636, 228779785880),
(1138418, 199686270600),
(1155536, 261639726420),
(1142590, 242414202510),
(1142951, 241034267190),
(1149535, 244872330580),
(1132212, 256354807720),
(1135810, 191304301740),
(1148336, 182833143400),
(1... | Rust | 0 |
"""自律的なワークフロー実行のサンプル。"""
from genesis_agi.core.unified_manager import UnifiedManager
from genesis_agi.llm.client import LLMClient
from genesis_agi.operators.operator_registry import OperatorRegistry
from genesis_agi.operators.base_operator import BaseOperator
from genesis_agi.utils.cache import Cache
from typing import... | Python | 1 |
else {
for i in 0..keys_left.len() {
let next_key = keys_left[i];
if !distances.contains_key(&(last_key, next_key)) {
continue;
}
let to_next = distances[&(last_key, next_key)];
let mut rest = keys_left.clon... | Rust | 0 |
LineF)
apFileM = apFileM.replace("#-vga qxl","-vga none")
#apFileM = apFileM.replace("-monitor stdio","-monitor none")
apFileM = apFileM.replace("#-display none","-display none")
apFileM = apFileM.replace("RE... | Python | 1 |
)
with open(pairs_filename, 'w') as f:
f.write('10 300\n')
f.write('0001 1 2\n')
f.write('0001 1 0002 1\n')
f.write('0002 1 0003 1\n')
f.write('0001 1 0003 1\n')
f.write('0002 1 2\n')
f.write('0001 2 0002 2\n')
f.write('0002 2 0003 2\n')
f.writ... | Python | 1 |
d_default_scheme_if_necessary(
"https://phip1611.de".to_owned(),
))
.unwrap(),
)
.expect("must accept http");
assert_scheme_is_allowed(
&Url::from_str(&prepend_default_scheme_if_necessary(
"ftp://phip1611.de".to_owned(),
... | Rust | 0 |
# import libraries
import numpy, pylab
from pylab import *
# plot DOF convergence graph
axis('equal')
pylab.title("Error convergence")
pylab.xlabel("Degrees of freedom")
pylab.ylabel("Error [%]")
data = numpy.loadtxt("conv_dof_hp_iso_multi.dat")
x = data[:, 0]
y = data[:, 1]
loglog(x, y, "-s", label="hp-FEM (iso)")
da... | Python | 1 |
replace_pos <= args.span.end() {
if let Some(named) = &args.named {
for (name, _) in named.iter() {
let full_flag = format!("--{}", name);
if full_flag.starts_with(&substring) {
matching... | Rust | 0 |
(), filepath)
}
fn unseal(filepath: &str) -> Result<Self, EnclaveError> {
let buf = open(filepath)?;
Ok(Self::from(buf))
}
}
impl SealedKey for Seed {
fn seal(&self, filepath: &str) -> Result<(), EnclaveError> {
seal(&self.as_slice(), filepath)
}
fn unseal(filepath: &s... | Rust | 0 |
/// A signed 64-bit integer.
Int64,
/// An unsigned 8-bit integer.
UInt8,
/// An unsigned 16-bit integer.
UInt16,
/// An unsigned 32-bit integer.
UInt32,
/// An unsigned 64-bit integer.
UInt64,
/// A 32-bit floating point number.
Float32,
/// A 64-bit floating point ... | Rust | 0 |
}
},
)?;
let st = self.state.clone();
let allowed_hosts = self.allowed_hosts.clone();
let max_concurrent_requests = self.max_concurrent_requests;
linker.func(
Self::MODULE,
"req",
move |caller: Caller<'_>,
... | Rust | 0 |
from dndme.commands import Command
class ReorderInitiative(Command):
keywords = ["reorder"]
help_text = """{keyword}
{divider}
Summary: Reorder the combatants with a particular initiative value.
Usage: {keyword} <initiative value> <combatant1> [<combatant2> ...]
Example: {keyword} 17 Frodo Sam Gandalf
"""
... | Python | 1 |
import torch
import time
def update_state(demand,dynamic_capcity,selected,c=20):#dynamic_capcity(num,1)
depot = selected.squeeze(-1).eq(0)#Is there a group to access the depot
current_demand = torch.gather(demand,1,selected)
dynamic_capcity = dynamic_capcity-current_demand
if depot.any():
... | Python | 1 |
import numpy as np
import pandas as pd
multi = pd.MultiIndex.from_tuples([("IND","GAME1"),
("IND","GAME2"),
("IND","GAME3"),
("IND","GAME4"),
("AME","GAME1"),
... | Python | 1 |
// occurrences of "-" replaced with "_" and has "HTTP_" prepended to
// give the meta-variable name."
req.headers.iter().for_each(|header| {
let key = format!(
"HTTP_{}",
header.0.as_str().to_uppercase().replace("-", "_")
);
// Per spec 4.1.18, skip some heade... | Rust | 0 |
Key::Space => 0x2c,
Key::Minus => 0x2d,
Key::Equals => 0x2e,
Key::LeftBrace => 0x2f,
Key::RightBrace => 0x30,
Key::Backslash => 0x31,
Key::NonUsHash => 0x32,
Key::Semicolon => 0x33,
Key::Apostrophe => 0x34,
Key::GraveAccent => 0x35,
... | Rust | 0 |
force_zeros_for_empty_prompt=False,
)
else:
text_config = create_ldm_bert_config(original_config)
text_model = convert_ldm_bert_checkpoint(checkpoint, text_config)
tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased", local_files_only=local_files_only)
pipe =... | Python | 1 |
_POW17[0] == 17.0);
const_assert!(F32_POW18[1] / F32_POW18[0] == 18.0);
const_assert!(F32_POW19[1] / F32_POW19[0] == 19.0);
const_assert!(F32_POW20[1] / F32_POW20[0] == 20.0);
const_assert!(F32_POW21[1] / F32_POW21[0] == 21.0);
const_assert!(F32_POW22[1] / F32_POW22[0] == 22.0);
const_assert!(F32_POW23[1] / F32_POW23[0... | Rust | 0 |
active_adapter)
result = result.to(torch_result_dtype)
return result
def __repr__(self) -> str:
rep = super().__repr__()
return "lora." + rep
def dispatch_default(
target: torch.nn.Module,
adapter_name: str,
lora_config: LoraConfig,
**kwargs,
) -> Optional[to... | Python | 1 |
fn hello_parser(i: &str) -> nom::IResult<&str, &str> {
// // alt!(i, tag!("hello") | tag!("goodbye"))
// nom::branch::alt((
// nom::bytes::complete::tag("hello"),
// nom::bytes::complete::tag("goodbye"),
// ))(i)
// }
// ---------------------------------------------------------------------... | Rust | 0 |
from django.db import models
from django.conf import settings
from content.models import Post, StoryImage
class Comment(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name='comments')
text = models.CharField(max_length=255)
user = models.ForeignKey(
settin... | Python | 1 |
sum(
Constantes.CARÁCTERES_NUMÉRICOS.index(char.upper())
* (16 ** (len(x) - j - 1))
for j, char in enumerate(x)
) # <-- TRANSFORMAMOS DE HEXADECIMAL A NUMERO DE 0 A 255
/ 255
for x in [color_nivel[i : i + 2] for i in range(0, len(col... | Python | 1 |
y (will still fall back to camera if there are none)
Scene,
/// Use camera flash as the light source
Camera,
}
#[derive(Clone, Debug)]
pub enum RussianRoulette {
/// Select survival probability based on path throughput
Dynamic,
/// Constant survival probability
Static(Float),
/// No rus... | Rust | 0 |
f(coloured):
r_patch,p_patch = extract_rich_and_poor_textures(variance_values=pixel_var_degree,patches=color_patches)
else:
r_patch,p_patch = extract_rich_and_poor_textures(variance_values=pixel_var_degree,patches=gray_scale_patches)
rich_texture,poor_texture = None,None
with concurrent.fut... | Python | 1 |
t
return
def extract_rating_dicts(
completion: Dict[str, str]
) -> Tuple[Dict[str, int], Dict[str, int]]:
"""Extracts the rating dictionaries from the completion text.
Args:
- completion: Dict[str, str], the completion text from OpenAI API
Returns:
- clinically_significant: Dict[str, in... | Python | 1 |
0.5)
save_png(instance)
ele_2 = self.find_element(click_loc)
ele_2.click()
# 动作:输入
def key_input(self, loc, content=None):
"""
:param self:
:param loc: 输入框定位
:param content: 输入内容
:return:
"""
ele = self.find_element(loc)
e... | Python | 1 |
::Open => "Open",
fidl_sme::Protection::Wep => "WEP",
fidl_sme::Protection::Wpa1 => "WPA1",
fidl_sme::Protection::Wpa1Wpa2PersonalTkipOnly => "WPA1/2 PSK TKIP",
fidl_sme::Protection::Wpa2PersonalTkipOnly => "WPA2 PSK TKIP",
fidl_sme::Protection::Wpa1Wpa2Person... | Rust | 0 |
from flask import Blueprint
from flask import request, render_template
from src.middleware.auth_middleware import require_token
from src.controller.user_controller import (
register,
login,
request_password_reset,
reset_password,
)
from src.controller.product_controller import (
create_product,
... | Python | 1 |
class Solution:
def swapKth(self, arr, k):
# Code Here
n=len(arr)
start_index=k-1 # Converting into 0-indexing
end_index=n-k # kth element from the end
arr[start_index],arr[end_index]=arr[end_index],arr[start_index]
return arr
| Python | 1 |
"""
python implementation of Hilbert Schmidt Independence Criterion
hsic_gam implements the HSIC test using a Gamma approximation
Python 2.7.12
Gretton, A., Fukumizu, K., Teo, C. H., Song, L., Scholkopf, B.,
& Smola, A. J. (2007). A kernel statistical test of independence.
In Advances in neural information processin... | Python | 1 |
ation
# sample num_neg_samples edges from the population of common neighbour edges
idx = idx.to('cpu')
for _ in range(3): # Number of tries to sample negative indices.
rnd = sample(population, num_neg_samples, device='cpu')
mask = np.isin(rnd, idx)
if neg_idx is not None:
... | Python | 1 |
ld_lyr = CString::new("VK_LAYER_KHRONOS_validation").unwrap();
if debug_mode {
inst_lyrs.push(vald_lyr.as_c_str());
}
let inst_lyrs_raw = inst_lyrs.iter().map(|lyr|lyr.as_ptr()).collect::<Vec<_>>();
let mut inst_exts = vec![];
inst_exts.push(ash::extensions::ext::Deb... | Rust | 0 |
match command.split():
# ^ keyword
case ["quit"]:
# ^ keyword
print("Goodbye!")
quit_game()
case ["look"]:
# ^ keyword
current_room.describe()
case ["get", obj]:
# ^ keyword
character.get(obj, current_room)
case ["go", direction]:
# ^ keyword
curre... | Python | 1 |
usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<SmtProofEntryReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unc... | Rust | 0 |
#[derive(Reflect, Default)]
pub struct Sprites {
tree: usize,
player_south: usize,
}
/// Custom game state.
/// Two game states are required to start the loading process and one
/// to wait for them to be loaded.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub enum GameState {
Loading,
Ingame,
}
pub ... | Rust | 0 |
#!/usr/bin/env python3
"""
Enhanced Agricultural AI System Test Suite
This script demonstrates the significant improvements made to the agricultural AI system:
1. Enhanced Entity Normalization
2. Enhanced Query Processing with Entity-Aware Semantic Matching
3. Mistral-based Entity Extraction with Function Calling
4. ... | Python | 1 |
use serde::{de::DeserializeOwned, Serialize};
use super::{EncryptionSchedule, HoneyBadger, Params, SubsetHandlingStrategy};
use crate::{Contribution, NetworkInfo, NodeIdT};
/// A Honey Badger builder, to configure the parameters and create new instances of `HoneyBadger`.
pub struct HoneyBadgerBuilder<C, N> {
///... | Rust | 0 |
from edsl.coop.coop import Coop
def test_latest_stable_version():
c = Coop()
assert c._get_latest_stable_version("0.1.37") == "0.1.37"
assert c._get_latest_stable_version("0.1.37.dev1") == "0.1.36"
assert c._get_latest_stable_version("0.1.38.dev2") == "0.1.37"
# Check for single digit versions
... | Python | 1 |
if !pos.contains_key(up) {
let p = pos[&n]+d;
pos.insert(*up, p);
queue.push(*up);
}
}
for (down,d) in down_edges.get(&n).unwrap_or(&Vec::new()).iter() {
if !pos.contains_key(down) {
let p = pos[&n]-d;
... | Rust | 0 |
args = dict(cmap='gray', vmin=0, vmax=1)
subplotimg(axs[k1][k2], out[j], f'{n1} {n2}',
**args)
for ax in axs.flat:
ax.axis('off')
plt.savefig(
... | Python | 1 |
state: &mut State<C>,
ws_index: usize,
tag_index: usize,
) -> bool {
if ws_index < state.workspaces.len() && tag_index < state.tags.len() {
let workspace = &state.workspaces[ws_index].clone();
state.focus_workspace(workspace);
state.goto_tag_handler(tag_index + 1);
return... | Rust | 0 |
`call` instruction the flagset [AP_UP] is incorrect
/// or if in any other instruction the flagset AP_UP has more than 1 nonzero bit
/// or if the flagset `OPCODE` has more than 1 nonzero bit
/// Inputs: `size`, `res`, `dst`, `dst_addr`, `op1_addr`
/// Outputs: `(next_ap, next_fp, op0_update, op... | Rust | 0 |
plt.show()
# Now zoom out!
# In[52]:
M=400
# Generate a 'mesh grid', i.e. x,y values in an image
v0,v1=meshgrid(linspace(-10,10,M),linspace(-10,10,M))
batchsize=M**2 # number of samples = number of pixels = M^2
y_in=zeros([batchsize,2])
y_in[:,0]=v0.flatten() # fill first component (index 0)
y_in[:,1]=v1.flatten(... | Python | 1 |
1, 1, 28, 28))
.to_kind(Kind::Float)
.f_mul_scalar(1. / 255.)?;
let train_classes = mnist.classes().slice(s![..60_000]);
let train_labels = Tensor::of_slice(train_classes.as_slice().unwrap());
// Use the last 10_000 images as the test set.
let test_images = mnist.images().slice(s![60_000... | Rust | 0 |
L, "send count increase insufficient")
main.lh.unconfigure_net(PRIO_NET)
before_stats_main = main.lh.get_net_stats()
#print(before_stats_main)
for i in range(0, PING_TIMES):
rc = main.lh.exec_ping(agent_nids[PING_NID_NUM])
if not rc:
return lutfrc(LUTF_TEST_FAIL, "ping failed")
after_stats_main ... | Python | 1 |
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 1 |
t((very_start_time, start_height),
triplet,
fill='#d90429')
else:
draw_bar.text((image_width - text_width, start_height),
triplet,
fill='#d90429')
... | Python | 1 |
return Err(GenericNetlinkError::RequestFailed(format!(
"The NLA reply is not GenericNetlinkAttr::Ctrl: {:?}",
&genl_msg
)));
}
};
Err(GenericNetlinkError::RequestFa... | Rust | 0 |
ot.len() < nnum - nden + 1
&& (quot.len() < nnum - nden || !crate::ubig::cmp::lt(&num[nnum-nden..], den))
{
Err(Error::NoSpace)
}
else if nden == 1
{
let (nquot, rem) = div_assign_digit(num, den[0])?;
if nquot > quot.len()
{
Err(Error::NoSpace)
... | Rust | 0 |
(TABLE_SIZE))) + self.get2(x, y)]
}
pub fn get4<T: SignedInt>(&self, x: T, y: T, z: T, w: T) -> uint {
self.values[math::cast::<T, uint>(math::signed_modulus(w, math::cast(TABLE_SIZE))) + self.get3(x, y, z)]
}
}
#[cfg(test)]
mod tests {
use std::rand::random;
use perlin::perlin3_best;
... | Rust | 0 |
import socket
import RPi.GPIO as GPIO
import json
HOST = '0.0.0.0'
PORT = 12345
GPIO.setmode(GPIO.BOARD)
MOTOR_PINS = [32, 33, 12, 35]
for pin in MOTOR_PINS:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
pwm_motors = [GPIO.PWM(pin, 100) for pin in MOTOR_PINS]
for pwm in pwm_motors:
pwm.start(0)
... | Python | 1 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api.views.restaurants import RestaurantViewSet
router = DefaultRouter()
router.register(r'restaurants', RestaurantViewSet, basename='restaurant')
urlpatterns = [
path('', include(router.urls)),
]
| Python | 1 |
import sys
import os
import zipfile
import numpy as np
# because of display issue on travis
# https://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-server
import matplotlib as mpl
import unittest
mpl.use("Agg")
# assumed being called from obj2png/
sys.path.append("./src")
sys.pa... | Python | 1 |
Variable::RustObject(Arc::new(Mutex::new(Arc::new(m)))))))
}
}
x => return Err(module.error(call.args[0].source_range(),
&rt.expected(x, "string"), rt))
};
rt.pop_fn(call.name.clone());
Ok(Some(v))
}
fn load__source_imports(
rt: &mut Runtime,
call: &a... | Rust | 0 |
lbrot {
properties: Properties,
frame: Rect,
fractal: Vec<(usize, usize, f64)>,
min: f64,
max: f64,
}
impl Mandelbrot {
fn compute_fractal(&mut self, size: Size) {
let Self {
properties: Properties { position, scale },
..
} = *self;
let width = s... | Rust | 0 |
sses=ncls, average="macro")
ref.update(preds[:, lvl], target[:, lvl])
ref_vals.append(ref.compute().item())
expected = sum(w * v for w, v in zip(weights, ref_vals))
assert got == pytest.approx(expected, rel=1e-5, abs=1e-6)
# -------------------------- MetricCollection callable ---------------... | Python | 1 |
"""关闭"""
self.exit()
class CtpTdApi(TdApi):
def __init__(self, gateway, temp_path, user_id, password, broker_id, address, auth_code, user_production_info, api_name='ctp_td'):
super(CtpTdApi, self).__init__()
self.gateway = gateway
self.temp_path = temp_path
self.r... | Python | 1 |
"""
Implements the optimizer for the 1D MRF using Iterated Conditional Modes
"""
import numpy as np
def penalty(energy_band, arpes_mapping, energy_val, idx, eta):
"""
defines the local penalty function for some node in the mrf chain
"""
for idx, node in enumerate(energy_band):
# objective ... | Python | 1 |
impl TryFrom<u8> for Unify {
type Error = ();
fn try_from(value: u8) -> Result<Unify, ()> {
use Unify::*;
match value {
OPCODE_END => Ok(End),
OPCODE_UNIFY_TERM => Ok(Term),
OPCODE_UNIFY_TERM_SAVE => Ok(TermSave),
OPCODE_UNIFY_REF => Ok(Ref),
... | Rust | 0 |
defaults = {
"endpoint": "127.0.0.1:9000", # api 端口
"root_name": "chenggou",
"root_password": "12345678",
} | Python | 1 |
.TRAIN.BG_THRESH_LO))[0]
# Small modification to the original version where we ensure a fixed number of regions are sampled
if fg_inds.size > 0 and bg_inds.size > 0:
fg_rois_per_image = min(fg_rois_per_image, fg_inds.size)
fg_inds = npr.choice(fg_inds, size=int(fg_rois_per_image), replace=False)
bg_roi... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="django-deployer",
version="0.1.6",
description="Django deployment tool for popular PaaS providers",
long_description=open('README.rst').read() + '\n\n' + open('CHANGES.rst').read(),
keywords="Pa... | Python | 1 |
's no bsdf, it means we've hit the interface between two
// different mediums. We simply continue along the same direction.
ray = isect.spawn_ray(&ray.d);
bounces -= 1;
continue;
}
let bsdf = isect.bsdf.clone().unwrap();
... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [path("index.html", views.index, name="index"),
path("CreateProfile.html", views.CreateProfile, name="CreateProfile"),
path("CreateProfileData", views.CreateProfileData, name="CreateProfileData"),
path("Hospital.html", views.Hospit... | Python | 1 |
t.show()
output = PrettyTable(['Algorithm','Network Size', 'Avg probability of node selection'])
output.add_row(['Random Selection',networkSizeList[0],round(distanceList_01[0],10)])
output.add_row(['Greedy Selection',networkSizeList[1],round(distanceList_02[0],10)])
output.add_row(['Greedy Probabiity ... | Python | 1 |
failed_events.append(
{
"title": event.get("title", "未知活动"),
"url": (
event.get("registration_links", ["无"])[0]
if event.get("registration_links")
else "无"
),
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.