text string | label_name string | labels int64 |
|---|---|---|
option::Option::Some(RpcResponseHeaderProto_RpcErrorCodeProto::ERROR_APPLICATION),
2 => ::std::option::Option::Some(RpcResponseHeaderProto_RpcErrorCodeProto::ERROR_NO_SUCH_METHOD),
3 => ::std::option::Option::Some(RpcResponseHeaderProto_RpcErrorCodeProto::ERROR_NO_SUCH_PROTOCOL),
4 =... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
# Any modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
# Licensed to Elasticsearch B.V. under ... | Python | 1 |
from project.influencers.base_influencer import BaseInfluencer
from project.campaigns.base_campaign import BaseCampaign
class PremiumInfluencer(BaseInfluencer):
PAYMENT_PERCENTIGE = 0.85
def __init__(self,username: str, followers: int, engagement_rate: float):
super().__init__(username,followers,enga... | Python | 1 |
_NAMES_CODE(u16),
Q_CHARSET_DATABASE_CODE(u16),
Q_TABLE_MAP_FOR_UPDATE_CODE(u64),
Q_MASTER_DATA_WRITTEN_CODE(u32),
Q_INVOKERS(String, String),
Q_UPDATED_DB_NAMES(Vec<String>),
// NOTE this field take 3 bytes
Q_MICROSECONDS(u32),
}
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
pub struct... | Rust | 0 |
dyn Listener> = if websocket_server.is_null() {
Arc::new(NullListener::new())
} else {
Arc::new(FfiListener::new(websocket_server))
};
let block_processor = Arc::downgrade(&*block_processor);
let bootstrap_initiator = Arc::downgrade(&*bootstrap_initiator);
let ledger = Arc::clone(&*l... | Rust | 0 |
.field("expected_unmap_count", &self.expected_unmap_count)
.finish()
}
}
// Copyright 2019 Stichting Organism
//
// 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
... | Rust | 0 |
import pandas as pd
data = pd.read_csv("python_files/cbk/cbkrates.csv")
# display the first rows
print("Rows")
print(data.head())
# check datatypes
print("Data Types")
print(data.dtypes)
# check for missing values
print("Missing Values")
print(data.isnull().sum())
# rename columns
new_columns = [
"YEAR",
"... | Python | 1 |
_group_from_user<
'user,
'group,
U: Into<NamedReference<'user>> + Send + Sync,
G: Into<NamedReference<'group>> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), crate::Error>;
/// Adds a user to a permission group.
#[cfg(featu... | Rust | 0 |
have this key present, both the key and value are
/// updated.
#[inline]
pub fn insert_entry_and<F: FnOnce(&K, &V) -> T, T>(
&self,
key: K,
value: V,
with_previous_entry: F,
) -> Option<T> {
let hash = bucket::hash(&self.build_hasher, &key);
self.bucket_... | Rust | 0 |
("Memorial to Folly"),
];
let hand = Hand::from_opening_and_draws(&lands, &draws);
let result = hand.play_cmc_auto_tap(&card);
assert_eq!(result.paid, true);
}
#[test]
fn cards_can_pay_10_7() {
let card = card!("Niv-Mizzet, Parun");
let lands = vec![card!("Island"), card!("Watery Grave"),... | Rust | 0 |
default_initial_settings = {
"name": "Artillery Sidewinder X1",
"manufacturer": "Artillery",
"start_gcode": "G28 ; home all axes\n M117 Purge extruder\n G92 E0 ; reset extruder\n G1 Z1.0 F3000 ; move z up little to prevent scratching of surface\n G1 X2 Y20 Z0.3 F5000.0 ; move to start-line position\n G1 X2 ... | Python | 1 |
filename>src/codec.rs<gh_stars>1-10
use std::marker::PhantomData;
use tokio_util::codec::{Decoder, Encoder};
use bytes::{BufMut, BytesMut};
pub struct Decode<M> {
state: DecodeState,
_marker: PhantomData<M>,
}
impl<M> Default for Decode<M> {
fn default() -> Self {
Self {
state: Decod... | Rust | 0 |
3, (!p3_is_identity).into(), x4))
},
)?;
// TODO: Fix
// cs.enforce_zero(x3_lc - y_var);
cs.enforce_zero(LinearCombination::from(CS::ONE) - p3_is_identity_var - z_var);
let (aa_var, bb_var, y4_var) = cs.multiply(
|| "y3 * (1 - p3_is_identity) = y4",
... | Rust | 0 |
::println!(concat!("Breakpoint @ {}:{}:{}: ", $fmt), file!(), line!(), column!(), $($arg)*);
$crate::serial_println!(concat!("Breakpoint @ {}:{}:{}: ", $fmt), file!(), line!(), column!(), $($arg)*);
#[cfg(feature = "breakpoint")]
x86_64::instructions::interrupts::int3();
};
... | Rust | 0 |
if glyph2.is_null() {
dpx_warning(
b"No glyph class \"%s\" found.\x00" as *const u8 as *const i8,
&mut *second.offset(1) as *mut i8,
);
return;
}
pdf_link_obj(glyph2);
if verbose > 0i32 {
dpx_message(
... | Rust | 0 |
a {}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentMethodDetailsCardInstallmentsPlan {}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentMethodDetailsCardPresent {}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentMethodDetailsCardWallet {}
#[derive(Clone, Debug... | Rust | 0 |
import pandas as pd
import numpy as np
REQUIRED_COLS = ["customer_id","order_id","order_date","qty","price","discount","is_return","channel","category"]
def load_raw(path: str) -> pd.DataFrame:
df = pd.read_csv(path, parse_dates=["order_date"])
missing = [c for c in REQUIRED_COLS if c not in df.columns]
i... | Python | 1 |
VecR3,
lookat: VecR3,
vup: VecR3,
vfov: f64,
aspect_ratio: f64,
aperture: f64,
focus_distance: f64,
) -> Self {
let viewport_height = 2.0 * (vfov.to_radians() / 2.0).tan();
let viewport_width = aspect_ratio * viewport_height;
let w = (lookfro... | Rust | 0 |
mp eax, eax
);
}
Z => {
dynasm!(ops
; mov ah, [rsp + 0x02]
; not ah
; test ah, 0x40
);
}
Nz => {
dynasm!(ops
; test BYTE [rsp + 0x02], BYTE 0x40
);
}
... | Rust | 0 |
(default_level, level_filters.module_levels)
}
static LOGGER_HANDLE: Lazy<Mutex<Option<Arc<LoggerHandle>>>> = Lazy::new(|| Mutex::new(None));
pub fn init() -> Arc<LoggerHandle> {
init_with_default_level("info", None)
}
pub fn init_with_default_level(
default_level: &str,
pattern: Option<LogPattern>,
... | Rust | 0 |
debug!("ones {}, threes {}", ones, threes);
println!("PART 1: {}", ones * threes);
// PART 2
// Algorithm shamelessly stolen and modified from here:
// https://github.com/lu-reit/AdventOfCode_2020_Rust/blob/master/aoc_10/src/main.rs
// https://www.reddit.com/r/adventofcode/comments/ka8z8x/2020_da... | Rust | 0 |
actuator.volume_to_res_accumulator <= Volume::new::<gallon>(0.0001));
}
#[test]
fn brake_actuator_movement_medium_pressure() {
let mut brake_actuator = BrakeActuator::new(Volume::new::<gallon>(0.04));
brake_actuator.set_position_demand(1.2);
let medium_pressure = Pressure::new::<p... | Rust | 0 |
to select the best mask. For non-ambiguous prompts, such as multiple
input prompts, multimask_output=False can give better results.
return_logits (bool): If true, returns un-thresholded masks logits
instead of a binary mask.
Returns:
(torch.Tensor): The o... | Python | 1 |
cmd: 命令
enter: 是否自动发送
reply: 是否回复
use_cmd_start: 是否使用配置的命令前缀
Returns:
[text](mqqapi://) markdown格式的可点击回调文本,类似于链接
"""
if use_cmd_start:
command_start = get_config("command_start", [])
if command_start:
... | Python | 1 |
import numpy as np
from cpd_nonlin import cpd_nonlin
from cpd_auto import cpd_auto
def gen_data(n, m, d=1):
"""Generates data with change points
n - number of samples
m - number of change-points
WARN: sigma is proportional to m
Returns:
X - data array (n X d)
cps - change-points arr... | Python | 1 |
list()
except Exception as e:
print(f"Warning: Could not save NPU output sample in error case: {e}")
json.dump(json_result, f, indent=2)
print(f"\n=== Demo Failed ===")
print(f"Failed at: {step_name}")
... | Python | 1 |
,
workload_uri: String,
) -> Self {
CredentialProviderSettings {
iothub_hostname,
gateway_hostname,
device_id,
module_id,
generation_id,
workload_uri,
}
}
pub fn iothub_hostname(&self) -> &str {
&self.io... | Rust | 0 |
test]
fn test_push_path() {
macro_rules! t(
(s: $path:expr, $push:expr, $exp:expr) => (
{
let mut p = Path::new($path);
let push = Path::new($push);
p.push(&push);
assert_eq!(p.as_str(), Some($exp));
... | Rust | 0 |
town = [['C', 'D', 'A'], ['B', 'M', 'Z'], ['Q', 'P', 'O']]
Black_list = list(map(str, input()))
lst = [0]*26
count = 0
for i in range(3):
for j in range(3):
lst[ord(town[i][j])-65] += 1
for i in range(4):
for j in range(26):
if lst[j] != 0 and j == ord(Black_list[i]) - 65:
count +... | Python | 1 |
rocesslist = childslist + currentprocesslist
return currentprocesslist
def obtain_subprocesses_from_main_process(idprocess):
argsfinal = []
finalprocesslist = list()
p = subprocess.Popen("ps -ef | grep " + str(idprocess), shell=True, stdout=subprocess.PIPE)
out = p.communicate()[0]
args = out... | Python | 1 |
}
}
/// Get latest trades.
///
/// 1000 trades are returned.
///
/// For example: <https://www.mxc.co/open/api/v2/market/deals?symbol=BTC_USDT&limit=1000>
#[allow(non_snake_case)]
pub fn fetch_trades(symbol: &str) -> Result<String> {
gen_api!(format!(
"/open/api/v... | Rust | 0 |
// Instruction to set the buffer onto the IdlAccount.
let set_buffer_ix = {
let accounts = vec![
AccountMeta::new(buffer, false),
AccountMeta::new(IdlAccount::address(&program_id), false),
AccountMeta::new(keypair.pubkey(), true),
... | Rust | 0 |
c");
println!("cargo:rustc-link-search={}", dir.to_str().unwrap());
}
<reponame>hsyoi/Ana
use std::time::Duration;
use crate::judge;
use crate::workspace;
tonic::include_proto!("ana_rpc");
impl From<judge::Report> for Report {
fn from(report: judge::Report) -> Report {
Report {
result: se... | Rust | 0 |
# Messing with CSV (2)
# Author: Marcin Kaminski
import csv
mydict =[{'first': 'Andrew', 'last': 'Beatty', 'age':'2'},
{'first': 'joe', 'last': 'Bloggs', 'age':'22'},
{'first': 'Mary', 'last': 'mc', 'age':'2222'}
]
# field names
fields = ['first', 'last', 'age']
# name of csv f... | Python | 1 |
ed_bike: hex("#90BE6D"),
unzoomed_bus: hex("#FFD166"),
unzoomed_pedestrian: hex("#457B9D"),
// Agents
agent_colors: vec![
hex("#5C45A0"),
hex("#3E8BC3"),
hex("#E1BA13"),
hex("#96322F"),
hex("... | Rust | 0 |
from ._internal import functions
fibonacci = functions.fibonacci
check_positive = functions.check_positive
| Python | 1 |
rs
}
fn get_char_diff(from_str: &String, to_str: &String) -> Option<(Vec<char>, Vec<char>)> {
let from_chars = get_chars_sorted(from_str);
let to_chars = get_chars_sorted(to_str);
if from_chars == to_chars {
return None;
}
let mut chars_missing: Vec<char> = vec![];
let mut chars_lefto... | Rust | 0 |
ns = None
DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\rWrappersProtoP\001Z1google.golang.org/protobuf/types/known/wrapperspb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes'
_DOUBLEVALUE._serialized_start=51
_DOUBLEVALUE._serialized_end=79
_FLOATVALUE._serialized_start=81
... | Python | 1 |
_ => Err(BadDiskImageStatus(response.status, response.failure_reason).into()),
}
}
fn parse_disk_op_status(
&mut self,
response: DiskImageStatusResponse,
op_type: DiskOpType,
) -> Result<(bool, u32), Box<dyn Error>> {
let expected_status = match op_type {
... | Rust | 0 |
if share_plugin and share_plugin.is_complete:
share_record.delete()
PluginShareRecordEvent.objects.filter(record_id=share_record.ID).delete()
share_plugin.delete()
return Response(general_message(200, msg='', msg_show=''), 200)
PluginShareRecordEvent.objects.fi... | Python | 1 |
str_ = re.sub(r"\{[^{}]*?\}", formating, str_)
return str_
class Image:
@staticmethod
def solve_slide(slide_img: str, canvas_img: str) -> dict:
"""
滑块验证码解析
:param slide_img, canvas_img: base64编码的图片
:return dict: {
"slide": 滑行像素,
"canvas": 背景总长... | Python | 1 |
) {
let arr: Box<Buff> = std::mem::transmute(x);
std::mem::drop(CString::from_raw(arr.url as *mut c_char));
std::mem::drop(CString::from_raw(arr.tips as *mut c_char));
std::mem::drop(CString::from_raw(arr.come as *mut c_char));
}
#[no_mangle]
pub unsafe extern "cdecl" fn free_mintmark_list(x: *const c_... | Rust | 0 |
output.push(payload);
offset += mtu;
}
let payload = Vec::from(&payload[offset..]);
output.push(payload);
Some(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::RngCore;
const LENGTH: usize = 10000;
const MTU: usize = 1500;
#[test]... | Rust | 0 |
scharge Time Register"]
pub dvbusdis: crate::Reg<dvbusdis::DVBUSDIS_SPEC>,
#[doc = "0x82c - Device VBUS Pulsing Time Register"]
pub dvbuspulse: crate::Reg<dvbuspulse::DVBUSPULSE_SPEC>,
_reserved38: [u8; 0x04],
#[doc = "0x834 - Device IN Endpoint FIFO Empty Interrupt Mask Register"]
pub diepempms... | Rust | 0 |
e matched PathStats, and filter paths that are ignored by local excludes.
// Context ("global") ignore patterns are applied during `scandir`.
if exclude.is_ignored(&stat) {
future::ok(None).to_boxed()
} else {
match stat {
Stat:... | Rust | 0 |
use crate::agent::RouterState;
/// Any state that can be managed by the `Router` must meet the criteria of this trait.
pub trait YewRouterState<'de>: RouterState<'de> + PartialEq {}
impl<'de, T> YewRouterState<'de> for T where T: RouterState<'de> + PartialEq {}
<reponame>smilix/running2
mod routes;
mod models;
pub... | Rust | 0 |
5., 66.)
/// ));
///
/// let expected = Bone::Matrix(Matrix4::new_rotation_wrt_point(
/// axis_angle,
/// Point3::new(40., 50., 60.)
/// ));
///
/// assert_eq!(child.relative_to_parent(parent), expected);
/// ```
pub fn relative_to_parent(&self, parent_bone: Bone) -> Bone {
... | Rust | 0 |
Hocon::BadValue(
super::Error::Include {
path: String::from("https://raw.githubusercontent.com/mockersf/hocon.rs/master/tests/data/basic.conf")
}
)
);
}
}
<filename>model/src/invite/target_type.rs
use serde_repr::{Deserialize_repr,... | Rust | 0 |
from toee import *
# Gets the weapon in the left hand.
# This can be one of the following:
#
# 1. A weapon in the 'secondary' slot
# 2. A shield that allows bashing
# 3. A double wepaon in the 'primary' slot
def getLeftWeapon(attacker):
left = attacker.item_worn_at(item_wear_weapon_secondary)
if left == OB... | Python | 1 |
target_filter = None
if cross_site_action in ["compare_fields", "copy_fields"]:
source_filter = source_config.get('channel_filter')
target_filter = target_config.get('channel_filter')
if not source_filter or not target_filter:
raise Value... | Python | 1 |
locks[i].fill(0x7878787878787878); }
// repair
gf2p64_raid7::repair(&mut blocks, &mut p, &mut q, &mut r, &[i]).unwrap();
assert_eq!(&blocks[0], &(10..20).collect::<Vec<u64>>());
assert_eq!(&blocks[1], &(20..30).collect::<Vec<u64>>());
assert_eq!(&blocks[2], &(... | Rust | 0 |
c::new(menu),
size: info.size,
pos: info.pos,
}
}
pub fn info(&self) -> WindowInfo {
let mut active_tab = 0;
let workspaces: Vec<LapceWorkspace> = self
.tabs_order
.iter()
.enumerate()
.map(|(i, w)| {
... | Rust | 0 |
nager( mode=True, query=True )[0] == 'parallel' )
self.unit_test.assertTrue( cmds.pluginInfo('cacheEvaluator', loaded=True, query=True) )
self.unit_test.assertTrue( cmds.evaluator( query=True, en=True, name='cache' ) )
def checkValidFrames(self, expected_valid_frames, layers_mask = 0b01):
'... | Python | 1 |
ake");
if !output.status.success() {
std::io::stderr().write_all(&output.stderr).unwrap();
panic!("PARI: failed to ‘make install-nodata’");
}
}
{
let output = Command::new("make")
.arg("install-lib-sta")
.current_dir(pari_dir)
... | Rust | 0 |
elf {
LimitExpression { row_count }
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub(crate) enum Ordering {
Asc,
Desc,
}
impl FromStr for Ordering {
type Err = String;
fn from_str(s: &str) -> result::Result<Self, Self::Err> {
match s {
"asc" => Ok(Ordering::Asc),
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
streaming_service property
"""
from rebulk.remodule import re
from rebulk import Rebulk
from rebulk.rules import Rule, RemoveMatch
from ..common.pattern import is_disabled
from ...config import load_config_patterns
from ...rules.common import seps, dash
from ...rules.... | Python | 1 |
un normally
if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
LOGGER.warning(f"WARNING ⚠️ confidence threshold {opt.conf_thres} > 0.001 produces invalid results")
if opt.save_hybrid:
LOGGER.warning("WARNING ⚠️ --save-hybrid returns high mAP from hybr... | Python | 1 |
{
config::{Config, ServerConfig},
crypto::CipherType,
relay::{
socks5::{Address, UdpAssociateHeader},
tcprelay::client::Socks5Client,
},
run_local,
run_server,
};
const SERVER_ADDR: &'static str = "127.0.0.1:8093";
const LOCAL_ADDR: &'static str = "127.0.0.1:8291";
const UDP_EC... | Rust | 0 |
i], word ptr es:[edi]")()
CheckInstr(CmpsD, expected_result="cmpsd dword ptr [esi], dword ptr es:[edi]")()
CheckInstr(x86.Test)('EAX', 'EAX')
CheckInstr(x86.Test, expected_result="test edi, ecx")('ECX', 'EDI')
CheckInstr(x86.Test)(mem('[ECX + 0x100]'), 'ECX')
CheckInstr(x86.Test)('EAX', 0x11223344... | Python | 1 |
I64(i));
}
}
if cftype.type_of() == CFBoolean::type_id() {
return Ok(Value::Boolean(raw == mem::transmute(kCFBooleanTrue)));
}
cftype.show();
Err("unknown value")?
}
}
fn device_read_value(dev: *const am_device, key: &str) -> Result<Option<Value>> {
... | Rust | 0 |
#!/usr/bin/env python
# Runs an HTTP server on localhost:8000 which will serve the generated OpenAPI
# JSON so that it can be viewed in an online OpenAPI viewer.
# Copyright 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... | Python | 1 |
"""Optional third-party dependency imports for environment extractor modules."""
from __future__ import annotations
from typing import Callable
class MissingDependencyError(ImportError):
"""Raised when the required optional scientific python stack is missing."""
ERROR_MESSAGE = "错误:需要scipy和scikit-image库。请运行 '... | Python | 1 |
while j + 1 < len(temp_tempos) and temp_tempos[j + 1] == bpm:
j += 1
if bpm == 0:
bpm = DEFAULT_TEMPO
tempos.append(miditoolkit.midi.containers.TempoChange(bpm, acc_tick))
acc_tick += int((j - last_i + 1) * ticks_per_second / rate)
last_i = j
i = j... | Python | 1 |
if n not in schemas and schemas != ('*',):
continue
# Fetch table column details & foreign key details for each schema using parameterized queries
logger.info(f'Processing schema: {n}')
column_details = query_database(conn, GET_ALL_PUBLIC_TABLES_AN... | Python | 1 |
}
#[cfg(test)]
mod tests {
use super::*;
const FILE: &str = "inputs/day13_input_test.txt";
#[test]
fn day13_part1_test() {
let (points, folds) = parse_manual_instructions(FILE);
let mut grid = build_grid(&points);
assert_eq!(fold_page_once(&mut grid, folds[0]), 17);
... | Rust | 0 |
ES_AUTOPOWEROFF_COMMAND
message[9] = power_off_interval
await self.send_command(message)
async def set_water_hardness(self, hardness_level) -> None:
"""Set water hardness"""
message = BYTES_WATER_HARDNESS_COMMAND
message[9] = hardness_level
await self.send_command(me... | Python | 1 |
# Task 1: Load and Explore the Dataset
# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load the dataset (replace with your CSV path)
df = pd.read_csv('iris.csv')
# Display first few rows
print("First 5 rows of the dataset:")
print(df.head())
# Explore struct... | Python | 1 |
axes[i, 3].text(
3, 40, f'{tag} ROI ({perf})',
fontsize=fontsize,
bbox={'facecolor': 'white', 'pad': 1, 'alpha': 0.8,
'edgecolor': 'none'}
)
if masked_img is not None:
axes[i, 4].imshow(mas... | Python | 1 |
rms.CharField(label=_("pagepath"), required=False)
class Meta(object):
model = Menu
fields = ("name", "menuid", "type", "weight")
def allowed_fields(self, type, cleaned_data):
if type == Menu.Event.VIEW:
fields = ("url", )
elif type == Me... | Python | 1 |
"RDS": "Amazon RDS",
"S3": "Amazon S3",
"Redshift": "Amazon Redshift",
"Kafka": "Amazon MSK (Kafka)",
"Cognito": "AWS Cognito",
"CloudWatch": "AWS CloudWatch",
"WAF": "AWS WAF"
}
return mapping.get(component, component)
# ------------------ Cloud Prompt Generat... | Python | 1 |
"""Basic Inkycal run script.
Assumes that the settings.json file is in the /boot directory.
set render=True to render the display, set render=False to only run the modules.
"""
import asyncio
from inkycal import Inkycal
async def run():
"""Run Inkycal nonstop. Default mode."""
# create an instance of Inkyca... | Python | 1 |
import sys
from functools import lru_cache
from typing import Iterator, List, Tuple, Dict, Optional
dp = {}
for power in range(31):
# key is the number that we can achieve on this level
# value is if the current power of 2 is included to the sum for this key
# or not
if power == 0:
dp[power] =... | Python | 1 |
level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT. No part of simple-http-server, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2018 The deve... | Rust | 0 |
_ref().to_str().unwrap();
let device = &uefi_dev[..uefi_dev.len() - 1];
let partition = &uefi_dev[uefi_dev.len() - 1..];
CallError::from_res(Command::new("/usr/bin/efibootmgr").args(&[
"-c", "-w", "-L", name, "-d", device, "-p", partition, "-l", path
]).status())?;
Ok... | Rust | 0 |
Ok(server_time)
}
/// Obtain exchange information (rate limits, symbol metadata etc)
pub async fn exchange_info(&self) -> Result<ExchangeInformation> {
let data: String = self.client.get("/api/v3/exchangeInfo", "").await?;
let info: ExchangeInformation = from_str(data.as_str())?;
... | Rust | 0 |
#
# basicRAT survey module
# https://github.com/vesche/basicRAT
#
import ctypes
import getpass
import os
import platform
import socket
import time
import urllib
import uuid
SURVEY_FORMAT = '''
System Platform - {}
Processor - {}
Architecture - {}
Internal IP - {}
External IP - {}... | Python | 1 |
assets } => to_binary(&query_get_balances(deps, env, assets)?),
}
}
fn query_get_config(deps: Deps) -> StdResult<ConfigResponse> {
let config = CONFIG.load(deps.storage)?;
Ok(ConfigResponse {
owner: config.owner,
factory_contract: config.factory_contract,
staking_contract: config.s... | Rust | 0 |
{
match self {
NumLitState::Unspecified
| NumLitState::Float(FloatBits::Unspecified)
| NumLitState::Float(FloatBits::ThirtyTwo) => {
NumLitState::Float(FloatBits::ThirtyTwo)
}
_ => NumLitState::Err, // TODO emit diagnostic
}
}
pub fn float_64(self) -> Self {
match... | Rust | 0 |
std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// <p>Name of the resource that exceeds maximum number of tags allowed.</p>
pub fn resource_name(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_name = ... | Rust | 0 |
element header");
assert_eq!(header.tag(), Tag(0x0008, 0x1150));
assert_eq!(header.vr(), VR::UI);
assert_eq!(header.length(), Length(26));
assert_eq!(decoder.position(), 56);
let value = decoder
.read_value(&header)
.expect("should find a value after el... | Rust | 0 |
#take i/p from user and display its type
a=input('enter the string: ')
b=int(input('enter integer: '))
c=float(input('enter floating point value: '))
print(type(a),type(b),type(c)) | Python | 1 |
.key.clone());
}
}
// 层序遍历
pub fn level_order(root: &Link<K, V>, buf: &mut Vec<K>) {
let mut queue = VecDeque::new();
if let Some(node) = root {
queue.push_back(node);
}
while !queue.is_empty() {
if let Some(node) = queue.pop_front() {
... | Rust | 0 |
")]
pub struct PostUnfollow<'a> {
#[serde(skip_serializing)]
#[mastors(connection)]
conn: &'a Connection,
#[serde(skip_serializing)]
#[mastors(path_param)]
id: String,
#[serde(skip_serializing)]
#[mastors(authorization)]
authorized: bool,
}
impl<'a... | Rust | 0 |
= "strategic": # GRE风格
return self._create_gre_style_question(index, difficulty_config, language, subject)
elif difficulty_type == "business_analytical": # GMAT风格
return self._create_gmat_style_question(index, difficulty_config, language, subject)
elif difficulty_type == "theor... | Python | 1 |
from __future__ import with_statement
import unittest
from sikuli import *
class TestBasic(unittest.TestCase):
def testImport(self):
from sikuli import Region
#
# @unittest.skip("a known bug. with Region doesn't work in modules.")
# def testWith(self):
# bound = getROI()
# self.assertEqual(bound... | Python | 1 |
ays)]
pub fn is_clk_out_sel_0(&self) -> bool {
*self == CLK_OUT_SEL_A::CLK_OUT_SEL_0
}
#[doc = "Checks if the value of the field is `CLK_OUT_SEL_1`"]
#[inline(always)]
pub fn is_clk_out_sel_1(&self) -> bool {
*self == CLK_OUT_SEL_A::CLK_OUT_SEL_1
}
}
#[doc = "Write proxy for fiel... | Rust | 0 |
class Employee:
def __init__(self, name):
self.__name = name # Private Variable
self.tech = ['C++', 'Java', 'J2EE', 'Spring', 'Hibernate', 'Angular JS', 'React JS']
def __str__(self):
return self.__name + " - " + ", ".join([str(v) for v in self.tech])
emp1 = Employee('Miche... | Python | 1 |
pt(model, args.path)
else:
model = RAFT.from_pretrained(args.url, args=args)
if args.device == 'cuda':
device = torch.device('cuda')
else:
device = torch.device('cpu')
model = model.to(device)
... | Python | 1 |
fsck_error(desc, parents, log, format_args!("invalid file section (offset={}, size={}): overlaps the header", desc.section.offset, desc.section.size));
success = false;
}
// File section larger than the PAK file
if desc.section.size > high_mark {
fsck_error(desc, parents, log, format_args!("inval... | Rust | 0 |
from django.contrib import admin
from appointments.models import Appointment
# Register your models here.
admin.site.register(Appointment) | Python | 1 |
fn get_progress(&self, tag: Type, list: &crate::tasks::List, current: &str) -> (u32, u32) {
list.tasks
.iter()
.filter(|x| {
for tag in self.get_tags(tag, x) {
if tag == current || tag.starts_with(format!("{}-", current).as_str()) {
... | Rust | 0 |
import datetime
### LISTAS QUE IRÃO GUARDAR OS LIVROS DISPONÍVEIS E OS LIVROS ALUGADOS
lista_de_livros = []
lista_de_livros_alugados = []
###FUNÇÃO PARA LISTAR OS LIVROS DISPONÍVEIS
def listar_livros():
print('\nLISTA DE LIVROS')
print('=' * 100)
if not lista_de_livros:
print('-> Lista vazia.'... | Python | 1 |
(Ray::new(hit.p, hit.normal));
self
}
}
impl Default for BSDFResult {
fn default() -> Self {
BSDFResult {
diffuse: Color::zero(),
emissive: Color::zero(),
bounce: None,
}
}
}
///////////////////////
// Material
/**
Describes color of light after it hits the surface. And some other... | Rust | 0 |
# Copyright (c) 2024, Shanghai Iluvatar CoreX Semiconductor Co., Ltd.
# 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/license... | Python | 1 |
import logging
from galaxy.util.bunch import Bunch
log = logging.getLogger(__name__)
class RepositoryGridFilterManager:
"""Provides filtered views of the many Tool SHed repository grids."""
filters = Bunch(
CERTIFIED_LEVEL_ONE="certified_level_one",
CERTIFIED_LEVEL_TWO="certified_level_two"... | Python | 1 |
str!("../tests/expected_outputs/single_switch/config.rs"),
arg_parse_error: include_str!("../tests/expected_outputs/single_switch/arg_parse_error.rs"),
};
pub const EXPECTED_SHORT_SWITCHES: ExpectedOutput = ExpectedOutput {
raw_config: include_str!("../tests/expected_outputs/short_switches/raw_... | Rust | 0 |
s:position!() ("true" / "⊤") e:position!() { Spn::new(true, (s, e)) }
/ s:position!() ("false" / "⊥") e:position!() { Spn::new(false, (s, e)) }
/// Recognizes numbers: `0` and `[1-9][0-9]*`.
///
/// # Examples
///
/// ```rust
/// # use mikino_api::parse::rules::... | Rust | 0 |
= "certificate":
parameters["CertificateBody"] = contents
elif key == "private_key":
parameters["PrivateKey"] = contents
elif key == "chain":
parameters["CertificateChain"] = contents
if parameters and "cert_name" in kwargs:
parameters["ServerCertificateN... | Python | 1 |
else:
print(f"Validation Acc: {epoch_acc}, Loss: {epoch_loss}")
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
torch.save(model.state_dict(), best_model_params_path)
print()
time_elapsed = time.time() - since
print(f'Trai... | Python | 1 |
ers)") # Log output size
time.sleep(45)
print(Style.RESET_ALL, end="") # Reset the color back to normal after the message
# Writing results to CSV
with open(csv_file, mode='a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.