text string | label_name string | labels int64 |
|---|---|---|
"""Formula 6.7n from EN 1992-1-1:2004: Chapter 6 - Ultimate limit state."""
from blueprints.codes.eurocode.en_1992_1_1_2004 import EN_1992_1_1_2004
from blueprints.codes.formula import Formula
from blueprints.codes.latex_formula import LatexFormula
from blueprints.math_helpers import cot
from blueprints.type_alias imp... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged, common
class TestMatrixCommon(common.HttpCase):
def setUp(self):
super(TestMatrixCommon, self).setUp()
# Prepare relevant test data
# This is not included in ... | Python | 1 |
s call to the Rollup Get Jobs API that can be awaited"]
pub async fn send(self) -> Result<Response, Error> {
let path = self.parts.url();
let method = Method::Get;
let headers = self.headers;
let timeout = self.request_timeout;
let query_string = {
#[serde_with::s... | Rust | 0 |
if cfg!(debug_assertions) { CodeLogLevel::Debug }
else { CodeLogLevel::Warn }
}
#[inline] fn default_code_log_fileline() -> bool { true }
#[inline] fn default_code_log_detailed_errors() -> bool { false }
#[derive(Clone, Deserialize)]
pub struct Config {
#[serde(default = "default_code_log_level")]
pub code... | Rust | 0 |
(location: MultiLocation) -> Result<AccountId, MultiLocation> {
let id = match location {
MultiLocation {
parents: 0,
interior: X1(AccountId32 { id, network: NetworkId::Any }),
} => id,
MultiLocation { parents: 0, interior: X1(AccountId32 { id, network }) }
if network == Network::get() =>
id,... | Rust | 0 |
c::Decode)]
pub struct Origin<T>(pub core::marker::PhantomData<T>);
frame_support::decl_event! {
pub enum Event {
A,
}
}
frame_support::decl_error! {
pub enum Error for Module<T: Config> {
Something
}
}
frame_support::decl_storage! {
trait Store for Module<T: Config> as Module {}
add_extra_ge... | Rust | 0 |
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.norm1 = nn.LayerNorm(2)
def forward(self, x):
x = self.norm1(x)
return x
def main():
torch.se... | Python | 1 |
seconds,
transform.translation().y(),
transform.translation().z() + movement.z() * time.delta_seconds,
);
transform.set_translation(translation);
}
}
const ZOOM_SPEED: f32 = 0.5;
const MAX_ZOOM: f32 = 30.0;
const MIN_ZOOM: f32 = 10.0;
#[derive(Default)]
struct ZoomSystemSt... | Rust | 0 |
from flask import Flask, render_template_string, redirect, url_for
import subprocess, logging
app = Flask(__name__)
# 로그 파일 설정
logging.basicConfig(filename='button_clicks.log', level=logging.INFO, format='%(asctime)s - %(message)s')
# 기본 페이지, 버튼을 클릭하면 '/button' 페이지로 이동
@app.route('/')
def home():
return render_t... | Python | 1 |
json<T: Serialize>(path: &str, data: T) -> Result<(), Box<dyn Error>> {
let serialized = serde_json::to_string_pretty(&data)?;
let mut file = File::create(path)?;
file.write_all(serialized.as_bytes())?;
Ok(())
}
use rand::Rng;
fn logit(p: f64) -> f64 {
return (p / (1.0_f64 - p)).ln();
}
fn main()... | Rust | 0 |
y,
pub raydium_coin_token_account: Pubkey,
pub raydium_pc_token_account: Pubkey,
pub raydium_pool_temp_token_account: Pubkey,
pub raydium_pool_lp_token_account: Pubkey,
pub raydium_pool_withdraw_queue: Pubkey,
pub raydium_pool_id: Pubkey,
pub raydium_pool_authority: Pubkey,
pub raydium_p... | Rust | 0 |
# Unit test grid_search_sarimax
# ==============================================================================
import re
import pytest
import platform
import numpy as np
import pandas as pd
from skforecast.Sarimax import Sarimax
from skforecast.ForecasterSarimax import ForecasterSarimax
from skforecast.model_selectio... | Python | 1 |
(op_webstorage_clear)),
(
"op_webstorage_iterate_keys",
op_sync(op_webstorage_iterate_keys),
),
])
.state(move |state| {
if let Some(origin_storage_dir) = &origin_storage_dir {
state.put(OriginStorageDir(origin_storage_dir.clone()));
}
Ok(())
})
.bui... | Rust | 0 |
from autoop.core.ml.model import Model
from sklearn.linear_model import LogisticRegression
import numpy as np
class MultinomialLogisticRegression(Model):
"""
This is a wrapper of sklearn's LogisticRegression.
"""
def __init__(self, type: str) -> None:
"""
A way of instantiating Multi... | Python | 1 |
import os
import json
from pathlib import Path
# === 参数配置 ===
input_dir = Path("datasets/training_raw")
output_dir = Path("datasets/dpo")
output_dir.mkdir(parents=True, exist_ok=True)
# === MBTI 四个维度及其子类 ===
dimension_pairs = {
"decision": ("feeling", "thinking"),
"information": ("sensing", "intuition"),
... | Python | 1 |
gument or '') + new_value
concatenate_next = False
else:
last_argument = new_value
elif token.type == 'operator':
if token.value == ',':
if last_argument is not None:
messages.append(last_arg... | Python | 1 |
-resource-policy")
}
fn header_value(&self) -> Result<HeaderValue, InvalidHeaderValue> {
HeaderValue::from_str(self.to_string().as_str())
}
}
<reponame>bjeanes/sqlx<filename>sqlx-core/src/mssql/protocol/type_info.rs<gh_stars>0
use bitflags::bitflags;
use bytes::{Buf, Bytes};
use encoding_rs::Encodi... | Rust | 0 |
from __future__ import annotations
from collections import namedtuple
from pathlib import Path
import pytest
from retype import walk_not_git_ignored
@pytest.fixture()
def build(tmp_path):
def _build(files):
for file, content in files.items():
dest = tmp_path / file
dest.parent.m... | Python | 1 |
# original0, original1..., need to check both cases
if hasattr(from_module.parametrizations[parameter_name], "original"):
to_module.parametrizations[
parameter_name
].original = from_module.parametrizations[parameter_name].original
els... | Python | 1 |
ems = []
for pattern in item_patterns:
matches = re.findall(pattern, text, re.MULTILINE)
for match in matches:
item = match.strip()
if len(item) > 3 and item not in result["vendor"]:
items.append(item)
if items:
... | Python | 1 |
# spinner_async_experiment.py
# credits: Example by Luciano Ramalho inspired by
# Michele Simionato's multiprocessing example in the python-list:
# https://mail.python.org/pipermail/python-list/2009-February/675659.html
import asyncio
import itertools
import time
async def spin(msg: str) -> None:
for char in ite... | Python | 1 |
ed to this
/// size by the recording application.
pub fn get_snaplen(&self) -> usize {
match self.state.as_ref() {
None => 0,
Some(state) => state.packet_buffer.len(),
}
}
/// This function allows iterating over the packets in the packet capture, in a similar fash... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = [
"airbyte-cdk~=0.1",
]
TEST_REQUIREMENTS = [
"requests-mock~=1.9.3",
"pytest~=6.2",
"pytest-mock~=3.6.1",
]
setup(
entry_points={
"console_scripts": [
... | Python | 1 |
import sys
sys.stdout.reconfigure(encoding="utf-8")
sys.stdin.reconfigure(encoding="utf-8")
import streamlit as st
import streamlit.components.v1 as components
import re
import random
CODE_BUILD_KG = """
# 准备 GraphStore
os.environ['NEBULA_USER'] = "root"
os.environ['NEBULA_PASSWORD'] = "nebula" # default passwor... | Python | 1 |
from emmet.api.routes.materials.robocrys.query_operators import RoboTextSearchQuery
def test_robocrys_search_query():
op = RoboTextSearchQuery()
pipeline = [
{
"$search": {
"index": "description",
"regex": {
"query": ["cubic", "octahedra... | Python | 1 |
r
assert A.singular_values() == [2, 1]
A = eye(3)
A[1, 1] = x
A[2, 2] = 5
vals = A.singular_values()
# since Abs(x) cannot be sorted, test set equality
assert set(vals) == set([5, 1, Abs(x)])
A = EigenOnlyMatrix([[sin(x), cos(x)], [-cos(x), sin(x)]])
vals = [sv.trigsimp() for sv in... | Python | 1 |
utor.set_fake_time(executor.now().add(12.seconds()));
executor.wake_next_timer();
let fut = dummy_fn();
pin_mut!(fut);
let _poll = executor.run_until_stalled(&mut fut);
assert_eq!(test_map.get("my_test"), Some("my_test_url".into()));
// only entry which was marked as sta... | Rust | 0 |
mqK");
let album_id2 = String::from("628oezqK2qfmCjC6eXNors");
album_ids.push(album_id2);
album_ids.push(album_id1);
oauth_client()
.await
.current_user_saved_albums_delete(&album_ids)
.await
.unwrap();
}
#[maybe_async]
#[maybe_async_test]
#[ignore]
async fn test_current... | Rust | 0 |
_adapter {
let difference = adapter - jolts;
differences
.entry(difference)
.and_modify(|count| *count += 1)
.or_insert(1);
}
joltage = next_adapter;
}
differences
.entry(DEVICE)
.and_modify(|count| *count... | Rust | 0 |
PosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
pub enum FunctionPtrId<'a, Ex, Fb, En, Hi> {
FPId(&'a Sid<'a>),
FPClassConst(&'a (&'a ClassId<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>)),
}
impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop
f... | Rust | 0 |
ush an object that contains
data that cannot be serialized to JSON, such as inf, -inf, or NaN float values.
To fix this error:
1. Check your data for invalid float values (inf, -inf, NaN)
2. Replace or remove problematic values before pushing
3. Use the provided location information to identify spe... | Python | 1 |
t=emulation_env_config.host_manager_config.host_manager_port, ip=ip)
running = True
except Exception as e:
logger.info(f"Could not fetch Host manager status on IP:{ip}, error: {str(e)}, {repr(e)}")
if status is not None:
host_managers_statuses.appe... | Python | 1 |
}
#[doc = "Reader of register IC_CLR_TX_ABRT"]
pub type R = crate::R<u32, super::IC_CLR_TX_ABRT>;
#[doc = "Reader of field `CLR_TX_ABRT`"]
pub type CLR_TX_ABRT_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Read this register to clear the TX_ABRT interrupt (bit 6) of the IC_RAW_INTR_STAT register, and the IC_... | Rust | 0 |
length,
ConstantValue(_) => 0,
_ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
},
ty::TyRef(..) => 1,
ty::TyAdt(adt, _) => {
adt.variants[ctor.variant_index_for_adt(adt)].fields.len()
}
_ => 0
}
}
/// This computes the types of the sub ... | Rust | 0 |
Error(f"The input must be a 2D Tensor. Found dimension {x.ndim}.")
x = x / (torch.mean(x**2, dim=1, keepdim=True) ** 0.5 * 20)
out = self.encoder(x)
out = self.dprnn(out)
scores = []
for branch in self.branches:
scores.append(branch(out).squeeze(dim=1))
return... | Python | 1 |
, std::cmp::PartialEq)]
pub struct BatchPutPropertyValuesInput {
/// <p>The ID of the workspace that contains the properties to set.</p>
pub workspace_id: std::option::Option<std::string::String>,
/// <p>An object that maps strings to the property value entries to set. Each string in the mapping must be uni... | Rust | 0 |
oding-Playing…",
env!("CARGO_PKG_VERSION"),
app.frames,
);
app.time -= 1.0;
app.frames = 0;
}
let mut stopping = false;
screen::texture_set(&mut app.texture, &mut |pixels, pitch| {
unsafe {
GLOBAL.set = true;
GLOBAL.pixels = pi... | Rust | 0 |
g.gresid_rms = N.std(resid)
g.gresid_mean = N.mean(resid)
else:
g.sresid_rms = N.std(resid)
g.sresid_mean = N.mean(resid)
if hasattr(isl, 'dsources'):
for dsrc in isl.dsources: # Handle dummy sources (i... | Python | 1 |
stat.iowait = v,
6 => stat.irq = v,
7 => stat.softirq = v,
8 => stat.steal = v,
9 => stat.guest = v,
10 => stat.guest_nice = v,
_ => unreachable!(),
}
}
stats.push(stat);
}
Ok(stats)
}
... | Rust | 0 |
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `VSPOL`"]
pub type VSPOL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `VSPOL`"]
pub struct VSPOL_W<'a> {
... | Rust | 0 |
estamp,
user_id: user_id.ok_or_else(|| Error::missing_field("user_id"))?,
},
MatchEventType::Left => MatchEvent::Left {
event_id,
timestamp,
user_id: user_id.ok_or_else(|| Error::missing_field("user_id"))?,
},
... | Rust | 0 |
22 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, a... | Rust | 0 |
Foo::B
},
);
}));
assert!(res.is_err());
assert_eq!(&quax, &Foo::C);
}
}
<reponame>terakilobyte/octocrab
use super::*;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PullRequest {
pub url: String,
pub id: u64,
pub node_id: String,
pub html_u... | Rust | 0 |
f, ", ")?;
expr_arena[*value].print(expr_arena, text, f)?;
writeln!(f)
}
StmtKind::Pop => writeln!(f, "POP"),
StmtKind::Print(elems) => {
write!(f, "PRINT ")?;
for elem in elems.iter() {
match elem {
PrintElement::Comma(_) => write!(f, ", ")?,
PrintElement... | Rust | 0 |
(&self) -> LineSegment<S> {
LineSegment {
from: self.a,
to: self.c,
}
}
/// [Not implemented] Applies the transform to this triangle and returns the results.
#[inline]
pub fn transform<T: Transformation<S>>(&self, transform: &T) -> Self {
Triangle {
... | Rust | 0 |
# This file is part of cloud-init. See LICENSE file for license information.
from unittest import mock
import pytest
from cloudinit import distros, util
from tests.unittests.helpers import TestCase
class TestAlpineBusyboxUserGroup:
@mock.patch("cloudinit.distros.alpine.subp.subp")
@mock.patch("cloudinit.di... | Python | 1 |
///
/// # Parameters
///
/// `buffers` - Information about buffers. One for each returned by `buffers` function.
///
/// `images` - Information about images. One for each returned by `images` function.
///
/// `frames` - number of frames in swapchain. All non-read-only resources mus... | Rust | 0 |
import numpy as np
import numpy.random as rnd
from libtlda.scl import StructuralCorrespondenceClassifier
def test_init():
"""Test for object type."""
clf = StructuralCorrespondenceClassifier()
assert type(clf) == StructuralCorrespondenceClassifier
assert not clf.is_trained
# def test_fit():
# ""... | Python | 1 |
.scantxoutset("start", ["addr(mpQ8rokAhp1TAtJQR6F6TaUmjAWkAWYYBq)"])["unspents"][0]
blockhash = self.nodes[0].getblockhash(info["height"])
assert_equal(unspent["height"], info["height"])
assert_equal(unspent["blockhash"], blockhash)
assert_equal(unspent["confirmations"], 3)
# Ch... | Python | 1 |
lue}' (success: {result.success})")
if result.applied_rules:
print(f" Applied rules: {result.applied_rules}")
print("\n2. Numeric Field Cleaning:")
test_values = ["25", "$1,200", "invalid", "-5", "150"]
for value in test_values:
result = engine.clean_numeric_field(value, "poi... | Python | 1 |
6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
2181,
0,
0))]);
assert_eq!(chroot, Some("/mesos".to_owned()));
let (addrs, chroot) = Z... | Rust | 0 |
set() {
let header = PerrDestinationHeader {
flags: PerrDestinationFlags(0),
dest_addr: [1, 2, 3, 4, 5, 6],
hwmp_seqno: 0x0a090807,
};
let ext_addr = [0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10];
assert_eq!(
Err(FrameWriteError::new_invalid_data(
... | Rust | 0 |
c_transport_9r": 1,
"materials_required_for_protra": 1,
"materials_required_for_prosup": 1,
},
)
def total_materials_required_bu_techs():
"""
Total materials required estimated through the bottom-up (BU) method for specific technologies.
"""
return (
materials_required_for_ne... | Python | 1 |
from .datasets_scraper import DatasetsScraper, main
__all__ = ["DatasetsScraper", "main"] | Python | 1 |
from collections import defaultdict
for _ in range(int(input())):
numNodes, numEdges, numQs = map(int, input().split())
edges = defaultdict(list)
for _ in range(numEdges):
u,v = map(int, input().split())
edges[u].append(v)
seen = set()
ans = 0
for _ in range(numQs):
q =... | Python | 1 |
ctor to use waiter.CloudOperationPoller
operation = dm_write.WaitForOperation(
self.client,
self.messages,
op_name,
'delete',
dm_base.GetProject(),
timeout=OPERATION_TIMEOUT)
dm_util.LogOperationStatu... | Python | 1 |
red_iv = red_iv.suffix(iv);
blue_iv = blue_iv.suffix(iv);
assert!(red_iv.is_empty() || blue_iv.is_empty());
if red_iv.is_empty() {
next_red = iter_red.next();
} else {
next_red = Some((red_iv, red_val));
}
if blue_... | Rust | 0 |
import unittest
from managebac_checker.analysis import analyse_assignments
from tests.factories import make_assignment
class AnalysisTests(unittest.TestCase):
def test_counts_by_status(self):
submitted = make_assignment(status="Submitted", priority="low", submitted=True)
overdue = make_assignment... | Python | 1 |
e],
#[doc = "0xa0 - CHCFG5R1"]
pub chcfg5r1: CHCFG5R1,
#[doc = "0xa4 - CHCFG5R2"]
pub chcfg5r2: CHCFG5R2,
#[doc = "0xa8 - AWSCD5R"]
pub awscd5r: AWSCD5R,
#[doc = "0xac - CHWDAT5R"]
pub chwdat5r: CHWDAT5R,
#[doc = "0xb0 - CHDATIN5R"]
pub chdatin5r: CHDATIN5R,
_reser... | Rust | 0 |
ail
email_field = driver.find_element(By.ID, 'identifierId')
email_field.send_keys(email)
email_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'password')))
# Tìm và nhập mật khẩu
password_field = dr... | Python | 1 |
_memory_paragraphs: u16,
maximum_memory_paragraphs: u16,
initial_ss: u16,
initial_sp: u16,
checksum: u16,
initial_ip: u16,
initial_cs: u16,
relocation_table: u16,
overlay: u16,
overlay_information: u16,
}
impl MzHeader {
pub fn byte_size() -> usize {
28
}
pub fn parse(stream: &mut std::io::Read) -> Resu... | Rust | 0 |
unsafe {
let entrypoint: libloading::Symbol<Entrypoint> =
match library.get(ENTRYPOINT.as_bytes()) {
Ok(s) => s,
Err(e) => panic!(
"{:?} Unable to find {:?} in program ... | Rust | 0 |
collections::HashMap;
use std::fs;
use std::fmt;
use percent_encoding::{
AsciiSet,
CONTROLS,
utf8_percent_encode,
percent_decode_str
};
type Routes = HashMap<String, PathBuf>;
const FRAGMENTS: &AsciiSet = &CONTROLS.add(b' ').add(b'%');
#[derive(Clone)]
pub struct Router {
routes: Routes
}
impl ... | Rust | 0 |
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of fie... | Rust | 0 |
(_, a, _): (usize, usize, usize),
(_, _, _): (usize, Token<'input>, usize),
(_, b, _): (usize, usize, usize),
(_, r, _): (usize, Expression, usize),
) -> Expression
{
Expression::AssignDivide(Loc(a, b), Box::new(l), Box::new(r))
}
#[allow(unused_variables)]
fn __action58<
'input,
>(
input: ... | Rust | 0 |
# -*- coding: utf-8 -*-
from odoo import fields, models
class GroupOnDate(models.Model):
_name = 'test_read_group.on_date'
_description = 'Group Test Read On Date'
date = fields.Date("Date")
value = fields.Integer("Value")
class BooleanAggregate(models.Model):
_name = 'test_read_group.aggregate... | Python | 1 |
# senha = ''
# n = 0
# while n != '1234':
# n = int(input('Digite a senha: '))
# if n == 1234:
# print('Acesso liberado')
# break
# else:
# print('Senha incorreta, tente novamente!')
# Atividade 05:
# Contagem até o Número Inserido:
# Crie um programa que solicite um número ao usuário e use
# um l... | Python | 1 |
import glob, os, shutil, fileinput
import datetime
sep = os.sep
Import("env", "projenv")
for e in [ env, projenv ]:
# If compiler uses `-m32`, propagate it to linker.
# Add via script, because `-Wl,-m32` does not work.
if "-m32" in e['CCFLAGS']:
e.Append(LINKFLAGS = ["-m32"])
# e.Append(LINK... | Python | 1 |
mut server = ServerBuilder::default()
.timeout(Duration::from_secs(5))
.build("[::1]:2222")
.await?;
use tokio::process::Command;
let mut proc = Command::new("ssh")
.arg("-oStrictHostKeyChecking=no")
.arg("-oUserKnownHostsFile=/dev/null")
.arg("-p2222")
... | Rust | 0 |
///
/// See: <https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options>
#[derive(Clone, PartialEq, Eq, Default)]
pub struct CfgOptions {
enabled: FxHashSet<CfgAtom>,
}
impl fmt::Debug for CfgOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut i... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ASR Processor - Xử lý ASR với Google Speech Recognition + Circular Buffer
"""
import struct
import time
import tempfile
import wave
import os
import numpy as np
import audio_utils.server_config as config
from .audio_processing import audio_preprocessing_improved
from... | Python | 1 |
,
is_copy: bool,
env: &'b JNIEnv<'a>,
}
impl<'a, 'b> AutoByteArray<'a, 'b> {
/// Creates a new auto-release wrapper for a pointer-based byte array
///
/// Once this wrapper goes out of scope, `release_byte_array_elements` will be
/// called on the object. While wrapped, the object can be access... | Rust | 0 |
.LOSS_ALPHA = 0.25
# Focal loss parameter: gamma
_C.MODEL.RETINANET.LOSS_GAMMA = 2.0
# Prior prob for the positives at the beginning of training. This is used to set
# the bias init for the logits layer
_C.MODEL.RETINANET.PRIOR_PROB = 0.01
# Inference cls score threshold, anchors with score > INFERENCE_TH are
# cons... | Python | 1 |
+ 2] == -1
&& Board[i + 1][j + 1] == 0
{
return true;
}
if j < column - 3 && i < row - 3 {
if Board[i][j] == -1
&& Board[i + 3][j] == -1
&& Board[i][j + 3] == -1
&& Board[i + ... | Rust | 0 |
b use self::enums::PrintOperationResult;
pub use self::enums::PrintPages;
pub use self::enums::PrintQuality;
pub use self::enums::PrintStatus;
pub use self::enums::PropagationPhase;
pub use self::enums::RecentChooserError;
pub use self::enums::RecentManagerError;
pub use self::enums::RecentSortType;
pub use self::enums... | Rust | 0 |
ess_update_interval = Duration::from_millis(PROGRESS_UPDATE_INTERVAL_MILLIS);
let mut last_progress_bytes = 0;
let mut last_progress_time = Instant::now() - progress_update_interval;
while let Ok(n) = body.read(&mut bytes_buffer) {
if n == 0 {
return Ok(sum_bytes);
}
ch... | Rust | 0 |
"""
Source: http://code.activestate.com/recipes/578225-linux-ioctl-numbers-in-python/
Linux ioctl numbers made easy
size can be an integer or format string compatible with struct module
for example include/linux/watchdog.h:
#define WATCHDOG_IOCTL_BASE 'W'
struct watchdog_info {
__u32 options; /* Op... | Python | 1 |
def callback_fn(step: int, timestep: int, latents: torch.Tensor) ->None:
callback_fn.has_been_called = True
nonlocal number_of_steps
number_of_steps += 1
if step == 1:
latents = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 64, 64)
latents_slice = latents[0, -3:, ... | Python | 1 |
hesihai (Beijing) Technology Limited.
//
// 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 agree... | Rust | 0 |
eriod (c 1939 to c 1945)",
"3MPBLB-FI-A" => "Period of The Winter War 1939–1940 & the Continuation War 1941 to 1944",
"3MPBLB-PL-A" => "Period of the Warsaw Ghetto uprising of 1943",
"3MPBLB-PL-B" => "Period of the Warsaw Rising of 1944",
"3MPBL-AR-C" => "Argentina: period of Peronism & the Peron presid... | Rust | 0 |
from typing import Any, NamedTuple, cast
import numpy as np
# Subtype of tuple[int, int]
class XYGrid(NamedTuple):
x_axis: int
y_axis: int
# Test variance of _ShapeT_co
def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None:
return None
accepts_2d(np.empty(XYGrid(2, 2)))
accepts_2d(np.zeros(XYGri... | Python | 1 |
.com/reference/android/hardware/fingerprint/FingerprintManager.html#FINGERPRINT_ACQUIRED_PARTIAL)
pub const FINGERPRINT_ACQUIRED_PARTIAL : i32 = 1;
/// public static final [FINGERPRINT_ACQUIRED_TOO_FAST](https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager.html#FINGER... | Rust | 0 |
(*(::std::ptr::null::<EmptyStructPlaceholder>())).dummy as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(EmptyStructPlaceholder),
"::",
stringify!(dummy)
)
);
}
pub mod TfLitePadding {
pub type Type = ::std::os::raw:... | Rust | 0 |
def classify_traveler(self, answers: Dict[str, str]) -> ClassificationResult:
"""
Clasifica al viajero basado en sus respuestas.
Args:
answers: Dict con las respuestas del usuario
{"question_1": "adventure", "question_2": "outdoor", ...}
... | Python | 1 |
, None);
}
}
<filename>src/misc.rs
use serde::{Deserialize, Serialize};
use crate::utils::totalsize::TotalSize;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Deserialize, Serialize)]
pub struct SymbolId(pub usize);
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Deserialize, Serialize, TotalSize)]
pu... | Rust | 0 |
self, time: i64) {
self.fbb_.push_slot::<i64>(MempoolTx::VT_TIME, time, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MempoolTxBuilder<'a, 'b> {
let start = _fbb.start_table();
MempoolTxBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn f... | Rust | 0 |
m_loop.add_row(_get_struct_ncs_dom_lim_row(master_dom_id, i_r+1, r))
# now get to copies
for i_ncs_copy, ncs_copy in enumerate(group.copies):
copy_dom_id = 'd_%d' % (i_ncs_copy+2) # no 0, 1-master
ncs_dom_loop.add_row({
"_struct_ncs_dom.pdbx_ens_id":struct_ncs_ens_id,
... | Python | 1 |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of CARS
# (see https://github.com/CNES/cars).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... | Python | 1 |
])
re_ids = sorted([str(n.get("id")) for n in reloaded.nodes if n.get("id") is not None])
assert orig_ids == re_ids
@pytest.mark.parametrize("key", ["name", "id", "form", "nodes", "edges"])
def test_required_top_level_keys_present(key):
raw = _load_raw()
root = load_workflow_json(raw)
# Some upstr... | Python | 1 |
import torch.nn.functional as F
import torch.nn as nn
import torch
"""
This script define the structure of discriminator
According to the original Re-cycle GAN paper,
the structure of discriminator is 70x70 PatchGAN
And also it is also used in original CycleGAN official implementation
The code is ... | Python | 1 |
# is even function
# Jeffrey Smith
# write a function to tell if a number is even or odd
def is_even(num):
return num % 2 ==0
def calculate_total(meal, tax_rate, tip_rate):
tip = meal * tip_rate
tax = meal * tax_rate
return meal + tip + tax
def hey(num):
return num ** 2
def there(num):
if n... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#!/usr/bin/env python3
import importlib
import os
from unittest import mock
import testslide
from testslide import StrictMock
from ... | Python | 1 |
format=Format.GRAY8,
path="Patterns/House.tiff"),
ImageGen(STANDARD_IMG_SIZES,
format=Format.GRAY8,
path="Patterns/House2.tiff"),
ImageGen(STANDARD_IMG_SIZES,
format=Format.GRAY8,
path="P... | Python | 1 |
self.id.is_none()
}
pub fn previous_version(&self) -> Option<Self> {
let mut id = self.clone();
id.version = self.version.checked_sub(1)?;
Some(id)
}
}
impl std::fmt::Debug for Ident {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ns = mat... | Rust | 0 |
r64(4.000000000000001),
r64(3.666666666666666),
r64(4.0),
r64(4.333333333333333),
r64(4.666666666666667),
r64(4.333333333333333),
r64(4.666666666666667),
r64(5.0),
... | Rust | 0 |
# app.py
from flask import Flask, render_template, request
import joblib
app = Flask(__name__)
# Load the pre-trained model
car_price_model = joblib.load("C:\\Users\\ADMIN\\Desktop\\python\\ROHIT\\car_price\\build-model\\lr_model.joblib")
# Encoding dictionaries
fuel_type_stoi = {
"Petrol": 1,
"Diesel": 2,
... | Python | 1 |
fr, lr| -> Vec<f64>{
let p_ant = LpApply::get_gapless_ant(fr, lr, mp.clone(),
&sind,
&lin_par);
LpApply::subtract_along_burst(unsafe{Arc::get_mut_unchecked(x_v)}, //unsafe is bad, but I guaruntee no race conditions.
&p_ant,
&aznoise,
fa, la, fr, lr);
//return pat... | Rust | 0 |
: Func) -> anyhow::Result<&mut Self> {
self.bind_syscall(module, name, syscall, false)
}
/// Bind a syscall to the linker, but preserve last syscall error.
fn bind_keep_error(
&mut self,
module: &str,
name: &str,
syscall: Func,
) -> anyhow::Result<&mut Self> {
... | Rust | 0 |
],
# fmt: on
}
dummy_dataset = Dataset.from_dict(dummy_dataset_dict)
trainer = RewardTrainer(
model=self.model,
args=training_args,
tokenizer=self.tokenizer,
train_dataset=dummy_dataset,
... | Python | 1 |
}", u)),
Err(e) => assert!(e == format!("User already here: {:?} - {:?}", user_clone, user2_clone))
}
}
}
}// This file is part of nvml. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubuserco... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.