text string | label_name string | labels int64 |
|---|---|---|
empty(&self) -> bool {
self.insertions.is_empty() && self.deletions.is_empty()
}
/// Removes the event at the given position.
///
/// The position is always relative to the original list --- you should not
/// adjust indices to acommodate other insertions or removals.
///
/// Removi... | Rust | 0 |
from flask import Flask, request, render_template_string, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Mapped, mapped_column
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///tasks.db"
db = SQLAlchemy()
# Define a database model named Task for storing tas... | Python | 1 |
ProgramResult {
let info = self.to_account_info();
let mut data = info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut cursor = std::io::Cursor::new(dst);
self.inner.account.try_serialize(&mut cursor)?;
Ok(())
}
}
impl<'info, T: AccountSerialize + Ac... | Rust | 0 |
# You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
# Return the length of the longest substring containing the same letter you can get after performing the above operations.
... | Python | 1 |
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
# Main class
chatbot = ChatBot('First ChatBot')
# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)
# Train the chatbot based on the english corpus
trainer.train('chatterbot.corpus.english')
# Use lo... | Python | 1 |
pub fn import_array_from_c(array: Box<Ffi_ArrowArray>, field: &Field) -> Result<Box<dyn Array>> {
try_from(Arc::new(ArrowArray::new(array, field.clone())))
}
#[doc = "Register `INT_CLR_CH1` writer"]
pub struct W(crate::W<INT_CLR_CH1_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<INT_CLR_CH1_SPEC>;... | Rust | 0 |
rt!(t < Duration::from_millis(600));
}
#[test]
fn test_set_socket_receive_timeout_1500ms() {
let socket = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, 1 as libc::c_int) };
let d = Duration::from_millis(1500);
let res = set_socket_receive_timeout(socket, d);
match res... | Rust | 0 |
# coding: utf-8
import psycopg2
# Pensez a adapter les parametre ci-dessous à votre environnement
# Votre base de donnee doit etre creer avant de lancer ce script
con = psycopg2.connect(host='ipaddress_to_psql', user='psql__user', password='psql_password', dbname='psql_db_name')
def build_select_login(user: str, ps... | Python | 1 |
.unwrap()
.pre_order_traversal(&store.src_arena.borrow())
.collect::<Vec<NodeId<SrcNodeId>>>();
let dst_pre = store.dst_arena
.borrow()
.root()
.unwrap()
... | Rust | 0 |
name
msg_list.insert("end", s)
top.protocol("WM_DELETE_WINDOW", on_closing)
print("Generating key...")
client = Client("localhost", 5000)
client.establish_session()
top.mainloop()
else:
mb.showerror("Network Intrusion Check", "... | Python | 1 |
super::core;
use crate::errors::AmclError;
use crate::rand::RAND;
// Re-export constants from core.
pub use super::core::{G1_BYTES, G2_BYTES, SECRET_KEY_BYTES};
/// Domain Separation Tag for signatures on G1
pub const DST_G1: &[u8] = b"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_";
/// Domain Separation Tag for signa... | Rust | 0 |
"""API endpoints for prompt generation operations."""
import logging
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from database import get_db
from schemas.prompt import GeneratePromptRequest, GeneratePromptResponse
from services.prompt_service import Pr... | Python | 1 |
II文字 アルファベット大文字 P
pub const WIDE_ASCII_LATIN_UPPER_CASE_P: u32 = 0xFF30;
/// 全角 ASCII文字 アルファベット大文字 Q
pub const WIDE_ASCII_LATIN_UPPER_CASE_Q: u32 = 0xFF31;
/// 全角 ASCII文字 アルファベット大文字 R
pub const WIDE_ASCII_LATIN_UPPER_CASE_R: u32 = 0xFF32;
/// 全角 ASCII文字 アルファベット大文字 S
pub const WIDE_ASCII_LATIN_UPPER_CASE_S: u32 =... | Rust | 0 |
"""
技能模块
"""
from pyxll import xl_func, xl_macro, xl_app, xlcAlert
import common.base as base
from pyxll import xl_func, xl_macro
def parse_to_list(s):
use_p_list = []
add_p_list = []
str_list = s.split(";")
for _, v in enumerate(str_list):
if v != "":
s_list2 = v.split(":")
... | Python | 1 |
n = input()
s = 0
for i in range(len(n) - 1):
s += 9 * (10 ** i) * (i + 1)
s += ((int(n) - (10 ** (len(n) - 1))) + 1) * len(n)
print(s) | Python | 1 |
default()
}
}
}
impl Account {
fn tag_k_gen(x: Scalar) -> RistrettoPoint {
x*PEDERSEN_H()
}
fn tag_eval(x: Scalar) -> RistrettoPoint {
x.invert() * RISTRETTO_BASEPOINT_POINT
}
pub fn new() -> Account {
let mut csprng = thread_rng();
let sk = Scalar::ra... | Rust | 0 |
_path
def get_keys_state_dict(model, algorithm, mode: str = "local") -> List[str]:
"""."""
keys: List[str] = []
match algorithm:
case "fedper":
if mode == "local":
keys = list(filter(lambda x: "fc1" not in x, model.state_dict().keys()))
elif mode == "global"... | Python | 1 |
.host,
client: &self.client,
}
}
}
#[cfg(test)]
mod tests;
use crate::{Particle2D, ParticleKey};
pub struct Spring2D {
particle_a_id: ParticleKey,
particle_b_id: ParticleKey,
rest_length: f32,
rest_length_sq: f32,
stiffness: f32,
}
impl Spring2D {
pub fn new(
p... | Rust | 0 |
# main.py
import asyncio
from fastapi import FastAPI, HTTPException
# CORREÇÃO: A primeira importação agora é do nosso módulo de banco de dados,
# que garante que todas as conexões (Mongo e Firebase) sejam inicializadas.
import database
# O resto das suas importações permanece o mesmo.
from routers import auth, alert... | Python | 1 |
use std::ops::{BitAnd, BitOr, Deref, DerefMut};
use std::ptr::{self, NonNull};
pub struct GpuTask<'a> {
pending: bool,
cycle: u8,
tail: u8,
head: u8,
input: MappedMemory,
output: [MappedMemory; 2],
descriptor_sets: &'a [[vk::DescriptorSet; 2]],
command_buffer: &'a vk::CommandBuffer,
... | Rust | 0 |
process::exit(0);
}
}
} else {
break;
}
}
}
/// Convert a line confluence of to a line of markdown
fn to_markdown(input: &str) -> String {
let mut out = String::new();
let mut chars = input.chars();
loop {
if let Some(c) = chars.next() {
... | Rust | 0 |
import cv2
from ultralytics import YOLO
import logging
class YoloDetector:
def __init__(self, model_path='yolov5s.pt'):
logging.getLogger("ultralytics").setLevel(logging.WARNING)
self.model = YOLO(model_path)
def detect_objects(self, image):
results = self.model(image)
return r... | Python | 1 |
abb() {
let sphere = Sphere {
center: Point{x: 0.0, y: 0.0, z: -2.0},
radius: 1.0,
material: Material::NormalView,
};
let bb = sphere.bb();
let ray = Ray{
origin: Point{x: 0.0, y: 0.0, z: 0.0},
direction: Vec3{x: 0.0, y: 0.0, ... | Rust | 0 |
from django import template
import sciblog.settings as scisettings
register = template.Library()
@register.simple_tag
def ga_tracking_id():
"""
Returns data from Google Tag Manager defined in settings.py.
For more information about Google Tag Manager, see https://tagmanager.google.com/
To load in t... | Python | 1 |
}
// TODO overflow check
let mut payload_builder = TransactionBuilder::new().with_essence(essence);
for unlock in unlock_blocks {
payload_builder = payload_builder.add_unlock_block(unlock);
}
let payload = payload_builder
.finish()
.ma... | Rust | 0 |
from typing import Dict
import argparse
import datetime
import logging
import os
import tensorflow as tf
from kite.infer_call_prob.config import Config
from kite.infer_call_prob.file_feeder import FileFeederSplit
from kite.infer_call_prob.model import Model
from kite.infer_call_prob.train import train_logistic_model
... | Python | 1 |
ALOS_OS_PKG")]
pkg: String,
}
impl Environment for MinimalEnvironment {}
fn wait_for_systemd() -> String {
String::from_utf8(
Command::new("systemctl")
.arg("is-system-running")
.arg("--wait")
.output()
.expect("failed to execute 'systemctl is-system-runn... | Rust | 0 |
# Copyright 2024 Leonin League
#
# 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 agreed to in writing,... | Python | 1 |
ore allowing one task to notify (wake up) other `Task`s waiting on a `WaitCondition`.
/// See the [`condition_satisfied()`](#WaitCondition.condition_satisfied) method.
pub struct SatisfiedWaitCondition<'wc, F: WaitConditionFn> {
inner: &'wc WaitCondition<F>,
}
impl<'wc, F: WaitConditionFn> SatisfiedWaitCondition<'w... | Rust | 0 |
os(0),
BytePos(source.len().try_into().unwrap()),
),
None,
);
parser.parse_script()
}
trait ToParseNode<P> {
fn to_parse_node(self) -> P;
}
impl ToParseNode<js::Script> for swc::Script {
fn to_parse_node(self) -> js::Script {
if self.body.is_empty() {
r... | Rust | 0 |
yield Experience(
state=experiences[0].state,
action=experiences[0].action,
reward=total_reward,
done=experiences[0].done,
new_state=last_exp_state,
)
def split_head_tail_exp(self, experiences: Tuple[Experience]) -> Tuple[L... | Python | 1 |
x1C, path, ()).await
}
/// multiple service packet
#[inline]
fn multiple_service<P, D>(&mut self) -> MultipleServicePacket<'_, Self, P, D>
where
Self: Sized,
P: Encode,
D: Encode,
{
MultipleServicePacket::new(self)
}
}
#[async_trait::async_trait]
impl<T: Mes... | Rust | 0 |
bufferView=2,
componentType=pygltflib.FLOAT,
count=len(vt_np),
type=pygltflib.VEC2,
max=vt_np.max(axis=0).tolist(),
min=vt_np.min(axis=0).tolist(),
),
],
)
# set... | Python | 1 |
host = 'localhost'
user = 'root'
password = 'Neuron7@2023'
database = 'stock_india'
date_output_format = "%m-%d-%Y"
date_input_format = "%d-%b-%Y"
holiday_list_table_name = 'holidaylist'
equity_list_table_name ... | Python | 1 |
import tm1637
import time
Display = tm1637.TM1637(clk=20, dio=21)
# Clear display by showing an empty string
Display.show([0000]) # This clears the display
Display.SetBrightness(1)
while True:
# Your display logic here
time.sleep(1)
| Python | 1 |
import pygame
from stable_baselines3 import DQN
from delivery_drone_env import DeliveryDroneEnv
# Load the trained model
model = DQN.load("dqn_drone")
# Initialize the environment
env = DeliveryDroneEnv()
obs = env.reset()
# Initialize Pygame
pygame.init()
screen_size = 500
cell_size = screen_size // 5
screen = pyga... | Python | 1 |
data.frame_requested = true;
data.maybe_wakeup();
}
fn on_next_frame_begin(
&self,
additional_present_credits: u32,
future_presentation_infos: Vec<PresentationInfo>,
) {
assert!(!future_presentation_infos.is_empty());
self.future_presentation_infos.replace(fu... | Rust | 0 |
== transformation);
}
#[test]
fn rotate() {
let transformation = Transformation::Rotate(1.0, (3.0, 4.0));
let mut encoded = String::new();
transformation.serialize(&mut encoded);
let decoded = Transformation::deserialize(&mut encoded.chars());
let deco... | Rust | 0 |
erive(Debug)]
pub enum RelayError<E> {
Io(io::Error),
Upgrade(UpgradeError<E>),
NoRelayFor(PeerId),
Message(&'static str),
#[doc(hidden)]
__Nonexhaustive
}
impl<E> fmt::Display for RelayError<E>
where
E: fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
matc... | Rust | 0 |
h-Notes-(Arius)': (1156, 168, 1196, 208), # 高级技术笔记(阿里乌斯)
'Superior-Tech-Notes-(Arius)': (740, 168, 781, 208), # 特级技术笔记(阿里乌斯)
'Beginner-Tech-Notes-(Shanhaijing)': (881, 168, 919, 208), # 初级技术笔记(山海经)
'Normal-Tech-Notes-(Shanhaijing)': (1015, 168, 1059, 208), # 中级技术笔记(山海经)
'Advanced-Tech-Notes-(Shanha... | Python | 1 |
'last_updated': 1700000000
},
{
'rank': 5,
'name': 'Budget Ice Shot',
'class': 'Ranger',
'ascendancy': 'Deadeye',
'main_skill': 'Ice Shot',
'support_gems': ['Added Cold Damage', 'Pierce', 'Increased Critical Strikes'],
... | Python | 1 |
Type {
#[serde(rename = "Microsoft.Kusto/clusters/attachedDatabaseConfigurations")]
MicrosoftKustoClustersAttachedDatabaseConfigurations,
}
}
#[doc = "Azure capacity definition."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureCapacity {
#[doc = "Scale type."]
#[... | Rust | 0 |
py_from_slice(&self.frame_data_buf[..len]);
shared.data = ReceiverData::DataCopied;
self.condvar.notify_all();
break;
}
shared = self.condvar.wait(shared);
}
while !matches!(shared.data, ReceiverData::None) {
shared =... | Rust | 0 |
new(Vector2::new(0.0, -0.981));
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints = DefaultJointConstraintSet::new();
let force_generators = DefaultForceGeneratorSet::new();
/*
... | Rust | 0 |
person_box.track_id
person_bbox = person_box.bbox
if person_id == bag_to_person[track_id]:
distance = calculate_distance(bag_bbox, person_bbox)
if distance > distance_threshold:
is_unattended = True
... | Python | 1 |
rue) }
/// Disables the Sleep gate.
fn gate_sleep_disable(&self) -> &Self { self.set_gate_sleep_en(false) }
}
/// Query and Set the Peripheral Clock Enable on Deep Sleep Gate
///
/// Enabling this gate will allow the peripheral to continue operating while
/// the MCU is in a Deep Sleep state.
pub trait GateDe... | Rust | 0 |
;
}
impl<'a> Bar<'a> for () {
type Assoc = &'a ();
}
trait Qux<'a> {}
impl Qux<'_> for () {}
// This is not supported.
fn one_hrtb_outlives() -> impl for<'a> Foo<'a, Assoc = impl Sized + 'a> {}
//~^ ERROR higher kinded lifetime bounds on nested opaque types are not supported yet
// This is not supported.
fn on... | Rust | 0 |
curacy, recall, f1, precision = cal_metric(np.array(all_labels), np.array(all_logits))
writer.add_scalar("train/accuracy", accuracy, epoch)
for idx, r in enumerate(recall):
writer.add_scalar(f"train/{idx2label(idx)}_recall", r, epoch)
for idx, f in enumerate(f1):
writer.a... | Python | 1 |
net_id: SubnetId,
) -> CatchUpPackage {
make_catch_up_package_with_empty_transcript_with_version(registry_client, subnet_id, 1)
}
pub fn make_catch_up_package_with_empty_transcript_with_version(
registry_client: Arc<dyn RegistryClient>,
subnet_id: SubnetId,
version: u64,
) -> CatchUpPackage {
let v... | Rust | 0 |
from tkinter import *
window = Tk()
window.geometry("500x300")
def submit_value():
with open("yourform.txt", "a") as userfile:
userfile.write("Personal info\n")
userfile.write("Name: " + name_value.get()+"\n")
userfile.write("Email: "+ email_value.get()+"\n")
use... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Read the CSV file
df = pd.read_csv('../data/agile-half-hour-actual-rates-02-06-2024_01-07-2024.csv', parse_dates=['Period from', 'Period to'], date_parser=lambda x: pd.to_datetime(x, format='%d/%m/%Y %H:%M'))
df['Price_moving_avg'] = df['Agile Im... | Python | 1 |
().numpy(), e_img_hw[1], e_img_hw[0], t)
else:
assert False
for k in t:
metrics[k] = pred_lwh.new_tensor(t[k]) if not isinstance(t[k], str) else t[k]
if pred_extra is not None:
metrics.update(pred_extra)
return (gt_lines, gt_lwh, gt_cor_id), (pred_l... | Python | 1 |
#!/usr/bin/env python3
"""
Populate stock_prices_1d table using FMP Multiple Company Prices API
Uses the /v3/quote/ endpoint for batch quote retrieval
"""
import asyncio
import logging
from services.fmp_batch_data_service import FMPBatchDataService
from services.universe_builder import UniverseBuilder
# Configure log... | Python | 1 |
if len(scores) != len(candidates):
raise ValueError(f"Got {len(scores)} scores for {len(candidates)} candidates")
candidates.loc[:, 'rerank_score'] = scores
relevant = candidates[candidates['rerank_score'] > 40].sort_values('rerank_score', ascending=False)
if ... | Python | 1 |
-client","type":"subscribe","topic":"/market/level2:ETH-USDT","privateChannel":false,"response":true}"#,
commands[0]
);
assert_eq!(
r#"{"id":"crypto-ws-client","type":"subscribe","topic":"/market/match:BTC-USDT","privateChannel":false,"response":true}"#,
commands[1]
... | Rust | 0 |
, 64, 12, 125, 51, 202, 69, 67, 181, 146, 86,
]);
}
#[test_case]
fn test_issues_16() {
// See: https://github.com/sile/libflate/issues/16
let encoded =
include_bytes!("../data/issues_16/crash-1bb6d408475a5bd57247ee40f290830adfe2086e");
assert_eq!(
de... | Rust | 0 |
Safety:
// - length exactly matches the length of the vector.
// - single writer thread.
BucketsSharedWriter::new(&self.buckets, length, self.capacity)
}
}
/// A `Vector<T>` can be `Send` across threads whenever a `Vec<T>` can, unlike a
/// `Vec<T>` it is never `Sync` however.
///
///... | Rust | 0 |
import csv
from pathlib import Path
import warnings
from langchain._api import LangChainDeprecationWarning
warnings.simplefilter("ignore", category=LangChainDeprecationWarning)
from llama_index import VectorStoreIndex, StorageContext
from framework.vector_store import VectorRetriever
from vector_stores.node_parser i... | Python | 1 |
None => {
eprintln!("USAGE: {} CID\n", std::env::args().next().unwrap());
eprintln!(
"Will walk the unixfs file pointed out by the CID from default go-ipfs 0.5 \
configuration flatfs blockstore and write listing to stdout."
);
std:... | Rust | 0 |
int is spawned, to fill out the entity with components
fn fill_blueprint(&self, cmd: &mut EntityCommands);
/// Called when the bounds need to be updated (like resizing from the editor)
fn sync_dimensions(&self, edit: &EditableCollider, cmd: &mut EntityCommands) {
cmd.insert(CollisionShape::Cuboid {
... | Rust | 0 |
# --- Fornecido: Uma string s de DNA com até 1000 nucleotídeos --- #
# --- Problema: A quantidade de cada nucleotídeo em s, separado por espaço. A ordem é adenina (A), citosina (C), guanina (G) e timina (T) --- #
# --- Indicar o arquivo --- #
arquivo = ''
# --- Abrir o arquivo --- #
with open(arquivo, 'r') as txt:
... | Python | 1 |
')[1]) for folder in run_dir.iterdir() if str(folder.name).startswith('run')]
if len(exst_run_nums) == 0:
curr_run = 'run1'
else:
curr_run = 'run%i' % (max(exst_run_nums) + 1)
run_dir = run_dir / curr_run
if not run_dir.exists():
os.mak... | Python | 1 |
# Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
# The same number may be chosen from candidates an unlimited number of times. Two combinations are u... | Python | 1 |
h(&self, buffer: &mut [Complex<T>], scratch: &mut [Complex<T>]);
/// Computes multiple FFTs.
///
/// Divides `input` and `output` into chunks of size `self.len()`, computes an FFT on each input chunk,
/// and stores the result in the corresponding output chunk.
///
/// This method uses both the... | Rust | 0 |
reError> {
trace!("get_document called(request == {:?}", self.request);
future::result(self.request.body(hyper::Body::empty()))
.from_err()
.and_then(move |r| check_status_extract_body(self.hyper_client.request(r), StatusCode::NO_CONTENT))
.and_then(|_| Ok(()))
}... | Rust | 0 |
the Fn* traits.
struct LazyEncode<F> {
inner: F,
encoded: Option<Vec<u8>>,
}
impl<F: Fn() -> Vec<u8>> traits::Lazy<[u8]> for LazyEncode<F> {
fn get(&mut self) -> &[u8] {
self.encoded.get_or_insert_with(&self.inner).as_slice()
}
}
sig.verify(
LazyEncode { inner: || item.encode(), encoded: None },
... | Rust | 0 |
om: PhantomData,
}
}
#[inline]
pub fn new(val: usize) -> RemotePtr<T> {
RemotePtr {
ptr: Wrapping(val),
phantom: PhantomData,
}
}
#[inline]
pub fn as_usize(&self) -> usize {
self.ptr.0
}
/// As the name indicates this is just a c... | Rust | 0 |
axis):
x = np.arange(10)
xval = np.arange(3)
obj = cls(x, y, bc_type=bc_type)
assert obj(xval).size == 0
assert obj(xval).shape == xval.shape + y.shape[1:]
# Also check with an explicit non-default axis
yt = np.moveaxis(y, 0, axis) # (10, 0, 5) --> (0, 10, 5) ... | Python | 1 |
h-query-language).
Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating
conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up
to an hour behind during outages. Search functionality is n... | Python | 1 |
_| elem + 1).map_err(|_| -> Never { panic!() })
});
assert_eq!(sink.start_send(0), Ok(()));
flag_cx(|flag, cx| {
let mut task = sink.flush();
assert!(task.poll(cx).unwrap().is_pending());
tx.send(()).unwrap();
assert!(flag.get());
let sink = match task.poll(cx).unw... | Rust | 0 |
array_308 = object.key("EntityTypes").start_array();
for item_309 in var_307 {
{
array_308.value().string(item_309.as_str());
}
}
array_308.finish();
}
if let Some(var_310) = &input.allowed_statistics {
let mut array_311 = object.key("Allo... | Rust | 0 |
"""
Show how to make date plots in matplotlib using date tick locators and
formatters. See major_minor_demo1.py for more information on
controlling major and minor ticks
"""
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
... | Python | 1 |
///
/// # let result = read_to_string(path)?;
/// # assert_eq!(result, String::from("\x1f0123456789X"));
/// Ok(())
/// }
/// ```
pub fn write(
&self,
writer: &mut dyn std::io::Write,
) -> crate::error::Result<()> {
write!(writer, "\x1f{}{}", self.code, s... | Rust | 0 |
impl ::std::fmt::Debug for PrepareRecoveryResponseProto {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
impl ::protobuf::reflect::ProtobufValue for PrepareRecoveryResponseProto {
fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueR... | Rust | 0 |
<td>For loading and saving.</td> </tr>
<tr><td>wxJPEGHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxGIFHandler</td> <td>Only for loading, due to legal issues.</td> </tr>
<tr><td>wxPCXHandler</td> <td>For loading and saving.</td> </tr>
<tr><td>wxPNMHandler</td> <td>For loading and saving.</td> ... | Python | 1 |
p:(x,y),d,reflect_x:false,reflect_y:false
}
}
fn collide(&mut self, col : Collision) {
let mut vec = (0,0);
let (ul,ur,ll,lr) = col.sides;
if ul { vec.0 += 1; vec.1 +=1 };
if ur { vec.0 -= 1; vec.1 +=1 };
if ll { vec.0 += 1; vec.1 -=1 };
if lr... | Rust | 0 |
pub fn with_slot_duration(&mut self, slot_duration: u8) -> &mut Self {
self.slot_duration = slot_duration;
self
}
pub fn with_leaders(&mut self, leaders: &Vec<LeaderId>) -> &mut Self {
self.leaders.extend(leaders.iter().cloned());
self
}
pub fn with_fee(&mut self, l... | Rust | 0 |
.insert("a", 0);
map.insert("b", 1);
map.insert("c", 2);
map.insert("d", 3);
map.insert("e", 4);
map.insert("f", 5);
map.insert("g", 6);
map.insert("h", 7);
map
});
pub static ROWS: Lazy<HashMap<&str, usize>> = Lazy::new(|| {
let mut map = HashMap::new();
map.insert("1", 0);
... | Rust | 0 |
# Copyright 2015 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Python | 1 |
s = []
for data_line in task_data.split("\n"): # split() -> only one seprator
processed_task = data_line.split(",") # split()
processed_tasks.append(processed_task)
print(processed_tasks)
# output: [['5001', 'one', '3'], ['5341', 'two', '1'], ['7078', 'three', '5']]
# %%
messy_data = "process,mess_data... | Python | 1 |
n = int(input())
nums = list(map(int, input().split()))
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
print(max(dp))
| Python | 1 |
p.empty((0, 0))
if len(dist_xs) > 0:
# Get descriptors
# Compute descriptor distnaces
_dists = vt.compute_distances(qvecs_flat_m, dvecs_flat_m, dist_lbls)
dists = np.vstack(_dists.values()).T
else:
dists = np.empty((0, 0))
fsv = vt.re... | Python | 1 |
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2020-10-07 20:57:11
LastEditor: John
LastEditTime: 2021-04-29 15:41:48
Discription:
Environment:
'''
import matplotlib.pyplot as plt
import seaborn as sns
def plot_rewards(rewards,ma_rewards,tag="train",env='CartPole-v0',algo = "... | Python | 1 |
@click.group()
def modelkit_cli():
sys.path.append(os.getcwd())
pass
| Python | 1 |
import os
import secrets
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
class Config:
"""Base configuration class"""
SECRET_KEY = os.environ.get('SECRET_KEY') or secrets.token_urlsafe(32)
DEBUG = False
TESTING = False
# Security Headers
SEND_FILE_... | Python | 1 |
c=\'ScaleOperator\' id=\'ATScaler\' parameter=\"@rateAT\" scaleFactor=\"0.8\" weight=\"0.1\"/>\n <operator spec=\'ScaleOperator\' id=\'CGScaler\' parameter=\"@rateCG\" scaleFactor=\"0.8\" weight=\"0.1\"/>\n <operator spec=\'ScaleOperator\' id=\'GTScaler\' parameter=\"@rateGT\" scaleFactor=\"0.8\" weight=\"0.1\"... | Python | 1 |
iter_coords(r)
}
pub fn iter(&self) -> impl Iterator<Item=(C, &D)> {
self.iter_coords(None).into_iter().zip(self.data.iter())
}
pub fn iter_mut(&mut self) -> impl Iterator<Item=(C, &mut D)> {
self.iter_coords(None).into_iter().zip(self.data.iter_mut())
}
fn iter_at(&self, offs... | Rust | 0 |
"""Collection of miscellaneous logging, dict and plotting utilities."""
import logging
from matplotlib import pyplot as plt
from rich.logging import RichHandler
import src.typing as ty
__all__ = ['get_logger', 'flatten_dict', 'sort_dict', 'apply_cmap', 'set_logging_level']
def set_logging_level(level: str = 'warni... | Python | 1 |
usr/lib/libedit.tbd
vs
/usr/lib/libedit.dylib
"""
cflags = sysconfig.get_config_var('CFLAGS')
match = re.search(r'-isysroot\s*(\S+)', cflags)
apply_root = (
sys.platform == 'darwin'
and match
and (
dir.startswith(... | Python | 1 |
m_vec(4, 3, vec![10, 20, 22, 30, 40, 44, 50, 60, 66, 70, 80, 88]);
m1.set_slice(&(2, 3), &m2);
assert_eq!(
m1.as_ref().to_vec(),
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 10, 20, 15, 16, 17, 30, 40, 20, 21, 22, 50,
60,
]
);
}
<gh_stars>0
// Reprensents the P... | Rust | 0 |
from flask import Blueprint
from controllers.userController import get_token
token_blueprint = Blueprint('token_bp', __name__)
token_blueprint.route('/', methods=['POST'])(get_token)
| Python | 1 |
= ()
_role_name = "SQL expression element or literal value"
class InElementRole(SQLRole):
__slots__ = ()
_role_name = (
"IN expression list, SELECT construct, or bound parameter object"
)
class JoinTargetRole(AllowsLambdaRole, UsesInspection, StructuralRole):
__slots__ = ()
_role_na... | Python | 1 |
o: Vec3, fuzz: f32) -> Metal {
Metal {albedo, fuzz}
}
}
impl Scatterable for Metal {
fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray)
-> bool {
let reflected = r_in.direction().unit_vector().reflect(&rec.normal);
*scattered = Ray... | Rust | 0 |
.and_then(|value| value.try_into().ok())
.unwrap_or_default();
let build: BuildConfig = table
.remove("build")
.and_then(|value| value.try_into().ok())
.unwrap_or_default();
let rust: RustConfig = table
.remove("rust")
.and_then(|... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import os
import subprocess
from loguru import logger
import cv2
from .dist import get_world_size, is_main_process
__all__ = ["configure_nccl", "configure_module", "configure_omp"]
def configure_nccl():
""... | Python | 1 |
_transpose(self.base_len, signal, spectrum, &self.shuffle_map);
}
// Base-level FFTs
match &self.base_fft {
Neon32Butterfly::Len1(bf) => bf.perform_fft_butterfly_multi(spectrum).unwrap(),
Neon32Butterfly::Len2(bf) => bf.perform_fft_butterfly_multi(spectrum).unwrap(),
... | Rust | 0 |
0,1]*M[1,0]
R = M.base_ring()
track_precision = R._prec_type() in ['capped-rel','capped-abs']
S = copy(M)
shift_rows, shift_cols = self._matrix_flatten_precision(S)
shift = sum(shift_rows) + sum(shift_cols)
det = R(1)
sign = 1
valdet = 0
val = -... | Python | 1 |
}
pub struct Argument<'a> {
pub name: &'a str,
pub vtype: VTypeExt<'a>,
}
pub struct VStruct<'a> {
pub elts: Vec<Argument<'a>>,
}
pub struct VEnum<'a> {
pub elts: Vec<&'a str>,
}
pub struct VError<'a> {
pub name: &'a str,
pub doc: &'a str,
pub parm: VStruct<'a>,
}
pub enum VStructOrEnum... | Rust | 0 |
stop_rx) = watch::channel(());
let scheduler = Scheduler::new(None, None, QueueType::Fifo, stop_rx);
let started = Arc::new(AtomicUsize::new(0));
let completed = Arc::new(AtomicUsize::new(0));
let notify = Arc::new(Semaphore::new(0));
for _ in 0..100 {
let job = Box::pin({
let started = started... | Rust | 0 |
#! /usr/bin/env python3
#
import PISM
PISM.set_abort_on_sigint(True)
context = PISM.Context()
config = PISM.Context().config
# Default constants that may get overridden later.
Ly = 25e3 # 25 km
Lx = 50e3 # 50 km
Lz = 4000
My = 13
Mx = 23
Mz = 21
H0 = 60. # ice thickness at cliff
alpha = 0.008 # ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.