text string | label_name string | labels int64 |
|---|---|---|
Corsiva")
font.setPointSize(18)
self.push_update.setFont(font)
self.push_update.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0.0340909, stop:0 rgba(61, 61, 61, 255), stop:1 rgba(124, 124, 124, 255));\n"
"color: rgb(255, 253, 189)")
self.push_update.se... | Python | 1 |
", "ヘルスチェック"),
("/docs", "FastAPI ドキュメント"),
("/generate_music", "音楽生成 (Gradio互換API)"),
("/initialize", "パイプライン初期化"),
("/sample_data", "サンプルデータ (Gradio互換)")
]
available_endpoints = []
for endpoint, description in endpoints_to_test:
try:
url = f"{B... | Python | 1 |
# The Leginon software is Copyright under
# Apache License, Version 2.0
# For terms of the license agreement
# see http://leginon.org
#
import wx
import leginon.gui.wx.Settings
import leginon.gui.wx.IceTargetFinder
from leginon.gui.wx.Entry import Entry, IntEntry, FloatEntry
class Panel(leginon.gui.wx.IceTargetFinde... | Python | 1 |
, 0)])),
};
let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
let chain_source = test_utils::TestChainSource::new(Network::Testnet);
let logger = test_utils::TestLogger::with_id(format!("node {}", i));
let persister = test_utils::TestPersister::new();
let seed = [i as u8; 32];
let keys... | Rust | 0 |
ts
pExact: bool = args.Exact
pAccountList = args.Accounts
pstatus = args.pstatus
pFilename = args.Filename
# Setup logging levels
logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
logging.getLogger("boto3").setLevel(logging.CRITICAL)
logging.getLogger("botoco... | Python | 1 |
mpling_steps = sampling_options['steps']
ddim_eta = sampling_options['ddim_eta']
cfg_scale = sampling_options['CFG_scale']
caption = model.apply_prompt_template([prompt]* sample_quantity, [art_style]* sample_quantity, [PoA]* sample_quantity)
cond = dict(c_crossattn = [model.get_learned_conditioning(caption)] )
un... | Python | 1 |
ot_final_feature_L2_similarity_matrix[R_index, contrast_index] = L2_similarity
csv_data['final_feature_cos_similarity'].append(cos_similarity)
plot_final_feature_cos_similarity_matrix[R_index, contrast_index] = cos_similarity
df = pd.DataFrame(csv_data)
df.to_csv(os.pat... | Python | 1 |
l(envelope.serialize())
def read(self):
'''Read a message from the socket'''
envelope = NetworkEnvelope.parse(self.stream, testnet=self.testnet)
if self.logging:
print('receiving: {}'.format(envelope))
return envelope
def wait_for(self, *message_classes):
''... | Python | 1 |
import unittest
from elysium import Elysium
class TestElysium(unittest.TestCase):
def setUp(self):
self.elysium = Elysium()
def test_load_config(self):
self.assertIsNotNone(self.elysium.config)
def test_create_network(self):
self.assertIsNotNone(self.elysium.network)
def test... | Python | 1 |
) -> Decimal256 {
if aterra_supply.is_zero() {
return Decimal256::one();
}
// (aterra / stable_denom)
// exchange_rate = (balance + total_liabilities - total_reserves) / aterra_supply
(Decimal256::from_uint256(contract_balance) + state.total_liabilities - state.total_reserves)
/ De... | Rust | 0 |
ways)]
pub fn can_if1mctl_newdat(&self) -> CAN_IF1MCTL_NEWDATR {
let bits = ((self.bits >> 15) & 1) != 0;
CAN_IF1MCTL_NEWDATR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits ... | Rust | 0 |
T_KEY, algorithms=["HS256"])
user_id = payload.get("sub")
if user_id is None:
raise Exception("Invalid refresh token")
# Revoke old refresh token
revoke_refresh_token(refresh_token)
# Generate new access and refresh tokens
new_access_token = create_a... | Python | 1 |
"""
InventoryWindow クラス
インベントリ管理ウィンドウ
"""
import pygame
import pygame_gui
from pygame_gui.core.interfaces import IContainerLikeInterface
from typing import Dict, List, Any, Optional, Tuple, cast
from .window import Window
from .inventory_types import (
InventoryType, InventoryConfig, ItemSlotInfo, ItemCategory, ... | Python | 1 |
import pandas as pd
import os
import repository.exec_insert_query as eq
def insert_city_crimes_mvi():
path = f'{os.path.abspath(".")}/data_base/xlsx/MVI.xlsx'
df_mvi = pd.read_excel(path)
column_0 = df_mvi.columns[0]
year_columns = df_mvi.columns[1:]
relation_data = ""
cities = df_mvi[column_0].val... | Python | 1 |
from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from sqlalchemy import desc, asc, func, and_, or_
from datetime import date
from app.crud.base import CRUDBase
from app.models.sermon_material import SermonMaterial, SermonCategory
from app.schemas.sermon_material import (
SermonMaterialCr... | Python | 1 |
e is not None:
ip = get_ipython()
if ip:
kernel = ip
ip.showtraceback((etype, evalue, tb), tb_offset=0)
elif (self.comm is not None and
getattr(self.comm, "kernel", None) is not None and
# Check if it's ipykernel... | Python | 1 |
e of charge...",
"Shuplvvlrq lv khuheb judqwhg, iuhh ri fkdujh...",
);
purecipher_free(cipher_ptr);
}
#[test]
fn cipher_rot13() {
let cipher_ptr = purecipher_cipher_rot13();
assert_cipher_buffer(
cipher_ptr,
"Permission is hereby granted... | Rust | 0 |
line.lower():
level = 'success'
# 使用文件修改时间加上行号偏移作为时间戳
log_timestamp = base_timestamp + timedelta(seconds=i)
logs.append({
... | Python | 1 |
value) = &k_const.of(consts).value_opt {
tag = value.cast_as_usize() + 1;
continue;
}
k_const.of_mut(consts).value_opt = Some(KConstValue::Usize(tag));
tag += 1;
}
}
}
pub(crate) fn align_of(&self, mod_... | Rust | 0 |
:Allocator;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn dr... | Rust | 0 |
# Simple calculator using Python
# Function to Add two numbers
def add(num1, num2):
return num1 + num2
# Function to Subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to Multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to Divide two numbers
def divide(num1, ... | Python | 1 |
#!/usr/bin/env python
##
# @author This file is part of libsnark, developed by SCIPR Lab
# and contributors (see AUTHORS).
# @copyright MIT license (see LICENSE file)
import random
import hashlib
import struct
import math
def bitlength(p):
return int(math.ceil(math.log(p, 2)))
def SHA512_prng(i,... | Python | 1 |
///
/// `A8 ib`
///
/// `8086+`
///
/// `16/32/64-bit`
Test_AL_imm8,
/// `TEST AX, imm16`
///
/// `o16 A9 iw`
///
/// `8086+`
///
/// `16/32/64-bit`
Test_AX_imm16,
/// `TEST EAX, imm32`
///
/// `o32 A9 id`
///
/// `386+`
///
/// `16/32/64-bit`
Test_EAX_imm32,
/// `TEST RAX, imm32`
///
/// `RE... | Rust | 0 |
ce the model's ability to discern Spam messages.
3. **Hyperparameter Tuning:**
Perform hyperparameter tuning for each model to identify optimal settings that maximize overall performance. This involves adjusting parameters to achieve the best trade-off between precision and recall.
4. **Cross-Validation:**
Impl... | Python | 1 |
/// If a list of items are requested to be removed by a single function call (e.g. `delete_all`)
/// and this error is returned, then it's guaranteed that none of the items is removed.
TargetedRoot,
/// Error while canonicalizing path.
/// `code` contains a raw os error code if accessible.
CanonicalizePath {
... | Rust | 0 |
TEMPLATE_ROOT = './templates'
MODEL_TEMPLATE = 'code-templates/model.json'
MODEL_GENERATION_LOCATION = TEMPLATE_ROOT + '/json-model/'
LAYER_TYPE_DENSE = 'dense'
LAYER_TYPES = 'layer_types'
MODEL_GENERATION_TYPE = '.json'
MODEL_NAME = 'model_name'
DENSE_UNITS = 'units'
DENSE_ACTIVATION_FUNCTION = 'activation'
DENSE_ID =... | Python | 1 |
f_ffff) as u32)
}
#[doc = "Bit 9 - 9:9\\]
Internal. Only to be used through TI provided API."]
#[inline(always)]
pub fn dis_noise_filter(&self) -> DIS_NOISE_FILTER_R {
DIS_NOISE_FILTER_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - 8:8\\]
Internal. Only to be used through TI p... | Rust | 0 |
1)
# print(labels)
# print(pred)
# print("\n\n")
# print(labels)
# iterate over each prediction
# batch_size = labels.shape[0]
# # print(labels)
task_idx = res["prompt_idx"] // top_k
pred, _ = torch.mode(task_idx, dim=1)
tasks = labels //... | Python | 1 |
.success() {
true => Ok(0),
false => Ok(status.code().unwrap_or(1)),
}
}
*/
fn link_binary() -> OsString {
"ln".to_owned().into()
}
pub fn link<P>(from: P, to: P, soft: bool) -> Result<()>
where
P: AsRef<OsStr>,
{
let mut cmd = Command::new(link_binary());
if soft {
cmd.arg... | Rust | 0 |
from typing import List
# 분석할 주식 심볼 목록 (이곳에서 쉽게 추가/제거 가능)
# 예: S&P 500의 주요 기술주
STOCK_SYMBOLS: List[str] = [
"VDC", "TSLL", "TQQQ", "SCHD", "JEPQ", "JEPI",
"GLDM", "CIBR", "BITX",
"ARKG", "PFE", "KHC", "LLY", "WM",
"GOOGL", "AMZN", "VEEV", "MRK", "DUK", "NUE", "X", "NEE"
]
# 시장 지수 티커 (S&P 500)
MARKET_I... | Python | 1 |
_from_slice(new_key);
Ok(())
};
let signature = hss_sign::<H>(
&message,
signing_key_const.as_slice(),
&mut update_private_key,
None,
)
.expect("Signing should complete without error.");
assert!(hss_verify::<H>(&messag... | Rust | 0 |
clipboard: Clipboard,
modifiers: ModifiersState,
config: Config,
message_buffer: MessageBuffer,
display: Display,
font_size: Size,
event_queue: Vec<GlutinEvent<'static, Event>>,
search_state: SearchState,
}
impl<N: Notify + OnResize> Processor<N> {
/// Create a new event processor.
... | Rust | 0 |
import os
# import logging
# logging.basicConfig(level=logging.CRITICAL) # Suppress logging issues
# import pyttsx3
# engine = pyttsx3.init()
if __name__ == '__main__':
print("Welcome to RoboSpeaker 1.1 Created bu Harish")
while True:
x = input("Enter what you want me to pronounce: ")
... | Python | 1 |
),
Arc::clone(&db),
Arc::new(MockStorage {}),
Arc::new(MockServiceMapping {}),
)
.unwrap();
let params = ExecutorParams {
state_root: root,
height: 1,
timestamp: 0,
cycles_limit: std::u64::MAX,
proposer: Address::from_hash(Hash:... | Rust | 0 |
ecessor_nodes = list(node._input_nodes.keys())
self.successor_nodes = list(node.users.keys())
def check_merge(self):
merge_label = False
if self.node.op == "call_module":
target = self.node.target
root_module = self.node.graph.owning_module
submod = root_... | Python | 1 |
import time
import random
from beaver import BeaverDB
def main():
"""
Continuously publishes messages to a channel until manually stopped.
"""
print("--- Starting Publisher Process ---")
print("Publishing to 'live_events' channel. Press Ctrl+C to stop.")
db = BeaverDB("demo.db")
channel = ... | Python | 1 |
import shutil
from tests import run_main
from TTS.bin.train_encoder import main
from TTS.config.shared_configs import BaseAudioConfig
from TTS.encoder.configs.speaker_encoder_config import SpeakerEncoderConfig
def test_train(tmp_path):
config_path = tmp_path / "test_speaker_encoder_config.json"
output_path =... | Python | 1 |
"""
웹 어댑터 패키지
FastAPI 기반 웹 인터페이스를 제공합니다.
OAuth 2.0 인증 플로우를 위한 웹 인터페이스를 포함합니다.
"""
| Python | 1 |
el = [
nn.ReflectionPad1d(3),
WNConv1d(input_size, ngf, kernel_size=7, padding=0),
]
# Down-sample from raw audio scale
for i, r in enumerate(ratios):
model += [
nn.LeakyReLU(0.2),
WNConv1d(
mult * ngf,
... | Python | 1 |
<FollowPoint>
}
pub struct FollowPoint {
pub x: i32,
pub y: i32
}
pub struct HitSample {
pub normal_set: i32,
pub additional_set: i32,
pub index: i32,
pub volume: i32,
pub file_name: String
}
impl Default for HitSample {
fn default() -> Self {
HitSample {
normal_se... | Rust | 0 |
# coding: utf-8
"""
Slurm REST API
API to access and control Slurm
The version of the OpenAPI document: Slurm-24.11.5&openapi/slurmdbd&openapi/slurmctld
Contact: sales@schedmd.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E50... | Python | 1 |
from abc import ABC, abstractmethod
class Excelreader(ABC):
@abstractmethod
def readfromexcel(self):
pass
class Browser(Excelreader):
@abstractmethod
def startBrowser(self):
pass
@abstractmethod
def stopBrowser(self):
pass
class TC1(Browser):
def startBrowser(self)... | Python | 1 |
e.fromstring(xml))
def hexdump(bytestr, width=75, height=24, snipat=-2, modulo=2, ellipsis="..."):
"""Return hexdump representation of byte string.
>>> hexdump(binascii.unhexlify('49492a00080000000e00fe0004000100'))
'49 49 2a 00 08 00 00 00 0e 00 fe 00 04 00 01 00 II*.............'
"""
size = le... | Python | 1 |
import json
from pathlib import Path
from unittest.mock import patch
from api.shield.logfile.audit_loggers import FluentdAuditLogger, S3AuditLogger, LocalAuditLogger
from api.shield.model.authorize_request import AuthorizeRequest
from api.shield.model.authz_service_response import AuthzServiceResponse
from api.shield.m... | Python | 1 |
import pytest
from itertools import product
import numpy as np
from pandas.util import testing as tm
from pandas import MultiIndex, DataFrame, Series, date_range
@pytest.mark.slow
@pytest.mark.parametrize("n,m", product((100, 1000), (5, 20)))
def test_series_groupby_value_counts(n, m):
np.random.seed(1234)
... | Python | 1 |
import os
import requests
from langchain.tools import BaseTool
from pydantic import BaseModel
from typing import Type
class GetBitcoinDataInput(BaseModel):
"""Input schema for GetBitcoinData tool.
This tool doesn't require any input parameters but we still define the schema for consistency.
"""
pass
... | Python | 1 |
2802 BRAILLE PATTERN DOTS-2 */
pub const XKB_KEY_braille_dots_12 :u32 = 0x1002803; /* U+2803 BRAILLE PATTERN DOTS-12 */
pub const XKB_KEY_braille_dots_3 :u32 = 0x1002804; /* U+2804 BRAILLE PATTERN DOTS-3 */
pub const XKB_KEY_braille_dots_13 :u32 = 0x1002805; /* U+2805 BRAILLE PATTER... | Rust | 0 |
# MIT License
#
# Copyright (c) 2022 Mark Qvist / unsigned.io
#
# 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, mo... | Python | 1 |
from pulp import LpProblem, LpVariable, LpBinary, LpMinimize, lpSum
def schedule_tasks(tasks, crew_members):
# Preprocess tasks to add updated_requirement
for task in tasks:
# Use 'crew_required' if it exists, otherwise default to 1
task['updated_requirement'] = task.get('crew_required', 1)
... | Python | 1 |
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse, Response
from pydantic import BaseModel
import os
import numpy as np
# Use the advanced vectorizer (ChromaDB + ViT/CLIP)
from vector_db import ChromaVectorDB
fr... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Google reCAPTCHA integration',
'category': 'Hidden',
'version': '1.0',
'description': """
This module implements reCaptchaV3 so that you can prevent bot spam on your public modules.
""",
... | Python | 1 |
e_texture(&tile_set);
let stone_outline = Self::blank_stone(texture_creator, CHARCOAL, &tile_set);
let stone_depth = [
Self::blank_stone(texture_creator, rgba(169,109,0,255), &tile_set),
Self::blank_stone(texture_creator, rgba(50,120,0,255), &tile_set),
Self::blank_st... | Rust | 0 |
import cv2
import numpy as np
def pad_to_multiple_of_n(image, n=32):
original_height, original_width = image.shape[:2]
# 计算目标形状
target_width = ((original_width + n - 1) // n) * n
target_height = ((original_height + n - 1) // n) * n
# 创建一个纯白背景的图像
padded_image = np.ones((target_height, target_... | Python | 1 |
# step2_prepare_training_sources/data/cicada_song/segments_preprocessed/ 以下のサブディレクトリごとに、音声の長さの合計を計算する
from glob import glob
import soundfile as sf
dirs = glob('step2_prepare_training_sources/data/cicada_song/segments_preprocessed/*')
for d in dirs:
files = glob(f'{d}/*.wav')
length = 0
for f in files:
... | Python | 1 |
current_obs, next_obs,
reward, finish))
def _load_year_data_new (self):
# mins electricity consumption data for a year
ba... | Python | 1 |
}
let n_partial = n - n_int as Float;
sum += o * smooth_step(0.3, 0.7, n_partial) * noise_point(&(*p * lambda));
sum
}
pub fn turbulence(
p: &Point3f,
dpdx: &Vector3f,
dpdy: &Vector3f,
omega: Float,
max_octaves: Float,
) -> Float {
let len2 = dpdx.length_squared().max(dpdy.length_sq... | Rust | 0 |
return plaintexts, ciphertexts, ineffective
if args.verbose:
print(f"injecting faults into {args.round}th round")
print(f"index '{args.index}' type '{args.type}' bits '{args.bits}'")
plaintexts, ciphertexts, ineffective = generate_bias_ciphertexts(testkey, args.samples)
if args.verbose:
print(f"{ineff... | Python | 1 |
ost::Message` trait.
///
/// `NetworkEvents` is really just a thin wrapper around a
/// `channel::Receiver<NetworkNotification>` that deserializes inbound messages.
#[pin_project]
pub struct NetworkEvents<TMessage: Message + Default> {
#[pin]
inner: channel::Receiver<NetworkNotification>,
_marker: PhantomDa... | Rust | 0 |
let influx_type = fb_column.influx_type();
let column = self
.columns
.raw_entry_mut()
.from_key(fb_column.name())
.or_insert_with(|| {
(
fb_column.name().to_string(),
Column:... | Rust | 0 |
', '𒍕', '\u{e0045}', '✓', 'Ҷ', 'ފ', 'ﻋ',
'\u{1d17c}', 'ꘚ', '𖢾', 'ᨪ', '𔓖', '𐇨', 'ꨌ', '◝', '𒅀', '¥',
'\u{1fb0a}', 'ꑳ', 'ӎ', 'Ⰴ', 'ᛋ', '𘣛', 'Ṡ', '𝥑', 'Ằ', '𛆣', 'ﴓ',
'Ꝯ', '\u{e01d2}', '𞠆', 'γ', 'ꯡ', '㋦', '⊆', '൛', '\u{1fb7b}', '𐢬', '𛆬',
'𝄉', '亂', '⽡', '𞡬', 'ᝰ', '𘤢', 'Ⲇ', '𒁡', '\u{111bd}', '𒔅... | Rust | 0 |
yes, tallied_weight) > config.threshold {
//Threshold: More than 50% of the tokens that participated in the vote
// (after excluding “Abstain” votes) need to have voted in favor of the proposal (“Yes”).
poll_status = PollStatus::Passed;
passed = true;
} else {
... | Rust | 0 |
m_ptr(ptr) };
cstr.to_str().expect("invalid UTF-8")
}
/// The EXIF tag's support level with the given IFD and encoding.
///
/// This method returns the tag's support level according to the EXIF specification.
pub fn support_level(&self, ifd: IFD, encoding: DataEncoding) -> SupportLevel {
... | Rust | 0 |
operty_name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class TextTranslateResponse(AbstractModel):
"""TextTranslate返回参数结构体
"""
def __init__(self):
r"""
:param _TargetText: 翻译后的文本
:type TargetText: str
... | Python | 1 |
}
<gh_stars>0
use super::util::fixed_time_eq;
use std::cmp::{min, Eq, PartialEq};
use std::ops::{Add, Mul, Sub};
#[derive(Clone, Copy)]
pub struct Fe(pub [i32; 10]);
impl PartialEq for Fe {
fn eq(&self, other: &Fe) -> bool {
let &Fe(self_elems) = self;
let &Fe(other_elems) = other;
self_el... | Rust | 0 |
c = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 8);
self.w.bits |= ((value as u32) & 15) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct ADC_SSDC0_S3DCSELR {
bits: u8,
}
impl ADC_SSDC0_S3D... | Rust | 0 |
def enhance_fundus_image(image):
"""
Enhance the fundus image by converting it to the CIECAM02 color space,
extracting the J, C, h components, enhancing the J component,
and then reconstructing the enhanced color image.
"""
# Step 1: Read the input image (in RGB format)
# image_rgb = cv2.imr... | Python | 1 |
blish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVI... | Rust | 0 |
}
#[inline]
fn to_binary(self) -> i128 {
self as _
}
#[inline]
fn from_binary(bits: i128) -> Self {
bits as _
}
}
#[cfg(test)]
mod test_native_type {
use super::*;
use crate::types::Type;
#[test]
fn test_wasm_types() {
assert_eq!(i32::WASM_TYPE, T... | Rust | 0 |
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]:
ans = [-1] * len(workers)
usedBikes = [False] * len(bikes)
# buckets[k] := (i, j), where k = dist(workers[i], bikes[j])
buckets = [[] for _ in range(2001)]
def dist(p1: List[int], p2: List[int]) ... | Python | 1 |
#Maximum product subarray
#********Using Brute Force Method
# def maxSubarrayProduct(arr, n):
# result = arr[0]
# for i in range(n):
# mul = arr[i]
# for j in range(i + 1, n):
# result = max(result, mul)
# mul *= arr[j]
# result = max(result, mul)
# return res... | Python | 1 |
agent
import train
if "proprio" in args.obs_type:
dummy_env = build_single_proprio_env(
args.env_name, conf.BasicSettings.FrameSkip, args.seed)
elif "visual" in args.obs_type:
dummy_env = build_single_visual_env(
args.env_name, conf.BasicSettings.ObsShape[0],
... | Python | 1 |
riod=3,
slowk_matype=talib.MA_Type.SMA,
slowd_period=3,
slowd_matype=talib.MA_Type.SMA
)
if(target=='KD'):
rollingHigh=high.rolling(5).max()
rollingLow=low.rolling(5).min()
RSV=(close-rollingLow)/(rollingHigh-rollingLow)
... | Python | 1 |
#
# Tests for the 'osbuild.util.testutil.mock_command' module.
#
import os
import subprocess
import textwrap
from osbuild.testutil import mock_command
def test_mock_command_integration():
output = subprocess.check_output(["echo", "hello"])
assert output == b"hello\n"
fake_echo = textwrap.dedent("""\
... | Python | 1 |
model_data = self.parse_chunk(header, data)
results['wmo_models'] = model_data['models']
elif header.name == 'MDDF':
placement_data = self.parse_chunk(header, data)
results['m2_placements'] = placement_data['entries']
el... | Python | 1 |
t self) -> Option<S> {
if self.is_term {
return None;
}
match self.src_rx.recv() {
Err(e) => {
println!("WARNING: src recv error: {:?}", e);
return None;
}
Ok(item) => {
if item.is_none() {
self.is_term = true;
}
item
}
}
... | Rust | 0 |
class Foo {
#tag() {
return this;
}
#tag2 = this.#tag;
constructor() {
const receiver = this.#tag`tagged template`;
expect(receiver).toBe(this);
const receiver2 = this.#tag2`tagged template`;
expect(receiver2).toBe(this);
}
}
new Foo... | Rust | 0 |
let body = ReleaseDir(fetch(src));
req!(header, body)
}
FUSE_FSYNCDIR => {
let body = FSyncDir(fetch(src));
req!(header, body)
}
FUSE_STATFS => {
let body = StatFS();
req!(header, bo... | Rust | 0 |
lass:`.AsyncClientCertificateProvider` factories.
.. versionadded:: 5.19
.. versionchanged:: 5.27 Stabilized from preview.
"""
@staticmethod
def static(cert: ClientCertificate) -> AsyncClientCertificateProvider:
"""
Create a static client certificate provider.
The provide... | Python | 1 |
t however we probably want to check the response though,
// so we can block current thread and wait for it to finish.
// Note that since the request is being driven by the host, we don't have to wait
// for the request to have it complete, we will just not read the response.
let response = pending
.try_... | Rust | 0 |
rades.set_xlabel('Trade Number')
ax_trades.set_ylabel('P&L')
ax_trades.grid(True)
else:
ax_trades.text(0.5, 0.5, 'No trade history available',
horizontalalignment='center', verticalalignment='center')
ax_trades.set_title('Trade P&L')
# 6. Perform... | Python | 1 |
t DMsg::Success = msg {
return libc::c_int::from(NssStatus::Success);
}
libc::c_int::from(NssStatus::Success)
}
/// # Safety
///
/// This function intended to be called from nss
#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getspent_r(spptr: *mut Spwd, buf: *mut libc::c_char, buflen: libc::size_t,... | Rust | 0 |
mpany": company,
"Articles": articles,
"Comparative Sentiment Score": comparison,
"Final Sentiment Analysis": "Overall sentiment is mostly positive. Expect market impact."
}
st.json(result) # Display structured output
... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2020 Google Inc. 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 |
();
}
patterns
}<gh_stars>1-10
use custom_error::custom_error;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::result;
custom_error! {pub Error
PathIo {
source: io::Error,
path: PathBuf
} = @{format!("{}: {}", path.display(), source)},
// no need for this one for ... | Rust | 0 |
t_text": """
<Page 1>
Show me 1 table on the first page that shows tips and sorted by day
Using export button I want to export data to csv
Add filters by bill and by tip amount using slider
<Page 2>
Second page should contain kpi cards with population trends and
two popular charts that disp... | Python | 1 |
ution = vec![(0, 0); tiles.len()];
let mut taken = vec![false; tiles.len()];
let ok = solve(&tiles, dims, &mut solution, 0, &mut taken);
assert!(ok);
let img = get_image(dims, &tiles, &solution);
// print_grid(&img);
let all_imgs = generate_all_grids(&img);
for cur_img in all_imgs.iter() ... | Rust | 0 |
from .constants import *
from .fields import *
from .guild_preview import *
__all__ = (
*constants.__all__,
*fields.__all__,
*guild_preview.__all__,
)
| Python | 1 |
"""
A script to populate a project with some data
"""
import os
from typing import List
import phospho
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv("../backend/.env")
assert (
os.getenv("OPENAI_API_KEY") is not None
), "Please set the OPENAI_API_KEY environment variable"
assert (
os.... | Python | 1 |
m runtime e.g. the allocator
/// interface. To support this, the macro can be called like `#[runtime_interface(wasm_only)]`.
/// This instructs the macro to make two significant changes to the generated code:
///
/// 1. The generated functions are not callable from the native side.
/// 2. The trait as shown above is no... | Rust | 0 |
VectorPacked_customErrorCalc(vector as *mut f32, vector as *mut f32, buffer.len() as i32, DEFAULT_STREAM.stream) }
cuda_memcpy(buffer.as_mut_ptr(), vector, buffer.len()*size_of::<f32>(), cudaMemcpyKind::DeviceToHost);
cuda_free(vector);
buffer.iter().for_each(|x| print!("{}, ", x));
prin... | Rust | 0 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from materials.sections.structural_shapes import aisc_metric_shapes
from sympy.physics import units
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2014, LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
rati... | Python | 1 |
#coding=utf-8
#狄克斯特拉算法
#乐谱换钢琴问题
graph = {}
graph ["yuepu"] = {}
graph ["yuepu"]["changpian"] = {5}
graph ["yuepu"]["haibao"] = {0}
graph ["cahngpian"] ={}
graph ["cahngpian"]["jita"] ={15}
graph ["cahngpian"]["jiazigu"] ={20}
graph ["haibao"] = {}
graph ["haibao"]["jita"] = {30}
graph ["haibao"]["jiazigu"] = {35}
g... | Python | 1 |
run
root.destroy()
run = 0
def open_window():
window = tk.Tk()
commands.center_window(window)
def uni():
commands.open_website(f'{sub.private_link_may}')
commands.open_website(f'{sub.private_link_moo}')
commands.open_website(f'{sub.private_link_soul}')
... | Python | 1 |
NFORMATION_CLASS = 0i32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_ProcessSnapshotting\"`*"]
pub const PSS_QUERY_VA_CLONE_INFORMATION: PSS_QUERY_INFORMATION_CLASS = 1i32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_ProcessSnapshotting\"`*"]
pub const PSS_QUERY_AUXILIARY_PAGES_INFORMATION: PS... | Rust | 0 |
ions]
return extensions
def get_available_loras():
return ['None'] + sorted([item.name for item in list(Path(shared.args.lora_dir).glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=natural_keys)
def get_datasets(path: str, ext: str):
# include subdirectories for raw txt files t... | Python | 1 |
' => return self.parse_tag_name(),
'\"' => {
return match self.parse_quoted_string() {
Ok(quoted_string) => Token::StringLiteral(quoted_string),
Err(err_token) => err_token,
}
}
'0'..='9' => return self.parse_numeric_literal(),
_ => {
... | Rust | 0 |
f.Cinv[l,:,:], self.dCdt[a,l,:,:])) + 0.5*np.trace(np.dot( np.dot(self.Cinv[l,:,:], np.dot(self.dCdt[a,l,:,:], self.Cinv[l,:,:])), d[l,:,:]) ) )
# Do the projection
dLdt_projected = np.zeros(n_interesting)
for a in range(n_interesting):
dLdt_projected[a] = dLdt[a] - np.dot(P[a], dLd... | Python | 1 |
class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
MOD = 10 ** 9 + 7
dp = [0 for _ in range(high + 1)]
dp[0] = 1 # Base case: one way to create an empty string
for i in range(1, high + 1):
if (i - zero) >= 0:
dp... | Python | 1 |
ine(draw, &points[0], &points[1], steps_left, STEP_LINE);
if steps_left <= 0 {
return;
}
steps_left -= draw_line(draw, &points[1], &points[2], steps_left, STEP_LINE);
if steps_left <= 0 {
return;
}
steps_left -= draw_additional_lines(draw, &points[0], &points[1], &points[2], st... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [
path("products/", views.product_list, name="product_list"),
path("products/<int:id>/", views.product_detail, name="product_detail"),
path("products/<int:id>/like/", views.product_like, name="product_like"),
path("cart/", views.cart_view,... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.