text string | label_name string | labels int64 |
|---|---|---|
# coding: utf-8
"""
CNB OPENAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0
Contact: cnb@tencent.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class m... | Python | 1 |
import bge
def main():
cont = bge.logic.getCurrentController()
own = cont.owner
Resolutionid = cont.sensors["Resolution"].owner
Qualityid = cont.sensors["Quality"].owner
click = cont.sensors["click"].positive or cont.sensors["enter"].positive or cont.sensors["A"].positive
if own['wait']==True:
own['waittime'... | Python | 1 |
lc + one,
|lc| lc + sb_y.get_variable()
);
return Ok(());
}
}
#[cfg(test)]
mod test {
use ::eddsa::{PrivateKey, PublicKey};
use rand::{SeedableRng, Rng, XorShiftRng};
use super::*;
use ::circuit::test::*;
use ::circuit::boolean::{Boolean, AllocatedBit};
use pa... | Rust | 0 |
12, pcr12, ALT0), ("PTC12/LLWU_P18", "R3"), ("LPADC0_SE7", "PTC12/LLWU_P18", "LPSPI0_PCS0", "LPI2C1_SCL", "LPI2C0_SCLS", x, "TPM0_CH5", "EWM_OUT_b"),
PTC27: (ptc27, 27, pcr27, ALT0), ("PTC27", "P6"), (x, "PTC27", x, x, x, x, "TPM0_CH4", x),
PTC28: (ptc28, 28, pcr28, ALT0), ("PTC28", "U5"), (x, "PTC28", x, "LPS... | Rust | 0 |
from chatgptmain.judgeuser import Judgeuser
class judgeChatpt():
def judgeChatptfuction(self,wxuser):
print(wxuser)
#在这一步执行Judgeuser进行判断
botloaded,panduan=Judgeuser(wxuser)
if panduan is False:#如果没有此用户,就生成一个
# judgeChatpt().judgeChatptfuction("clear").clear_conversations... | Python | 1 |
SET_A::CYC2048),
9 => Val(EWOFFSET_A::CYC4096),
10 => Val(EWOFFSET_A::CYC8192),
11 => Val(EWOFFSET_A::CYC16384),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `CYC8`"]
#[inline(always)]
pub fn is_cyc8(&self) -> bool {
*self ... | Rust | 0 |
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from src.config import WEATHER_MCP_PORT, normal_stora... | Python | 1 |
uestId")
class DescribeAttackVulTypeListRequest(AbstractModel):
"""DescribeAttackVulTypeList请求参数结构体
"""
class DescribeAttackVulTypeListResponse(AbstractModel):
"""DescribeAttackVulTypeList返回参数结构体
"""
def __init__(self):
r"""
:param _List: 威胁类型列表
:type List: list of str... | Python | 1 |
ng nổ gradient_ là một hiện tượng phổ biến khiến cho giá trị dự báo bị quá lớn (thường là giá trị _nan_).
#
# * Không chuẩn hoá dữ liệu đầu vào có thể khiến cho quá trình huấn luyện thiếu ổn định và có thể không vượt qua được các _điểm cực trị địa phương_ để đi tới _cực trị toàn cục_.
#
# * Giá trị dự báo của biến mụ... | Python | 1 |
e)
res["link_info"]["location_info"].pop("device_name_offset", None)
if "target" in res:
res["target"].pop("index", None)
res["target"].pop("size", None)
if "items" in res["target"]:
for item in res["target"]["items"]:
... | Python | 1 |
from dataclasses import dataclass
from typing import Dict
@dataclass
class MCState:
temperature: float
energy: float
entropy: float
enthalpy: float
coherence: float
personality: Dict
phase: str
response: str = "" | Python | 1 |
from django import forms
from .models import UserBehavior
class UserPreferenceForm(forms.ModelForm):
class Meta:
model = UserBehavior
fields = ['favorited', 'play_count'] | Python | 1 |
pens diaglog box.
"""
# find help display and make sure it's hidden
element = self.driver.find_element_by_id('help-modal')
assert not(element.is_displayed())
# click the help icon
self.driver.find_element(
By.XPATH,
'/html/body/nav/div/div[2]/ul[... | Python | 1 |
, sticky=tk.W)
entry = tk.Entry(root)
entry.insert(0, str(default_value))
entry.grid(row=idx, column=1, padx=10, pady=5)
self.entries[label] = entry
tk.Label(root, text=tooltip, fg="gray").grid(row=idx, column=2, padx=10, pady=5, sticky=tk.W)
... | Python | 1 |
"""Metrics for quantile regression"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
def pinball_loss(target_value, quantile_values, quantile_levels, sample_weight=None, quantile_weight=None):
# "target_value" must be 2D pandas or numpy arrays
target_value = np.array(target_value).r... | Python | 1 |
# utils/indicators.py
import numpy as np
def calculate_sma(prices: list, period: int = 14) -> float:
if len(prices) < period:
return round(np.mean(prices), 2)
return round(np.mean(prices[-period:]), 2)
def calculate_rsi(prices: list, period: int = 14) -> float:
if len(prices) < period + 1:
... | Python | 1 |
if self.outside_ray_sampler is not None:
num_samples_all += self.outside_ray_sampler.num_samples
outputs["num_samples_per_batch"] = num_samples_all
normals = inside_outputs[
"gradients"] * weights[:, :num_inside, :] * inside_sphere
normals = paddle.sum(normals, axi... | Python | 1 |
#x?}, environ_buf={:#x?})",
environ,
environ_buf,
);
let vmctx = &mut *vmctx;
let argv_environ = get_argv_environ(vmctx);
let environ_count = match u32::try_from((*argv_environ).environ_count) {
Ok(host_environ_count) => host_environ_count,
... | Rust | 0 |
_from_slice(&ke2_state.km3).map_err(|_| InternalError::HmacError)?;
client_mac.update(&ke2_state.hashed_transcript);
if client_mac.verify(&ke3_message.mac).is_err() {
return Err(ProtocolError::InvalidLoginError);
}
Ok(ke2_state.session_key.to_vec())
}
fn ke2_messag... | Rust | 0 |
inicio = int(input("Ingrese el inicio del rango de numeros: "))
fin = int(input("Ingrese el fin del rango de numeros: "))
suma = 0
for num in range(inicio, fin + 1):
if num % 2 == 0:
suma += num
print ("la suma de los numeros pares es: ", suma)
| Python | 1 |
hunk = predict_chunk_content(model_id, response + "\n")
yield "{}".format(chunk.model_dump_json(exclude_unset=True))
# get answer with text query
pattern = re.compile(r'\"(.*?)\"')
result = re.search(pattern, response)
if result:
_text = result.group(1)
qu... | Python | 1 |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure PGO is working properly.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(forma... | Python | 1 |
nic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
... | Rust | 0 |
elf._session.get_snapshot(
force_refresh=ActionExecutor.should_update_snapshot(action),
diff_only=True,
)
assert self._session.snapshot is not None
meta = self._session.snapshot.last_info
logger.debug(
"Snapshot after action... | Python | 1 |
#[cfg(windows)]
pub fn assert_socket_non_blocking<S>(_: &S) {
// No way to get this information...
}
/// Assert that `CLOEXEC` is set on `socket`.
#[cfg(unix)]
pub fn assert_socket_close_on_exec<S>(socket: &S)
where
S: AsRawFd,
{
let flags = unsafe { libc::fcntl(socket.as_raw_fd(), libc::F_GETFD) };
... | Rust | 0 |
/// `#[property(get="path")]` | ⚠️ custom get (no set) | ✔️ custom get (no set)
/// `#[property(get="path", set)]` | ✔️ custom get, default set | ❌️
/// `#[property(get="path", set="path")]` | ⚠️ custom get + set | ✔️ custom get + set
///
/// "⚠️" means that this attribute com... | Rust | 0 |
if cf_info.used(continue_block_id) {
let new_id = split_block(builder, continue_block_id, true);
cf_info.retarget(continue_block_id, new_id);
if branch_conditional_ops.contains(&(continue_block_id, *looping_branch_idx)) {
modified_ids.insert(continue_block_... | Rust | 0 |
_nodes {
hash_tree.update_leaf_hash(&label, hash)?;
}
// Note: there are no know errors that could cause a valid deserialization to produce an
// invalid tree, since we're only storing leaf hashes, but its still a reasonable point
// to verify consistency.
hash_tree.v... | Rust | 0 |
tent: center; align-items: center; height: 100vh; margin: 0; }}
.container {{ background-color: #282828; padding: 40px; border-radius: 10px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.5); max-width: 90%; }}
h1 {{ color: #1DB954; }} p {{ font-size: 1.1em; line-height: 1.6;}}
... | Python | 1 |
#python3 / newer versions of gdb
pc = int(pc)
except gdb.error:
pc = int(str(pc), 16)
blk = gdb.block_for_pc(pc)
print(s, ptr['goid'], "{0:8s}".format(sts[int(ptr['status'])]), blk.function)
def find_goroutine(goid):
"""
find_goroutine attempts to find the goroutine identified by goid.
It retur... | Python | 1 |
Target: The active target.
"""
return self.active_target
def set_active_target(self, target: CFTarget) -> None:
"""Set the active target with the target name provided.
Args:
target (Target): The target object to set as the active target
"""
self.targ... | Python | 1 |
self.num_examine:
response_str = self.tokenizer.decode(data.batch["responses"][i][:length], skip_special_tokens=True)
prompt_str = self.tokenizer.decode(data.batch["prompts"][i], skip_special_tokens=True)
ground_truth = data[i].non_tensor_batch["reward_model"].get("groun... | Python | 1 |
(2))
}
pub fn get_cell_fill(&self, i: usize, j: usize) -> (Path, Path) {
let point = self.coords_to_position(i, j);
let size = Size::new(
self.cell_width,
self.cell_height,
);
let cell_background = Path::rectangle(point, size);
let mut point= Poin... | Rust | 0 |
#!/usr/bin/env python
import gzip
import sys
INPUTVCF = sys.argv[1]
CONVERTER = sys.argv[2]
OUTINFOMATRIX =sys.argv[3]
OUT = open(OUTINFOMATRIX, "w")
out = "\t".join(["SNP","CHRPOS","REF","ALT","R2","AF"])
print(out, file = OUT)
variant_dic = {}
with open(CONVERTER, "r") as f:
for line in f:
line = line.rstrip().s... | Python | 1 |
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from train_model import load_data
# Load dữ liệu
(x_train, y_train), (x_test, y_test) = load_data()
# Chuẩn hoá dữ liệu
x_test = x_test.astype('float32') / 255.0
# Chuyển đổi thành one-hot encoding
y_test = tf.keras.utils.to_ca... | Python | 1 |
t_test(base, mouse_position);
}
}
Event::MouseLeave => {
gui.hovered = None;
}
_ => {
if let Some(hovered) = &gui.hovered {
let hovered = hovered.borrow();
hovered.handle_event(&e); // TODO: replies
}
}
}
}
})
.display(|| {
let... | Rust | 0 |
Poll::Pending => Poll::Pending,
}
} else {
Poll::Pending
}
}
}
#[pyclass]
struct PyDoneCallback {
cancel_tx: Option<oneshot::Sender<()>>,
}
#[pymethods]
impl PyDoneCallback {
#[call]
pub fn __call__(&mut self, fut: &PyAny) -> PyResult<()> {
let py = f... | Rust | 0 |
import FWCore.ParameterSet.Config as cms
import DQM.TrackingMonitor.TrackingMonitor_cfi
import DQMOffline.Alignment.TkAlCaRecoMonitor_cfi
#---------------
# AlCaReco DQM #
#---------------
__selectionName = 'SiStripCalMinBias'
ALCARECOSiStripCalMinBiasTrackingDQM = DQM.TrackingMonitor.TrackingMonitor_cfi.TrackMon.clo... | Python | 1 |
unwrap();
assert_eq!(
TransportHeader { protocol: TransportProtocol::RequestResponse },
transport_header
);
let request_response_header = RequestResponseHeader::from_bytes(&mut reader).unwrap();
assert_eq!(
RequestResponseHeader { request_id: 259 },
request_response_head... | Rust | 0 |
from dotenv import load_dotenv
from core import load, process_issues, make_api_request
from util import get, field_type, now, clean, map_field
load_dotenv()
jql = 'issuekey IN (EDU-1, HOUSE-15)'
def standard_fields(issues):
load([
{
'issue_id': issue['id'],
'issue_key': issue['key'... | Python | 1 |
31Hz1ik1FBwyrfAmH4WEgbMr3SHpnXqNAWXaSBm");
// - Macro for creating a program with functions that other people can call
#[program]
// - Module
pub mod myepicproject {
use super::*;
// - function with type signature
// - Initialize the total_gif count on the base accout
pub fn start_stuff_off(ctx: Cont... | Rust | 0 |
< d1 => ( 1.0, 0.0 + INPUT_V * (dlt - d0), PI * 1.0 / 2.0),
dlt if d1 <= dlt && dlt < d2 => ( 1.0, 1.0, PI * 1.0 / 2.0 + INPUT_OMEGA * (dlt - d1)),
dlt if d2 <= dlt && dlt < d3 => ( 1.0 - INPUT_V * (dlt - d2), 1.0, ... | Rust | 0 |
RWops) -> c_int;
pub fn IMG_isPNM(src: *const SDL_RWops) -> c_int;
pub fn IMG_isTIF(src: *const SDL_RWops) -> c_int;
pub fn IMG_isXCF(src: *const SDL_RWops) -> c_int;
pub fn IMG_isXPM(src: *const SDL_RWops) -> c_int;
pub fn IMG_isXV(src: *const SDL_RWops) -> c_int;
pub fn IMG_isWEBP(src: *const SDL_RWops) -> c_int;
//... | Rust | 0 |
from fastapi import HTTPException, status
ExistingUserExeption = HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Этот Email уже зарегестрирован',
)
UncorectEmailOrPasswordExeption = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Неверный email или пароль',
)
NoTokenE... | Python | 1 |
t_index, 0].item(),
'base_vel_y': env.simulator.base_lin_vel[robot_index, 1].item(),
'base_vel_z': env.simulator.base_lin_vel[robot_index, 2].item(),
'base_vel_yaw': env.simulator.base_ang_vel[robot_index, 2].item(),
'contact_forces_z': env... | Python | 1 |
`debugserver_types` crate, because it's automatically
//! generated from an outdated JSON schema. Generating types on our own using
//! `schemafy` has a disadvantage: even if we put it in a separate crate, it
//! still has a big negative impact on the Rust Language Server perfomance. On
//! top of that, using `schema... | Rust | 0 |
> List[Dict[str, Any]]:
"""Возвращает список доступных моделей Yandex GPT."""
# Yandex GPT API не предоставляет endpoint для получения списка моделей
# Возвращаем известные модели
return [
{
"name": "Yandex GPT Lite",
"model_name": "yandexgpt-l... | Python | 1 |
Some products have multiple factorizations, but
* only when one factor has at least a 2.5x ratio to the factors of the other
* factorization. This is because any smaller ratio would not make a difference
* when ensuring the VCO's frequency is within spec.
*
* Throughout the calculation function, fixed point arith... | Rust | 0 |
import os
# 保存当前代码页
original_codepage = os.popen("chcp").read().strip()
# 更改代码页为 UTF-8
os.system("chcp 65001")
import encrypt
import patch
import random
import compiler
import argparse
import banner
parser = argparse.ArgumentParser()
# 在参数构造器中添加两个命令行参数
parser.add_argument('--i', type=str, default="shellcode文件路径")
pars... | Python | 1 |
# Copyright (c) 2025 PaddlePaddle Authors. 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 required by appli... | Python | 1 |
ec![0u8; bytes_per_frame * (cycle_range.end - cycle_range.start) as usize];
Self {
cycle_start: cycle_range.start,
cycle_end: cycle_range.end,
bitranges: bitranges.into(),
bytes_per_frame,
data: data.into(),
}
}
pub fn get(&self, sign... | Rust | 0 |
from os import system, path, getcwd
import subprocess
mingwPath = 'C:\\mingw\\mingw32\\bin\\'
gccPath = path.join(mingwPath, 'g++')
objCopyPath = path.join(mingwPath, 'objcopy')
stubFile = path.join(getcwd(), 'stub.cpp')
out_AsmScriptFile = path.join(getcwd(), 'asm.s')
out_ObjectFile = path.join(getcwd(), 'asm.o')
o... | Python | 1 |
vampytest.assert_eq([*prompt.iter_channels()], expected_output)
def test__OnboardingPromptOption__iter_roles():
"""
Tests whether ``OnboardingPromptOption.iter_roles`` works as intended.
"""
role_id_0 = 202303040019
role_id_1 = 202303040020
role_0 = Role.precreate(role_id... | Python | 1 |
: Float, ay: Float, az: Float) {
verify_initialized!(self, "pbrt.rotate");
self.for_active_transforms_mut(|ct| *ct = *ct * Transform::rotate(angle, [ax, ay, az]));
}
/// Sets the current transforms to look at the given directions.
fn look_at(&mut self, eye: [Float; 3], look: [Float; 3], up:... | Rust | 0 |
.', '/')
sysctl_write(f'net.mpls.conf.{system_interface}.input', 1)
else:
system_interfaces = []
# If MPLS interfaces are not configured, set MPLS processing disabled
for interface in glob('/proc/sys/net/mpls/conf/*'):
system_interfaces.append(os.path.basename... | Python | 1 |
An iterator over the relocations in an `CoffSection`.
pub struct CoffRelocationIterator<'data, 'file> {
file: &'file CoffFile<'data>,
relocations: pe::relocation::Relocations<'data>,
}
impl<'data> CoffFile<'data> {
/// Get the COFF headers of the file.
// TODO: this is temporary to allow access to feat... | Rust | 0 |
import pydantic as _pydantic
class Influences(_pydantic.BaseModel):
elder: bool | None = None
shaper: bool | None = None
crusader: bool | None = None
redeemer: bool | None = None
hunter: bool | None = None
warlord: bool | None = None
# Shared item props
class _BaseItem(_pydantic.BaseModel):
... | Python | 1 |
#!/usr/bin/python3
print("\"Programming is like building a multilingual puzzle")
| Python | 1 |
}
fn step(&mut self) {
if let Some(called_number) = self.call_order.pop() {
self.last_call = Some(called_number);
let mut just_bingoed: Vec<&BingoBoard> = Vec::new();
for b in &mut self.boards {
if b.bingo {
// no need to continu... | Rust | 0 |
from app.errors.base import BaseAPIException
from app.errors.processing import ProcessingException
from app.errors.validation import ValidationException
__all__ = [BaseAPIException, ProcessingException, ValidationException]
| Python | 1 |
助建站系统 1.0",
"zidian.rar":"新华字典查询网站",
"site8002.rar":"ASP+Ajax+Jquery无刷新留言本",
"ZonGG_1.3_build20120415.rar":"忠网广告管理系统ZonGG 1.3 build 20120415",
"kcjiaju.rar":"康城家具企业网站系统 1.1",
"QvodCms_4.0.2.rar":"QVODCMS点播系统 4.0.2",
"3dflash.rar":"追梦3Dflash相册管理系统 1.0",
"ESMS_06.0108.H.rar":"安然企业网站管理系统 06.0108.H",
"huisi2.5.rar"... | Python | 1 |
8_unchecked(self.xml_verbose_bytes()) }
}
/// Create enumerated value from XML verbose bytes.
#[inline]
pub fn from_xml_verbose_bytes(bytes: &[u8]) -> Result<Self> {
match bytes {
Self::PROTEIN_LEVEL_XML_VERBOSE => Ok(ProteinEvidence::ProteinLevel),
Self::TRANSCRIPT... | Rust | 0 |
write access to buffer 0. Use this flag to enable the display
/// driver to select the most efficient presentation technique for the
/// swap chain.
///
/// <div style="padding: 10px 10px 2px 10px; margin: 10px; background-color: #F2F2F2">
///
/// **Note**
/// There are differences between ... | Rust | 0 |
import pytest
from projeto.models.pessoa import Pessoa
from projeto.models.endereco import Endereco
from projeto.models.enum.sexo import Sexo
from projeto.models.enum.uf import Unidade_federativa
@pytest.fixture
def criar_pessoa():
pessoa_1 = Pessoa("Lucas",24,Sexo.MASCULINO,
Endereco("Rua A", ... | Python | 1 |
(anonymous=True)
private_node_one_anonymous_link.nodes.add(private_node_one)
private_node_one_anonymous_link.save()
return private_node_one_anonymous_link
@pytest.fixture()
def private_node_one_url(self, private_node_one):
return f'/{API_BASE}nodes/{private_node_one._id}/'
... | Python | 1 |
import os
import json
import pickle
import logging
import numpy as np
import pandas as pd
from tqdm import tqdm
from pycitysim.map import Map
from datetime import datetime
from calSegForEval import calSegForEval
from shapely import Point
CONSUMPTION_INDEX = {
"low": 1,
"slightly_low": 2,
"median": 3,
... | Python | 1 |
new_zeros(center_xs.shape)
# project the points on current lvl back to the `original` sizes
lvl_begin = 0
for lvl_idx, num_points_lvl in enumerate(num_points_per_lvl):
lvl_end = lvl_begin + num_points_lvl
stride[lvl_begin:lvl_end] = self.strides[lvl_idx] * radius
... | Python | 1 |
::CMP_SPEC>;
#[doc = "Compare. This register stores the compare value, which is used to set the maximum count value to initiate a reload of the timer to 0x0001."]
pub mod cmp;
#[doc = "PWM register accessor: an alias for `Reg<PWM_SPEC>`"]
pub type PWM = crate::Reg<pwm::PWM_SPEC>;
#[doc = "PWM. This register stores the ... | Rust | 0 |
": [
10 * M,
10 * M,
], # This device always uses 10M, no matter what is configured.
"bandwidth": [10 * M, 10 * M],
"rx_rf_gain": list(range(0, 16)),
"rx_if_gain": list(range(0, 16)),
"rx_baseband_gain": list(range(0, 16)),
}
DEVICE_CONFIG["AirSpy Mini"] = {
"center_freq": dev_... | Python | 1 |
import re
from docutils import nodes, utils
from docutils.parsers.rst import Directive, directives, roles
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer, get_lexer_by_name
import pelican.settings as pys
class Pygments(Directive):
"""Source code... | Python | 1 |
('activity', models.CharField(max_length=255)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='UserR... | Python | 1 |
误
:raises ValueError: 密码格式错误
"""
access_setting = await self.update_deck_access_setting(
deck_id,
validation_request_access=True,
validation_password=validation_password,
)
access_setting = cast(DeckAccessSettingInfo | DeckAccessSetting, access... | Python | 1 |
class Solution:
def isPalindrome(self, s: str) -> bool:
l = 0
r = len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return Tru... | Python | 1 |
pOnly"
} else {
"use_kpm=; Max-Age=0; Domain=.kth.se; Path=/; HttpOnly"
},
)
.build())
}
/// The form data required when posting to `enable_or_disable`.
///
/// Currently only contains an `action` string.
#[derive(Debug, Deserialize)]
struct StatusForm {
acti... | Rust | 0 |
-of-closed-islands/
// Runtime: 0 ms
// Memory Usage: 2.2 MB
pub fn closed_island(mut grid: Vec<Vec<i32>>) -> i32 {
let mut res = 0;
let n = grid.len();
let m = grid[0].len();
for i in 0..n {
for j in 0..m {
if grid[i][j] == 0 && dfs(i, j, &mut grid, n, m) {
res += 1;... | Rust | 0 |
pos in area.into_iter() {
self.frames[self.index].push(Texel {
symbol,
bg,
fg,
pos,
styles: SymbolStyles::new(),
});
}
self.calculate_bounds()
}
/// Applies *texels* starting at given *pos*... | Rust | 0 |
raph).to(device)
ici_graph = get_graph(ici_graph).to(device)
user_mps, item_mps = [uibiu_graph, uiu_graph], [ibi_graph, ici_graph] #
elif dataset == 'movielens-1m':
# umgmu_graph = sp.load_npz('data/movielens-1m/umgmu.npz')
# uu_graph = sp.load_npz('data/movielens-1m/uu.npz')
... | Python | 1 |
filename))
else:
# Non-whitelisted formats may not be able to load in a reentrant
# fashion.
with image_load_lock:
surf = pygame.image.load(f, renpy.exports.fsencode(filename))
except Exception as e:
raise Exception("Could not load image {!r}: {!... | Python | 1 |
from cura.Scene.GCodeListDecorator import GCodeListDecorator
def test_setAndGetList():
decorator = GCodeListDecorator()
decorator.setGCodeList(["Test"])
assert decorator.getGCodeList() == ["Test"]
def test_copyGCodeDecorator():
decorator = GCodeListDecorator()
decorator.setGCodeList(["Test"])
... | Python | 1 |
9_1,
}
}
#[doc = "Checks if the value of the field is `HRS9_0`"]
#[inline(always)]
pub fn is_hrs9_0(&self) -> bool {
*self == HRS9_A::HRS9_0
}
#[doc = "Checks if the value of the field is `HRS9_1`"]
#[inline(always)]
pub fn is_hrs9_1(&self) -> bool {
*self == HRS9_A::HRS9_1
}
}
#[doc = "Ha... | Rust | 0 |
: stage_info.into(),
}
}
/// 1 to max_stage
pub fn stage(&self) -> u8 {
self.stage
}
pub fn max_stage(&self) -> u8 {
self.max_stage
}
/// Progress as '% * 1000'
pub fn progress(&self) -> u32 {
self.progress
}
/// Status or state name as a byte ... | Rust | 0 |
| -> _ {
::rustc_serialize::Encodable::encode(&(*__self_0_8), _e)
}) {
::std::result::Result::Ok(__try_var) => __try_var,
::std::result::Result::Err(__try_var) => {
return ::std::result::Result::Err(__try_var);
... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
import os
import numpy
from sklearn.preprocessing import MinMaxScaler
save_path = '/home/ubuntu/data/metal_vacancy/'
data1 = np.load('/home/ubuntu/data/metal_vacancy/data.npy')
scaler = MinMaxScaler(feature_range=(-0.5, 0.5))
tmp = scaler.fit_transform(np.transpos... | Python | 1 |
ge<usize>,
value: Option<Range<usize>>,
},
}
impl InnerPredicate {
fn to_pred<'a>(&self, s: &'a str) -> Predicate<'a> {
use InnerPredicate as IP;
use Predicate::{
DebugAssertions, Feature, Flag, KeyValue, ProcMacro, Target, TargetFeature, Test,
};
match self... | Rust | 0 |
import inspect
from functools import wraps
from zope.dottedname.resolve import resolve
def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'):
""" Resolve dotted names in function arguments
Usage:
>>> @resolver('obj')
>>> def func(param, obj):
>>> assert isinsta... | Python | 1 |
the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#ep... | Python | 1 |
import os
import torch
import random
import numpy as np
import torch.nn as nn
from sklearn.metrics import f1_score
from params import NUM_CLASSES
def seed_everything(seed):
"""
Seeds basic parameters for reproductibility of results
Arguments:
seed {int} -- Number of the seed
"""
ran... | Python | 1 |
te FRAME pallets:
/// <https://substrate.dev/docs/en/knowledgebase/runtime/frame>
pub use pallet::*;
pub use primitives::p_provider::*;
pub use primitives::p_resource_order::*;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
const PALLET_ID: PalletId = Pall... | Rust | 0 |
.publish_message(self.db.name(), &topic.into(), pot::to_vec(payload)?)
.await;
Ok(())
}
async fn publish_to_all<P: serde::Serialize + Sync>(
&self,
topics: Vec<String>,
payload: &P,
) -> Result<(), bonsaidb_core::Error> {
self.server
... | Rust | 0 |
def test_json_content_without_content_type(self, mock_handler):
"""Test JSON content without explicit content type"""
result_response = MagicMock()
result_response.status_code = 200
result_response.headers = {} # No Content-Type
result_response.content = {"key": "value"}
... | Python | 1 |
fea = fea_hooks[0].fea.squeeze()
target = self.get_target(output2)
if self.ifcombine:
target = torch.cat((target[0:batch], train_label), 0)
for i in range(self.epoch):
#### forward
# fea = self.model.get_feature(x)... | Python | 1 |
#!/usr/bin/env python3
"""
Quick‑and‑dirty latency test for a TGI instance running on localhost:8000.
"""
import json
import time
import requests # pip install requests
ENDPOINT = "http://localhost:8000/generate"
# 1) Build the prompt and generation parameters ------------------------------
prompt = (
"### Sys... | Python | 1 |
func(self):
def func(x, y):
return paddle.reshape(x, []) + y
self.func = func
class TestExpand0Dto3D(TestFunc):
def prepare_data(self):
self.input_spec = [InputSpec(shape=[], dtype='float32')]
self.input = [paddle.randn([])]
def prepare_func(self):
def fun... | Python | 1 |
#la ventaja de esta sintaxis es que abre el archivo y cierra el archivo
#sin necesidad de usar el close() como lo vimos anteriormente
#y no vamos agrea el try ni el finally donde le agragamos el cotenido al archivo
with open ('prueba.txt', 'r' , encoding='utf8' ) as archivo:
print(archivo.read()) | Python | 1 |
ath::{Path, PathBuf};
use std::process;
use std::time::UNIX_EPOCH;
use shutter::error::Result;
use shutter::image::PostImage;
const EXIT_SUCCESS: i32 = 0;
const EXIT_FAILURE: i32 = 1;
fn print_profile(user_profile: &shutter::profile::Profile) {
println!("Username: {}", user_profile.username);
println!(
... | Rust | 0 |
import json
from ipfs_blockchain import get_from_ipfs, add_to_ipfs, globalSC
class WorkerResearchCenter:
def __init__(self, name):
self.name = name
self.aggregated_params = None
def aggregate_parameters(self, client_hashes):
aggregated_model = {}
count = 0
for client_ha... | Python | 1 |
# -*- coding: utf-8 -*-
''' Check surface loads on plane elements.
Test based on equilibrium equations. This test has been created to debug an
error in the computation of the quad surface load resisting force.
'''
from __future__ import print_function
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__co... | Python | 1 |
ITY;
///
/// let graph = Graph::<(), f32>::from_edges(&[
/// (0, 1, 2.0), (1, 2, 10.0), (1, 3, -5.0),
/// (3, 2, 2.0), (2, 3, 20.0),
/// ]);
///
/// assert_eq!(weighted_diameter(&graph, |edge| *edge.weight()), Some(inf));
///
/// // Negative cycle.
/// let graph = Graph::<(), f32>::from_edges(&[
... | Rust | 0 |
)
info_window.title("Information")
info_window.geometry("415x140")
info_window.resizable(False, False)
info_label = Label(info_window, text="Eğitim amaçlıdır.bu programı kullanarak tamamen kendi\n riskiniz üzerine kullanıldığınızı kabul etmiş olursunuz.\nHerhangi bir sorumluluk kabul etmemekteyim.\npro... | Python | 1 |
-> u32;
/// Converts an emitted event into a tag that can be emitted by the runtime.
///
/// # Key
///
/// ```text
/// <module (variable size bytes)> <code (big-endian u32)>
/// ```
///
/// # Value
///
/// CBOR-serialized event value.
///
fn into_tag(self) -> Tag {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.