text string | label_name string | labels int64 |
|---|---|---|
#!/usr/bin/env python
"""
Usage: python show_negative_chains.py <path_to_a_saved_DBM.pkl>
Show negative chains of a saved DBM model.
"""
from __future__ import print_function
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-claus... | Python | 1 |
EffectManager> {
return None;
}
}
impl EntityTrait<Context> for Goal {
type State = GoalState;
fn get_base(&self) -> &EntityBase {
return &self.entity_base;
}
fn get_state_history(&self) -> &StateHistory<Self::State> {
return &self.state_history;
}
fn apply_state(&self, state: Self::State)... | Rust | 0 |
'status_message': _('It seems that you either not have the rights to access the shif reports '
'or that you try to access it outside normal circumstances. '
'If you think there is a problem, please contact an administrator.... | Python | 1 |
from setuptools import setup, find_packages
from pathlib import Path
THISDIR = Path(__file__).parent
def read_requirements(fname):
with open(THISDIR / "requirements" / fname, "r") as f:
return f.read().splitlines()
core_required = read_requirements("core.txt")
apps_required = read_requirements("apps.tx... | Python | 1 |
'''tzinfo timezone information for America/Regina.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Regina(DstTzInfo):
'''America/Regina timezone definition. See datetime.tzinfo for details'''
zone = 'America/Regina'
... | Python | 1 |
import pandas as pd
import requests
from bs4 import BeautifulSoup
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=input("Enter OPENAI API Key here: "))
def readJobData(csv_path: str) -> pd.DataFrame:
"""Read CSV containing job postings."""
return pd.rea... | Python | 1 |
"""
Reading files with neo.io
=========================
"""
####################################################
# Start with package import and getting a datafile
import urllib
import neo
url_repo = "https://web.gin.g-node.org/NeuralEnsemble/ephy_testing_data/raw/master/"
# Plexon files
distantfile = url_repo + ... | Python | 1 |
#!/usr/bin/python3
import requests, json
print('\n 1. Login in Odoo and get access tokens:')
r = requests.get(
'http://localhost:8069/api/auth/get_tokens',
headers = {'Content-Type': 'text/html; charset=utf-8'},
data = json.dumps({
'username': 'admin',
'password': 'admin',
}),
#ve... | Python | 1 |
ease get an refresh token",
"error_code": "refresh_token_required",
},
),
)
app.add_exception_handler(
InsufficientPermission,
create_exception_handler(
status_code=status.HTTP_401_UNAUTHORIZED,
initial_detail={
"message... | Python | 1 |
changelog format")
.map_err(|e| vec![LintError::via_display(e)])?;
let mut errors = vec![];
for entry in parsed.aws_sdk_rust.iter().chain(parsed.smithy_rs.iter()) {
if let Err(e) = validate(entry) {
errors.push(LintError::via_display(e))
}
}
if errors.is_empty() {
... | Rust | 0 |
to_string(),
}),
// For other errors, return a 500
_ => default_500(&e),
}
})
}
/// Handles requests to /software_versions for retrieving software_version info by query parameters
///
/// This function is called by Actix-Web when a get request is made to the /software_ve... | Rust | 0 |
# -*- coding: UTF-8 -*-
# date: 30.08.2014 13:39:12
#
LANG_TEXT = {
"de_DE": {
"T1": "Für Sprachauswahl Hoch/Runter-Tasten nutzen. Danach OK drücken.",
"T2": "Sprachauswahl",
"T3": "Abbrechen",
"T4": "Speichern",
},
"ar_AE": {
"T1": "من فضلك أستخدم ذر السهم العلوى أو السفلى لإختيار اللغه. ثم أضغط موافق .",
... | Python | 1 |
Some(target_cfg) = bcx.target_info.cfg() {
if let Some(table) = bcx.config.get_table("target")? {
let mut matching_runner = None;
for key in table.val.keys() {
if CfgExpr::matches_key(key, target_cfg) {
let key = format!("target.{}.runner", key);
... | Rust | 0 |
r(#[from] rusoto_core::RusotoError<rusoto_s3::PutObjectError>),
#[error("uuid parse error: {0:?}")]
UuidParseError(#[from] uuid::Error), /*#[error("pubsub error: {0:?}")]
PubsubError(#[from] pubsub::Error),*/
}
impl ResponseError for ServerError {}
impl ErrorExtensions... | Rust | 0 |
lf.assertEqual(input_tape[0], input_tape[1])
self.assertEqual(input_tape[2], input_tape[3])
# If requested input size isn't a multiple of duplication, go lower
input_tape = env.generate_input_data(3)
self.assertEqual(len(input_tape), 2)
self.assertEqual(input_tape[0], input_tape[... | Python | 1 |
ling_rate_hz': self.fs,
'normalized_frequencies': [self.low, self.high],
'cascade_mode': self.use_cascade,
'highpass_order': self.order // 2,
'lowpass_order': self.order // 2 + 1,
'coefficients_b': self.b.tolist(),
'coefficients_a': self.a.tolist()... | Python | 1 |
### Copyright (C) 2017 NVIDIA Corporation. All rights reserved.
### Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
import torch
def create_model(opt):
from .DSSLIC_model import DSSLICModel
model = DSSLICModel()
model.initialize(opt)
print(... | Python | 1 |
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
create_contract_at_sale_order_confirmation = fields.Boolean(
string="Automatically Create Contracts At Sale Order Con... | Python | 1 |
/join to a string.
let mut s = String::with_capacity(100);
if v.len() > 0 {
s.push_str(v[0].to_string().as_str());
for i in v[1..].into_iter() {
s.push_str(";");
s.push_str(i.to_string().as_str());
... | Rust | 0 |
#!/usr/bin/env python
import argparse
from lirc.lirc import Lirc
from flask import Flask
from flask import render_template
# from flask import request, redirect, url_for
BASE_URL = ''
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Initialise the Lirc config parser
lircParse = Lirc('/etc/lirc/lir... | Python | 1 |
xperimentHandler()
# Try to save data to csv
for encoding in ['utf-8', 'utf-16']:
for asDecimal in range(143859):
# Add each unicode character to the data file
try:
chr(asDecimal).encode(encoding)
except UnicodeEncodeError:
... | Python | 1 |
import os
import plistlib
import tempfile
import unittest
from unittest import mock
import pre_commit_macadmin_hooks.check_plists as target
class TestCheckPlists(unittest.TestCase):
def test_build_argument_parser(self):
parser = target.build_argument_parser()
args = parser.parse_args(["file1.pli... | Python | 1 |
import rio
THEME = rio.Theme.from_colors(
mode="dark",
background_color=rio.Color.from_hex("#111827"),
neutral_color=rio.Color.from_hex("#1f2937"),
heading_fill=rio.Color.from_hex("#ffffff"),
)
# Text on the landing page is unusually large. These constants control the
# landing page styles for it (and... | Python | 1 |
beatmap(&self, id: u64) -> Result<BeatmapContent> {
let content = self
.client
.borrow()
.await?
.get(&format!("https://osu.ppy.sh/osu/{}", id))
.send()
.await?
.bytes()
.await?;
Ok(BeatmapContent {
... | Rust | 0 |
shortFlag == "short":
summary_df = pd.DataFrame(
{
"contig": contig_names,
"length": contig_length,
"mean_depth_short": mean_depth_col,
"sd_depth_short": sd_depth_col,
"q25_depth_short": q25_depth,
"q75_... | Python | 1 |
ics-update] placeholder
text
@error (http-status-code) "404" 404
@error (content) "not-found" The requested fabric is not found.
@error-example "not-found"
No Fabric matches the given query.
"""
fabric = Fabric.objects.get_fabric_or_404(
id, reque... | Python | 1 |
# Copyright (c) 2024 PaddlePaddle 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 appli... | Python | 1 |
import torch
from torch import nn
from transformers.utils import requires_backends, logging, is_timm_available
from transformers.models.auto import AutoBackbone
logger = logging.get_logger(__name__)
if is_timm_available():
from timm import create_model
logger = logging.get_logger(__name__)
class VitDetVision... | Python | 1 |
from collections import deque
def create_graph(tubes):
graph = {}
for i, tube in enumerate(tubes):
content = {}
for ball in tube:
if ball in content:
content[ball] += 1
else:
content[ball] = 1
graph[i] = content
return graph
... | Python | 1 |
rned if the
/// number is exceeded.
///
/// Specify `None` to disable handling redirects. A redirect
/// is not an error, instead you will get a `Response`
/// for the redirect response.
pub fn redirect_limit(mut self, n: Option<usize>) -> Self
{
self.set_redirect_limit(n);
self
}
}
/* automatically generat... | Rust | 0 |
1].g as u16;
let b1: u16 = p[1].b as u16;
if col.c0 > col.c1 {
p[2].r = ((2 * r0 + 1 * r1) / 3) as u8;
p[2].g = ((2 * g0 + 1 * g1) / 3) as u8;
p[2].b = ((2 * b0 + 1 * b1) / 3) as u8;
p[2].a = 0xff;
p[3].r = ((1 * r0 + 2 * r1) / 3) as u8;
p[3].g = ((1 * g0 + 2 * g... | Rust | 0 |
pes.html#numba.typeof",
"numba.types": "https://numba.readthedocs.io/en/stable/reference/types.html",
"numba.types.array": "https://numba.readthedocs.io/en/stable/reference/types.html#numba.types.Array",
"numba.types.npdatetime": "https://numba.readthedocs.io/en/stable/reference/types.html#numba.types.NPDat... | Python | 1 |
&MODULUS
}
}
/// A trait for `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`.
pub trait SignedPrimitive:
Sealed
+ Signed
+ PrimInt
+ Integer
+ Num<FromStrRadixErr = ParseIntError>
+ Bounded
+ FromStr<Err = ParseIntError>
+ FromPrimitive
+ Into<BigInt>
+ Default
+ fmt... | Rust | 0 |
) -> &mut StructType {
if self.struct_type.is_none() {
self.struct_type.set_default();
}
self.struct_type.as_mut().unwrap()
}
// Take field
pub fn take_struct_type(&mut self) -> StructType {
self.struct_type.take().unwrap_or_else(|| StructType::new())
}
}
im... | Rust | 0 |
k_repo_exists::ResponseData>(
&git_account.token,
&git_account.user,
query,
);
Either::B(
response
.map_err(|e| RepoExistsError::ApiError(e))
.and_then(|r| {
println!("{:#?}", r);
Ok(r.repository.is_some())
}),
... | Rust | 0 |
<HString> { unsafe {
let mut out = null_mut();
let hr = ((*self.lpVtbl).get_SignatureAlgorithmName)(self as *const _ as *mut _, &mut out);
if hr == S_OK { Ok(HString::wrap(out)) } else { err(hr) }
}}
#[inline] pub fn get_signature_hash_algorithm_name(&self) -> Result<HString> { unsafe {... | Rust | 0 |
Direct")]
pub mod WiFiDirect;
pub type ILowLevelDevicesAggregateProvider = *mut ::core::ffi::c_void;
pub type LowLevelDevicesAggregateProvider = *mut ::core::ffi::c_void;
pub type LowLevelDevicesController = *mut ::core::ffi::c_void;
//! Constants representing various standard inventory slot indices
//! for the `Player... | Rust | 0 |
ideoFileClip(temp_512_path + '.tmp.mp4')
audio_clip = AudioFileClip(self.save_path)
final_clip = video_clip.set_audio(audio_clip)
final_clip.write_videofile(temp_512_path, codec='libx264', audio_codec='aac')
os.remove(temp_512_path + '.tmp... | Python | 1 |
, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, Throughput,
};
use memmap2::{Mmap, MmapOptions};
use rand::{thread_rng, RngCore};
use tempfile::{tempdir, TempDir};
// Don't use an OS backed tempfile since it might change the performance characteristics of our copy
struct NormalTempFile {
dir: TempDir,
... | Rust | 0 |
import os
import sys
import time
import numpy as np
import random
import yaml
import joblib
import pandas as pd
from datetime import datetime
# ランダムシードの設定
# random.seed(42)
# np.random.seed(42)
# 基本関数
from basis import distance_toa
from basis import target_coordinates
# 特徴量の算出
from feature import distance_error_squa... | Python | 1 |
{
return Err(ProtoError::from("tsig validation error: wrong key"));
}
// 2. Check MAC
let mac = tsig.mac();
if signature.len() < mac.len() || mac != &signature[..mac.len()] {
// tsig might be shorter if truncated, so we check if it is a prefix of the
... | Rust | 0 |
cls, tools: Sequence[BaseTool]) -> None:
validate_tools_single_input(cls.__name__, tools)
if len(tools) == 0:
raise ValueError(
f"Got no tools for {cls.__name__}. At least one tool must be provided."
)
for tool in tools:
if tool.description is ... | Python | 1 |
imicCrimson = 474,
BigMimicHallow = 475,
BigMimicJungle = 476,
Mothron = 477,
MothronEgg = 478,
MothronSpawn = 479,
Medusa = 480,
GreekSkeleton = 481,
GraniteGolem = 482,
GraniteFlyer = 483,
EnchantedNightcrawler = 484,
Grubby = 485,
Sluggy = 486,
Buggy = 487,
TargetDummy = 488,
BloodZombi... | Rust | 0 |
ption<&'a str>,
pub group: Option<&'a str>,
pub disabled: Option<bool>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, diesel::Queryable, diesel::Insertable)]
pub struct Theme {
/// The channel the theme belongs to.
pub channel: String,
/// The name of the theme.
pub name: String,
/// If... | Rust | 0 |
rite_signal(
tmp_filename,
signal,
sample_rate=int(sample_rate), # <-- Sample rate needs to be cast to int
floating_point=False,
strict=True,
)
# Correct number of channels - will read OK
read_signal(tmp_filename, sample_rate=16000, n_channels=2)
# Incorrect nu... | Python | 1 |
iter='ffmpeg', fps=self.fps, dpi=300)
# plt.show()
""" ---------------------- Private Helper Methods --------------------- """
@staticmethod
def __draw_formula(ax):
formula = r"$h_{G}=\frac{1}{|\mathcal{V}|} \sum_{v \in \mathcal{V}} \frac{ | \{ (w,v) : w \in \mathcal{N}(v) \wedge y_v = y... | Python | 1 |
ico numéricas
academic_vars = [var for var in ACADEMIC_VARS if 'PUNT' in var]
# Realizar PCA
pca, X_pca, explained_variance, loadings = perform_pca(df, academic_vars)
# Generar y guardar gráficos
os.makedirs(FIGURES_DIR, exist_ok=True)
# Scree plot
scree_file = FIGURES_DIR / '... | Python | 1 |
connector: &Connector,
credentials: &Credentials,
) -> Result<Self, session::Error> {
let host_challenge = Challenge::new();
let command_message = command::Message::from(&CreateSessionCommand {
authentication_key_id: credentials.authentication_key_id,
host_challenge,... | Rust | 0 |
DEFAULT,
// This config leverages default fields but uses the same PeerId and secondary files as
// the random.complete.node.config.toml. It verifies the assumptions about loading
// files even if the paths aren't present
RANDOM_DEFAULT,
// This config explic... | Rust | 0 |
jAnnotationFeature(
feature_id=feature_id,
record_id=record_id,
display_name=display_name,
gene_name=gene_name,
region_type=region_type,
chain_type=chain_type,
chain=chain,
isotype=isotype,
allele_name=allele_nam... | Python | 1 |
sfer_nft(deps, env, info, recipient, token_id),
ExecuteMsg::SendNft {
contract,
token_id,
msg,
} => execute_send_nft(deps, env, info, contract, token_id, msg),
}
}
pub fn execute_mint(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: MintMsg,
... | Rust | 0 |
fn bench_stream_aggr_count_1_group_by_decimal_col(b: &mut criterion::Bencher, input: &Input) {
let fb = FixtureBuilder::new(input.src_rows).push_column_decimal_0_n();
let group_by = vec![ExprDefBuilder::column_ref(0, FieldTypeTp::NewDecimal).build()];
let expr = ExprDefBuilder::aggr_func(ExprType::Count, Fi... | Rust | 0 |
RITE_POLICY_VALID: u32 = 32;
pub const ACPI_PPTT_LINE_SIZE_VALID: u32 = 64;
pub const ACPI_PPTT_CACHE_ID_VALID: u32 = 128;
pub const ACPI_PPTT_MASK_ALLOCATION_TYPE: u32 = 3;
pub const ACPI_PPTT_MASK_CACHE_TYPE: u32 = 12;
pub const ACPI_PPTT_MASK_WRITE_POLICY: u32 = 16;
pub const ACPI_PPTT_CACHE_READ_ALLOCATE: u32 = 0;
... | Rust | 0 |
ure="ble-gatt-client")]
raw::BLE_GATTC_EVTS_BLE_GATTC_EVT_HVX => gatt_client::on_hvx(ble_evt, get_union_field(ble_evt, &evt.evt.gattc_evt)),
#[cfg(feature="ble-gatt-client")]
raw::BLE_GATTC_EVTS_BLE_GATTC_EVT_EXCHANGE_MTU_RSP => gatt_client::on_exchange_mtu_rsp(ble_evt, get_union_field(ble_evt, ... | Rust | 0 |
ice(),
&self.metadata.iv[..],
&key[..],
)?;
let meta_content: Vec<String> = bincode::deserialize(metadata.as_slice())?;
for (index, meta_entry) in meta_content.iter().enumerate() {
if meta_entry == name {
let entry = &self.entries[index];
... | Rust | 0 |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from moveit_msgs.msg import DisplayRobotState
from moveit_msgs.srv import GetPositionIK, GetPositionIKRequest
from sensor_msgs.msg import JointState
class InteractiveMarkerControl:
def __init__(self):
rospy.init_node('interactive... | Python | 1 |
&mut Vec<Vec<u8>>) {
for (k, node) in c.iter() {
cv.push(*k);
if node.val.is_some() {
results.push(cv.clone());
}
Self::collect(&node.children, cv, results);
cv.pop();
}
}
// fn _collect_match_pattern(
// p: &NodePtr<T>,
// pattern: &[u8],
// cv: &mut Vec<u8>,
// results: &mut Vec<Ve... | Rust | 0 |
from typing import Any, Dict, List, Optional, Sequence, Tuple
from llama_index.legacy.core.llms.types import ChatMessage, MessageRole
from llama_index.legacy.llms.generic_utils import get_from_param_or_env
DEFAULT_ANYSCALE_API_BASE = "https://api.endpoints.anyscale.com/v1"
DEFAULT_ANYSCALE_API_VERSION = ""
LLAMA_MOD... | Python | 1 |
err", "world")
.assert()
.stderr(predicate::str::similar("world\n"));
Command::cargo_bin("bin_fixture")
.unwrap()
.env("stdout", "hello")
.env("stderr", "world")
.assert()
.stderr(b"world\n" as &[u8]);
Command::cargo_bin("bin_fixture")
.unwrap()
... | Rust | 0 |
"data"
///
/// # Parameters
/// - ocf: Opcode Command Field
/// - ogf: Opcode Group Field
/// - packed_data: The packed structure of the return parameter as sent by the controller.
/// - data: The type to convert the packed_data from.
/// - This type must implement the function 'try_from' in some fation (but this ma... | Rust | 0 |
bold(),
);
}
}
SnapshotUpdate::NewFile => {
if let Some(ref snapshot_file) = self.snapshot_file {
let mut new_path = snapshot_file.to_path_buf();
new_path.set_extension("snap.new");
ne... | Rust | 0 |
args.$subc_flag = self.$subc_flag;
)*
$(
args.$subc_arg = if_option!(
$($subc_arg_type_tt)+,
THEN { self.$subc_arg.or($subc_arg_default) }
ELSE { self.$subc_arg.unwrap_or($subc_arg_default.into()) }
);
)*
)*
$(
$(
args.$flag = self.$flag || $flag_from... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017, 2018 Guenter Bartsch
#
# 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... | Python | 1 |
(&self) -> bool {
match self {
FSM::Executing(_) => true,
_ => false,
}
}
pub fn to_commit(&self) -> bool {
match self {
FSM::Empty => false,
FSM::Setup => false,
FSM::Executing(to_commit) => *to_commit,
FSM::Paused(... | Rust | 0 |
let mut list = ReversibleList::empty();
assert_eq!(collect(&list, &arena), vec![]);
list.push_front(&mut arena, 1);
assert_eq!(collect(&list, &arena), vec![1]);
list.push_front(&mut arena, 2);
list.push_front(&mut arena, 3);
assert_eq!(collect(&list, &arena), vec![3, 2, 1]);
list.reverse(&m... | Rust | 0 |
import RPi.GPIO as GPIO
import time
import os
import glob
SMOKE_PIN = 17
# These two lines mount the device:
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
# Get all the filenames beginning with 28 in the path base_dir.
device_folder_list = glob.glob(base_dir + '28*... | Python | 1 |
e51c, 0x4f6e3257],
iv: [0xd407301c, 0xfa29af85, 0x25981c17],
pt: &hex!("a6c9e0f248f07a3046ece12125666921"),
aad: &hex!("10e72efe048648d40139477a2016f8ce"),
ct: &hex!("1be9359a543fd7ec3c4bc6f3c9395e89"),
tag: [0xe2e9c07d, 0x4c3c10a6, 0x137ca433, 0xda42f9a8],
},
Gcm {
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. 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 requir... | Python | 1 |
|prop| prop.extract(request.metadata()));
tracing::Span::current().set_parent(parent_cx);
let name = request.into_inner().name;
expensive_fn(format!("Got name: {:?}", name));
// Return an instance of type HelloReply
let reply = hello_world::HelloReply {
message: for... | Rust | 0 |
trainer, env=env, agents=agent)
# start training
trainer.train()
# # ---------------------------------------------------------
# # comment the code above: `trainer.train()`, and...
# # uncomment the following lines to evaluate a trained agent
# # ---------------------------------------------------------
# from skrl.... | Python | 1 |
result)
}
pub fn base_url(&self) -> Result<Url, IncompatibleSourceSettingsError> {
let url = Url::parse(
format!(
"{}://{}:{}/",
self.job_manager_uri_scheme, self.job_manager_host, self.job_manager_port
)
.as_str(),
)?;
... | Rust | 0 |
# Copyright 2024 The HuggingFace Inc. team. 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 appl... | Python | 1 |
import cv2
import sys
print(sys.argv[0])
print('A demo program of WeChat QRCode Detector:')
camIdx = -1
if len(sys.argv) > 1:
if sys.argv[1] == "-camera":
camIdx = int(sys.argv[2]) if len(sys.argv)>2 else 0
img = cv2.imread(sys.argv[1])
else:
print(" Usage: " + sys.argv[0] + " <input_image>")
... | Python | 1 |
const MPG123_ENC_16 = 0x0040;
const MPG123_ENC_24 = 0x4000;
const MPG123_ENC_32 = 0x0100;
const MPG123_ENC_SIGNED = 0x0080;
const MPG123_ENC_FLOAT = 0x0e00;
const MPG123_ENC_SIGNED_16 = Self::MPG123_ENC_16.bits
... | Rust | 0 |
)
})
.collect();
let aliased_rule_variants: Vec<_> =
alias_map.iter().map(|(tgt, _)| tgt.clone()).collect();
let shortcut_branches: Vec<_> = alias_map
.iter()
.flat_map(|(_tgt, srcs)| srcs)
.map(|AliasSrc { ident, is_shortcut }| {
quote!(
... | Rust | 0 |
,
slot_duration,
initial_delay,
sync_delay,
)),
_ => Box::new(Err("Invalid strategy".into()).into_future()),
}
}
/// Verify one node added after `initial_delay` epochs is in sync
/// after `sync_delay` epochs.
pub fn verify_one_node_sync<E: EthSpec>(
network:... | Rust | 0 |
es());
vm.Walk(3);
true
}
pub fn Divide(vm: &mut Machine) -> bool {
let payload = Payload::GetThreeRegisters(vm);
let a = u32::from_be_bytes(vm.registry.Get(payload.1));
let b = u32::from_be_bytes(vm.registry.Get(payload.2));
vm.registry.Set(payload.0, (a * b).to_be_bytes());
vm.Walk(3);... | Rust | 0 |
from rest_framework import serializers
from lms.models import Course, Lesson, Subscription
from lms.validators import validate_youtube_url
class LessonSerializer(serializers.ModelSerializer):
video = serializers.URLField(validators=[validate_youtube_url])
class Meta:
model = Lesson
fields = ... | Python | 1 |
#!/usr/bin/env python3
"""
Draft Management Workflow Examples
This file demonstrates how to use create_draft and export_drafts tools
in Coze workflows, showcasing the UUID-based draft management system.
"""
import json
def example_basic_workflow():
"""Example: Basic draft creation and export workflow"""
pri... | Python | 1 |
elements into the DOM
//! let body: HtmlElement = body();
//! body.append_child(&h1_1).unwrap();
//! body.append_child(&h1_2).unwrap();
//! body.append_child(&h1_3).unwrap();
//! }
//! // selecting all elements with the class name "active-element"
//! {
//! let elements: Vec<Element> = get_elements... | Rust | 0 |
Ordering::Less => p1 = pos,
Ordering::Equal => return new_fuel.0, // real minimum is between pos and pos+1
}
}
}
/// Computes fuel consumption for pos and pos+1
fn compute_fuel(pos: usize, crabs: &[usize]) -> (usize, usize) {
crabs.iter().fold((0, 0), |x, c| {
(x.0 + c.abs_... | Rust | 0 |
#!/usr/bin/python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import fileinput
import hashlib
import sys
from multiprocessing import Pool
def get_hashes_and_lines(raw_... | Python | 1 |
("1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569", 10).unwrap();
let q_x_0 = BigUint::from_str_radix("352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160", 10).unwrap();
l... | Rust | 0 |
t"]
#[inline(always)]
pub fn variant(&self) -> REGION62_A {
match self.bits {
false => REGION62_A::DISABLED,
true => REGION62_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
... | Rust | 0 |
niform_location),
false,
&projection_matrix,
);
}
#[cfg(feature = "bind_sampler_support")]
if self.gl_version.bind_sampler_support() {
unsafe { gl.bind_sampler(0, None) };
}
#[cfg(feature = "bind_vertex_array_support")]
... | Rust | 0 |
"MustRunAs should mutate request when 'overwrite' is set"
);
let json = jsonpath::select(
res.mutated_object.as_ref().unwrap(),
"$.spec.containers[*].securityContext.runAsUser",
)
.unwrap();
assert_eq!(
json,
vec![1000]... | Rust | 0 |
dump(df)
dump(models)
dump(formats)
for i, fmt in enumerate(formats):
hatch = ""
if fmt == "diff":
color = "#b3e6a8"
label = "Search/replace blocks"
elif fmt == "udiff":
color = "#b3d1e6"
... | Python | 1 |
llect();
assert_eq!(split, ["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
let split: Vec<&str> = data.splitn(4, |c: char| c == ' ').collect();
assert_eq!(split, ["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
// Unicode
let split: Vec<&str> = data.splitn(4, 'ä').collect();
asser... | Rust | 0 |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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... | Python | 1 |
class Premise:
"""前提id"""
DEBUG_MODE_SETTING_ON = "debug_mode_setting_on"
""" 系统状态 设置里可以开启debug模式 """
DEBUG_MODE_ON = "debug_mode_on"
""" 系统状态 现在是debug模式 """
DEBUG_MODE_OFF = "debug_mode_off"
""" 系统状态 现在不是debug模式 """
IS_H = "is_h"
""" 系统状态 当前玩家或玩家交互对象为H模式 """
NOT_H = "not_h"
... | Python | 1 |
.0 {
DocBase::Beside(_, ref mut rest) => {
match *other.0 {
DocBase::Beside(_, _) => {
let other = *other.0;
match other {
DocBase::Beside(o_first, o_rest) => {
res... | Rust | 0 |
:Bencher) {
let mut buf = crate::random_image(test::black_box(1_000_000));
let darkness = test::black_box(8);
b.iter(|| darken(&mut buf, darkness));
}
<filename>src/lib.rs
pub mod routes;
pub mod db;
<reponame>stonebanks/sendsecure-rs<filename>src/json_objects/response/mod.rs
pub mod success;
use derive_u... | Rust | 0 |
.print(&mut ctx), "a=2".to_string());
}
#[test]
fn graph_attr_test() {
let mut ctx = PrinterContext::default();
let n_attr = GraphAttributes::Node(vec![attr!("a",2), attr!("b",3)]);
assert_eq!(n_attr.print(&mut ctx), "node[a=2,b=3]".to_string());
}
#[test]
fn subgraph_t... | Rust | 0 |
#!/usr/bin/python3
"""
Copyright (c) 2025 Mateusz Stadnik
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, m... | Python | 1 |
from manim import *
class ObjectManipulation(Scene):
def construct(self):
square = Square(side_length=1, color=ORANGE)
self.play(Create(square), run_time=1)
self.play(square.animate.move_to(np.array([2, 1, 0])), run_time=1)
self.play(square.animate.scale(1.5), run_time=1)
se... | Python | 1 |
female: Vec<Item>,
}
#[derive(Debug, Deserialize)]
struct Data {
first_name: FirstName,
last_name: Vec<Item>,
}
lazy_static! {
static ref DATA: Data = serde_yaml::from_str(include_str!("data/names.yml")).unwrap();
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Gender {
Male,
Female,
}
impl fmt::Display... | Rust | 0 |
: &Selector) -> SassResult<Value> {
args.max_args(2)?;
let color = match arg!(args, scope, super_selector, 0, "color") {
Value::Color(c) => c,
v => {
return Err((
format!("$color: {} is not a color.", v.to_css_string(args.span())?),
args.span(),
... | Rust | 0 |
|()| {
thread::sleep(Duration::from_secs(10));
});
let err = handle.join_timeout(Duration::from_millis(100)).unwrap_err();
assert!(err.is_timeout());
let handle = pool.spawn((), |()| {
thread::sleep(Duration::from_millis(100));
42
});
let val = handle.join_timeout(Dura... | Rust | 0 |
vec3 output_color;
#define saturate(v) clamp(v, 0, 1)
const vec3 LOW_COLOR = vec3(0,0,1);
const vec3 MID_COLOR = vec3(0,1,0);
const vec3 HIGH_COLOR = vec3(1,0,0);
void main() {
float value = 0;
if (channel > 0 && channel < 3) {
value = texture(input_texture, frag_uv)[channel];
} else {
/... | Rust | 0 |
location = location_input.value
description = description_input.value
point_number = number_of_point_input.value
# Химические показатели
aluminum = Aluminum_input.value
ammonium = ammonium_input.value
iron =... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.