text string | label_name string | labels int64 |
|---|---|---|
class Solution:
def numberOfGoodSubsets(self, nums: List[int]) -> int:
kMod = 1_000_000_007
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
n = 1 << len(primes)
# dp[i] := # of good subsets w/ set of primes = i bit mask
dp = [1] + [0] * (n - 1)
count = collections.Counter(nums)
for num, fre... | Python | 1 |
#!/usr/bin/env python
'''
@Author : Damien Cauquil
'''
import sys
import lief
import re
from struct import unpack,pack
def parse_versions_sect(content):
"""
Parse 64-bit versions section
"""
symbols_crc = {}
nb_symbols = int(len(content)/64)
for i in range(nb_symbols):
crc = unpack... | Python | 1 |
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import get_user_model
from . import settings as app_settings
from .base.admin import (
AbstractNasAdmin, AbstractRadiusAccountingAdmin, AbstractRadiusBatchAdmin, AbstractRadiusCheckAdmin,
AbstractRadiusGroupAdmin, Abstra... | Python | 1 |
import os
import torch
import random
import numpy as np
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP']
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def get_paths_from_images(path):
... | Python | 1 |
().map(|o| self.outlet_fact(*o)).collect::<TractResult<TVec<_>>>()?;
op.pulsed_output_facts(&*input_facts)?
};
let id = self.add_node(name, op, output_facts)?;
inputs
.iter()
.enumerate()
.try_for_each(|(ix, i)| self.add_edge(*i, InletId::new(id, i... | Rust | 0 |
import database
import json
with open('config.json') as json_file:
data = json.load(json_file)
password = data["password"]
username = data["admin_username"]
def add_admin(password):
test = database.check_username_exists(username)
if not test:
database.add_user(username,password)
add_admin(passw... | Python | 1 |
Operation => write!(f, "Unsupported Operation"),
Error::Sys(errno) => write!(f, "{:?}: {}", errno, errno.desc()),
}
}
}
pub trait NixPath {
fn is_empty(&self) -> bool;
fn len(&self) -> usize;
fn with_nix_path<T, F>(&self, f: F) -> Result<T>
where F: FnOnce(&CStr) -> T;
}
... | Rust | 0 |
lue that can be
/// produced by the analog component.
allowed_values: VolatileCell<u32>,
/// Reflects the current time counter value that the TRNG has while waiting for
/// its analog counterpart.
timer_counter: VolatileCell<u32>,
/// Most significant bits for the slicing portion that are used... | Rust | 0 |
rdering::from_view_direction(
p.0 - self.data.view_chunk.0,
),
)?;
}
}
Ok(())
})
},
)?;
... | Rust | 0 |
# data process for MICCAI Chalenge 2024
# TUS-REC Challenge
# Trackerless 3D Freehand Ultrasound Reconstruction (TUS-REC) Challenge
import os
import h5py
import torch
from data_process_functions import *
DATA_DIR = 'Path/To/Dataset'
FILENAME_CALIB = 'Path/To/CSV'
# get object names in HDF5 file
DataSet = h5py.File(o... | Python | 1 |
::Iter<'a, i64>, // deltas
cid: i64, // current id
dlats: std::slice::Iter<'a, i64>, // deltas
clat: i64,
dlons: std::slice::Iter<'a, i64>, // deltas
clon: i64,
keys_vals_slice: &'a [i32],
keys_vals_index: usize,
info_iter: Option<DenseNodeInfoIter<'a>>,
}
impl<... | Rust | 0 |
ferences.png".format(plotname), dpi=250)
# plot 2: orbit tracks over time
plt.figure()
plt.plot(kra[:, 1:5, 0], kde[:, 1:5, 0], "indigo", label="Orbitize approx.")
plt.plot(kra[-1, 1:5, 0], kde[-1, 1:5, 0], "o")
plt.plot(rra[:, 1:5, 0], rde[:, 1:5, 0], "r", label="Rebound", alp... | Python | 1 |
def get_producer_map(ssa):
"""
Return dict from versioned blob to (i, j),
where i is index of producer op, j is the index of output of that op.
"""
producer_map = {}
for i in range(len(ssa)):
outputs = ssa[i][1]
for j, outp in enumerate(outputs):
producer_map[outp... | Python | 1 |
write!(f, "LoggerConfigurationError: [{}]", message),
}
}
}
impl Error for LoggerError {}
impl From<log::SetLoggerError> for LoggerError {
fn from(error: log::SetLoggerError) -> Self {
LoggerError::LoggerConfigurationError { message: format!("{}", error) }
}
}
impl From<std::io::Error> f... | Rust | 0 |
_0(self) -> &'a mut W {
self.variant(IDW::I2S_0)
}
#[doc = "I2S_1"]
#[inline]
pub fn i2s_1(self) -> &'a mut W {
self.variant(IDW::I2S_1)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 63;
... | Rust | 0 |
_hues()
entity_hues = {}
colorized_tex = tex
for e in entities_reverse_order:
# Get a hue to color this entity
if preset_hue is not None:
hue = preset_hue
else:
hue = next(hue_generator)
# Save a reference to this colorized entity to return to the c... | Python | 1 |
from pynvml import *
nvmlInit()
# https://www.nvidia.com/content/PDF/nvidia-ampere-ga-102-gpu-architecture-whitepaper-v2.pdf
nvidia_rtx_3090 = {
"name": "NVIDIA GeForce RTX 3090",
"compute_capability": "8.6",
"memory": 24, # in GB
"bandwidth": 936.2, # in GB/s
"fp16_tflops": 71,
"fp32_tflops... | Python | 1 |
"using `libc::strlen` on a `CString` or `CStr` value",
"try this (you might also need to get rid of `unsafe` block in some cases):",
sugg,
Applicability::Unspecified // Sometimes unnecessary `unsafe` block
);
}
... | Rust | 0 |
np.save("final_results/Last_sindy_prior_samples_Celegans_2stages_sparsity" + str(sparsity) + "_threshold_" + str(vae.threshold) + "_total_var_" + str(total_var_coeff) + "_batch_size" + str(batch_size) + "_len_seq" + str(len_seq_) + "_latent_dim_" + str(latent_dim) + "_different_deriv2_L2_" + multipleTraj + "_premask_no... | Python | 1 |
class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
result_set = set()
current_ors = set()
for num in arr:
current_ors = {num | x for x in current_ors} | {num}
result_set |= current_ors
return len(result_set)
| Python | 1 |
#
# Copyright (c) 2009-2016, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El
m = 500
n = 250
display = True
worldRank = El... | Python | 1 |
,
r#"
if . == 0 then "zero" elif . == 1 then "one" else "many" end
"#,
r#"
2
"#,
r#"
"many"
"#
);
test!(
comparison1,
r#"
. < 5
"#,
r#"
2
"#,
r#"
true
"#
);
test!(
and_or_not1,
r#"
42 and "a string"
"#,
r#"
null
"#... | Rust | 0 |
or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! Detect recursion when doin... | Rust | 0 |
# Input weighted graph
n = int(input("Number of edges: "))
graph = {}
for _ in range(n):
u,v,w = input("Edge (u v w): ").split()
w = int(w)
if u not in graph: graph[u] = {}
if v not in graph: graph[v] = {}
graph[u][v] = w
start = input("Start node: ")
def dijkstra(start):
dist = {node: flo... | Python | 1 |
def piramide(n):
carac = "*"
for i in range(n):
print(" "*(6-i),carac)
carac += "*"*2
piramide(6) | Python | 1 |
import logging
import pandas as pd
from library.grouping.grouping_transformer import GroupingArgs
from .grouping_methods import GROUPING_METHODS
logger = logging.getLogger(__name__)
def group_by_metadata(
metadata_df: pd.DataFrame, grouping_args: GroupingArgs
) -> pd.DataFrame:
if grouping_args.method not... | Python | 1 |
"""The command for finding workspaces."""
from jupiter.core.domain.concept.workspaces.workspace import Workspace
from jupiter.core.domain.storage_engine import DomainUnitOfWork
from jupiter.core.framework.use_case_io import (
UseCaseArgsBase,
UseCaseResultBase,
use_case_args,
use_case_result,
)
from ju... | Python | 1 |
mulation failure error.
#[derive(Error, Debug)]
pub struct TxSimulationFailure {
message: String,
module_name: String,
code: u32,
}
impl Display for TxSimulationFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl SDKError fo... | Rust | 0 |
sib_base
sib_index: RegSpec,
vex_reg: RegSpec,
scale: u8,
length: u8,
operand_count: u8,
operands: [OperandSpec; 4],
imm: u64,
disp: u64,
pub opcode: Opcode,
}
impl yaxpeax_arch::Instruction for Instruction {
fn well_defined(&self) -> bool {
// TODO: this is incorrect!
... | Rust | 0 |
s() {
use toql::prelude::{ResolverError, ToqlError};
let cache = Cache::new();
let mut toql = MockDb::from(&cache);
// Load text1 without aux param
// -> Fails
let q = query!(Level1, "text1");
let err = toql.load_many(&q).await.err().unwrap();
assert_eq!(
err.to_string(),
... | Rust | 0 |
import cv2
from dataclasses import dataclass
from stereo_calib.charuco import constants as CharucoConfig
@dataclass
class CharucoBoardData:
"""
A data class to hold Charuco board configuration.
Attributes:
aruco_dict (int): Aruco dictionary type.
squares_vertically (int): Number of squar... | Python | 1 |
= DW_AT(0x5d);
pub const DW_AT_DECIMAL_SIGN : DW_AT = DW_AT(0x5e);
pub const DW_AT_DIGIT_COUNT : DW_AT = DW_AT(0x5f);
pub const DW_AT_PICTURE_STRING : DW_AT = DW_AT(0x60);
pub const DW_AT_MUTABLE : DW_AT = DW_AT(0x61);
pub const DW_AT_THREADS_SCALED : DW_AT = DW_AT(0x62);
pub const DW_AT_EXPLICIT : DW_AT = DW_AT(0x63)... | Rust | 0 |
import requests
from base64 import b64decode, b64encode
from tqdm import tqdm
# Bit flip code based on https://crypto.stackexchange.com/a/66086.
# we need to decode from base64 twice because the cookie was encoded twice.
def bit_flip(pos, bit, data):
raw = b64decode(b64decode(data).decode())
list1 = bytearray... | Python | 1 |
ild(&line, 8, 1);
}
#[test]
fn test_parse_line_with_wild_2() {
let line = [Symbol(8), Symbol(4), Symbol(8), Symbol(4), Symbol(5)];
assert_with_wild(&line, 4, 4);
let line = [Symbol(8), Symbol(8), Symbol(8), Symbol(4), Symbol(5)];
assert_with_wild(&line, 4, 4);
let ... | Rust | 0 |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""PyBoard pin names"""
from adafruit_blinka.microcontroller.stm32.stm32f405 import pin
X1 = pin.A0
X2 = pin.A1
X3 = pin.A2
X4 = pin.A3
X5 = pin.A4
X6 = pin.A5
X7 = pin.A6
X8 = pin.A7
X9 = pin.B6
X10 = pin... | Python | 1 |
0));
let mut found: bool = false;
for ip in &iface.ips {
if ip.is_ipv4() {
my_ip = ip.ip();
found = true;
break;
}
}
... | Rust | 0 |
from flask import Flask, send_file, abort,Blueprint
from flask_bcrypt import Bcrypt
from flask_marshmallow import Marshmallow
import sqlite3
app = Flask(__name__, instance_relative_config=True)
ma = Marshmallow(app)
conn = sqlite3.connect('data_1.db', check_same_thread=False)
conn.isolation_level = None
db = conn.cur... | Python | 1 |
class Persona:
def __init__(self, name:str, lastname:str, age:int):
self.setName(name)
self.setLastName(lastname)
self.setAge(age)
def __str__(self) -> str:
return f"Nome: {self.name}\nCognome: {self.lastname}\nEtà: {self.age}"
def setName(self, name:str) -> None:
... | Python | 1 |
th
.as_ref()
.with_sig_extension()
.ok_or("invalid sig path")?)
}
struct Params<'a> {
pk: &'a Option<PublicKey>,
sig_path: Option<PathBuf>,
hash: Option<String>,
}
fn fexec<P, S, T>(path: P, args: T, params: Params) -> Result<Infallible>
where
P: AsRef<Path>,
S: AsRef<str>,... | Rust | 0 |
# This class prints out the generated schedule at the end of our search process.
from Schedule import Schedule
class Printer:
#Constructor
def __init__(self) -> None:
pass
@staticmethod
def print_schedule(schedule: Schedule):
#schedule = schedule.get_copy() <- not sure if need this... | Python | 1 |
to DIRECTORY.");
let overwrite_mode = determine_overwrite_mode(&matches);
let backup_mode = determine_backup_mode(&matches);
if overwrite_mode == OverwriteMode::NoClobber && backup_mode != BackupMode::NoBackup {
show_error!(
"options --backup and --no-clobber are mutually exclusive\n\
... | Rust | 0 |
_::into_raw(f),
)
}
}
fn connect_tag_changed<F: Fn(&Self, &TextTag, bool) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn tag_changed_trampoline<P, F: Fn(&P, &TextTag, bool) + 'static>(
this: *mut ffi::GtkTextTagTable,
tag: *mut ffi::GtkText... | Rust | 0 |
erator for &'a mut LinkedList<T> {
type Item = &'a mut T;
type IntoIter = IterMut<'a, T>;
fn into_iter(self) -> IterMut<'a, T> {
self.iter_mut()
}
}
impl<T: Hash> Hash for LinkedList<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
for item in self.iter() {
item.hash(state... | Rust | 0 |
fn $test_name() {
assert_eq!($test_func( $param ), $expect);
}
)+
}
}
tests! {
hands_match {
test_01(1, 327);
test_02(2, 655);
test_03(3, 982);
test_04(4, 1309);
test_05(5, 1636);
test_06(6, 1964);
test_07(7, 229... | Rust | 0 |
PRI_0` writer - Priority value 0"]
pub struct PRI_0_W<'a> {
w: &'a mut W,
}
impl<'a> PRI_0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff);
self.w
}
}
#[d... | Rust | 0 |
"""add null for tg_id
Revision ID: 8be416cb06b5
Revises: f62772bc0fe1
Create Date: 2025-08-01 19:46:48.761579
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '8be416cb06b5'
down_revision: Union[str, None] = 'f62772bc0fe1... | Python | 1 |
t used. Required. The string must be at most 31 characters long.u Sizeu The size of the font used. This size is given in our units (1/12 of the system font height). Assuming that the system font is set to 12 point size, this is equivalent to the point size.u StyleBitsi u A combination of style bits.u T... | Python | 1 |
u8;
let byte_two = (value << 4 & 0xF0 | value >> 8 & 0x0F) as u8;
let byte_three = (value & 0xFF) as u8;
// We really want this to go fast
unsafe {
// Unroll one of the iteratations to allow writing
// the PWM feedback value first (shifted into the 24th channel)
... | Rust | 0 |
import numpy as np
from scipy import signal
from Softmax import *
from ReLU import *
from Conv import *
from Pool import *
def MnistConv(W1, W5, Wo, X, D):
alpha = 0.01
beta = 0.95
momentum1 = np.zeros_like(W1)
momentum5 = np.zeros_like(W5)
momentumo = np.zeros_like(Wo)
N = len(D)
... | Python | 1 |
ring::Relaxed) {
return Err(BoomerError::TimeoutOnReady)
}
s1.off(id1).await;
s2.off(id2).await;
return Ok((s1, s2));
}
<reponame>qrilka/fluvio<gh_stars>100-1000
use std::io::Error as IoError;
use dataplane::core::{Version, Decoder, Encoder};
use dataplane::bytes::Buf;
use dataplane::bytes::B... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# # COURSE: Master statistics and machine learning: Intuition, Math, code
# ##### COURSE URL: udemy.com/course/statsml_x/?couponCode=202509
# ## SECTION: Visualizing data
# ### VIDEO: Bar plots
# #### TEACHER: Mike X Cohen, sincxpress.com
#
# In[ ]:
# import libraries
import ... | Python | 1 |
kernel: tensor3(&[[[0.0f32]], [[0.0]], [[0.0]], [[0.0]]])
.into_array::<f32>()
.unwrap()
.into_dyn(),
bias: None,
};
assert_eq!(pb.tract().unwrap(), pb.reference());
Ok(())
}
#[test]
fn group_7() -> anyhow::Result<()> {
let pb = ConvProblem {
... | Rust | 0 |
r.memory("Attempted to load context from long-term memory", jarvis.current_context)
try:
jarvis.chat_loop()
except KeyboardInterrupt:
logger.system("Received keyboard interrupt, shutting down")
console.print("\n[bold red]JARVIS shutting down...[/bold red]")
except Exception as e... | Python | 1 |
# 아마도 MST 문제 : prim 알고리즘과 친해지기
# 시간복잡도 계산 : N은 최대 100개로 MST를 통해 문제 풀이 시
# 99 X 99 < 10000으로
from heapq import heappush, heappop
n = int(input())
x, y = [0.0] * 101, [0.0] * 101
for i in range(1, n + 1):
x[i], y[i] = map(float, input().split())
# 관계그래프 작성
graph = [[] for _ in range(101)]
for i in range(1, n + 1):... | Python | 1 |
RowsIter {
table: self,
_ph: PhantomData,
}
}
fn zip<T>(self, second_table: T) -> Result<Zip<Self, T>>
where
T: LazilyEncodedTable<F, Item = Self::Item, Error = Self::Error>,
Self: Sized,
{
ensure!(
self.size() == second_table.size(... | Rust | 0 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
df=pd.read_csv("data.csv")
print(df.head())
df = df.drop("CustomerID", axis=1)
df['Gender'] = df['Gender'].map({'Male': 0, 'Female': 1})
X=... | Python | 1 |
l();
utils::set_exit_tx(&self.exit_tx, tx);
Ok(rx)
}
// TODO add spawn_catch, which enforces UnwindSafe and uses catch_unwind
}
#[cfg(test)]
mod tests {
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_variables)]
use tokio_core::reactor::{
Core,
Handle
};
use super::*... | Rust | 0 |
fn rule_3(a_state: AddressState, b_state: AddressState) -> Ordering {
if a_state != b_state {
// Rule 3: Avoid deprecated addresses.
//
// Note that, since we've already filtered out tentative addresses,
// the only two possible states are deprecated and assi... | Rust | 0 |
# Copyright (C) 2018-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.front.caffe.extractors.utils import get_canonical_axis_index
from openvino.tools.mo.utils.error import Error
def slice_axis_ext(attrs):
axis = attrs.int("axis", 0)
begin = attrs.int("begin", 0)
end = ... | Python | 1 |
client_version = payload['client_version']
fn, args, kwargs = _get_payload_function_data(payload)
suppress_warnings |= payload['suppress_warnings']
logging.info('Received command. fn: {} args: {} kwargs: {}'.format(fn.__name__, args, kwargs))
try:
... | Python | 1 |
ships_numbers = [4, 8, 15, 17, 23, 42]
ships = ["Destroyer", "Cruiser", "Linker", "Submarine", "Carrier"]
ships.extend(ships_numbers)
print(ships[-2])
print(ships[0])
print(ships[1:])
print(ships[2:])
print(ships[3:])
print(ships[4:])
print(ships)
print(ships[1: 3])
ships[1] = "Dreadnought"
print(ships[1:], " value ju... | Python | 1 |
import torch
# 检查是否有可用的GPU
if not torch.cuda.is_available():
print("CUDA is not available. This script requires a GPU to run.")
exit()
# 定义元素的数量
# const unsigned n = 1 << 30;
n = 1 << 30
print(f"Preparing to calculate softmax for {n} elements on the GPU...")
# 将设备设置为cuda
device = torch.device('cuda')
try:
... | Python | 1 |
#!/usr/bin/env python3
"""
System Evaluators
================
RAG system evaluation functions.
"""
import json
from pathlib import Path
from typing import Dict, Any
from RAG.app.logger import get_logger
from .answer_evaluators import calculate_answer_correctness
def evaluate_rag_system(ground_truth_path: Path, pip... | Python | 1 |
]
fn test_scientific_no_decimal_negative_exponent() {
assert_eq!(num_integral_digits("123e-4").unwrap(), 1);
}
#[test]
fn test_scientific_with_decimal_negative_exponent() {
assert_eq!(num_integral_digits("123.45e-6").unwrap(), 1);
assert_eq!(num_integ... | Rust | 0 |
"""
llm-prompt-optimizer CLI
Author: Sherin Joseph Roy
Email: sherin.joseph2217@gmail.com
GitHub: https://github.com/Sherin-SEF-AI/prompt-optimizer.git
LinkedIn: https://www.linkedin.com/in/sherin-roy-deepmost/
Command-line interface for the llm-prompt-optimizer framework (PyPI: llm-prompt-optimizer).
"""
import cli... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path('connect/', views.connect, name='connect'),
path('select_config/', views.select_config, name='select_config'),
path('edit-filter/', views.edit_filter, name='edit_filter'),
path('create_xml/', views.create_xml, name='create_xml'),
] | Python | 1 |
expected_vals = expected_values.get(compound_name, [])
for i, col in enumerate(sample_cols[:4]):
val = clean_nist_row.get(col, 'MISSING')
excel_expected = expected_vals[i] if i < len(expected_vals) else 'Unknown'
... | Python | 1 |
"""Steps and utility functions for taking screenshots."""
import uuid
from lettuce import (
after,
step,
world,
)
import os.path
import json
def set_save_directory(base, source):
"""Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this di... | Python | 1 |
orientation, PIN_LENGTH);
} else {
panic!("No outline found for part!");
}
}
}
panic!("No pin found!")
}
pub fn write_circuit_to_svg(circuit: &Circuit, name: &str) {
let mut top_document = Document::new().set("viewBox", (-2000, -2000, 7000, 7000));
let mu... | Rust | 0 |
Default::default()
});
}
Ok(LocalFs {
dir: config.dir,
readahead: config.readahead,
readahead_sec: config.readahead_sec,
file_table: RwLock::new(HashMap::new()),
metrics,
..Default::default()
})
}
type AccessLogEntry = (u64, u32, u32);
// Access ent... | Rust | 0 |
}
// Platform-specific shims
_ => {
match this.tcx.sess.target.target.target_os.as_str() {
"linux" => return linux::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
"macos" => return macos::EvalContextExt... | Rust | 0 |
k'}
```
"""
if type(index) != str:
index = str(index)
return self.graph.nodes[index]
def predecessors(self, index):
"""
Wrapper of networkx.digraph.predecessors()
"""
if type(index) != str:
index = str(index)
... | Python | 1 |
time() {
let mut alarm_manager = default_alarm_manager();
alarm_manager.alarms[2].is_enable = true;
alarm_manager.alarms[2].set_hour(17);
alarm_manager.alarms[2].set_min(30);
alarm_manager.alarms[2].mode.insert(Mode::ONE_TIME);
let datetime = DateTime {
year:... | Rust | 0 |
ail_record >= 0 and current_tail_page >= 0 and greaterthan([current_tail_page, current_tail_record ] , oldTPS) ):
baseRID = self.pageRange[PageRangeIndex].tailPages[current_tail_page].baseRID[current_tail_record]; # implement baseRID everywhere
baseRID = self.page_directory[baseRID]
... | Python | 1 |
"""
A pure Python implementation of the quick sort algorithm
For doctests run following command:
python3 -m doctest -v quick_sort.py
For manual testing run:
python3 quick_sort.py
"""
from __future__ import annotations
def quick_sort(collection: list) -> list:
"""A pure Python implementation of quick sort algori... | Python | 1 |
.Default::default()
};
const NUM_FRAMES: usize = 5;
for _ in 0..NUM_FRAMES {
ctx.begin_frame(raw_input.clone());
demo_windows.ui(&ctx, &Default::default(), &mut None);
let (_output, paint_jobs) = ctx.end_frame();
assert!(!paint_jobs.is_empty());
}
}
<filename>pokemon_mod... | Rust | 0 |
extra {
PlaceExtra::Vtable(vtable) => vtable,
_ => bug!("Expected vtable when dropping {:#?}", place),
};
let place = self.unpack_unsized_mplace(place)?;
let instance = self.read_drop_type_from_vtable(vtable)?;
(inst... | Rust | 0 |
r("保存专辑/歌单的歌词"))
@Slot()
def save_lyric(self, location: Literal["dir", "tag"]) -> None:
"""保存预览的歌词"""
if self.lyrics is None:
MsgBox.warning(self, self.tr("警告"), self.tr("请先下载并预览歌词"))
return
if not self.lyrics or self.preview_plainTextEdit.toPlainText() == "":
... | Python | 1 |
import pycomus
if __name__ == "__main__":
# MultiLayerDryWetSim(File-Input):
# Create Model
model = pycomus.ComusModel(model_name="MultiLayerDryWetSim(File-Input)")
# Control Params
modelControlParams = pycomus.ComusConPars.load(model, "./InputFiles/CtrlPar.in")
# Output Params
modelOutP... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
from strategies import moving_average_strategy
def load_historical_data(csv_file):
data = pd.read_csv(csv_file, parse_dates=["Date"])
data = data.sort_values("Date")
return data
def backtest_strategy(data):
strategy_data = moving_average_strategy(dat... | Python | 1 |
from opencompass.multimodal.models.minigpt_4 import (
MiniGPT4VQAPromptConstructor,
MiniGPT4VQAPostProcessor,
)
# dataloader settings
val_pipeline = [
dict(type='mmpretrain.LoadImageFromFile'),
dict(type='mmpretrain.ToPIL', to_rgb=True),
dict(type='mmpretrain.torchvision/Resize',
size=(224... | Python | 1 |
and accessing elements of a vector, used commonly in graphics
shader programming. Swizzling is available on vectors whose element type
implements `Clone`.
Single-element accessors return the element itself. Multi-element accessors
return vectors of the appropriate size.
## Element names
Only the first four elements of... | Rust | 0 |
g trainers."""
from big_mood_detector.infrastructure.fine_tuning.population_trainer import (
create_population_trainer,
)
# PAT trainer
pat_trainer = create_population_trainer(
model_type="pat",
task_name="depression",
)
assert pat_tra... | Python | 1 |
_bytes) in block_iter.skip(1) {
let block = block_bytes
.zcash_deserialize_into::<Block>()
.expect("block is structurally valid");
for (idx, tx) in block.transactions.iter().enumerate() {
for output in tx.outputs() {
let addr = output.address(network)... | Rust | 0 |
t.download_button(
"📅 Download Itinerary",
itinerary_text,
f"itinerary_{plan.budget_preference}.md",
"text/markdown"
)
with export_cols[2]:
if st.session_state.bu... | Python | 1 |
}
#[test]
fn test_nft_invalid_nft_data() {
// deploy contract
let mut context = Context::default();
let nft_bin: Bytes = Loader::default().load_binary("nft-validator");
let nft_out_point = context.deploy_contract(nft_bin);
let always_success_out_point = context.deploy_contract(ALWAYS_SUCCESS.clone(... | Rust | 0 |
/ joins](https://en.wikipedia.org/wiki/Join_%28SQL%29#Left_outer_join) the two input
/// iterators. The resulting iterator contains all the records from the left input iterator,
/// even if they do not match the right input iterator.
///
/// The input iterators do *not* need to be sorted. The right inp... | Rust | 0 |
address: Default::default(),
// caller: alice_evm_addr(),
// apparent_value: Default::default()
// }
// ),
// ExitError::Other("invalid action".into())
// );
// });
// }
// #[test]
// fn schedule_call_precompile_should_work() {
// new_test_ext().execute_with(|| {
// let context = Contex... | Rust | 0 |
'automake',
'binutils',
'curl',
'git',
'grep',
'gnutls-utils',
'libtool',
'maven',
'maven-shade-plugin',
'openssl',
'openssl-libs',
'openssl-d... | Python | 1 |
_base_ = [
'../_base_/models/ccnet_r50-d8.py',
'../_base_/datasets/pascal_voc12_aug.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(num_classes=21), auxiliary_head=dict(num_classes=21))
| Python | 1 |
def _embed_init(self, initrange=0.05):
"""Initialize the embedding weights"""
nn.init.uniform_(self.embed.weight, -initrange, initrange)
| Python | 1 |
row_data.append(item.text())
else:
row_data.append("")
writer.writerow(row_data)
QMessageBox.information(
self,
"Success",
f"Saved as CSV file successfully!\nLo... | Python | 1 |
a=c1.fetchall()
for i in a:
print(i)
break
elif choice==9:
sql_s="select*from order_details"
c1.execute(sql_s)
a=c1.fetchall()
for i in a:
print(i)... | Python | 1 |
| of four bytes.
//!
//! \yskip\hang first byte: |skip_byte|, indicates that this is the final program
//! step if the byte is 128 or more, otherwise the next step is obtained by
//! skipping this number of intervening steps.\par
//! \hang second byte: |next_char|, ``if |next_char| follows the current character,
//... | Rust | 0 |
"""
check over data and file integrity before processing
"""
import numpy as np
from config import settings
from debugging import error_types
def check_timestamps(df, timestamps):
# first check - makes sure there is around 0.03s between each frame
time_off = np.zeros(len(timestamps)) # records indices where ... | Python | 1 |
) {
match *self {
OutputFormat::Normal => println!("{name} = {value} {unit}", name = register,
value = value.0, unit = value.1),
OutputFormat::Compact => print!("{} ", value.0),
OutputFormat::Iec62056 (ref address) => {
// Prepend "*" to unit i... | Rust | 0 |
import sys
from ddpm import modules
sys.path.append("../")
import torch
def get_cond_fn(
controller: modules.Drifter,
controller_cond: modules.CondScorer,
scale_factor: float,
drift: float,
):
print("[get_cond_fn] drift: ", drift)
def cond_fn(c, x, t):
# c = c.to(x.device)
... | Python | 1 |
uld not connect to ComfyUI, either ComfyUI is not running or ComfyUI is outdated and requires updating.", gr.Accordion(visible=False)
# Validate that some firewall hasn't blocked it
try:
ws.ping()
except:
ws.close()
return "Connection to ComfyUI lost. Please ensure ComfyUI is running or a firewall... | Python | 1 |
profanities = allow_profanities;
}
local_storage.remove_item("allow_profanities")?;
}
if let Some(theme_str) = local_storage.get_item("theme")? {
if let Ok(theme) = theme_str.parse::<Theme>() {
manager.theme = theme;
}
local_st... | Rust | 0 |
img-master/img/2020/12/25/12/34/25/86521567_p8_master1200.jpg",
"medium": "https://i.pximg.net/c/540x540_70/img-master/img/2020/12/25/12/34/25/86521567_p8_master1200.jpg",
"original": "https://i.pximg.net/img-original/img/2020/12/25/12/34/25/86521567_p8.jp... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.