text string | label_name string | labels int64 |
|---|---|---|
dler.content_type,
Accept=self.content_handler.accept,
**self.endpoint_kwargs,
)["Body"]
return self.content_handler.deserialize_output(response=response)
def _get_query_embedding(self, query: str, **kwargs: Any) -> Embedding:
query = query.replace("\n", " ")
... | Python | 1 |
# Let's assume that the user input will be always String
# It will capitalize the first letter of each word in the string/input provided.
user_input = input("Type the phrase you want to be a Title\n e.g Typing \"my title\" will return \"My Title\"\n> ")
print(" " + user_input.title())
| Python | 1 |
be nice if `find_last` could prioritize the later splits,
// basically flipping the `join` args, without needing indexed `rev`.
// (or could we have an unindexed `rev`?)
let x = two_threads(|| octillion().find_last(|_| true));
assert_eq!(x, Some(OCTILLION - 1));
}
#[test]
fn find_last_octillion_inclus... | Rust | 0 |
# Copyright 2022-2025 The Ramble Authors
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except accord... | Python | 1 |
riable_invalid() {
let schema = prepopulated_schema();
let known = Known::for_schema(&schema);
let q = r#"[:find ?y ?age :in ?x :where [(ground [?x]) [?y ...]] [?y :foo/age ?age]]"#;
// This fails even if we know the type: we don't support grounding bindings
// that aren't known at algebrizing time... | Rust | 0 |
) with"]
#[doc = "muxConfigPresent = 0, out of band StreamMuxConfig"]
#[doc = "- 10: Audio Sync Stream (LOAS)"]
pub const AACENC_PARAM_AACENC_TRANSMUX: AACENC_PARAM = 768;
pub const AACENC_PARAM_AACENC_HEADER_PERIOD: AACENC_PARAM = 769;
pub const AACENC_PARAM_AACENC_SIGNALING_MODE: AACENC_PARAM = 770;
pub const AACENC_... | Rust | 0 |
import argparse
from datetime import datetime, timedelta
import subprocess
def run_steps_for_date(target_date: str, end_date: str):
print(f"\n📅 {target_date} の処理を開始します")
steps = [
"4th_step1_generate_racer_stats.py",
"4th_step2_generate_train_racer_level_trio.py",
"4th_step3_train_mod... | Python | 1 |
///
/// # Example
///
/// ```no_run
/// use dbl::types::Filter;
///
/// let filter = Filter::new().search("lib:serenity foobar");
/// ```
pub async fn search(&self, filter: &Filter) -> Result<Listing, Error> {
let url = Url::parse_with_params(&api!("/bots"), &filter.0).map_er... | Rust | 0 |
#
# @lc app=leetcode id=208 lang=python
#
# [208] Implement Trie (Prefix Tree)
#
# @lc code=start
# class Trienode(object):
# def __init__(self):
# self.children = {}
# self.isEnd = False
class Trie(object):
# 1. use dict to restore each node and its children
# 2. use a mark in the end of e... | Python | 1 |
path;
request_source = RequestSource::CallingContext;
context = self.import_yaml(self.resolve_filename(
&file,
&next_request_source,
&context,
... | Rust | 0 |
import base64
import hashlib
import os
import re
import json
import requests
from requests.auth import AuthBase, HTTPBasicAuth
from requests_oauthlib import OAuth2Session
# First, you will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
# Inside your terminal you wil... | Python | 1 |
> -map_size && x < map_size && y > -map_size && y < map_size)
|| ((x == -map_size || x == map_size) && (y == -map_size || y == map_size))
{
continue;
}
let state = if x == 0 && y == -map_size {
... | Rust | 0 |
import sqlite3
import socket
# Connect to the SQLite database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT)'... | Python | 1 |
println!("{:?}", value.convert::<String>())
}
},
Err(err) => println!("{:?}", err.to_string()),
};
}));
let Time_2 = time::now();
println!("{:?}", time::strftime("%a, %d %b %Y %T %z", &Time_2));
// // println!("{:?}",Time.tm_nsec - Time_2.tm_nsec);
O... | Rust | 0 |
'ZOOM_CENTER',
'center': viewport.center,
'zoom_level': viewport.zoom_level
}
except AttributeError:
raise ValueError('viewport')
return payload
@doc_subst(map_params_doc_snippets)
class Map(ConfigurationMixin, GMapsWidgetMixin, widgets.DOMWi... | Python | 1 |
import matplotlib.pyplot as plt
from PIL import Image
if __name__ == '__main__':
image_pairs = {
# 'data/images/2018-06-25--16-59-0/200000/03-in.png': 'data/images/2018-06-25--16-59-0/200000/03-out.png',
# 'data/images/2018-06-25--16-59-0/200000/05-in.png': 'data/images/2018-06-25--16-59-0/200000/0... | Python | 1 |
times += 1;
}
uart::uart_puts("[END] mpu9250 sample\r\n");
loop{}
}
// ループによるウェイト
fn wait(n: i32) {
let mut v: i32 = 0;
for i in 1..n {
unsafe { core::ptr::write_volatile(&mut v, i) };
}
}
#[allow(dead_code)]
pub fn memdump(addr: usize, len: usize) {
unsafe {
f... | Rust | 0 |
k(self, *args, **kwargs):
self._lock = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
def get_lock(self):
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
tqdm = _tqdm_cls()
def is_progress_bar_enabled() -> bool:
"""Return a boolean indi... | Python | 1 |
<|user|>
Question: {input}
Context: {context}
Answer: </s>
<|assistant|>""",
},
"notus-7b-v1": {
"model_id": "argilla/notus-7b-v1",
"remote_code": False,
"start_message": f"<|system|>\n{DEFAULT_SYSTEM_PROMPT}</s>\n",... | Python | 1 |
.clone())
}
Ledger::<T>::insert(controller, staking_ledger);
let slash_amount = <T as Config>::Currency::minimum_balance() * 10u32.into();
let balance_before = <T as Config>::Currency::free_balance(&stash);
}: {
crate::slashing::do_slash::<T>(
&stash,
... | Rust | 0 |
from .fetch_urls import Driver
from .data_scraper import DataScraper
from .query import get_items_by_ids
from concurrent.futures import ThreadPoolExecutor
class ScrapingSession:
def __init__(self, search_item):
self.search_item = search_item
self.driver = Driver(self.search_item)
sel... | Python | 1 |
* sigma))
y0 = int(max(0, center_y - delta * sigma))
x1 = int(min(width, center_x + delta * sigma))
y1 = int(min(height, center_y + delta * sigma))
# gaussian filter
for y in range(y0, y1):
for x in range(x0, x1):
d = (x - center_x) ** 2 + (y - cent... | Python | 1 |
module path cannot be a parent of a shorter module path
if parent.len() > possible_child.len() {
return false;
}
// If the path up to the parent isn't the same as the child,
if parent != &possible_child[..parent.len()] {
return false;
}
// Either the path is exactly the same, ... | Rust | 0 |
ewards as a suppliers -
// (dot_speed * 0.25) per block each
assert_ok!(MinterestProtocol::transfer_wrapped(
alice_origin(),
BOB,
MDOT,
50_000 * DOLLARS
));
// Alice should receive tokens as a supplier for a 10 blocks since the last claim
// mnt_accrued = 0.5 MNT + 0.1(dot_speed)... | Rust | 0 |
major_offsets,
// minor_indices,
// minor_dim,
// }
// }
// /// Appends another sparsity pattern to this one, in the sense that it is extended
// /// along its major dimension.
// ///
// /// Panics if `self` and `other` have different minor dimensions.
// pub fn append_pattern(&mut self, other:... | Rust | 0 |
}
}
fn cause(&self) -> Option<&dyn StdError> {
match *self.0 {
ErrorKind::UTF8(ref e) => Some(e),
ErrorKind::UTF8Str(ref e) => Some(e),
ErrorKind::HostError(_) => None,
ErrorKind::BadDispatch(_) => None,
}
}
}
impl fmt::Display for Error {
... | Rust | 0 |
Wharrimean is|Tình huống|The thing of it is|Tausta|Taust|Tapausaihio|Tapaus|Szenariogrundriss|Szenario|Szablon scenariusza|Stsenaarium|Struktura scenarija|Skica|Skenario konsep|Skenario|Situācija|Senaryo taslağı|Senaryo|Scénář|Scénario|Schema dello scenario|Scenārijs pēc parauga|Scenārijs|Scenár|Scenaro|Scenariusz|Scen... | Python | 1 |
mmon/pool.c",
"zstd/lib/common/threading.c",
"zstd/lib/common/xxhash.c",
"zstd/lib/common/zstd_common.c",
"zstd/lib/compress/fse_compress.c",
"zstd/lib/compress/huf_compress.c",
"zstd/lib/compress/zstd_compress.c",
"zstd/lib/compress/zs... | Rust | 0 |
svg_size.height;
// let affine = Affine::new([
// scale,
// 0.0,
// 0.0,
// scale,
// 1.0 + 18.0 + padding,
// ... | Rust | 0 |
ame__ == '__main__':
M = 10
NSample=20; tend=2; xlen=1; Nt=100; Re_min = 200; Re_max=800
roeqs = CustomedEqs(NSample=NSample, tend=tend, xlen=xlen, Nt=Nt, Re_min = Re_min, Re_max=Re_max)
roeqs.setM(M)
# Net = CustomedNet(roeqs=roeqs,layers=[2,20,20,20,M])
# print(Net.labeledLoss)
... | Python | 1 |
import albumentations as A
import cv2
def get_transform(train, cfg):
if train:
use = []
if cfg.hflip:
use.append(A.HorizontalFlip(0.5))
if cfg.contrast:
use.append(A.RandomBrightnessContrast(brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), p=cfg.prob))
... | Python | 1 |
dwPlatformId: DWORD,
szCSDVersion: [WCHAR; 128],
wServicePackMajor: WORD,
wServicePackMinor: WORD,
wSuiteMask: WORD,
wProductType: BYTE,
wReserved: BYTE,
}}
pub type POSVERSIONINFOEXW = *mut OSVERSIONINFOEXW;
pub type LPOSVERSIONINFOEXW = *mut OSVERSIONINFOEXW;
pub type RTL_OSVERSIONINFOEXW = OS... | Rust | 0 |
import requests
class PerStoreApiClient():
def __init__(self,
base_url="https://petstore.swagger.io/v2",
token="special-key"):
self.session = requests.session()
self.base_url = base_url
self.session.headers = {
"Authorization": f"{token}",
... | Python | 1 |
conf,
D=8,
W=256,
d_in=3,
d_in_view=3,
multires=0,
multires_view=0,
output_ch=4,
skips=[4],
rgb_dims=3,
use_viewdirs=False):
super().__... | Python | 1 |
, start_x+1, &message);
}
attroff(attribute);
},
WindowContent::List => { // Display a list of items or options
let list_data = items;
attron(A_UNDERLINE());
for i in 0..list_data.len() {
for j in 0..x_dim {
... | Rust | 0 |
if _detected:
print('%s------O------M------G--------------->-%s' % (Bcolors.Red, Bcolors.Endc))
print('- Scanner Found %s%d%s infected files!' % (Bcolors.Yellow, _infected_file_count, Bcolors.Endc))
print('- See the %s%s%s \n' % (Bcolors.Cyan, _scan_result_logs_, Bcolors.Endc))
else:
... | Python | 1 |
len() > 3 {
let name = name_os_str.into_string().unwrap();
let third_char = name.chars().nth(3).unwrap();
if third_char.is_numeric() && name.starts_with("cpu") {
logical_cpus += 1;
}
}
}
Ok(logical_cpus)
}
#[allow(dead_code)]
const DE_BRUI... | Rust | 0 |
ol(_mem.favorite)))
fav.set_doc("Favorite Channel")
bell = RadioSetting("bell", "Bell",
RadioSettingValueBoolean(bool(_mem.bell)))
bell.set_doc("Bell Alert")
stby_screen = RadioSetting(
"stby_screen", "Standby Screen Color",
RadioSett... | Python | 1 |
"dox"))]
fn connect_property_source_port_min_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_source_port_min_trampoline<P, F: Fn(&P) + 'static>(
this: *mut nm_sys::NMSettingVxlan,
_param_spec: glib_sys::gpointer,
... | Rust | 0 |
.wait_with_output()?;
let stderr = String::from_utf8(ret.stderr)?;
if !ret.status.success() {
return Err(Box::new(HermitNetworkError::from(format!(
"Command {} with args {} failed! Exit code {}, stderr: {}",
command,
args.join(" "),
ret.status,
stderr
))));
}
let output = String::from_utf8(ret.s... | Rust | 0 |
END_ADVANCED_STATE_CREATE_INFO_EXT : i32 = 1000148002;
pub const STRUCTURE_TYPE_PIPELINE_COVERAGE_TO_COLOR_STATE_CREATE_INFO_NV : i32 = 1000149000;
pub const STRUCTURE_TYPE_BIND_ACCELERATION_STRUCTURE_MEMORY_INFO_KHR : i32 = 1000165006;
pub const STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR : i32 = 10... | Rust | 0 |
claims);
assert_eq!(header.get("kid").unwrap(), "kid1234");
assert_eq!(header.get("my_hdr").unwrap(), "my_hdr_val");
}
}
#[test]
#[should_panic(expected = "InvalidInput")]
fn dont_allow_sign_with_verify_algorithm() {
let my_claims = json!({
"sub": "<EMAIL>",
"company": "ACME",
... | Rust | 0 |
ate_predecessors(&mut self) {
// FIXME: consider being more fine-grained
self.predecessors = None;
}
pub fn ensure_predecessors(&mut self, body: &Body<'_>) {
if self.predecessors.is_none() {
let mut result = IndexVec::from_elem(smallvec![], body.basic_blocks());
... | Rust | 0 |
p_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
# start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
# start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
# ... | Python | 1 |
= i;
assert_eq!(*j, 100);
}
use crate::page::{MonitorsTable, MonitorsTableRow, Page};
use anyhow::{bail, Result};
use chrono::prelude::*;
use chrono_tz::Tz;
use pinwheel::prelude::*;
use sqlx::prelude::*;
use std::sync::Arc;
use tangram_app_context::Context;
use tangram_app_core::{
alerts::Monitor,
error::{bad_r... | Rust | 0 |
import argparse
import glob
import json
import os
import pickle
import shutil
import cv2
import numpy as np
import torch
# import torchvision.transforms as transforms
# from PIL import Image
# from diffusers import AutoencoderKL
# from face_alignment import NetworkSize
# from mmpose.apis import inference_topdown, init... | Python | 1 |
}
fn new() -> TaggedRunMetadata {
TaggedRunMetadata::new()
}
fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| {
... | Rust | 0 |
use bstr::BString;
use fnv::FnvHashMap;
use crate::handle::{Handle, NodeId};
// use crate::pathhandlegraph::{PathBase, PathRef, PathRefMut};
use super::Node;
pub type PathId = i64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathStep {
Front(i64),
End(i64),
Step(i64, usize),
}
impl PathStep {
... | Rust | 0 |
parser)),
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser),
);
free(XMLBuf as *mut c_void);
XML_ParserFree(parser);
exit(4 as c_int);
}
XMLBufPtr = XMLBufPtr.offset(bufferS... | Rust | 0 |
print("🔄 Generating source and stream registry...")
# Collect all configurations
registry = collect_sources_and_streams()
# Write registry - use /sources if in Docker
import os
if os.path.exists('/sources'):
sources_dir = Path('/sources')
else:
sources_dir = Path(__... | Python | 1 |
if summary:
summary.setdefault('experiment_metadata', {}).update({'seed': seed})
with open(summary_file, 'w') as f:
json.dump(summary, f, indent=2)
print(f"📋 Summary saved: {summary_file}")
return summary_file
return json.dumps(summary, indent=2)
def main():
... | Python | 1 |
_ => rhs(),
}
}
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::Error,
argh::FromArgs,
fuchsia_async as fasync,
fvm_stress_test_lib::run_test,
log::info,
... | Rust | 0 |
import os
from collections import Counter
def read_fasta(filename):
"""Reads a FASTA file and returns a dictionary of sequences keyed by sequence header."""
sequences = {}
with open(filename, 'r') as file:
sequence = ''
header = ''
for line in file:
line = line.strip()
... | Python | 1 |
ble_intens(idx);
enable_counter(idx);
}
/// Interrupts should be disabled
#[cfg(any(target_arch = "aarch64"))]
pub fn disable_event(idx: u32) {
disable_intens(idx);
disable_counter(idx);
}
#[cfg(any(target_arch = "aarch64"))]
pub fn write_pmcr(val: u32) {
unsafe {
asm!("msr pmcr_el0, $0" :: "r"(val));
}
}
#[c... | Rust | 0 |
Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const SKIHashSha1: KeyIdentifierHashAlgorithm = 1i32;
#[doc = "*Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const SKIHashCapiSha1: KeyIdentifierHashAlgorithm = 2i32;
#[doc = "*Required features: `\"Win32_Security_Crypt... | Rust | 0 |
d.com
zxip.com
zxiubbs.com
zxrcw.com
zxwbb.com
zxxk.com
zxyhw.com
zxzhijia.com
zy.com
zy12580.com
zy169.net
zycdxw.com
zycmmt.com
zycq.org
zyctd.com
zynews.com
zynw.com
zyqc.cc
zyrb.com
zyrc.net
zyt-life.com
zyue.com
zyuexc.com
zyxuan.org
zyzhan.com
zz361.com
zz51.com
zz597.com
zz91.com
zzbaike.com
zzbbs.com
zzbm.org
z... | Python | 1 |
Header, Nonce,
TokenSymbol,
};
use sp_core::{bytes::from_hex, crypto::AccountId32, Bytes, H160, H256};
use sp_runtime::{
traits::{BlakeTwo256, Convert, IdentityLookup},
Perbill,
};
use sp_std::{collections::btree_map::BTreeMap, str::FromStr};
pub type AccountId = AccountId32;
type Balance = u128;
paramet... | Rust | 0 |
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
match index {
0 => Some(&mut self.entity),
1 => Some(&mut self.transform),
_ => None,
}
}
fn name_at(&self, index: usize) -> Option<&str> {
match index {
0 => Some(... | Rust | 0 |
ame=name)
# The ``foldl`` view of Scan Op.
def foldr(fn,
sequences,
outputs_info,
non_sequences=None,
mode=None,
name=None):
"""
Similar behaviour as haskell' foldr.
Parameters
----------
fn
The function that ``foldr`` applies at each iter... | Python | 1 |
2*u32)
//but we need to read flags and checksum, so we need 8192/4-12+3
const BUF_LEN: usize = (multiboot::MULTIBOOT_SEARCH as usize / 4) - 9;
let mut buf: [u32; BUF_LEN] = [0; BUF_LEN];
//let buf_sz = std::cmp::max(kernel_file_size as usize, BUF_LEN);
//let mut buf = Vec::with_capacity(bu... | Rust | 0 |
put_contains(output: &str, expected: &str) {
if !output.contains(expected) {
panic!("output does not contain '{}': {:?}", expected, output);
}
}
}
mod helper {
pub fn get<S: AsRef<str>>(addr: S) -> String {
let output = reqwest::blocking::get(addr.as_ref())
.unwrap()
.bytes()
.unwrap();
... | Rust | 0 |
mvlabat.github.io/bevy_egui_web_showcase/index.html) [[source](https://github.com/mvlabat/bevy_egui_web_showcase)].
//!
//! **Note** that in order to use `bevy_egui`in WASM you need [bevy_webgl2](https://github.com/mrk-its/bevy_webgl2) of at least `0.4.1` version.
//!
//! ## Usage
//!
//! Here's a minimal usage example... | Rust | 0 |
}
}
// Check rows.
for y in 0..BOARD_SIZE {
let mut acc = 0;
for x in 0..BOARD_SIZE {
acc += PRECALC_MASKS[b.get_cell(x, y) as usize];
}
if (acc & 0xee_eeee_eee0) != 0 {
return false;
}
}
// Check columns.
for x in 0..BOA... | Rust | 0 |
att_masks = []
chosen_seq_lens = []
rejected_ids = []
rejected_att_masks = []
rejected_seq_lens = []
infos = {
"input_length": [],
"chosen_reason_suffix_ids_range": [],
"rejected_reason_suffix_ids_range": [],
}
index = ... | Python | 1 |
symbol, (i % 3, i / 3) )))
.max_by(|a, b| {
let &(_, ref a_val) = a;
let &(_, ref b_val) = b;
if a_val < b_val {
std::cmp::Ordering::Less
} else if a_val > b_val {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
}) {
state[i / 3][i % 3] = symbol;
}
state
}
fn ma... | Rust | 0 |
from motion import Component
import pytest
c = Component("ComponentWithParams", params={"multiplier": 2})
@c.init_state
def setUp():
return {"value": 0}
@c.serve("add")
def plus(state, props):
return c.params["multiplier"] * (state["value"] + props["value"])
@c.update("add")
def increment(state, props):... | Python | 1 |
xB0, 0xBD, 0x8D, 0xF3, 0xA1, 0x67, 0x42, 0x2B, 0xDE, 0x34, 0xC0, 0x22, 0xCB, 0x2E, 0x5D, 0x45, 0x8C, 0xDD, 0xD2, 0xC6, 0x7E, 0x4E, 0xFE, 0xB9, 0x75, 0xCE, 0x2A, 0xA3, 0xD9, 0xB2, 0x5B, 0x37, 0x46, 0xE1]
}
];
for test_case in test_cases {
let lea128ccm = Lea128Ccm::new(&test_case.key);
// Encryption
le... | Rust | 0 |
screen
glutInitWindowPosition(0, 0)
# Okay, like the C version we retain the window id to use when closing, but for those of you new
# to Python, remember this assignment would make the variable local and not global
# if it weren't for the global declaration at the start of main.
window = glutCreateWindow("Less... | Python | 1 |
, WalletTx},
DecryptedOutput,
};
use crate::error::SqliteClientError;
pub mod chain;
pub mod error;
pub mod wallet;
/// A newtype wrapper for sqlite primary key values for the notes
/// table.
#[derive(Debug, Copy, Clone)]
pub struct NoteId(pub i64);
impl fmt::Display for NoteId {
fn fmt(&self, f: &mut fmt:... | Rust | 0 |
on_name: S) -> Self {
self.0.follower(operation_name, |o| o.start()).into()
}
/// Wrap this span in a SpanWrap along with some user data
pub fn wrap<T>(self, data: T) -> SpanWrap<T> {
SpanWrap::new(data, self.0.context().cloned().map(HSpanContext))
}
/// e.g. for times when a funct... | Rust | 0 |
import math
figure = str(input())
if figure == 'square':
side_a = float(input())
S = side_a * side_a
print(f"{S:.3f}")
elif figure == 'rectangle':
side_a = float(input())
side_b = float(input())
S = side_a * side_b
print(f"{S:.3f}")
elif figure == 'circle':
radius = float(input())
... | Python | 1 |
return jsonify(create_response(
status='success',
data={
'tesseract_available': False,
'version': None,
'languages': 'eng+ind',
'test_result': f'OCR test failed: {str(e)}',
'sta... | Python | 1 |
# Problem: Two City Scheduling - https://leetcode.com/problems/two-city-scheduling/
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
costs.sort(key = lambda x: abs(x[0]-x[1]), reverse = True)
ava = len(costs)//2
place = [0,0]
ans = 0
for i in costs... | Python | 1 |
# Creating MST(Minimum Spanning Tree) using Kruskal's method.
# The method of creating MST using Kruskal's Algorithm is:
# 1) The graph edges are ordered in an ascending order depending on its weight.
# 2) we go through the edges from smaller to bigger and put it in the MST, but
# with condition that when the edge ... | Python | 1 |
_INS_FCMPEQ = 268
SPARC_INS_FCMPES = 269
SPARC_INS_WR = 270
SPARC_INS_XMULX = 271
SPARC_INS_XMULXHI = 272
SPARC_INS_XNORCC = 273
SPARC_INS_XNOR = 274
SPARC_INS_XORCC = 275
SPARC_INS_XOR = 276
SPARC_INS_RET = 277
SPARC_INS_RETL = 278
SPARC_INS_ENDING = 279
# Group of SPARC instructions
SPARC_GRP_INVALID = 0
# Generic... | Python | 1 |
import matplotlib.pyplot as plt
from nova.design.inverse import Inverse
from nova.frame.coilgeom import ITERcoilset
build_coilset = True
pmag = Inverse()
if build_coilset:
ITER = ITERcoilset(
coils="pf",
dCoil=0.2,
n=5e2,
limit=[3, 10, -5.75, 5.75],
levels=61,
biot... | Python | 1 |
import sys
from unittest import TestCase
import dirtyjson
from dirtyjson.compat import unichr, text_type
class TestUnicode(TestCase):
def test_big_unicode_decode(self):
uc = u'z\U0001d120x'
self.assertEqual(dirtyjson.loads('"' + uc + '"'), uc)
self.assertEqual(dirtyjson.loads('"z\\ud834\\... | Python | 1 |
everShortCircuit, Residual, Try};
mod chain;
mod cloned;
mod copied;
mod cycle;
mod enumerate;
mod filter;
mod filter_map;
mod flatten;
mod fuse;
mod inspect;
mod intersperse;
mod map;
mod map_while;
mod peekable;
mod rev;
mod scan;
mod skip;
mod skip_while;
mod step_by;
mod take;
mod take_while;
mod zip;
#[stable(fe... | Rust | 0 |
names=[\'testScenario\']. Cancelling", content)
def test_run_scenarios_invalid(self):
#cleanup logfile
try:
with open(logmod.logfile, "w", encoding="UTF-8") as file:
pass
except FileNotFoundError:
self.fail()
sm = ScenarioManagerFactory(sta... | 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 = 10000
n = 5000
rho = 10
display = False
... | Python | 1 |
array
vec.iter().enumerate().for_each(|e| {
let (i, obj) = e;
let js_string = cx.string(obj);
let _ = js_array.set(&mut cx, i as u32, js_string);
});
Ok(js_array)
}
fn convert_js_array_to_vec(mut cx: FunctionContext) -> JsResult<JsNumber> {
// Take the first argument, which mu... | Rust | 0 |
(),
[5, 8, 4, 7, 10].iter().copied().collect(),
);
game.play_recursive();
assert!(matches!(game.winner, Some(Player::Player2)));
let result = game.winning_score();
assert_eq!(result, Some(291));
}
}
<reponame>shaipe/wechat-sdk-rs<filename>mp/src/message/event.rs
/... | Rust | 0 |
b'Q', b'N', b'Q', b'O', b'Q', b'P',
b'Q', b'Q',
];
pub const DIGIT_TO_BASE28_SQUARED: [u8; 1568] = [
b'0', b'0', b'0', b'1', b'0', b'2', b'0', b'3', b'0', b'4', b'0', b'5', b'0', b'6', b'0', b'7',
b'0', b'8', b'0', b'9', b'0', b'A', b'0', b'B', b'0', b'C', b'0', b'D', b'0', b'E', b'0', b'F',
b'0', b'G',... | Rust | 0 |
g_ax, time[1:], spot_deg_inhibited[1:, :])
plot_ax(ppgpp_deg_ax2, time[1:], spot_deg_rxns[1:], secondary=True, dashed=True)
elong_mean = total_elong / timesteps
growth_mean = total_growth / timesteps
ppgpp_mean = total_ppgpp / timesteps
# Format plot axes
post_plot_formatting(growth_ax, division_times, '... | Python | 1 |
for Pattern {
/// Constructs a Pattern object with all the default settings
///
/// #Example
///
/// ```rust
/// use pbd::dpi::Pattern;
/// let pattern = Pattern::default();
/// ```
fn default() -> Self {
Pattern {
regex_consonant_upper: Regex::new(r"[B-DF-HJ-NP-... | Rust | 0 |
import ctypes
import glob
# find the shared library, the path depends on the platform and Python version
engine_lib = ctypes.CDLL('./engine.so')
engine_lib.get_best_move.argtypes = [ctypes.c_char_p] # Takes a string (char*)
engine_lib.get_best_move.restype = ctypes.c_char_p # Returns a string (char*)
board_state ... | Python | 1 |
#
# RTL base direction changes order of the items.
# Also demonstrate how horizontal scrolling works with RTL.
#
cont = lv.obj(lv.scr_act())
cont.set_style_base_dir(lv.BASE_DIR.RTL,0)
cont.set_size(300, 220)
cont.center()
cont.set_flex_flow(lv.FLEX_FLOW.ROW_WRAP)
for i in range(20):
obj = lv.obj(cont)
obj.set... | Python | 1 |
)
# 将 StudyRecord 对象转换为字典,并添加累计学习时长、累积掌握单词数和累计学习单词数
study_record_dict = {
"user_id": study_record.user_id,
"book_id": study_record.book_id,
"study_date": study_record.study_date.strftime("%Y-%m-%d"),
"new_words": study_record.new_words,
... | Python | 1 |
'''reference: https://github.com/dongjun-Lee/text-classification-models-tf'''
import os
import wget
import tarfile
import re
from nltk.tokenize import word_tokenize
import collections
import pandas as pd
import pickle
import numpy as np
TRAIN_PATH = "dbpedia_csv/train.csv"
TEST_PATH = "dbpedia_csv/test.csv"
def dow... | Python | 1 |
""" A primitive tool to remove all tiles but the first one from a cbcl file.
Usage:
python3 trim.py <input_file> <output_file>
Documentation for .cbcl format (p7):
https://support.illumina.com/content/dam/illumina-support/documents/documentation/software_documentation/bcl2fastq/bcl2fastq2-v2-20-software-guide-150... | Python | 1 |
self.urb.urbtype {
// urbtype if (UrbType::Control as u8) == urbtype => &self.buf.as_ref()[8..],
// _ => self.buf.as_ref(),
// }
// }
pub fn data_mut(&mut self) -> &mut [u8] {
match self.urb.urbtype {
urbtype if (UrbType::Control as u8) == urbtyp... | Rust | 0 |
outer.mm.node or len(user.all_input_nodes[0].users) == len(experts):
continue
if not (
Linear.configure_from(user)
and (gated_mlp := find_nearest(GatedMLP, user, follow_parent=False))
and (gated_mlp_mul := gated_mlp.mul)
and (do... | Python | 1 |
: CUpointer_attribute_enum =
CUpointer_attribute_enum(2);
}
impl CUpointer_attribute_enum {
pub const CU_POINTER_ATTRIBUTE_DEVICE_POINTER: CUpointer_attribute_enum =
CUpointer_attribute_enum(3);
}
impl CUpointer_attribute_enum {
pub const CU_POINTER_ATTRIBUTE_HOST_POINTER: CUpointer_attribute_en... | Rust | 0 |
hash));
}
parts.push(String::from(env!("GIRT_BUILD_DATE")));
format!("interactive-rebase-tool {} ({})", VERSION, parts.join(" "))
}
pub(crate) fn run() -> Exit {
Exit::from(build_version())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[serial_test::serial]
fn test_run() {
assert!(run()
.get_messa... | Rust | 0 |
}
fn endpoint_c(s: EndpointC) -> Result<(), Box<dyn Error>> {
offer_cancel_mpst!(s, recv_mpst_c_from_d, {
Branching0fromDtoC::Done(s) => {
close_mpst_multi(s)
},
Branching0fromDtoC::More(s) => {
let (_, s) = recv_mpst_c_from_d(s)?;
let s = send_check_c_t... | Rust | 0 |
alo::format!(in bump, "{}",
unwrap!(unwrap!(root_rendering_component.game_data.game_config.clone(),"root_rendering_component.game_data.game_config.clone()")
.card_moniker.get(unwrap!(game_data.card_grid_data.get(game_data.card_index_of_second_click)).card_number_and_img_src)))
... | Rust | 0 |
total amount of albums.
"""
data = await self.__client.http.artist_albums(
self.id, limit=1, offset=0, market=market
)
return data["total"]
@set_required_scopes(None)
async def top_tracks(self, country: str = "US") -> List["spotify.Track"]:
"""Get Spotify ca... | Python | 1 |
erErrorParser, GTestErrorParser],
'stress_crash': [CompilerErrorParser, DbCrashErrorParser],
'write_stress': [CompilerErrorParser, WriteStressErrorParser],
'asan': [CompilerErrorParser, GTestErrorParser, AsanErrorParser],
'asan_crash': [CompilerErrorParser, AsanErrorParser, DbCrashErrorParser],
'ubs... | Python | 1 |
]),
},
)
}
// Paren delimited multiple argument lists with key-value elements
#[test]
fn multiple_paren_kv_args() {
test_parse(
"+TEST: (1=abc)(2,xyz=3)",
Response::Success {
name: String::from("TEST"),
is_extension: true,
arguments: Argu... | Rust | 0 |
::Add,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum BlendFactor {
One,
Zero,
SrcAlpha,
OneMinusSrcAlpha,
}
impl BlendFactor {
fn as_wgpu(&self) -> wgpu::BlendFactor {
match self {
BlendFactor::SrcAlpha => wgpu::BlendFactor::SrcAlpha,
Blend... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.