text string | label_name string | labels int64 |
|---|---|---|
tion):
raise
else:
raise TceCloudSDKException(e.message, e.message)
def CreateAccount(self, request):
"""本接口(CreateAccount)用于创建云数据库账号。一个实例可以创建多个不同的账号,相同的用户名+不同的host是不同的账号。
:param request: 调用CreateAccount所需参数的结构体。
:type request: :class:`tcecloud.d... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from mmseg.datasets import BaseSegDataset
from mmseg.registry import DATASETS
classes_exp = ('unlabelled', 'road', 'road marks', 'vegetation',
'painted metal', 'sky', 'concrete', 'pedestrian', 'water',
'unpainted metal', 'glass')
palette_exp... | Python | 1 |
from typing import Dict, List, Union
import reacton.ipyvuetify as v
import nextpy.interfaces.jupyter as widget
import nextpy.interfaces.jupyter.util
@widget.component
def progress(
value: Union[bool, float] = True,
color="primary",
style: Union[str, Dict[str, str], None] = None,
classes: List[str] =... | Python | 1 |
you?").unwrap());
assert_eq!(msg.encode().unwrap(), PFP_CHALLENGE_TOKEN.to_vec());
}
#[test]
fn no_challenge_encoding() {
let msg = NowAuthPFPChallenge::new_without_question();
assert_eq!(PFP_NO_CHALLENGE_TOKEN.to_vec(), msg.encode().unwrap());
}
#[rustfmt::skip]
const... | Rust | 0 |
d_benefit_amounts_from_different_company",
crate::progenitor_support::encode_path(&employee_id.to_string()),
);
self.client
.post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?)))
.await
}
/**
* Get an employee benefit.
*
* This func... | Rust | 0 |
");
println!("protected with a password (or not, but un-advised) that you can print and store");
println!("securely in order to recover your wallet and your funds.");
println!("{}", style::NoItalic);
// 2. get a password
let pwd = <PASSWORD>();
// 3. generate the scrambled entropy
let shield... | Rust | 0 |
#!/usr/bin/env python
# BEGIN_COPYRIGHT
#
# Copyright 2009-2025 CRS4.
#
# 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 ap... | Python | 1 |
import sherpa_onnx
from pathlib import Path
class TTSSherpaOnnx:
def set_recognizer(
samplerate: int = 16000, models_root:str="", lang="zh", num_threads=2,rule_fsts_list =[]
) -> sherpa_onnx.OfflineRecognizer:
models_root_path = Path(models_root)
model_dir = os.path.join(... | Python | 1 |
from a PubSub node.
#[derive(Debug, Clone, PartialEq)]
pub struct Item {
/// The identifier for this item, unique per node.
pub id: Option<ItemId>,
/// The JID of the entity who published this item.
pub publisher: Option<Jid>,
/// The payload of this item, in an arbitrary namespace.
pub paylo... | Rust | 0 |
assert rls_resp.json["details"] == {"description": "Wrong format"}
def test_rls_filter_expr(self, control_api, saved_dataset, sync_us_manager):
config = load_rls_config("dl_api_lib_test_config")
field_a, field_b = saved_dataset.result_schema[0].id, saved_dataset.result_schema[1].id
saved_da... | Python | 1 |
(&['&', 'G', 'T', ';']);
},
'<' => {
output.extend_from_slice(&['&', 'L', 'T', ';']);
},
'"' => {
output.extend_from_slice(&['&', 'Q', 'U', 'O', 'T', ';']);
},
'\\' => {
... | Rust | 0 |
= db.DateTimeProperty(auto_now_add=True)
query = db.StringProperty()
successful = db.BooleanProperty(default=True)
user = AutoUpdatingUserProperty()
# Guaranteed unique, for pagination.
paginate_mtime = db.StringProperty()
def put(self): # pylint: disable=g-bad-name
"""Override put to automatically c... | Python | 1 |
se crate::*;
#[test]
fn test_read_header() {
println!(
"p1: {:?}\np2: {:?}",
PacketReader::read_header(vec![4, 0, 0, 0, 0, 0, 0]),
PacketReader::read_header(vec![24, 0, 0, 7, 0, 0, 0, 11, 5, 104, 101, 108, 108, 111])
);
}
#[test]
fn test_header()... | Rust | 0 |
class Graph:
def __init__(self, vertices):
# Initialize the number of vertices and the adjacency matrix
self.V = vertices
self.adj_matrix = [[0 for _ in range(vertices)] for _ in range(vertices)]
def add_edge(self, u, v,w):
# Add an edge (u, v, w) to the graph
self.adj_... | Python | 1 |
ero:
self.live.log_artifact(args.output_dir)
def on_train_end(self, args, state, control, **kwargs):
if self._initialized and state.is_world_process_zero:
from transformers.trainer import Trainer
if self._log_model is True:
fake_trainer = Trainer(args=ar... | Python | 1 |
self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
self.assertEqual(mail.outbox[0].to[1], 'second@example.com')
def test_mass_mail_sending(self):
"Test that mass mail is redirected to a dummy outbox during test setup"
response = self.client.get('/test_client/mass_mail_sending_v... | Python | 1 |
ionary
self.InitiateExeDict()
def UpdateMsgLog(self, msg=""):
# Date and time
nowStr = datetime.now().strftime("%d/%b/%y - %H:%M:%S")
disp = "##############" \
+ nowStr \
+ "############## \n" \
+ msg \
+ "\n###########... | Python | 1 |
EMAIL>>
// All rights reserved. This file is part of yabs, distributed under the BSD
// 3-Clause license. For full terms please see the LICENSE file.
extern crate error_chain;
extern crate toml;
extern crate walkdir;
extern crate ansi_term;
extern crate serde_json;
extern crate log;
extern crate regex;
error_chain! {... | Rust | 0 |
\xf4*M\x8b\
5\x16LZ\x7f\x99Bo\x02pr\xfeF\x96\x9f\xf9\
\xf1\xf4\xbb\x96_9\xad'\x7fcfW}{\xf7w\
Eq\xb9u\x8ep\x93ow4'\xaf\xb0N1\x12\
\x8d\xed\xa9\xffV\xd5\x1b\xf28\xe4\x1fD\xe5\x8b\xde\xa6\
)\xcb\x0a\xbddSv\xb1\x00\x10\x80\x03'\xfe\x89\xdd\
W\xab\xc8?\x01\x98j\x93B\xbf\xdb\xd1\x5c\xf7^\x9b\
\xb1Gf\xfem\xcf\x8d\xf3\xfdD\x0a... | Python | 1 |
HandTrackerFrame)
-> NiteStatus;
}
extern "C" {
pub fn niteHandTrackerFrameAddRef(handTrackerHandle: NiteHandTrackerHandle,
pFrame: *mut NiteHandTrackerFrame)
-> NiteStatus;
}
extern "C" {
pub fn nite... | Rust | 0 |
0u8; 256];
#[allow(clippy::clippy::needless_range_loop)]
for i in 0..256 {
let mut tmp = 0;
if i & 1 != 0 {
tmp += 1;
}
if i & 2 != 0 {
tmp += 1;
}
if i & 4 != ... | Rust | 0 |
# Copyright 2024 Google LLC
#
# 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 applicable law or agreed to in writing, ... | Python | 1 |
llSrc::Csi => 4_000_000,
PllSrc::Hsi(div) => 64_000_000 / (div.value() as u32),
PllSrc::Hse(freq) => freq,
PllSrc::None => 0,
};
match pll_num {
1 => input_freq / (self.pll1.divm as u32),
2 => input_freq / (self.pll2.divm as u32),
... | Rust | 0 |
N IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
use std::collections::HashMap;
use std::error::Error;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::ops::Add;
use std::rc::Rc;
use std::str::FromStr;
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_route53::model::{
Change, ChangeAction, ChangeB... | Rust | 0 |
0x5f, 0xa2, 0x1b, 0xf6, 0x66}
DEFINE_GUID!{IID_ID2D1TransformGraph,
0x13d29038, 0xc3e6, 0x4034, 0x90, 0x81, 0x13, 0xb5, 0x3a, 0x41, 0x79, 0x92}
DEFINE_GUID!{IID_ID2D1Transform,
0xef1a287d, 0x342a, 0x4f76, 0x8f, 0xdb, 0xda, 0x0d, 0x6e, 0xa9, 0xf9, 0x2b}
DEFINE_GUID!{IID_ID2D1DrawTransform,
0x36bfdcb6, 0x973... | Rust | 0 |
{
prime = factor1;
}
if is_prime(factor2) && factor2 > prime {
prime = factor2;
}
}
factor1 -= 2;
factor2 = (NUMBER / factor1 as f64) as i64;
while NUMBER % factor1 as f64 != 0.0 && NUMBER % factor2 as f64 != 0.0 {
... | Rust | 0 |
from hummingbot.data_feed.candles_feed.mexc_perpetual_candles.mexc_perpetual_candles import MexcPerpetualCandles
__all__ = ["MexcPerpetualCandles"]
| Python | 1 |
ramerate::SDL_initFramerate(raw);
FPSManager { raw: raw }
}
}
/// Set the framerate in Hz.
pub fn set_framerate(&mut self, rate: u32) -> Result<(), String> {
let ret = unsafe { gfx::framerate::SDL_setFramerate(self.raw, rate as uint32_t) };
match ret {
0 => O... | Rust | 0 |
tl::StrongRelease(x, y) => write!(f, "({} M {})", x, y),
}
}
}
impl<AP: fmt::Display> fmt::Display for LtlNNF<AP> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
LtlNNF::True => write!(f, "true"),
LtlNNF::False => write!(f, "false"),
Ltl... | Rust | 0 |
spark_submit",
[
(
"Cannot execute: /opt/spark/spark-2.4.5-bin-hadoop2.7/bin/spark-submit --master local "
"--conf spark.sql.shuffle.partitions=1"
"--conf spark.env.DBND__CORE__DATABAND_URL=https://databand.ai "
"--conf spark.env.DBND__CORE__DATABAND_ACCESS_TO... | Python | 1 |
last_pattern, game_state)
print(f" 验证结果: {'通过' if validation['valid'] else '失败'}")
if not validation['valid']:
print(f" 错误反馈: {validation['error_message']}")
except Exception as e:
print(f" 验证异常: {e}")
def test_comprehensive_validation():
"""测试全面的验证逻辑... | Python | 1 |
_token: &'a EditorFileToken,
current_character: usize,
}
impl<'a> EditorFileTokenIterator<'a> {
pub fn new(editor_file_token: &'a EditorFileToken) -> Self {
Self {
editor_file_token,
current_character: 0,
}
}
}
impl<'a> std::iter::Iterator for EditorFileTokenIterato... | Rust | 0 |
ress=True, **kwargs):
r"""Constructs a VoVNet-39 model as described in
`"An Energy and GPU-Computation Efficient Backbone Networks"
<https://arxiv.org/abs/1904.09730>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progres... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
def generate_cosine_graph(step, x_min, x_max, output_file):
"""
Генерирует график функции y = cos(x) с заданным шагом и сохраняет координаты в файл.
:param step: Шаг изменения x
:param x_min: Минимальное значение x
:param x_max: Максимальное з... | Python | 1 |
def test16_dictionary_like_interface(variant_scalar_rgb):
"""Test new dictionary-like methods and deprecation warnings"""
from drjit.scalar import Array3f
import warnings
p = mi.Properties()
p['name'] = 'test'
p['value'] = 42
p['vector'] = Array3f(1, 2, 3)
p['flag'] = True
# Test ... | Python | 1 |
from scene_parser.scene_parser_interface import SceneParserInterface
class BasicSceneParser(SceneParserInterface):
def __init__(self):
self.keywords = ["One day", "Then one day", "However", "Then", "At that moment", "And", "Eventually"]
def parse(self, text: str) -> dict[int, str]:
paragraphs ... | Python | 1 |
esolved_dependants)
def get_leaf_boms() -> list[str]:
"Get BOMs that have no dependencies."
bom = frappe.qb.DocType("BOM")
bom_item = frappe.qb.DocType("BOM Item")
boms = (
frappe.qb.from_(bom)
.left_join(bom_item)
.on((bom.name == bom_item.parent) & (bom_item.bom_no != ""))
.select(bom.name)
.where((... | Python | 1 |
# Databricks notebook source
# MAGIC %md
# MAGIC # Load `mpt-7b-8k-instruct` model from Langchain on Databricks
# MAGIC
# MAGIC This example notebook shows how to wrap Databricks endpoints as LLMs in LangChain.
# MAGIC
# COMMAND ----------
# MAGIC %md
# MAGIC ## Install required packages
# COMMAND ----------
# MAGI... | Python | 1 |
let r = u64::from_le_bytes(rhs.try_into().unwrap());
let res = u64::from_le_bytes(result.try_into().unwrap());
let res2 = if index == 0 { l ^ r } else { l ^ res };
result.copy_from_slice(res2.to_le_bytes().as_slice());
}
32 => {
let l = U256::... | Rust | 0 |
import pytest
from django.contrib.auth.models import User, Group
from auth.serializers import (
CustomTokenObtainPairSerializer,
UserProfileSerializer,
GroupSerializer,
)
from rest_framework_simplejwt.tokens import RefreshToken
@pytest.mark.django_db
def test_custom_token_obtain_pair_serializer():
"""
... | Python | 1 |
# The MIT License (MIT)
#
# Copyright (c) 2014 Richard Moore
#
# 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, mod... | Python | 1 |
# -*- coding: utf-8 -*-
import os
from odoo import api, fields, models, _
from odoo.exceptions import AccessError, UserError
class DbBackupDetails(models.Model):
_name = 'db.backup.details'
_description = 'Database Backup Details'
name = fields.Char(string='Name')
file_path = fields.Char(string="Fi... | Python | 1 |
from django.urls import path
from .views.show import *
from .views.change import (
AddPhoto, del_photo,
AddAlbum, AlbumUpdate, PhotoUpdate,
)
urlpatterns = [
path('', HomePage.as_view(), name='index'),
path('albums/', AlbumListView.as_view(), name='show_albums_list'),
path('albums/filters', Filter... | Python | 1 |
import subprocess
from cli.logger import get_logger
import os
from pathlib import Path
from dotenv import load_dotenv
from graphrag.config.load_config import load_config
logger = get_logger('common')
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def load_project_env(project_name: str):
l... | Python | 1 |
&item[result.start()..result.start()+1] {
"\'" => &item[result.start()+1..result.end()-1],
_ => &item[result.start()..result.end()]
};
let name = hash(&(name.to_string()));
if rules.contains_key(&name) {panic!("Rule '{}' already defined", name)};
let mut index = result.end() + 1... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
# -*- coding: utf-8 -*-
#
#
# Copyright 2013 Netflix, Inc.
#
# 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 ... | Python | 1 |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class OktoberfestTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?oktoberfest-tv\.de/[^/]+/[^/]+/video/(?P<id>[^/?#]+)'
_TEST = {
'url': 'http://www.oktoberfest-tv.de/de/kameras/video/hb-zelt',
'i... | Python | 1 |
import json
def convert_prompt_dataset(
input_file: str = "app/test/prompt/prompt_eval_100.jsonl",
output_file: str = "app/test/prompt/prompt_eval_messages_100.jsonl",
) -> str:
with open(input_file, "r", encoding="utf-8") as f:
lines = f.readlines()
results = []
for line in lines:
... | Python | 1 |
_CYCLELEN_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SLV_RDSTA_DUMMY_CYCLELEN` writer - In the slave mode it is the length in spi_clk cycles of dummy phase for read-status operations. The register value shall be ... | Rust | 0 |
n compute_nodes:
instances = self.host_api.instance_get_all_by_host(context,
compute_node['service']['host'])
hyp = self._view_hypervisor(compute_node, False, instances)
hypervisors.append(hyp)
return dict(hypervisors=hypervisors)
@wsgi.serializers(xm... | Python | 1 |
2, verbose="acc", disable=False, output_info=False, transform=None):
model.eval()
num_total, num_acc = 0, 0
prog_bar = tqdm(dl_val, file=sys.stdout, leave=False, disable=disable)
time_start = time.perf_counter()
with torch.no_grad():
for _, (batch_x, batch_y) in enumerate(prog_bar, 0):
... | Python | 1 |
ec<Attribute>) -> Handle;
/// Create a comment node.
fn create_comment(&mut self, text: String) -> Handle;
/// Append a node as the last child of the given node. If this would
/// produce adjacent sibling text nodes, it should concatenate the text
/// instead.
///
/// The child node will ... | Rust | 0 |
!(a*(b+c), a*b + a*c);
/// # }
/// ```
///
pub use gf256_macros::gf;
// An 8-bit binary-extension finite-field
#[gf(polynomial=0x11d, generator=0x2)]
pub type gf256;
// A 16-bit binary-extension finite-field
#[gf(polynomial=0x1002d, generator=0x2)]
pub type gf2p16;
// A 32-bit binary-extension finite-field
#[gf(pol... | Rust | 0 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask_restful import Api
from flask import request
from . import administrators_blueprint
from api_1_0.administratorsResource.administratorsResource import AdministratorsResource
from api_1_0.administratorsResource.administratorsOtherResource import AdministratorsOthe... | Python | 1 |
f . d dl Z ddlmZ G d de Zy) N )method_cachec h e Zd ZdZd Zd Zd Zd Zd Z fdZ d Z
e fd Zd
Z
ddZ xZS )
FoldedCasea{
A case insensitive string class; behaves just like str
except compares equal... | Python | 1 |
,// Pabsd_mm_mmm64
0x0000_0037, 0x8400_0000,// Pabsd_xmm_xmmm128
0x2000_0037, 0x0300_0001,// VEX_Vpabsd_xmm_xmmm128
0x2000_0037, 0x0400_0001,// VEX_Vpabsd_ymm_ymmm256
0x2000_0037, 0x1200_0002,// EVEX_Vpabsd_xmm_k1z_xmmm128b32
0x2000_0037, 0x1200_0002,// EVEX_Vpabsd_ymm_k1z_ymmm256b32
0x2000_0037, 0x0900_0002,// E... | Rust | 0 |
#Start from here
#Message for welcome to our students
print("Hello in GPA calculator ")
# 7 subjects >> college
#150 * 7 = 1050 Degree
# important value (25%)
# Please enter your 1st subject marks:
x1 = input("please enter your 1st subject marks : ")
x2 = input("please enter your 2st subject marks : ")
x3 = input("... | Python | 1 |
: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::ne... | Rust | 0 |
stats: HashMap<i32, HashMap<String, models::json::SNMPBotResultEntryObjectValue>> = HashMap::new();
snmpbot_query(&device_fqdn, &mut stats, &iftable_url);
snmpbot_query(&device_fqdn, &mut stats, &ifxtable_url);
let mut report = models::json::InterfaceMonitorReport::new(&device_fqdn);
for (ifindex, ob... | Rust | 0 |
#Family Class Program
#Brianna Zaffina
#12/11/2023
from dataclasses import dataclass
@dataclass
class Family:
name:str = " "
address:str = " "
age:int = 0
phone:str = " "
def __init__(familyMem, name, address, age, phone):
familyMem.__name = name
familyMem.__address = address
... | Python | 1 |
import uvicorn
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from langchain_core.messages import HumanMessage
from workflow.agentic_work... | Python | 1 |
l TypedMapKey for Key {
/// type Value = usize;
/// }
///
/// let mut letters: TypedMap = TypedMap::new();
/// for ch in "a short treatise on fungi".chars() {
/// let counter = letters.entry(Key(ch)).or_insert(0);
/// *counter += 1;
/// }
/// assert_eq!(letters.get(&Key('s'... | Rust | 0 |
urrent,
)
x = x + dt * xdot
# Check if we're safe or not
if controller_under_test.dynamics_model.failure(x).any():
num_collisions += 1
break
# Check if we're at the goal or not
if co... | Python | 1 |
pub fn new() -> Self {
let mut options = Self::default();
options.help_available = true;
options
}
}
#[derive(PartialEq, Debug)]
pub enum HelpBehaviour {
Strike,
Hide,
Nothing,
}
impl HelpBehaviour {
pub fn from_str(s: &str) -> Option<Self> {
Some(match s.to_lower... | Rust | 0 |
new("log/btc_relay.log").to_path_buf(),
log_level: LevelFilter::Debug,
log_roll_size: 100,
log_roll_count: 5,
rpc_timeout: 15,
}
}
}
impl CmdConfig {
/// Generate config from command.
pub fn init() -> Result<(Config, Option<Command>)> {
let cm... | Rust | 0 |
# Google map 軌跡資料集json檔案轉換成DataFrame再轉換成CSV2檔案匯出
import json
import pandas as pd
def data_fransfer():
with open("時間軸.json", "r", encoding="utf-8") as f:
raw_data = json.load(f)
raw_data_fixed = raw_data.copy()
#print(raw_data_fixed.keys)
df = pd.DataFrame(columns=["No", "Lat", "Lon", "timest... | Python | 1 |
lient,
account_info,
device_id,
hass.data[DOMAIN][account_id][DATA_INTELLIGENT_SETTINGS.format(device_id)] if DATA_INTELLIGENT_SETTINGS.format(device_id) in hass.data[DOMAIN][account_id] else None,
mock_intelligent_data
)
return hass.data[DOMAIN][account_id][DATA_INTELLIGENT_SETTINGS.fo... | Python | 1 |
[np.datetime64("2021-06-03T10:00"), np.datetime64("2021-06-03T11:00")]
)
akarray = ak.highlevel.Array(nparray)
with pytest.raises(TypeError):
akarray * 2
assert ak.highlevel.Array([np.timedelta64(3, "D")])[0] == np.timedelta64(3, "D")
def test_NumpyArray_layout_as_objects():
array0 = ak... | Python | 1 |
. The `label` pointer may be `NULL` if `label_len` is zero"]
#[doc = " (an empty label, which is the default in PKCS#1 v2.2)."]
#[doc = ""]
#[doc = " - The public key."]
#[doc = ""]
#[doc = " - The destination buffer. Its maximum length (in bytes) is provided;"]
#[doc = " if that length is lower than the pu... | Rust | 0 |
:0")
.log_expect("At least one local address should be free");
listener
.local_addr()
.log_expect("Should be able to pull address from listener")
.port()
};
// Now, iterate over all ports
let addresses = "localhost:0"
.to_socket_addrs()
... | Rust | 0 |
def rectangle_area(length=2, width=3):
"""Return a rectangle's area."""
return length * width
print(rectangle_area())
print(rectangle_area(10))
print(rectangle_area(10, 5))
def rectangle_area_Test(length, width):
"""Return a rectangle's area."""
return length * width
print(rectangle_area_Test(width... | Python | 1 |
bidirectional=bidirectional,
)
else:
raise NotImplementedError(f"Not implemented {sequence_model}")
# Fully connected layer
if bidirectional:
self.real_fc_output_layer = nn.Linear(hidden_size * 2, output_size)
self.imag_fc_output_... | Python | 1 |
def stopMove(self):
self.update_idletasks()
self.graphFrame.readjust(0)
def windowsCollapseEvent(window, collapse):
""" windowsOS api magic to allow clicks to not be handled by PELD windows """
window.update_idletasks()
GWL_EXSTYLE=-20
WS_EX_TRANSPARENT=0x00000020
hwnd =... | Python | 1 |
<Item=String> + 'a {
Self::process_env_var_list(link_paths, sys_link_paths).into_iter()
.map(move |path| {
let out = iter::once(Self::emit_link_search(&path, typ));
#[cfg(target_vendor = "apple")] {
out.chain(
iter::once(Self::emit_link_search(&path, Some("framework")))
)
}
#[cfg(no... | Rust | 0 |
u8> = s.bytes().collect();
buffer.append(&mut bytes);
return buffer;
}
pub fn encode_vector(mut v: Vec<u8>) -> Vec<u8> {
let mut buffer: Vec<u8> = vec![];
let len: u64 = v.len() as u64;
buffer.append(&mut encode_unsigned(len));
buffer.append(&mut v);
return buffer;
}
pub fn encode_nested_... | Rust | 0 |
print("- Some email providers require app-specific passwords")
return False
except smtplib.SMTPException as e:
print()
print(f"❌ SMTP Error: {e}")
print("🌐 Check your SMTP server settings")
return False
except Exception as e:
... | Python | 1 |
for (i, x) in weights_0_1.mut_data().iter_mut().enumerate() {
*x -= alpha * weight_delta_0_1.data()[i];
}
for (i, x) in weights_1_2.mut_data().iter_mut().enumerate() {
*x -= alpha * weight_delta_1_2.data()[i];
}
}
progre... | Rust | 0 |
()>(f: F) {
match unsafe { libc::fork() } {
0 => {
f();
unsafe {
libc::_exit(0);
}
},
-1 => unreachable!(),
pid => unsafe {
libc::waitpid(pid, core::ptr::null_mut(), 0);
},
... | Rust | 0 |
rror!("Error parsing row: {:?}", err);
e += 1;
}
}
}
info!("Finished: Reading input file");
info!(
"Records successfully read: {}. Records not read (errors): {}",
sku_specs_allowed_values.len(),
e
);
// Read in the Specificaiton Groups and... | Rust | 0 |
/ );
// err(
// "struct Foo { a: int, bar: Bar }
// struct Bar { b: int, foo: Foo }",
// pos(2, 35),
// SemError::RecursiveStructure,
// );
// }
// #[test]
// fn test_class_in_struct() {
// ok_with_test("class Foo(a: bool, b: int... | Rust | 0 |
}
}
fn keyboard_animation_control(
keyboard_input: Res<Input<KeyCode>>,
mut animation_player: Query<&mut AnimationPlayer>,
animations: Res<Animations>,
mut current_animation: Local<usize>,
mut foxes: ResMut<Foxes>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
foxes.moving =... | Rust | 0 |
tempdir()?;
println!("{:?}", p.path());
let env1 = LocalEnv::open(p.path()).await?;
let eng = Engine::open(env1).await?;
eng.create_tenant("t1").await?;
let tenant = eng.tenant("t1").await?;
tenant.create_bucket("b1").await?;
tenant.create_bucket("b2").await?;... | Rust | 0 |
# #local scope
# def greet():
# message= "Good Morning"
# print(message)
# greet()
# #Global scope
# greeting="Hello"
# def say_hello():
# print(greeting + " from inside the function")
# # say_hello()
# # print(greeting+ " from outside the function")
# # #importing modules
# import math
# print(math.sq... | Python | 1 |
t_file_size / total_size) * total_progress
hf_weights = (
load_safetensors(bin_file) if bin_file.suffix == ".safetensors" else lazy_load(bin_file)
)
copy_fn(
sd,
hf_weights,
... | Python | 1 |
"""Subagents for the system monitor pipeline."""
from . import cpu_info_agent, disk_info_agent, memory_info_agent, synthesizer_agent | Python | 1 |
to_string());
tmp.insert("max-width".to_string(), "800px".to_string());
tmp
}
.into()
}
))
)
}
#[test]
fn test_charset() {
assert_eq!(
parse_charset("@charset \"UT... | Rust | 0 |
alaysia': 'ms', 'melayu': 'ms',
# Polish variations
'pl': 'pl', 'polish': 'pl', 'polski': 'pl', 'poland': 'pl', 'polska': 'pl',
# Swedish variations
'sv': 'sv', 'swedish': 'sv', 'svenska': 'sv', 'sweden': 'sv', 'sverige': 'sv',
# Swahili variations
'sw': 'sw', 'swahili': 'sw', 'ki... | Python | 1 |
.expect("Error reading file");
}
struct Config {
query: String,
filename: String,
}
fn parse_config(args: &[String]) -> Config {
let query = args[1].clone();
let filename = args[2].clone();
Config { query, filename }
}
/*
`args` in `main` is... | Rust | 0 |
-> io::Result<()> {
unsafe {
self.setsockopt(
libc::SOL_SOCKET,
libc::SO_KEEPALIVE,
keepalive.is_some() as c_int,
)?;
if let Some(dur) = keepalive {
// TODO: checked cast here
self.setsockopt(
... | Rust | 0 |
from .main import app # isort: skip
from .assets import project_assets
from .clone import project_clone
from .document import project_document
from .dvc import project_update_dvc
from .pull import project_pull
from .push import project_push
from .run import project_run
| Python | 1 |
# Generated by Django 3.2.23 on 2023-11-20 04:57
import InvenTree.fields
from django.db import migrations
import djmoney.models.fields
import djmoney.models.validators
class Migration(migrations.Migration):
dependencies = [
('part', '0118_auto_20231024_1844'),
]
operations = [
migration... | Python | 1 |
(($key:expr) : $($rest:tt)*) $copy:tt) => {
ijson_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*));
};
// Refuse to absorb colon token into key expression.
(@object $object:ident ($($key:tt)*) (: $($unexpected:tt)+) $copy:tt) => {
ijson_expect_expr_comma!($($unexpected)+);
... | Rust | 0 |
from tortoise import BaseDBAsyncClient
async def upgrade(db: BaseDBAsyncClient) -> str:
return """
CREATE TABLE IF NOT EXISTS "textsummary" (
"id" SERIAL NOT NULL PRIMARY KEY,
"url" TEXT NOT NULL,
"summary" TEXT NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREA... | Python | 1 |
n = int(input())
if n != 1:
i = 2
while n != 1:
if i * i > n:
break
if n % i == 0:
while n % i == 0:
n //= i
print(i)
i += 1
if n != 1:
print(n) | Python | 1 |
reponame>KeatonTech/valerie<filename>examples/hello_world/src/lib.rs<gh_stars>100-1000
use valerie::prelude::components::*;
use valerie::prelude::*;
fn launch_page() -> Node {
h1!("Hello, World!").into()
}
#[valerie(start)]
pub fn run() {
App::render_single(launch_page());
}
<gh_stars>0
pub mod eval;
pub mod ... | Rust | 0 |
.with_doc(String::from(r#"
Specifies the ZooKeeper connection string in the form <code>hostname:port</code> where host and port are the
host and port of a ZooKeeper server. To allow connecting through other ZooKeeper nodes when that ZooKeeper machine is
... | Rust | 0 |
Arc<Mutex<dyn JavaInstance>>>,
pub fields: HashMap<String, Arc<Mutex<dyn JavaInstance>>>
}
impl JavaInstance for BytecodeInstance {
fn is_bytecode(&self) -> bool { return true; }
fn get_class_name(&self) -> String {
return self.class_name.clone();
}
fn cast_as(&self, _this: Arc<Mutex<dyn Ja... | Rust | 0 |
ite_str(~"\n\n");
}
fn get_crate_attributes(data: @~[u8]) -> ~[ast::attribute] {
return get_attributes(reader::Doc(data));
}
type crate_dep = {cnum: ast::crate_num, name: ast::ident,
vers: ~str, hash: ~str};
fn get_crate_deps(intr: @ident_interner, data: @~[u8]) -> ~[crate_dep] {
let mut de... | Rust | 0 |
Err(Error::new(ErrorKind::Other, "Unable to find correct HUNK_HEADER"));
};
// Skip header/string section
try!(file.read_u32::<BigEndian>());
let table_size = try!(file.read_u32::<BigEndian>()) as i32;
let first_hunk = try!(file.read_u32::<BigEndian>()) as i32;
let las... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.