text string | label_name string | labels int64 |
|---|---|---|
import unittest
from analyze import declared_gender
class TestDeclaredGender(unittest.TestCase):
def test_declared_gender(self):
for description, expected_gender in [
("pronoun: she", "female"),
("she,her", "female"),
("she/her", "female"),
("she/her/hers",... | Python | 1 |
self.high_speed = 30000
self.medium_speed = 30000
self.low_speed = 30000
# 等待式控制状态管理
self.servo_moving = False
self.move_start_time = 0
self.move_timeout = config.get('move_timeout', 3.0)
self.position_tolerance = config.get('position_tolerance',... | Python | 1 |
ащает максимальное из них. (лямбда)
# Задача 5
# Напишите функцию, которая проверяет, является ли число четным. (лямбда)
# Задача 6
# Напишите функцию, которая принимает произвольное количество чисел и возвращает их сумму. Используйте *args.
# Задача 7
# Напишите функцию, которая принимает произвольное количество к... | Python | 1 |
.into_iter()
.map(|r| r.event)
.filter_map(|e| {
if let Event::pallet_smart_contract(inner) = e {
Some(inner)
} else {
None
}
})
.collect::<Vec<_>>();
let mut expected_events: std::vec::Vec<RawEvent<Acco... | Rust | 0 |
).
For information about available fields see [buff_cpu_should_handle](index.html) module"]
pub struct BUFF_CPU_SHOULD_HANDLE_SPEC;
impl crate::RegisterSpec for BUFF_CPU_SHOULD_HANDLE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [buff_cpu_should_handle::R](R) reader structure"]
impl crate::Readable f... | Rust | 0 |
def scale_dataframe(dataframe: pd.DataFrame, scaling_method: str):
"""new_df = dataframe_scaling(old_df, 'std')
Scaling features in dataframe according to specific scaling strategy.
TODO: More scaling options and selective feature(col) scaling for dataframe.
Args:
dataframe (pandas.Dataframe):... | Python | 1 |
>>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> {
// class.path == "android/icu/util/Calendar", java.flags == PUBLIC, .name == "getType", .descriptor == "()Ljava/lang/String;"
unsafe {
let __jni_args = [];
let __jni_env = __jni_bindgen::Env::from_ptr... | Rust | 0 |
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import numpy as np
from tqdm import tqdm
class PerplexityFilter:
"""
Perplexity filter using Hugging Face models, such as GPT-Neo or similar models.
"""
def __init__(self, model, tokenizer, threshold, window_size='all'):
s... | Python | 1 |
CIDSystemInfo\x00" as *const u8 as *const i8),
tmp,
);
/* Quick exit for non-embedded & fixed-pitch font. */
if CIDFont_get_embedding(font) == 0 && opt_flags & 1i32 << 1i32 != 0 {
pdf_add_dict(
(*font).fontdict,
pdf_new_name(b"DW\x00" as *const u8 as *const i8),
... | Rust | 0 |
from ....type.rare import Rare
from ....type.weap import Catalyst, WeaponStat, WeaponStatType
from ....type.weap.tier import Tier
class DodocoTales(Catalyst):
name: str = "Dodoco Tales"
seco_stat: WeaponStat = WeaponStat(stat_name=WeaponStatType.attack_perc, stat_data=12.0)
tier: Tier = Tier.Tier_1
ra... | Python | 1 |
# coding: utf-8
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Mexico - Month 13 Trial Balance",
"summary": "Mexico Month 13 Trial Balance Report",
"version": "1.0",
"author": "Vauxoo / Odoo",
"category": "Accounting/Localizations/Reporting",
"website": "h... | Python | 1 |
/// cargo test -p async-raft --test snapshot_overrides_membership
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn snapshot_overrides_membership() -> Result<()> {
let (_log_guard, ut_span) = init_ut!();
let _ent = ut_span.enter();
let snapshot_threshold: u64 = 10;
let config = Arc:... | Rust | 0 |
V_INT {}
#[doc = "Feedback divisor\\n (note: this PLL does not support fractional division)"]
pub mod fbdiv_int;
#[doc = "Controls the PLL post dividers for the primary output\\n (note: this PLL does not have a secondary output)\\n the primary output is driven from VCO divided by postdiv1*postdiv2\n\nThis register you ... | Rust | 0 |
se:
print("Conta não encontrada.")
elif opcao == "12":
print("Saindo...")
break
else:
print("Opção inválida.")
except Exception as e:
print(f"Ocorreu um erro: {e}")
# -------------------------------------... | Python | 1 |
# Should still work without channel extraction
sensor_info = mapper.get_sensor_info("TEST123")
assert sensor_info is not None
assert sensor_info["channel"] == "" # Empty channel
def test_unknown_sensor_type(self):
"""Test handling unknown sensor types gracefully."""
... | Python | 1 |
time = cpu_time.elapsed();
println!("CPU time: {:?}", cpu_time);
unsafe {
gl::EndQuery(gl::TIME_ELAPSED);
// retrieving the recorded elapsed time
// wait until the query result is available
let mut done = 0... | Rust | 0 |
def split_file(path):
with open(path, 'r') as f:
threshold = int(f.readline())
lines = f.read().split('\n')
file_name = 'rosalind_base.fq.txt'
with open(file_name, 'w') as f:
for line in lines:
line += '\n'
f.write(line)
f.close()
return threshold, ... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright (C) 2024 BIRU
#
# This file is part of Tenzu.
#
# Tenzu is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at your option) any later... | Python | 1 |
# encoding: utf-8
import pytest
import ckan.tests.helpers as helpers
@pytest.mark.ckan_config("ckan.plugins", u"example_iconfigurer")
@pytest.mark.usefixtures("with_plugins")
class TestExampleIConfigurer(object):
def test_template_renders(self, app):
"""Our controller renders the extension's config templ... | Python | 1 |
import sys
from ddd.cli import setup_bash_completion
from ddd.cli import DDDCLI
def main():
"""CLI主入口"""
# 处理特殊命令
if len(sys.argv) > 1 and sys.argv[1] == "--setup-completion":
setup_bash_completion()
return
# 创建CLI实例并运行
cli = DDDCLI()
args = sys.argv[1:] # 移除脚本名称
cli.run(... | Python | 1 |
"""FrankenUI Dashboard Example"""
# AUTOGENERATED! DO NOT EDIT! File to edit: ../example_dashboard.ipynb.
# %% auto 0
__all__ = [
"rev",
"sub",
"sal",
"act",
"top_info_row",
"recent_sales",
"teams",
"opt_hdrs",
"team_dropdown",
"hotkeys",
"avatar_dropdown",
"top_nav",
... | Python | 1 |
et.merge_range(f'A{row}:F{row}', f'Start Date : {rec["start_date"]}', side)
row += 1
sheet.merge_range(f'A{row}:F{row}', f'End Date : {rec["end_date"]}', side)
row += 1
sheet.merge_range(f'A{row}:B{row}', 'Paper', cell_format)
sheet.merge_r... | Python | 1 |
文字
textarea2 = driver.find_element(
By.XPATH, "/html/body/div[2]/div[3]/div[2]/div[4]/div[3]/div/textarea"
)
driver.execute_script("arguments[0].scrollIntoView(true);", textarea2)
time.sleep(1)
enter_text(
driver,
"/html/body/div[2]/div[3]/div[... | Python | 1 |
"""EvidenceReference model for specific citations linking evaluation to source data."""
from typing import Literal
from pydantic import BaseModel, Field
class EvidenceReference(BaseModel):
"""Specific citation linking evaluation to source data."""
source_type: Literal["lint_output", "test_result", "file_ch... | Python | 1 |
x.to_be_bytes();
writer.insert(&x, &x).unwrap();
}
let bytes = writer.into_inner().unwrap();
assert_ne!(bytes.len(), 0);
let reader = Reader::new(Cursor::new(bytes.as_slice())).unwrap();
let mut cursor = reader.into_cursor().unwrap();
for n in 0..24020i32 ... | Rust | 0 |
"message": "ledger not found by version(1000000000000000000)",
"diem_ledger_version": "0"
}),
);
}
#[tokio::test]
async fn test_get_account_resources_by_invalid_ledger_version() {
let context = new_test_context();
let resp = context
... | Rust | 0 |
o_be_reduced]
# we have to recompute numpool now:
network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \
shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing, new_shp,
self.unet_... | Python | 1 |
#!/usr/bin/env python
# This should work:
#
# Changed blah and foo to do this or that. Re #10 and #12, and qa #12.
#
import re
import sys
from datetime import datetime
from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_u... | Python | 1 |
= "Checks if the value of the field is `PORTC`"]
#[inline(always)]
pub fn is_portc(&self) -> bool {
*self == EXTIPSEL4_A::PORTC
}
#[doc = "Checks if the value of the field is `PORTD`"]
#[inline(always)]
pub fn is_portd(&self) -> bool {
*self == EXTIPSEL4_A::PORTD
}
#[doc ... | Rust | 0 |
1e-3, momentum=0.01)),
pts_middle_encoder=dict(
type='PointPillarsScatter', in_channels=64, output_shape=[400, 400]),
pts_backbone=dict(
type='SECOND',
in_channels=64,
norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01),
layer_nums=[3, 5, 5],
layer_stride... | Python | 1 |
rovider_linked_to_an_offerer(
self,
mocked_venue_provider_job,
client,
):
venue = offerers_factories.VenueFactory()
user = user_factories.ProFactory()
offerers_factories.UserOffererFactory(user=user, offerer=venue.managingOfferer)
provider = providers_factorie... | Python | 1 |
XBS[mask, i * n_splines + j] = linear_extr
mask = X[:, i] > xmax
if np.any(mask):
k = n_splines - 1 - j
linear_extr = f_max[k] + (X[mask, i] - xmax) * fp_max[k]
if use_sparse:
... | Python | 1 |
the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use std::fmt;
use serde::{Deserialize, Serialize};
use mz_lowertest::MzReflect;
use mz_repr::{ColumnType, Datum, RowArena, ScalarType};
use crate::... | Rust | 0 |
player_tracking),
'actions': len(self.action_history)
}
def calculate_moving_average(self, queue, new_value, default=-1):
"""Calculate moving average from a queue of values"""
if new_value != default:
queue.append(new_value)
# If queue is empty o... | Python | 1 |
64>().unwrap();
let vesting_interval = vesting_interval.parse::<u64>().unwrap();
if block_time < start_time {
return Ok(Uint128::zero());
}
let num_interval = 1 + (end_time - start_time) / vesting_interval;
if block_ti... | Rust | 0 |
NumFrames.setter
def NumFrames(self, NumFrames):
self._NumFrames = NumFrames
@property
def Width(self):
return self._Width
@Width.setter
def Width(self, Width):
self._Width = Width
@property
def Height(self):
return self._Height
@Height.setter
def ... | Python | 1 |
n=1
par=impar=0
while n!=0:
n=int(input('Digite um numero:'))
if n!=0:
if n%2==0:
par=par+1
else:
impar=impar+1
print('Voce digitou {} numeros pares e {} numeros impares:'.format) | Python | 1 |
if path_obj.is_dir() {
Err(WcError::IsDirectory(path.to_owned()))
} else {
let file = File::open(path)?;
word_count_from_reader(file, settings, path)
}
}
}
fn wc(files: Vec<String>, settings: &Settings) -> Result<(), u32> {
let mut total_word_count = WordCoun... | Rust | 0 |
import torch
# Key prefixes and delimiters
prefixes = {
'default': 'model/model/',
'comfyui': 'lora_unet_'
}
delimiters = {
'default': '/',
'comfyui': '_'
}
dora_name = {
'default': 'dora_mag',
'comfyui': 'dora_scale'
}
def main(args):
path_in = args.path_in
path_out = path_in if args.... | Python | 1 |
ping_pong_group.PingPongGroupData(
ping_pong_info_storage=self,
order_group_id=order_group_id,
group_key=group_key,
init_only=True,
)
)
await restored_group.restore... | Python | 1 |
"""
=================
Run RANSAC
=================
In this example we show how to run the RANSAC of ``pyprep``.
.. currentmodule:: pyprep
""" # noqa: D205 D400
# Authors: The PyPREP developers
# SPDX-License-Identifier: MIT
###############################################################################
# First we... | Python | 1 |
from flask import request
class HTTP:
def getRequestIP(self):
'''
Returns the request IP
'''
# Nginx Ingress Controller returns the X-Forwarded-For in X-Original-Forwarded-For
# The last IP from the list is the client IP
if request.environ.get('HTTP_X_ORIGINAL_... | Python | 1 |
import os
import sys
sys.path.append(os.path.abspath("../"))
from typing import List
from unittest import TestCase
from unittest.mock import Mock, patch
from insightconnect_plugin_runtime.exceptions import ConnectionTestException, PluginException
from komand_cisco_umbrella_investigate.actions.cooccurrences.action im... | Python | 1 |
from PIL import Image
import io
import base64
async def process_image(image_data: bytes) -> Image.Image:
"""پردازش تصویر ورودی"""
try:
image = Image.open(io.BytesIO(image_data))
# تبدیل به RGB اگر لازم است
if image.mode in ('RGBA', 'P'):
image = image.convert('RGB')
... | Python | 1 |
import sys
sys.path.append("./")
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from vanet_env import env_config
def summnet_preprocess(num_content=env_config.NUM_CONTENT):
path = os.path.join(os.path.dirname(__file__), "data", "SMMnet", "course-meta.csv")
df = pd.read_csv(path... | Python | 1 |
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = [
# "bump2version",
# "rich",
# "termcolor",
# "typer",
# ]
# ///
jsonrpc1 = """
Content-Length: 407
{"jsonrpc":"2.0","id":"27","method":"codeLens/resolve","params":{"range":{"start":{"line":36,"character":1053},"end":{"line":53,"character":134... | Python | 1 |
# -*- coding: utf-8 -*-
'''Home made test. Verification of Douglas Peucker algorithm implementation.'''
from __future__ import print_function
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AO_O)"
__copyright__= "Copyright 2015, LCPT and AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@ciccp... | Python | 1 |
warnings.warn("Failed to terminate worker processes in"
" multiprocessing pool: %r" % e)
# Clean up the temporary resources as the workers should now be off.
self._temp_folder_manager._clean_temporary_resources()
@property
def _temp_folder(self... | Python | 1 |
new(&ctx.gpu);
let environment_image = ctx
.new_image_from_file(
"image_environment_map",
"assets/textures/env_carpentry_shop_02_2k.jpg",
)
.unwrap();
let shader_vertex = ctx
.new_shader(
"shader_vertex",
graphene::ShaderStage::Ver... | Rust | 0 |
import uuid
from dependency_injector.wiring import Provide, inject
from fastapi import APIRouter
user_router = APIRouter(
prefix="/user",
tags=["user"]
)
@user_router.get("/")
@inject
async def get_users():
pass
@user_router.get("/{id}")
@inject
async def get_user(
id: uuid.UUID
):
pass
@user_... | Python | 1 |
'''
Figure 1: 2D system
Homogeneous Distribution Curve
Non Local Distribution Curve
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import h5py
from matplotlib import rc
from matplotlib.patches import Rectangle
# Functions
def up(mu, path, pe, w):
f = h5py.File(f'{path}_mu{mu:.2f... | Python | 1 |
<<<<<<< HEAD:competitive Programing-chatGpt/recurision/reverse_str.py
<<<<<<< HEAD
=======
>>>>>>> b1e894c8f4f88706e4e6472a63308c77b347ce99:Competitive_programing/recurision/reverse_str.py
'''
Write a recursive function to reverse a string.
'''
def reverse_str(s):
if len(s)==0:
return s
else:
... | Python | 1 |
x = os.path.splitext(parsed.path)[1] or ".png"
with urllib.request.urlopen(arturl, timeout=10) as response: # Add timeout
if self._download_cancelled:
return
data = response.read()
# Check one more time if cancelled
if self._down... | Python | 1 |
ype': ['DoS', 'Probing', 'U2R', 'R2L'][attack_num-1],
'Actual_Count': actual_positives,
'Detected_Count': true_positives,
'Accuracy': accuracy,
'Precision': precision,
'Recall': recall,
'False_Positives': false_positives,
'False_Negatives': false_negatives
}
... | Python | 1 |
gbp, usd_ois_t1, gbp_ois_t1, gbpusd_basis_t1)
mkt_usdjpy_t1 = Market(s_usd_per_jpy, usd_ois_t1, jpy_ois_t1, usdjpy_basis_t1)
for name, trade, mkt_t, mkt_t1 in [
("EURUSD", t_eur, mkt_eurusd, mkt_eurusd_t1),
("GBPUSD", t_gbp, mkt_gbpusd, mkt_gbpusd_t1),
("USDJPY", t_jpy, mkt_usdjpy, mkt_usdjpy_t1),
]:
e... | Python | 1 |
import math
import pickle
import re
from collections import defaultdict
from typing import List
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from torch.utils.benchmark import Measurement as TMeasurement
from vllm.utils import FlexibleArgumentParser
if __name__ == "__main__":
parser =... | Python | 1 |
LEN_MASK, l as u64);
}
#[inline(always)]
fn meta_len(&self) -> u8 {
get(self, META_LEN_SHIFT, META_LEN_MASK) as u8
}
#[inline(always)]
fn set_token_count(&mut self, c: u8) {
set(self, TOKEN_LEN_SHIFT, TOKEN_LEN_MASK, c as u64);
}
#[inline(always)]
fn token_count(&self... | Rust | 0 |
>The value that's associated with the account limit name.</p>
pub fn set_value(mut self, input: std::option::Option<i32>) -> Self {
self.value = input;
self
}
/// Consumes the builder and constructs a [`AccountLimit`](crate::model::AccountLimit)
pub fn build(self)... | Rust | 0 |
from mcp.server.fastmcp import FastMCP
from langchain_community.tools import DuckDuckGoSearchRun
mcp = FastMCP("Math")
search = DuckDuckGoSearchRun()
@mcp.tool()
def weather_sesrch(query:str) -> str:
"""onlien web search"""
return search.invoke(query).encode("UTF-8")
if __name__ == "__main__":
mcp.run() | Python | 1 |
llo");
Ok(())
}
#[tokio::test]
async fn kill_and_try_wait_normal() -> Result<()> {
let mut child = Command::new("yes").stdout(Stdio::null()).spawn()?;
assert!(child.try_wait()?.is_none());
child.kill().await?;
sleep(DIE_TIME).await;
assert!(child.try_wait()?.is_some());
sleep(DIE_TIME).await;
assert!(child.try... | Rust | 0 |
`response` of `fanotify_response`.
pub(crate) const FAN_ALLOW: c_uint = 0x01;
/// Deny grant of permission.
///
/// Use for field `response` of `fanotify_response`.
pub(crate) const FAN_DENY: c_uint = 0x02;
//! File chunking and hashing utilities.
use std::collections::BTreeMap;
use std::fmt::Write;
use serde::{Des... | Rust | 0 |
Operation, Op, SequenceCrdt};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fmt::{self, Debug, Formatter},
hash::Hash,
};
use xor_name::XorName;
// Type of data used for the 'Actor' in CRDT vector clocks
type ActorType = PublicKey;
/// Data mutation operation to apply to Sequence.... | Rust | 0 |
# SPDX-License-Identifier: BSD-2-Clause
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
from tests.lib.parse import parse
from tests.lib.testcase import ConfluenceTestCase
from tests.lib.testcase import setup_builder
class TestConfluenceSinglepageToctree(ConfluenceTestCase):
@setup_builder('singleco... | Python | 1 |
from unittest.mock import MagicMock
import pytest
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage, HumanMessage
from talos.core.agent import Agent
from talos.prompts.prompt import Prompt
from talos.prompts.prompt_manager import PromptManager
class MockPromptMan... | Python | 1 |
let mut x592: fiat_secp256k1_u1 = 0;
fiat_secp256k1_addcarryx_u32(&mut x591, &mut x592, x590, x540, x574);
let mut x593: u32 = 0;
let mut x594: fiat_secp256k1_u1 = 0;
fiat_secp256k1_addcarryx_u32(&mut x593, &mut x594, x592, x542, x576);
let x595: u32 = ((x594 as u32) + (x543 as u32));
let mut x596: u32 = ... | Rust | 0 |
from playwright.sync_api import Page, expect
from shiny.playwright import controller
from shiny.run import ShinyAppProc
from shinychat.playwright import ChatController
def test_validate_chat_transform_assistant(
page: Page, local_app: ShinyAppProc
) -> None:
page.goto(local_app.url)
chat = ChatController... | Python | 1 |
#faca um programa em python eque receba um numero positivo maior que zero,calcule e mostre :
#a)o numero digitado ao quadrado
#b)o numero digitado ao cubo
#c)a raiz quadrada do numero digitado
#d)a raiz cubica do numero digitado
# Solicita ao usuário que insira um número positivo maior que zero
numero = int(input("D... | Python | 1 |
{6c}', // \u{1e3d} -> l
'\u{6d}', // \u{1e3e} -> m
'\u{6d}', // \u{1e3f} -> m
'\u{6d}', // \u{1e40} -> m
'\u{6d}', // \u{1e41} -> m
'\u{6d}', // \u{1e42} -> m
'\u{6d}', // \u{1e43} -> m
'\u{6e}', // \u{1e44} -> n
'\u{6e}', // \u{1e45} -> n
'\u{6e}', // \u{1e46} -> n
'\u{6e}', // \u{1e47} -> n
'\u{6e}', // \u... | Rust | 0 |
set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
... | Rust | 0 |
) {
if *left {
*left = right;
}
}
}
/// Merge strategies for numeric types.
///
/// These strategies are only available if the `num` feature is enabled.
#[cfg(feature = "num")]
pub mod num {
/// Set left to the saturated some of left and right.
pub fn saturating_add<T: num_trait... | Rust | 0 |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | Python | 1 |
_repo))
break
else:
if old_repo not in [x[0] for x in to_move]:
to_rm.append(old_repo)
really_to_add = list()
for repo in to_add:
if repo.src not in [x[0].src for x in to_update]:
really_to_add.append(repo)
to_add = really_to_add
# sort... | Python | 1 |
root'
self.assertEqual(composedVarSet.GetVariantNames(), ['a', 'b', 'root'])
# Add a new variant spec 'payload' to "standin" in the payload layer and
# verify the notice handler verifications were triggered.
Sdf.VariantSpec(payloadVarSet, "payload")
self.assertEqual(numNoticesR... | Python | 1 |
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.ht... | Python | 1 |
import cv2
import os
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import normalize
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.k... | Python | 1 |
<Item = &'a str>,
) -> SocketAddr {
let bind = next_addr();
let socket = UdpSocket::bind(bind)
.map_err(|e| panic!("{:}", e))
.ok()
.unwrap();
for line in lines {
assert_eq!(
socket
.send_to(line.as_bytes()... | Rust | 0 |
raise ValueError(f'invalid reprt_code (use one of {reprt_code_dict}')
if fs_div not in fs_div_dict:
raise ValueError(f'invalid fs_div (use one of {fs_div_dict}')
corp_code = self.find_corp_code(corp)
if not corp_code:
raise ValueError(f'could not find "{corp}... | Python | 1 |
#!/usr/bin/env python3
import re
import sys
log_pattern = re.compile(r'^(\S+) - - \[\d{2}/\w+/\d{4}:(\d{2}):\d{2}:\d{2}')
for line in sys.stdin:
match = log_pattern.search(line)
if match:
ip = match.group(1)
hour = match.group(2)
print(f"{hour}\t{ip}\t1") | Python | 1 |
from pydantic import BaseModel
from restack_ai.function import function, log, FunctionFailure
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
class OpenAiChatInput(BaseModel):
user_content: str
system_content: str | None = None
model: str | None = None
@function.defn()
as... | Python | 1 |
'''
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
'''
class Solution:
# ... | Python | 1 |
EDR/LE (interleaved discovery)
///
/// This command can only be used when the controller is powered.
pub async fn start_discovery(
&mut self,
controller: Controller,
address_types: BitFlags<AddressTypeFlag>,
) -> Result<BitFlags<AddressTypeFlag>> {
let mut param = BytesMu... | Rust | 0 |
senceContainerMultipleWrappings
},
smpte_identifier!(0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00) => {
Ul::MxfOP1aSingleItemSinglePackageUniTrackStreamInternal
},
smpte_identifier!(0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x03, 0x00) => {
... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# PySPED - Python libraries to deal with Brazil's SPED Project
#
# Copyright (C) 2010-2012
# Copyright (C) Aristides Caldeira <aristides.caldeira at tauga.com.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Library General Public Lic... | Python | 1 |
= r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IMB_A {
match self.bits {
false => IMB_A::_0,
true => IMB_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
... | Rust | 0 |
"""
Enables multiple commonly used features.
Method resolution order:
- `tqdm.autonotebook` without import warnings
- `tqdm.asyncio` on Python3.6+
- `tqdm.std` base class
Usage:
>>> from tqdm.auto import trange, tqdm
>>> for i in trange(10):
... ...
"""
import sys
import warnings
from .std import TqdmExperiment... | Python | 1 |
import os
import sys
from database.core import connect_to_db, disconnect_from_db
from pathlib import Path
# Set up path for imports
current_dir = Path(__file__).resolve().parent
parent_dir = str(current_dir.parent)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
sys.path.insert(0, "/database")
sys.pat... | Python | 1 |
assert_eq!(packet.addr(), test_addr());
assert_eq!(packet.payload(), test_payload().as_slice());
assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Unreliable);
assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);
}
#[test]
fn assure_creation_unreliable_sequenced()... | Rust | 0 |
import random
import perlin_noise
import pygame as pg
import math
from visual import effects as eff
import time
import physics
random.seed(time.time())
sf = pg.Surface((600, 600), pg.SRCALPHA)
def rotation_coordinate(rotation):
return (math.sin(math.radians(rotation)),
-math.cos(math.radians(rotatio... | Python | 1 |
"""CLI entry point for the drone traffic generator."""
from __future__ import annotations
import sys
from tools.traffic_runner import run
if __name__ == "__main__":
sys.exit(run("drone"))
| Python | 1 |
icenses/>.
#![deny(unused_crate_dependencies)]
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse2, Result};
mod impl_builder;
mod impl_channels_out;
mod impl_dispatch;
mod impl_message_wrapper;
mod impl_misc;
mod impl_overseer;
mod parse_attr;
mod parse_struct;
use impl_bu... | Rust | 0 |
::{model_comment::*, model_post::*};
use crate::schema::*;
use crate::utils::{connections::*, email::notification, time::*, url_converter::url_converter};
pub fn posts_and_comments(post_url: &str, db: &DB) -> Context {
let mut context = Context::new();
let post = Post::find_by_url(&post_url, &*db).unwrap();
... | Rust | 0 |
h = enc_out # ASSUME: single output
return enc_out, encoded_length
def run_decoder_joint(self, enc_logits, targets, target_length, *states):
# ASSUME: Decoder is RNN Transducer
if targets is None:
targets = torch.zeros(enc_logits.shape[0], 1, dtype=torch.int32)
targ... | Python | 1 |
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, Response
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
import math
import logging
from pathlib import Path
from app import models, schemas, crud
from app.api import dep... | Python | 1 |
import os
import matplotlib.pyplot as plt
import torch
# Scatter plot comparing ground truth vs predicted dc_mean to visualize performance spread.
def plot_scatter(model, dataloader, device):
model.eval()
gt_values = []
pred_values = []
with torch.no_grad():
for images, labels in dataloader:
... | Python | 1 |
_pktlen: u32,
pub max_lro_pkt_size: u32,
pub max_rx_queues: u16,
pub max_tx_queues: u16,
pub max_mac_addrs: u32,
pub max_hash_mac_addrs: u32,
pub max_vfs: u16,
pub max_vmdq_pools: u16,
pub rx_offload_capa: u64,
pub tx_offload_capa: u64,
pub rx_queue_offload_capa: u64,
pub tx_... | Rust | 0 |
-> {
assert_eq!(res, (Spn::len_mk(7, 4), "a rational".into()))
}
}
try_parse!{
|bytes| token_parser(bytes, 7), b"732", (s, res) -> {
assert_eq!(res, (Spn::len_mk(7, 3), "an integer".into()))
}
}
try_parse!{
|bytes| token_parser(bytes, 7), b"false)", (s, res) -> {
assert_eq!(res... | Rust | 0 |
res the following crate features to be activated: `WebGl2RenderingContext`*"]
pub const SRGB8: u32 = 35905u64 as u32;
#[doc = "The `WebGL2RenderingContext.SRGB8_ALPHA8` const."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `WebGl2RenderingContext`*"]
pub cons... | Rust | 0 |
assert res._ndarray.flags["C_CONTIGUOUS"]
res = arr2d[::2, ::2].copy()
assert res._ndarray.flags["C_CONTIGUOUS"]
res = arr2d.copy("F")
assert not res._ndarray.flags["C_CONTIGUOUS"]
assert res._ndarray.flags["F_CONTIGUOUS"]
res = arr2d.copy("K")
assert res._ndar... | Python | 1 |
("unsatisfied: {}", cs.which_is_unsatisfied().unwrap());
return Err(RuntimeError::UnsatisfiedConstraint);
}
let unconstrained = cs.find_unconstrained();
if !unconstrained.is_empty() {
log::error!("Unconstrained: {}", unconstrained);
return Err(RuntimeError::InternalError(
... | Rust | 0 |
elem: *mut snd_mixer_elem_t,
mask: ::std::os::raw::c_uint,
) -> ::std::os::raw::c_int,
>;
pub type snd_mixer_compare_t = ::std::option::Option<
unsafe extern "C" fn(
e1: *const snd_mixer_elem_t,
e2: *const snd_mixer_elem_t,
) -> ::std::os::raw::c_int,
>;
pub type snd_mixer_event_t =... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.