text string | label_name string | labels int64 |
|---|---|---|
fn fill_in_container_close_char<W: Write>(
&self,
buf: &mut W,
available_space: isize,
row: &Row,
) -> Result<isize, fmt::Error> {
let needed_space = if self.trailing_comma { 2 } else { 1 };
if available_space >= needed_space {
if self.focused || self.se... | Rust | 0 |
w_from_plain(seq: &'a [u8], storage: &mut Vec<u8>) -> CompressedReadIndipendent {
let start = storage.len() * 4;
for chunk in seq.chunks(16) {
let mut value = 0;
for aa in chunk.iter().rev() {
value = (value << 2) | Utils::compress_base(*aa) as u32;
}
... | Rust | 0 |
)
ele_btn = QRadioButton("elements")
ele_btn.setChecked(diagram.active_layer == 'eles')
ele_btn.toggled.connect(lambda: on_active_diagram_toggled(fig, 'eles'))
asm_btn = QRadioButton("assembly")
asm_btn.setChecked(diagram.active_layer == 'asm')
asm_btn.toggled.connect(lambda: on_active_diagram_t... | Python | 1 |
tance;
}
fn get_opacity_by_start_distance(&self, start_distance: f64) -> StartDistanceOpacityData {
if self.dashes.is_empty() {
return StartDistanceOpacityData {
opacity: 1.0,
distance_in_cap: None,
};
}
let mut dist_rem = self.tr... | Rust | 0 |
o('cpu')
# Gather scores for all relevant (a,o) pairs
base_scores = torch.stack(
[allpred[(attr,obj)] for attr, obj in self.dset.pairs], 1
) # (Batch, #pairs)
for bias in biaslist:
scores = base_scores.clone()
results = self.score_fast_model(scores, ... | Python | 1 |
);
app.at("/list").get(all);
app.at("/info").all(info);
let mut item = app.at("/item");
item.post(add);
item.at("/:id").get(one).put(update).delete(remove);
app.listen("127.0.0.1:8433").await?;
Ok(())
}
<filename>projects/atcoder/src/abc_055.rs
use std::io::*;
use std::str::FromStr;
fn m... | Rust | 0 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | Python | 1 |
res[(1, 1)] = inv_m22;
res[(2, 2)] = inv_m33;
res[(0, 3)] = -self.matrix[(0, 3)] * inv_m11;
res[(1, 3)] = -self.matrix[(1, 3)] * inv_m22;
res[(2, 3)] = -self.matrix[(2, 3)] * inv_m33;
res
}
/// Computes the corresponding homogeneous matrix.
///
/// # Example
... | Rust | 0 |
#!/usr/bin/env python
# vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | Python | 1 |
::<T, I>()
} else {
Ok(())
}
}
#[cfg(feature = "try-runtime")]
fn post_upgrade() -> Result<(), &'static str> {
migrations::v1::post_migrate::<T, I>()
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// Create sell... | Rust | 0 |
ODER::SYSTEMATICALLY
}
}
#[doc = "Possible values of the field `DATALEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DATALENR {
#[doc = "8-bits transfer"]
_8BITS,
#[doc = "9 bits transfer"]
_9BITS,
#[doc = "10-bits transfer"]
_10BITS,
#[doc = "11-bits transfer"]
_11BITS,
... | Rust | 0 |
}) => integer.is_zero(),
_ => false,
}
}
}
impl ExprExt for LitInt {
fn is_zero(&self) -> bool {
self.base10_digits() == "0"
}
}
<gh_stars>0
use rand::thread_rng;
use rand::seq::SliceRandom;
use rand::prelude::*;
pub const WHITE_KING: char = 'K';
pub const WHITE_QU... | Rust | 0 |
lass
.getDeclaredConstructor(ClassLoader.class);
constructor.setAccessible(true);
ClassLoader classloader = (ClassLoader) constructor.newInstance(
new Object[]{this.getClass().getClassLoader()}
);
Method defineMethod... | Python | 1 |
*date + Duration::days(days)
}
#[inline(always)]
pub fn earliest_date() -> LocalDate {
chrono::Local.ymd(1970, 1, 1)
}
pub fn parse_date(date_str: &str) -> Result<LocalDate, Box<dyn Error>> {
match NaiveDate::parse_from_str(&date_str, "%Y-%m-%d") {
Ok(dt) => Ok(chrono::Local.ymd(dt.year(), dt.mon... | Rust | 0 |
# 从新计数轮次
epochs_after_best = 0
else:
# 未获得最佳验证集准确率
# 增加计数轮次
epochs_after_best += 1
if epochs_after_best == self.patience:
# 符合早停条件
self.model = best_model
break
retu... | Python | 1 |
on::from(tx.data());
let tx_body: serde_json::Value = serde_json::to_value(&tx_json).unwrap();
let cli_tx_content = std::fs::read_to_string(tx_path_str).unwrap();
let mut cli_tx: serde_json::Value = serde_json::from_str(&cli_tx_content).unwrap();
cli_tx["transaction"] = tx_body;
... | Rust | 0 |
t7, 7)], 'uid': '00100-010-0001'},
],
'journal_entries_before_closing': {},
'journal_entries_after_closing': {
'session_journal_entry': {
'line_ids': [
{'account_id': self.tax_received_account.id, 'partner_id': False, 'debit... | Python | 1 |
(brief));
}
/// Parses command-line options and runs retest.
fn main() {
let args: Vec<String> = env::args().collect();
let mut options = Options::new();
options.optflag("h", "help", "Print this help menu");
options.optflag("v", "version", "Print the program version");
options.optopt("f", "file", ... | Rust | 0 |
:param out_dir: The directory, in which the memory-mapped array is stored.
:param arr: The numpy array of new samples
:return:
"""
arr = np.asarray(arr)
out_dir = Path(out_dir)
kwargs = _read_mmap_kwargs(out_dir)
shape = kwargs["shape"]
order = kwargs["order"]
dtype = np.dtype(kwarg... | Python | 1 |
[derive(Debug)]
pub struct $interface
{
pub vtable: *const $vtable
}
#[repr(C)]
pub struct $vtable
{
pub base: gom::iUnknownVTable,
$(pub $func: extern "stdcall" fn(*mut $interface, $($t),*) -> $rt),*
}
unsafe impl AsP... | Rust | 0 |
self, reader: R ) -> Result<bool,Error> {
let mut cnt=0;
let mut r = 0;
for line in reader.lines() {
let str = line.unwrap();
if &str[..1] == "@" && cnt == 0 {
self.head.extend(str.as_bytes());
self.head.extend(b"\n");
... | Rust | 0 |
else:
output_dims = 2
key_last_dims = [self._num_kv_heads, self._key_dim]
value_last_dims = [self._num_kv_heads, self._value_dim]
self._dot_product_equation = "...SKH,...TKnH->...nKTS"
self._combine_equation = "...nKTS,...SKH->...TnKH"
einsum_equation, bias_axes, out... | Python | 1 |
et prefix_len = (!u32::from_be_bytes(ip.netmask.octets())).leading_zeros();
IpNet::V4(
Ipv4Net::new(ip.ip, prefix_len as u8).expect("if_addrs returned a valid prefix"),
)
}
IfAddr::V6(ip) => {
let prefix_len = (!u128::from_be_bytes(ip.netmask.octets())... | Rust | 0 |
emplateids
if not os.path.exists(
os.path.join(self.models_target_dir, templateid, self.model_filename)
)
]
# make reference model
forcefield = app.ForceField(ff, implicit_water_model)
reference_model_id = get_highest_seqid_existing_model(models_t... | Python | 1 |
use chacha20poly1305::Key;
use indexmap::{indexset, IndexMap, IndexSet};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use std::fs;
use std::fs::File;
use std::io::{BufReader, Error, ErrorKind};
use std::net::SocketAddr;
use std::path::PathBuf;
use crate::defaults::{KEY_SIZE, PACKAGE_NAME, RECEIVE... | Rust | 0 |
Vertices()[diag].Mul(1 - t).Add(clip.Vertices()[diag+2].Mul(t))
}
return r2.Point{randomPointFromInterval(clip.X), randomPointFromInterval(clip.Y)}
}
// Choose a random point in the rectangle defined by points A and B, sometimes
// returning a point on the edge AB or the points A and B themselves.
func chooseP... | Rust | 0 |
3 - 2));
let initial = create(RangedConstraintRelation::Greater, Some(R32!(1)), None);
let mut index = Index::new(&initial).unwrap();
assert!(index.presolve_slack(0).is_ok());
assert_eq!(index.counters.constraint, vec![0]);
assert_eq!(index.counters.variable, vec![0; 3]);
assert_eq!(index.updat... | Rust | 0 |
bus(scsi_addr: &str) -> Result<()> {
let tokens: Vec<&str> = scsi_addr.split(':').collect();
if tokens.len() != 2 {
return Err(anyhow!(
"Unexpected format for SCSI Address: {}, expect SCSIID:LUA",
scsi_addr
));
}
// Scan scsi host passing in the channel, SCSI id ... | Rust | 0 |
"`reset()` method sets LPACTH1 to value 0"]
impl crate::Resettable for LPACTH1_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1333.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner()
}... | Rust | 0 |
peer_multiaddr_failure_count_for_dns_error_on_connect_failed() {
let (mut mgr, _conn_rx) = make_manager(1, 20);
let inner = mgr.core_inner();
let test_peer = make_peer(2077);
let test_multiaddr = test_peer.multiaddrs.all().pop().expect("multiaddr");
inner.add_peer(test_peer.clone());
mgr.conne... | Rust | 0 |
m_bf.append(state['exp_avg'])
v_bf.append(state['exp_avg_sq'])
s_bf.append(state['shadow'])
elif p.dtype == torch.float32:
g_32.append(p.grad.data)
p_32.append(p.data)
m_32.append(state[... | Python | 1 |
ry=vocab,
transform=transform,
batch_size=batch_size,
num_workers=num_workers,
imp_max=imp_max,
fin_s_max=fin_s_max,
fin_w_max = fin_w_max,
... | Python | 1 |
#!/usr/bin/env python
from evdev import UInput, AbsInfo, ecodes as e
from bluetooth import *
import sys
if sys.version < '3':
input = raw_input
addr = None
if len(sys.argv) < 2:
print("No device specified. Searching all nearby bluetooth devices for")
print("the boogie board sync input")
else:
addr ... | Python | 1 |
e:
print(f" 应用模块Selenium解析失败: {str(e)}")
return None
def parse_product_materials_selenium(self, soup, product_data, product_info):
"""使用Selenium解析产品资料标签页"""
download_links = []
# 查找产品资料下载链接
tab3_div = soup.find('div', id='tab3')
if... | Python | 1 |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.messages import constants
from django.contrib import auth
def cadastro (request):
#print(request.META)
#return HttpResponse('Ol... | Python | 1 |
import numpy as np
import pandas as pd
class RFM:
df: pd.DataFrame = None
df_rfm: pd.DataFrame = None
def __init__(self, rows: list[dict]):
self.df = pd.DataFrame(rows)
self.df["date"] = pd.to_datetime(self.df["date"])
def rfm_analysis(self) -> pd.DataFrame:
self.df.columns =... | Python | 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
from odoo.addons.account.models.chart_template import template
class AccountChartTemplate(models.AbstractModel):
_inherit = 'account.chart.template'
@template('do')
def _get_do_template_data(self):
... | Python | 1 |
let result = super::create_subscription(&db_connection, new_chat.clone(), None);
assert_eq!(
result.err(),
Some(super::SubscriptionError::RssUrlNotProvided)
);
Ok(())
})
}
}
<gh_stars>0
use actix::prelude::*;
use futures::Fut... | Rust | 0 |
self) -> usize {
match self.as_ref() {
Some(a) => 1 + a.borsh_len(),
None => 1,
}
}
}
impl<T: BorshSize> BorshSize for Vec<T> {
fn borsh_len(&self) -> usize {
if self.is_empty() {
4
} else {
4 + self.len() * self[0].borsh_len()
... | Rust | 0 |
cksDbWeight::get().writes(4_u64))
}
// Storage: Labs Labs (r:1 w:1)
// Storage: Orders PendingOrdersBySeller (r:1 w:0)
// Storage: Timestamp Now (r:1 w:0)
// Storage: Labs UnstakeTime (r:1 w:0)
fn unstake_lab() -> Weight {
47_988_000_u64
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(R... | Rust | 0 |
import torch.nn.functional as F
import torch
filter = torch.tensor([[[[0, 0, 1],
[0, 1, 1],
[1, 0, -1]]],
[[[1, 0, 0],
[0, 0, 1],
[1, 0, 1]]]])
inputs = torch.tensor([1, 2, 0, -1, 0, 1, 1, 0, 0, 1... | Python | 1 |
vs. Exponential')
# twelfth trial
#plt.figure('cube exp log')
#plt.clf()
#plt.plot(mySamples, myCubic, 'g--', label = 'cubic', linewidth = 2.0)
#plt.plot(mySamples, myExponential, 'r',label = 'exponential', linewidth = 4.0)
#plt.yscale('log')
#plt.legend()
#plt.title('Cubic vs. Exponential')
#plt.figure('cube exp lin... | Python | 1 |
(*temp)[words] = 0xFFFF_FFFF;
}
}
let control = xous::syscall::map_memory(
xous::MemoryAddress::new(HW_MEMLCD_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map control port");
... | Rust | 0 |
\t\t\tcheckExprDependant( testCounts, *result, \"test" + intrinsicName + "\", __LINE__ );\n" )
outs.write( "\t\t}\n" )
outs.write( '\t\tif ( astWhen( "Using literal parameters" ) )\n' )
outs.write( "\t\t{\n" )
outs.write( computeLiteralParams( paramsGroup, "\t\t\t" ) )
outs.write( "\t\t\tauto result = expr::make" ... | Python | 1 |
import cv2
# Load Haar cascade
harcascade = "model/haarcascade_russian_plate_number.xml"
plate_cascade = cv2.CascadeClassifier(harcascade)
# Start video capture
cap = cv2.VideoCapture(0)
cap.set(3, 640) # width
cap.set(4, 480) # height
min_area = 500
count = 0
while True:
success, img = cap.read()
if not ... | Python | 1 |
//! follow the design description presented in the README.md file located in
//! the [`compute`](crate::compute) module and the function descriptions
//! presented in this document.
pub mod basic;
pub mod decimal;
pub mod time;
use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
use num::Zero;
use crate::datatypes::{Data... | Rust | 0 |
sult = vec![data[0]; k];
unsafe {
let shared = result.as_mut_slice() as *mut [i32];
let worker1 = Worker1 {
data : &result
};
let worker2 = Worker2 {
data : &result
};
let consumers : Vec<Box<dyn Consumer>>... | Rust | 0 |
break
elif max_abs_cost := max(abs(state.a_cost), abs(state.b_cost)) > MAX_ABS_COST:
print(f"\nMax Abs Cost = {max_abs_cost} exceeded limit of {MAX_ABS_COST}!")
break
print(f"\n-------------------------------\n")
if converged_flag:
print(f"Converged after {len(iter... | Python | 1 |
needed since res is temporary and will be newly initialized at the start of the next loop.
// Looking at the IX_ORDER_ARRAY we can now see that the loop starts anew (41,43*256times,46,...).
// This continues for a total of 7 times because 7 inputs.
// Note: As we can see at every new round the 256 b.mul ix have differe... | Rust | 0 |
a for the chart_generator to use.",
)
research_node = functools.partial(agent_node, agent=research_agent, name="Researcher")
# chart_generator
chart_agent = create_agent(
llm_openai,
[python_repl],
system_message="Create chart and save the chart locally.",
)
chart_node = functools.partial(agent_node, agent... | Python | 1 |
8, 2, sys::ImGuiDataType_U32 }
imgui_input_matrix! { (u32, u32, u32, u32, u32, u32, u32, u32), 8, 1, sys::ImGuiDataType_U32 }
imgui_input_matrix! { (i32, i32, i32, i32, i32, i32, i32, i32), 8, 8, sys::ImGuiDataType_S32 }
imgui_input_matrix! { (i32, i32, i32, i32, i32, i32, i32, i32), 8, 7, sys::ImGuiDataType_S32 }
im... | Rust | 0 |
human readable information.
pub fn info(&self) -> &'static str {
self.err_info
}
}
/// Read key bytes from a base32-encoded String.
///
/// # Example
/// ```
/// use totp_rfc6238::oath_uri::key_from_base32;
/// let expected = b"<KEY>";
/// // Base32 only uses uppercase letters. So, lowercase letters w... | Rust | 0 |
hs);
*c = cost
}
// check again!
let collisions = self.find_collisions(&paths);
if collisions.is_empty() {
debug!("Routing worked after sorting");
break;
}
// for now we only use the first collision... | Rust | 0 |
ithout_interrupts(|| {
let mut w = WORLD.lock();
let mut d = DISPLAY.lock();
let (width, height) = (w.width, w.height);
d.clear();
d.draw_bo... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import six
from bson.objectid import ObjectId
from motorengine.fields.base_field import BaseField
from motorengine.utils import get_class
class ReferenceField(BaseField):
'''
Field responsible for creating a reference to another document.
Usage:
.. tes... | Python | 1 |
nvestmentDiscretion").text = (
self.investment_discretion_combo.currentText()
)
ET.SubElement(security, "SharesPrincipal").text = (
self.shares_principal_combo.currentText()
)
ET.SubElement(security, "VotingAuthority... | Python | 1 |
or_id, answer_id, param)
return res_post, usage, is_ai
def get_ai_origin(self, data, author_id=False, answer_id=False, param={}):
# 通用方法
# author_id: 请求的 partner_id 对象
# answer_id: 回答的 partner_id 对象
# param,dict 形式的参数
# 调整输出为2个参数:res_post详细内容,is_ai是否ai的响应
s... | Python | 1 |
"""
GameMenuWindow クラス
ESCキーで表示されるメインゲームメニュー
"""
from typing import Dict, List, Any, Optional
try:
import pygame
except ImportError:
pygame = None # type: ignore
try:
import pygame_gui
except ImportError:
pygame_gui = None # type: ignore
from .window import Window
from src.utils.logger import log... | Python | 1 |
# coding: utf-8
"""
Pastel Network API Gateway
Pastel Network’s Gateway provides Web3 developers with easy, robust, and reliable access to the Pastel Network and its underlying protocols via a lightweight, centralized service.<br/> For more information on Pastel Network, review our <a href=https://docs.pastel... | Python | 1 |
from pathlib import Path
from scenedetect import open_video, split_video_ffmpeg, SceneManager, AdaptiveDetector, HistogramDetector, ContentDetector, FrameTimecode, ThresholdDetector
INPUT_VIDEO_PATH = "game.mp4"
video = open_video(INPUT_VIDEO_PATH)
scene_manager = SceneManager()
# Use FrameTimecode to specify mini... | Python | 1 |
# poly类型的函数
import re
import pandas as pd
def find_poly(str, poly_char, count):
"""
:param str: 需要寻找的母字符串
:param poly_char: 有可能poly的氨基酸 如'Q'
:param count: 多少个连续的氨基酸算poly
:return: 符合poly的子字符串个数 0就是没有这个poly
"""
pattern = f'{poly_char}{{{count},}}' # 'g{5,}'就是超过5个的g {{}}来表示一个普通的{}
matche... | Python | 1 |
from aocd import get_data
data = get_data(day=20, year=2024)
# data = '''###############
# #...#...#.....#
# #.#.#.#.#.###.#
# #S#...#.#.#...#
# #######.#.#.###
# #######.#.#...#
# #######.#.###.#
# ###..E#...#...#
# ###.#######.###
# #...###...#...#
# #.#####.#.###.#
# #.#...#.#.#...#
# #.#.#.#.#.#.###
# #...#...#...... | Python | 1 |
elf.post(BASE_TOKEN_URI)
.body(Body::BufBody(body.as_bytes(), body.len()))
.send()?;
serde_json::from_reader(response).map_err(From::from)
}
}
<filename>src/memory/mmu/tlb.rs
use super::PAGE_MASK_16KB;
use crate::core::cop0::{EntryHi, EntryLo};
/// TLB of the EE Core is 48 entries ... | Rust | 0 |
elf {
Self {
workload,
client: ApiClient::new(client),
}
}
pub(super) fn into_watch(self, backoff: ExponentialBackoff) -> Watch<S> {
StreamWatch::new(GrpcRecover(backoff), self)
}
}
impl<S> Service<u16> for Discover<S>
where
S: tonic::client::GrpcService... | Rust | 0 |
::new(-4.0 * scale, -4.0 * scale, 256.0, 256.0);
canvas.draw_rect(bounds, paint);
}
fn draw_line_2d_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
let lattice = &mut Matrix::default();
lattice.set_scale((8.0, 8.0), None).pre_rotate(30.0, None);
paint
.set_path_effect(line_... | Rust | 0 |
"""
Arena (Grand Roof)
linked:
0
strings:
0: N:\\FDP\\data\\Param\\event\\common_func.emevd
84:
86:
88:
90:
92:
94:
"""
# [COMMON_FUNC]
from .common_func import *
from soulstruct.darksouls3.events import *
from soulstruct.darksouls3.events.instructions import *
@ContinueOnRest(0)
def Constructor():
"""Eve... | Python | 1 |
"""
CCB_AI Consolidated Prompt Configuration
모든 프롬프트를 중앙화하여 중복을 제거하고 일관성을 보장합니다.
"""
from typing import Dict, List, Any
from shared.utils.age_group_utils import AgeGroup
class ConsolidatedPrompts:
"""통합된 프롬프트 관리자"""
# 시스템 메시지 템플릿
SYSTEM_MESSAGES = {
"chatbot_a": {
"base": "너는 부기라... | Python | 1 |
ng(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "a struct of type AccessControlAttributeValue")
}
fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut source: Option<:... | Rust | 0 |
_voting_period must be greater than {}",
Self::INITIAL_VOTING_PERIOD_FLOOR
))
} else if initial_voting_period > Self::INITIAL_VOTING_PERIOD_CEILING {
Err(format!(
"NervousSystemParameters.initial_voting_period must be less than {}",
Self::I... | Rust | 0 |
<<sample3_multiple>>
print(testmodule.version .. "my other snippet")
----
"#;
let reader = AsciidocReader::new();
let opts = options::Opts::from_iter(vec![""].into_iter());
let mut env = util::Env::Cache(util::Cache::new());
let ast = reader.parse(content, &opts, &mut env)?;
let mut lisa = Lisa::from_env(... | Rust | 0 |
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, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to ... | Rust | 0 |
. . . . . . . . . . .
1 . . . . . . . . . .
^ v . . . . . . . . .
^ > v . . . . . . . .
. 0 < . . . . . . . ."#,
)
.unwrap();
let mut floodfill = FloodFill::new(game.grid.width, game.grid.height);
floodfill.flood_snakes(&game.grid, &game.s... | Rust | 0 |
import tkinter
import serial
ser = serial.Serial(
port="COM5",
baudrate=115200,
timeout=0.1,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
xonxoff=False,
rtscts=False,
dsrdtr=False
)
app = tkinter.Tk()
app.geometry("900x500")
app.title("Heating... | Python | 1 |
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
# Memoization dictionary
memo = {}
def helper(s1: str, s2: str) -> bool:
# Check if the strings are already equal
if s1 == s2:
return True
# Check if sort... | Python | 1 |
og² N) in the number of elements.
/// - Space: O(1).
///
/// No memory allocation nor deallocation occurs.
pub fn split<R>(&mut self, range: R, token: &mut GhostToken<'brand>) -> TripodTree<'brand, T>
where
R: RangeBounds<usize>,
{
let length = self.len(token);
let rang... | Rust | 0 |
sult::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as... | Rust | 0 |
let cc = pmat * coords.to_homogeneous();
let pt2 = SMatrix::<f64, 1, 2>::new(cc[0] / cc[2], cc[1] / cc[2]);
approx::assert_abs_diff_eq!(pt1[0], pt2[0], epsilon = 1e-5);
approx::assert_abs_diff_eq!(pt1[1], pt2[1], epsilon = 1e-5);
}
}
#[test]
fn test_to_from_pmat... | Rust | 0 |
principal that created the cluster and the Amazon Web Services account root user can perform EMR actions, regardless of IAM permissions policies attached to other IAM principals.</p>
/// <p>The default value is <code>true</code> if a value is not provided when creating a
/// cluster using the EMR API <a>RunJob... | Rust | 0 |
# Program to determine Armstrong number in python.
num=int(input("Enter a number:"))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**3
temp //=10
if num==sum:
print(num,"is an Armstrong number")
else:
print(sum,"is not an Armstrong number") | Python | 1 |
import string
import re
import nltk
#nltk.download('twitter_samples')
#nltk.download('stopwords')
#nltk.download('averaged_perceptron_tagger')
#nltk.download('wordnet')
from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords, twitter_samples, wordnet
from nltk.stem import WordNetLemmatizer
stopwor... | Python | 1 |
d_range(0, d.len() as i64) as usize
}
/// Return a random value within a range
///
pub(crate) fn random<T: Randomable>(min: T, max: T) -> T {
rand_range::<T>(min, max)
}
/// Replace hashtags (octothorps) in a string with random numbers
///
pub(crate) fn replace_with_numbers(s: String) -> String {
if s.is_empt... | Rust | 0 |
print("ATTEMPTED FUNCTION CALL BUT WAS UNABLE...")
messages.append({"role": "assistant", "content": response})
return messages
# except subprocess.CalledProcessError as e:
# print("Unable to generate ChatCompletion response")
# print(f"Exc... | Python | 1 |
.entry(name.clone()).or_insert(Kind::Array(vec![]));
match v {
Kind::Array(v) => {
while v.len() <= i {
v.push(None);
}
if v[i].is_some() {
panic!("??? two ... | Rust | 0 |
self.points
}
pub fn set_points(&mut self, points: Vec<SplinePoint<T>>) {
if let Ok(result) = Self::new(points) {
*self = result;
}
}
pub fn curves(&self) -> &[Curve<T>] {
&self.cached
}
pub fn find_time_for_axis(&self, mut axis_value: Scalar, axis_index: u... | Rust | 0 |
{
|_vm, res: Result| {
matches!(res.unwrap_err(),
EbpfError::ExceededMaxInstructions(pc, initial_insn_count)
if pc == 34 && initial_insn_count == 7
)
}
},
7
);
}
#[test]
fn test_instruction_coun... | Rust | 0 |
0, c1, c2))
}
#[inline]
fn negate_in_place<CS: ConstraintSystem<ConstraintF>>(
&mut self,
mut cs: CS,
) -> Result<&mut Self, SynthesisError> {
self.c0.negate_in_place(&mut cs.ns(|| "negate c0"))?;
self.c1.negate_in_place(&mut cs.ns(|| "negate c1"))?;
self.c2.nega... | Rust | 0 |
minate() {
let instruction = Instruction::terminate();
assert!(instruction.should_terminate);
let commands = &instruction.commands;
assert_eq!(commands.len(), 1);
let expect = Command::echo("goodbye!");
assert_eq!(&commands[0], &expect);
}
#[test]
fn test_echo() {
let message = "this is a... | Rust | 0 |
"sámekultuvrapolitihkkalaš",
"sámekulturpolitihkalaš",
6.496088,
&["sámekulturpolitihkalaš", "sámekulturpolitihkkaraš"],
),
(
"hálidivččii",
"háliidivččii",
6.484202,
&[
"báldii",
"báládii",
"holdii",
... | Rust | 0 |
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def mse_loss(pred, target):
"""Warpper of mse loss."""
return F.mse_loss(pred, target, reduction='none')
@LOSSES.register_module()
class MSELoss(nn.Module):
"""MSELoss.
... | Python | 1 |
from app.preprocessing import main
if __name__ == '__main__':
main()
| Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
微信公众号批量阅读量抓取器
基于现有代码架构,整合文章链接获取和阅读量抓取功能
"""
import os
import re
import json
import time
import random
import requests
import pandas as pd
import winreg
import ctypes
import contextlib
from datetime import datetime, timedelta, timezone
from bs4 import BeautifulSoup
fr... | Python | 1 |
"Flexible CRC Engine"]
pub struct FCE_KE2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FCE_KE2 {}
impl FCE_KE2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fce_ke0::RegisterBlock = 0x5002_0060 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inli... | Rust | 0 |
radio_text(text: &mut [char; 64], data: &RdsData) -> bool {
if let Some(data) = get_rds_radio_text(data) {
if let Some((text_data, offset)) = data.text {
match text_data {
RdsRadioTextData::Two(a, b) => {
text[offset] = a;
text[offset + 1] ... | Rust | 0 |
MIN_SPECIALIZATION_NAME_LENGTH = 3
MAX_SPECIALIZATION_NAME_LENGTH = 150
| Python | 1 |
"""
1) Reverse singly-linked list
2) Detect cycle in a list
3) Merge two sorted lists
4) Remove nth node from the end
5) Find middle node
Author: Wenru
"""
from typing import Optional
class Node:
def __init__(self, data: int, next=None):
self.data = data
self._next =... | Python | 1 |
non-zero: {}", code);
}
},
Err(_) => {
eprintln!("\
Unable to open authentication URL\n\
Open the link below to process\n\
{}\
", oauth_uri);
}
};
}
<filename>06/expressions/src/main.rs
fn main() {
{
... | Rust | 0 |
.format(self.udev_path, self.target_dir))
else:
print(_("You don't have the required permissions to change your wheel settings."))
exit(-1)
if not device:
print(_("No device available."))
model = Model(device)
if args.... | Python | 1 |
f == ADC14IFG27_A::ADC14IFG27_0
}
#[doc = "Checks if the value of the field is `ADC14IFG27_1`"]
#[inline(always)]
pub fn is_adc14ifg27_1(&self) -> bool {
*self == ADC14IFG27_A::ADC14IFG27_1
}
}
#[doc = "ADC14MEM28 interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]... | Rust | 0 |
#!/usr/bin/env python
# vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | Python | 1 |
127.0.0.1:8888"),
cache_ttl: 30*60,
cache_tti: 5*60,
cookie_name: Cow::from("PHPSESSID"),
})
}
#[test]
fn create_key() {
assert_eq!(get_access_key(), AccessKey {
object: Some(String::from("tver")),
model: Some(String::from("pa... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.