text string | label_name string | labels int64 |
|---|---|---|
ration(duration: &str) -> Result<Duration> {
let mut dur = Duration::default();
let re = Regex::new(DURATION_MATCH).unwrap();
for cap in re.captures_iter(duration) {
let add_to = if let Some(days) = cap.name("days") {
let days = days.as_str().parse::<u64>()?;
let seconds = ... | Rust | 0 |
owngrade,
Webservices,
Cuzz,
}
impl FromStr for AppVerifierTest {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"heaps" => Ok(AppVerifierTest::Heaps),
"com" => Ok(AppVerifierTest::COM),
"rpc" => Ok(AppVerifierTest::RPC... | Rust | 0 |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.random.randn(2000) * 10
y = np.random.randn(2000) * 10
z = np.random.rand(2000) + 40 - np.sqrt(np.square(x) + np.square(y))
plt.xlabel('x coordinate (m)')
plt.ylabel('y coordinate (m)')
plt.title('Mountain Elevation')
... | Python | 1 |
(self.weight * smoothing_factor.to(self.device))
wei_scales, _ = self.wei_oc_obs.calculate_qparams()
# 5 return results
return smoothing_factor.to(self.device), act_scales, wei_scales.to(self.device)
class SmoothQuantObservedLinear(torch.nn.Linear):
def __init__(
self,
in_f... | Python | 1 |
er_python_dot_notation_variables(raw_str, result):
"""Test template variables that contain a dot character (`.`)."""
context = {
"foo": "bar",
"num": 123,
"sqlfluff": {
"foo.bar": "foobar",
"self.number": 42,
"obj.schema": "my_schema",
"obj... | Python | 1 |
",
RenderFeatureFlagT::feature_flag_debug_name()
);
self.is_included_index_unchecked(index)
}
#[inline(always)]
pub fn is_included_index(
&self,
index: RenderFeatureFlagIndex,
) -> bool {
assert!(
index < MAX_RENDER_FEATURE_FLAG_COUNT,
... | Rust | 0 |
aux_loss = self.criterion(aux, y)
return x.max(1)[1], main_loss, aux_loss
else:
return x
if __name__ == '__main__':
import os
import time
input = torch.rand(1, 3, 1024, 2048).cuda()
model = PSPNet(layers=18, bins=(1, 2, 3, 6), dropout=0.1, classes=... | Python | 1 |
stats without user intervention. Lastly it can give a notification whenever a new challenge was
//! completed by one of the tracked users.
//!
//! ## Slack commands
//
//! The service currently knows all the following commands that can be triggered by sending a Slack
//! message with `@<botname> <command>`:
//!
//! ###... | Rust | 0 |
TEST_HELPERS(double);
TEST_HELPERS(char);
TEST_HELPERS(short);
TEST_HELPERS(int);
TEST_HELPERS(long);
TEST_HELPERS(uchar);
TEST_HELPERS(ushort);
TEST_HELPERS(uint);
TEST_HELPERS(ulong);
}
void single_source_alloc_test() {
if (failed) {
rsDebug("Single Source Alloc Test Fa... | Rust | 0 |
from ebs_deploy import out, get, parse_env_config, parse_option_settings
def add_arguments(parser):
"""
Args for the init command
"""
parser.add_argument('-e', '--environment', help='Environment name', required=False, nargs='+')
parser.add_argument('-w', '--dont-wait', help='Skip waiting for the ... | Python | 1 |
r, Any]) -> str:
"""
Generate code for creating a layer.
Args:
params: Parameters for the layer
Returns:
Lua code string
"""
name = params.get("name", f"Layer {params.get('index', 1)}")
color = params.get("color", "#00... | Python | 1 |
import cv2
print(cv2.__file__)
# 加载人脸和眼睛检测的级联分类器
face_cascade = cv2.CascadeClassifier('D:\python\Lib\site-packages\cv2\data\haarcascade_eye.xml')
eye_cascade = cv2.CascadeClassifier('D:\python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头画面... | Python | 1 |
_system(update_mouse_location.system())
;
}
}
struct MainCamera;
pub struct MousePositionInWorld(Vec2);
impl MousePositionInWorld {
pub fn transform(&self) -> Transform {
Transform::from_xyz(self.x, self.y, 0.0)
}
}
impl Deref for MousePositionInWorld {
type Target = Vec2;
fn der... | Rust | 0 |
, Underflow>;
#[derive(Debug, Clone)]
pub struct Underflow;
impl<State> Adc <State>
{
// type Error = Underflow;
// Read normal sample
pub fn read(&mut self, pin: & Pin<impl PinId, state::Analog<direction::Input>>) -> Result<u16> {
self.arm_normal_channel(pin.state.channel);
self.raw.swt... | Rust | 0 |
,
)
.build();
let mut rng = thread_rng();
let vals: Vec<_> = (0..1000).map(|_| rng.gen::<f32>()).collect();
let input = tract_ndarray::arr1(&vals).into_shape((10, 100)).unwrap();
let resp = o
.onnx_request(
"model_which_will_be_tested",
ORequest::with_bo... | Rust | 0 |
::new(&DOT_ENV_PATH).exists() {
let file = read_env_file().unwrap();
delete_env_file().unwrap();
assert!(!dot_env_file_exists());
restore_env_file(file.clone()).unwrap();
assert!(dot_env_file_exists());
let result = read_env_file().unwrap();
... | Rust | 0 |
contents[:i-1] + contents[i:]
icursor -= 1
ew.bell()
elif self.__hexp.get():
contents = hex(v)[2:]
else:
contents = int(v)
ew.delete(0, END)
ew.insert(0, contents)
ew.icursor(icursor)
def __maybeupdate(self, event=None):
... | Python | 1 |
'''
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, X, of N integers and an array, W, representing the respective weights of X's elements, calculate ... | Python | 1 |
# Copyright (c) 2010- The University of Notre Dame.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
""" Weaver stack module """
from weaver.logger import debug
import sys
# Stack class
class Stack(list):
""" Basic stack data structure. """
def empt... | Python | 1 |
}
self.bme680_set_regs(®[0..element_index])?;
// Restore previous intended power mode
self.power_mode = intended_power_mode;
Ok(())
}
/// Retrieve settings from sensor registers
///
/// # Arguments
///
/// * `desired_settings` - Settings to be retrieved... | Rust | 0 |
break 'outer;
}
cur_end += 1;
}
break;
}
}
break;
}
}
// Make sure there is no whitespace to the right of the break.
while c... | Rust | 0 |
interrupt"]
NONMASKABLE,
#[doc = "Maskable interrupt"]
MASKABLE,
}
impl INTTYPER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_s... | Rust | 0 |
a
dr @ s d Z ddgZddlZddlZddlZddlZddlZddlZddlZddl Z ddl
Z
ddlZddlm
Z ddlZdZG dd dZd d
Zdd ZG d
d dZdd Zdd ZdddZdd ZG dd dZdd Zedkre dS )a program/module to trace Python program or function exe... | Python | 1 |
writer: *mut ffi::archive,
) -> Result<()> {
let mut buffer = std::ptr::null();
let mut offset = 0;
let mut size = 0;
unsafe {
loop {
match ffi::archive_read_data_block(archive_reader, &mut buffer, &mut size, &mut offset)
{
ffi::ARCHIVE_EOF => return Ok((... | Rust | 0 |
import streamlit as st
import altair as alt
from processing import predict_categories_and_generate_report
from parser import load_and_clean_data
from advisor import analyze_budget
from predict_next_month import predict_next_month_spending
import pandas as pd
st.title("Personal Budget AI")
st.write("Hi, I'm Finny - ... | Python | 1 |
FeatureBits { fields }
}
pub fn fields(self) -> [u32; 2] {
self.fields
}
pub fn disable(&mut self, pos: (usize, u32)) {
self.fields[pos.0] &= !(1 << pos.1);
}
pub fn is_enabled(self, pos: (usize, u32)) -> bool {
self.fields[pos.0] & !(1 << pos.1) != 0
}
}
/... | Rust | 0 |
#!/usr/bin/env python3
from hdwallet import HDWallet
from hdwallet.mnemonics import (
BIP39Mnemonic, MONERO_MNEMONIC_WORDS, BIP39_MNEMONIC_LANGUAGES
)
from hdwallet.cryptocurrencies import Cardano as Cryptocurrency
from hdwallet.hds import CardanoHD
from hdwallet.derivations import (
CIP1852Derivation, ROLES
)... | Python | 1 |
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
patterns = [tuple(a ^ row[0] for a in row) for row in matrix]
return max(Counter(patterns).values())
| Python | 1 |
author: String::new(),
cover: None,
}));
let ui = UI::init().expect("Couldn't initialize UI library");
let mut window = Window::new(&ui, "Stevia GUI", 380, 480, WindowType::NoMenubar);
let multiline_entry = MultilineEntry::new(&ui);
let mut log_ctx = LogContext {
ui: &ui,
e... | Rust | 0 |
v = (*v * levels).floor() / levels
}
fn channeled_map_mut<F, T>(mut f: F) -> impl FnMut(&mut Channeled<T>)
where
F: FnMut(&mut T),
{
move |input| {
input.as_mut_ref().for_each(&mut f);
}
}
pub fn open_config_or_default() -> Result<VizPipelineConfig> {
match open_config() {
Ok(Some(conf... | Rust | 0 |
"""
用户分析Agent测试脚本
用于测试和演示User Analyst Agent的功能
"""
import asyncio
import sys
import os
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from app.agents.user_analyst_agent import UserAnalystAgent, UserProfile
from app.infra.db.async_database import get_session_context
from app.utils.logge... | Python | 1 |
# 记录警告但继续,也许它已经有权限了
chmod_output = chmod_result.output.decode('utf-8', errors='ignore')[:200]
logger.warning(f"chmod +x 命令失败 (Exit Code: {chmod_result.exit_code}), Output: {chmod_output}. 尝试继续...")
else:
log... | Python | 1 |
ect("that the vm is valid from inside of request_animation_frame");
let vm = &stored_vm.vm;
let func = func.clone();
let args = vec![vm.ctx.new_float(time)];
let _ = vm.invoke(func, args);
let closure = f.borrow_mut().take();
drop(closure);
}) as Box<Fn(f64)>));
... | Rust | 0 |
import requests
url = 'http://18.206.219.103/ask'
headers = {'Content-Type': 'application/json'}
data = {'question': 'What are pure functions in javascript?'}
response = requests.post(url, headers=headers, json=data)
print(response.json()) | Python | 1 |
creaseRatingImplicit(generation_config, behavior_schema, behavior_df, item_df, item_schema, context_df)
new_behaviors, new_ratings = increase.extend_rating_random(100)
# Append new_behaviors to the existing behaviors dataset
existing_behaviors_df = pd.read_csv(r'resources\dataset_imascono\Paper\behavior2.csv')
updated... | Python | 1 |
"""Update status bar and progress"""
self.status_label.setText(message)
self.progress_bar.setValue(progress)
# Handle spinner animation based on progress
if progress < 100:
# Operation in progress, show spinner and ensure cancel button is visible
i... | Python | 1 |
import numpy as np
def compute_iou(ra, rb):
"""intersection over union of two axis aligned rectangles ra and rb"""
if ra.xmax < rb.xmin or rb.xmax < ra.xmin or ra.ymax < rb.ymin or rb.ymax < ra.ymin:
return 0
l = max(ra.xmin, rb.xmin)
r = min(ra.xmax, rb.xmax)
t = max(ra.ymin, rb.ymin)
... | Python | 1 |
q_dragged.iter_mut() {
// set position of sprite to offset from cursor
let pos = cursor_state.cursor_world + cursor_state.cursor_offset;
transform.translation.x = pos.x;
transform.translation.y = pos.y;
}
}
fn drop(
commands: &mut Commands,
atlas_assets: Res<Assets<Texture... | Rust | 0 |
64,
}
#[post("/actcast", format = "application/json", data = "<cast>")]
fn actcast(conn: DBConn, cast: Json<Incoming>) -> status::Accepted<content::Json<&'static str>> {
use schema::counts::dsl::*;
let incoming = cast.into_inner();
let secs = incoming.timestamp as i64 / 1000;
let nsecs = (incoming.tim... | Rust | 0 |
let token = req
.headers()
.get("MyToken")
.and_then(|value| value.to_str().ok())
.ok_or(MissingToken)?;
Ok(Token(token.to_string()))
}
}
#[handler]
async fn index(token: Token) {
assert_eq!(token.0, "token<PASSWORD>");
}
#[tokio::main]
async fn main() -... | Rust | 0 |
l From<&[u8]> for Tag {
fn from(raw: &[u8]) -> Self {
match raw {
b"ConstantValue" => Tag::ConstantValue,
b"Code" => Tag::Code,
b"StackMapTable" => Tag::StackMapTable,
b"Exceptions" => Tag::Exceptions,
b"InnerClasses" => Tag::InnerClasses,
... | Rust | 0 |
}
#[derive(Serialize, Deserialize, Clone)]
pub struct OutboundTlsConfig {
pub host_name: String,
pub allow_insecure: bool,
}
<reponame>DogeDark/dioxus
use dioxus::prelude::*;
fn main() {
dioxus::tui::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx! {
div {
width: "100... | Rust | 0 |
"""
Usage:
webvtt segment <file> [--target-duration=SECONDS] [--mpegts=OFFSET] [--output=<dir>]
webvtt -h | --help
webvtt --version
Options:
-h --help Show this screen.
--version Show version.
--target-duration=SECONDS Target duration of each segment in seconds [default: ... | Python | 1 |
# Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, visit
# https://nvlabs.github.io/stylegan2/license.html
"""Inception Score (IS)."""
import numpy as np
import tensorflow as tf
import dnnlib.tflib a... | Python | 1 |
{
let count = self.extra_ties.entry(y).or_insert(0);
*count += 1;
}
// Update updated_k with ties.
self.updated_k = self.first_of_ties(self.neighbors.len() - 1);
} else {
// Insert sorted.
let new = Neighbor::new(... | Rust | 0 |
(), step);
if vertical_velocities.len() > 0 {
step_vertical_velocities.insert(step, vertical_velocities);
}
}
}
let mut hit_launches = HashSet::new();
let mut find_hits = |&steps, horizontal| {
if let Some(verticals) = step_vertical_velocities.get(&s... | Rust | 0 |
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
class QueryRequest(BaseModel):
question: str = Field(..., description="Question to ask the agent")
class QueryResponse(BaseModel):
answer: str = Field(..., description="Agent's response")
agent_type: Optional[str] = Field(Non... | Python | 1 |
*available_out = (*available_out).wrapping_sub(copy_output_size);
(*s).next_out_ = NextOutIncrement(&(*s).next_out_, (copy_output_size as (i32)));
(*s).available_out_ = (*s).available_out_.wrapping_sub(copy_output_size);
(*s).total_out_ = (*s).total_out_.wrapping_add(copy_output_size as u64);
if let &mu... | Rust | 0 |
ticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use drive2::Drive;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_r... | Rust | 0 |
mmap.c#L1637-L1642
pub fn brk(desired: u64) -> u64 {
// https://github.com/torvalds/linux/blob/763978ca67a3d7be3915e2035e2a6c331524c748/mm/mmap.c#L195
const SYSCALL_ID: u32 = 12;
unsafe { syscall_1_arg(SYSCALL_ID, desired) }
}
pub fn sbrk(delta: i64) -> *mut u8 {
let current = brk(0);
let new = de... | Rust | 0 |
entity_csv` file received.
"""
roi_contour = cls.get_roi_contour_for_entity(config, entity["id"])
with open(today_entity_csv, "r") as log:
objects_logs = {}
lastest_entries = deque(csv.DictReader(log), entries_in_interval)
for entry in lastest_entries:
... | Python | 1 |
return {}
section_name = self._scoped_config['services']
services_section = self._full_config.get('services', {}).get(
section_name
)
if not services_section:
error_msg = (
f'The profile is configured to use the services '
... | Python | 1 |
trace!("emit srem-iregex-iregex");
let reg_op1 = self.emit_ireg(&ops[op1], f_content, f_context, vm);
let reg_op2 = self.emit_ireg(&ops[op2], f_content, f_context, vm);
self.emit_runtime_entry(
&entrypoints::SREM_I... | Rust | 0 |
pub fn d20_map_string(&self) -> String {
let mut string = String::new();
for (&d20_roll, dice_roll) in &self.d20_map {
string
.push_str(format!("{:2} -> {:2}\n", d20_roll as i8 + self.soh, dice_roll).as_str())
}
string
}
pub fn set_dice(&mut self, dic... | Rust | 0 |
, std, baseline, polarity, noise=False):
"""
Function to itterate through several combinations of signal amplitude and offset
to determine the poinst at which multiplicity is no longer 0.
This point defined the limit of the CFD resolution.
"""
min_offset = []
amp = []
for i in np.arang... | Python | 1 |
state["messages"][-1].content)
# Get the next step from the plan
next_step = plan.steps[state["current_step"]]
next_agent = next_step.agent
next_task = next_step.task
# Return command to invoke the next agent
return Command(goto="invoke_agent", update={"next": next_agent, "next_task": next_tas... | Python | 1 |
Eq, PartialEq)]
pub enum VariableType {
Continuous,
Integer,
}
impl Not for VariableType {
type Output = VariableType;
fn not(self) -> VariableType {
match self {
VariableType::Continuous => VariableType::Integer,
VariableType::Integer => VariableType::Continuous,
... | Rust | 0 |
plt.annotate(wrapped_text, (pos[node][0], pos[node][1]-0.15), ha='center', va='top',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5))
# Get current axes limits
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# Add margins to the axes limits
x_margin = (xlim[1] - xl... | Python | 1 |
(&mut self) -> _EPW {
_EPW { w: self }
}
#[doc = "Bit 7 - Selects IN or OUT endpoint"]
#[inline]
pub fn io(&mut self) -> _IOW {
_IOW { w: self }
}
#[doc = "Bit 8 - Stall selected endpoint"]
#[inline]
pub fn stall(&mut self) -> _STALLW {
_STALLW { w: self }
}
}... | Rust | 0 |
py: pyo3::Python<'_>,
builder: &pyo3::PyAny,
private_key: &pyo3::PyAny,
hash_algorithm: &pyo3::PyAny,
) -> PyAsn1Result<CertificateRevocationList> {
let sigalg = x509::sign::compute_signature_algorithm(py, private_key, hash_algorithm)?;
let mut revoked_certs = vec![];
for py_revoked_cert in... | Rust | 0 |
7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43];
let not_primes = vec![0, 1, 4, 6, 8, 9, 12, 15, 21, 25, 27, 33, 35];
for p in primes {
assert!(ps[p]);
}
for q in not_primes {
assert!(!ps[q]);
}
}
}
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::{... | Rust | 0 |
angle()), self.angle_to_param(-acos + cp.angle())])
}
}
pub fn entry_tangent(&self) -> Vec2 { self.derivative().at(0.0).normalized() }
pub fn exit_tangent(&self) -> Vec2 { self.derivative().at(1.0).normalized() }
pub fn enclosing_polygon_local_space(&self) -> ArrayVec<[Vec2; MAX_POLYGON_VERTI... | Rust | 0 |
r)
for helpers in not_full_res["helpers"].values():
for helper in helpers:
not_full_set.add(helper)
self.assertCountEqual(full_set - not_full_set,
set(DMESG_EMITTING_HELPERS))
self.assertCountEqual(not_full_set - full_set, set())
d... | Python | 1 |
to prevent the panic.
fn unregister(&mut self, accelerator: &str) -> crate::Result<()>;
}
/// Clipboard manager.
pub trait ClipboardManager {
/// Writes the text into the clipboard as plain text.
///
/// # Panics
///
/// Panics if the app is not running yet, usually when called on the `tauri::Builder#setup... | Rust | 0 |
SlaveProfileDrawable for WindSpeedContext {
fn get_master_zoom(&self, acp: &AppContextPointer) -> f64 {
acp.skew_t.get_zoom_factor()
}
fn set_translate_y(&self, new_translate: XYCoords) {
let mut translate = self.get_translate();
translate.y = new_translate.y;
self.set_tran... | Rust | 0 |
e_query!(
channels,
songs,
);
use std::collections::HashMap;
use std::path::PathBuf;
use swift_bridge_build::ApplePlatform as Platform;
use swift_bridge_build::{create_package, CreatePackageConfig};
fn main() {
create_package(CreatePackageConfig {
bridge_dir: PathBuf::from("swift-package-rust-libr... | Rust | 0 |
dim_combinations[dim] = [value // scale_factor]
else:
scale_factor = (
reshape.vector_shapes[dim] // reshape.target_vector_shape[dim]
)
begin = value * scale_factor
dim_combinations[dim] = list(range(begin, begin + scale_factor))
reshap... | Python | 1 |
ng
/// a sender and a receiver.
pub fn new() -> (Self, Self) {
let inner = Arc::new(Inner {
done: AtomicBool::new(false),
waker: AtomicCell::new(None),
});
(Notify(inner.clone()), Notify(inner))
}
/// Stores the action as bein completed,
/// eventual... | Rust | 0 |
style(cb: *mut lv_obj_t, type_: lv_cb_style_t, style: *const lv_style_t);
}
extern "C" {
#[doc = " Get the text of a check box"]
#[doc = " @param cb pointer to check box object"]
#[doc = " @return pointer to the text of the check box"]
pub fn lv_cb_get_text(cb: *const lv_obj_t) -> *const cty::c_char;
}
... | Rust | 0 |
from .manifest import Manifest, manifest
def test_manifest_decorator_basic():
"""Test that the manifest decorator adds manifest attribute to function."""
@manifest(fork_name="phase0", preset_name="minimal")
def test_function():
return "test"
assert hasattr(test_function, "manifest")
asse... | Python | 1 |
# appends parent path to syspath to make ocatari importable
# like it would have been installed as a package
import random
import sys
import matplotlib.pyplot as plt
import ipdb
sys.path.insert(0, '../../') # noqa
import pickle
from ocatari.core import OCAtari
from ocatari.vision.utils import mark_bb, make_darker
fro... | Python | 1 |
iter().find(|x| **x == String::from("--dump-resolved")) {
println!("{:#?}", resolved.borrow());
}
interpreter::interprete(resolved, Vec::new());
}
fn exit_with_style(msg: &str) {
// have ~style~
eprintln!("{}", msg);
process::exit(1);
}
pub struct SrcFile {
path: String,
contents:... | Rust | 0 |
[T; N * 2],
}
impl<T: Default + Copy, const N: usize> S<T, N>
where
[T; N * 2]: Sized,
{
pub fn test() -> Self {
S { s: [T::default(); N * 2] }
}
}
<reponame>manishmeganathan/cellautomata<gh_stars>1-10
use rand::Rng;
use ggez::graphics;
use crate::commons::navigation::Direction4;
use crate::simula... | Rust | 0 |
#!/usr/bin/env python3
"""module 8-all
lists all documents in collection in python
"""
def list_all(mongo_collection) -> list:
"""list all documents in mongo_collection
Args:
mongo_collection (Collection) -> pymongo collection
Returns:
list: List of documents in collection
"""
retu... | Python | 1 |
r_stdout(sm.value_of("dest"))
.expect("unable to write to the specified file"),
),
("fungible-transfer", Some(sm)) => {
let alloc = sm.values_of("alloc").expect("required argument");
let map: Result<Vec<BalanceAllocation>, String> = alloc.map(conv_allocations).col... | Rust | 0 |
lName(self):
return self._GpuModelName
@GpuModelName.setter
def GpuModelName(self, GpuModelName):
self._GpuModelName = GpuModelName
def _deserialize(self, params):
if params.get("InstanceFamilyConfig") is not None:
self._InstanceFamilyConfig = InstanceFamilyConfig()
... | Python | 1 |
# Moved in Django 1.8 from django to tests/auth_tests/urls.py
from django.urls import re_path
from django.contrib.auth.decorators import login_required
from django.contrib.auth.urls import urlpatterns
try:
from django.contrib.auth.views import (
login, logout, password_change, password_reset, password_re... | Python | 1 |
import os.path as osp
import numpy as np
import neuron.ops as ops
from neuron.config import registry
from .dataset import SeqDataset
__all__ = ['OxUvA']
@registry.register_module
class OxUvA(SeqDataset):
"""`OxUvA <https://oxuva.github.io/long-term-tracking-benchmark/>`_ Dataset.
Publication:
``Lo... | Python | 1 |
parser.skip_whitespace();
if parser.next_char() == '}' {
break; // end of declaration
}
declarations.push(parse_declaration(parser));
}
assert_eq!('}', parser.consume_char()); // end of declaration
return declarations;
}
// selector of format => type#id.class1.class2.c... | Rust | 0 |
unwrap_or(0) as usize;
set(cx, entity, i, value);
}
// The call above may have mutated anything reachable through `cx`.
// Reload any invalidated borrows.
let (w, a) = cx.fields();
world = w;
assets = a;... | Rust | 0 |
euid() {
new_ucmd!()
.args(&["-O", "nonexistent_file"])
.run()
.status_code(1);
}
#[test]
#[cfg(all(not(windows), not(target_os = "freebsd")))]
fn test_file_not_owned_by_euid() {
new_ucmd!()
.args(&["-f", "/bin/sh", "-a", "!", "-O", "/bin/sh"])
.succeeds();
}
#[test]
#[... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# escpos/tests/test_asc.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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... | Python | 1 |
rn Mariana Islands'), ('NO', 'Norway'), ('OM', 'Oman'), ('PK', 'Pakistan'), ('PW', 'Palau'), ('PS', 'Palestinian Territories'), ('PA', 'Panama'), ('PG', 'Papua New Guinea'), ('PY', 'Paraguay'), ('PE', 'Peru'), ('PH', 'Philippines'), ('PN', 'Pitcairn Islands'), ('PL', 'Poland'), ('PT', 'Portugal'), ('PR', 'Puerto Rico')... | Python | 1 |
_prop_mod(EffectId.module_bonus_microwarpdrive)
propmod.state = State.active
self.fit.ship = ship
self.fit.modules.mid.append(propmod)
self.assertAlmostEqual(
ship.attrs[AttrId.max_velocity], 2735.871, places=3)
# Action
self.fit.modules.low.append(thrustmod)
... | Python | 1 |
# -*- coding: utf-8 -*-
from django.forms.models import model_to_dict
from modernrpc.core import rpc_method
from tcms.rpc.api.forms.testcase import CategoryForm
from tcms.rpc.decorators import permissions_required
from tcms.testcases.models import Category
@permissions_required("testcases.view_category")
@rpc_metho... | Python | 1 |
ctions::{HashMap, HashSet};
pub struct Inlining;
impl optimization::Interprocedural for Inlining {
fn optimize<'src, 'ast>(program: &mut FirmProgram<'src, 'ast>) -> Outcome {
let g = CallGraph::new(program).construct();
breakpoint!("before inline: graph", g, &|n: &FirmMethodP<'src, 'ast>| {
... | Rust | 0 |
from functools import reduce
def ascending(a, b): return a - b
def descending(a, b): return -ascending(a, b)
def selectionSort(xs, compare = ascending):
return [] if not xs else __select(xs, compare)
def __select(xs, compare):
selected = reduce(
lambda m, k: m if compare(m, k) < 0 else k, xs)
rem... | Python | 1 |
e:
//
// impl<T, I: Iterator> FromBytes for Foo<T, I>
// where
// T: Copy,
// I: Clone,
// I::Item: Clone,
// T: FromBytes,
// I::Item: FromBytes,
// {
// }
//
// Finally, we use a different technique to generate the bounds for the ty... | Rust | 0 |
SyncStatus::Synced { .. }, PeerSyncStatus::Synced { .. })
| (
PeerSyncStatus::Advanced { .. },
PeerSyncStatus::Advanced { .. }
)
| (PeerSyncStatus::Behind { .. }, PeerSyncStatus::Behind { .. })
| (
... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.T... | Python | 1 |
let path = path.as_ref();
let mut file = File::open(path)?;
let mut string = String::new();
file.read_to_string(&mut string)?;
let cfg = toml::from_str(&string).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(cfg)
}
pub fn create<P: AsRef<Path>>(path: P) -> Re... | Rust | 0 |
x62\xC1\xFE\xCB\x6F\xD3"
/// decoder = Decoder(64, data, ip=0x1234_5678)
///
/// # The decoder is iterable
/// for instr in decoder:
/// print(f"Decoded: IP=0x{instr.ip:X}: {instr}")
///
/// Output:
///
/// .. testoutput::
///
/// Decoded: IP=0x12345678: xchg ah,[rdx+rsi+16h]
/// Decoded: IP... | Rust | 0 |
: Number + Real {}
/// Corresponds to the Integer abstract type.
pub trait Integer: Number + Real {}
/// Corresponds to the Signed abstract type.
pub trait Signed: Number + Real + Integer {}
/// Corresponds to the Unsigned abstract type.
pub trait Unsigned: Number + Real + Integer {}
pub type Bool = bool;
impl Number... | Rust | 0 |
"""
두번째 테스트 케이스에서 fail...
"""
# 구름 이동 함수
def move(d,s,clouds):
moved_clouds = []
for cloud in clouds:
x, y = cloud
nx = (x + di[d][0]*s) % N
ny = (y + di[d][1]*s) % N
moved_clouds.append((nx,ny))
return moved_clouds
# 비내리기 함수
def water_magic(clouds):
for cloud in clou... | Python | 1 |
Option<&GraphicsNode> {
match *self {
#[cfg(feature = "dim3")]
Node::Plane(ref n) => Some(n.scene_node()),
Node::Ball(ref n) => Some(n.scene_node()),
Node::Box(ref n) => Some(n.scene_node()),
Node::Capsule(ref n) => Some(n.scene_node()),
#[... | Rust | 0 |
import os
import json
import requests
import yaml
from dotenv import load_dotenv
load_dotenv()
API_BASE = os.getenv("LMSTUDIO_API_BASE", "http://localhost:1234/v1")
MODEL_NAME = os.getenv("LMSTUDIO_MODEL_NAME", "mistral-nemo-instruct-2407")
CONFIG_PATH = "config.yaml"
OUTPUT_PATH = "questions.json"
def generate_ques... | Python | 1 |
#[clap(
after_help("More info at: https://github.com/saschagrunert/pinns.rs"),
global_setting(AppSettings::ColoredHelp),
version(env!("VERSION"))
)]
/// A simple utility to pin Linux namespaces
pub struct Config {
#[get_copy = "pub"]
#[clap(
default_value("info"),
long("log-level"),... | Rust | 0 |
alue() -> Self::Ux {
0
}
}
<gh_stars>0
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source Li... | Rust | 0 |
videotoolbox
try:
test_cmd = subprocess.run(
["ffmpeg", "-hwaccel", "videotoolbox", "-i", "/dev/null", "-f", "null", "-"],
stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True, check=False
)
if test_cmd.returncode == 0:
_FF... | Python | 1 |
import os
from unsloth import FastLanguageModel
from datasets import load_dataset
from unsloth.chat_templates import get_chat_template
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported
max_seq_length = 4096
dtype = (
None # None for auto detection. Flo... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.