text string | label_name string | labels int64 |
|---|---|---|
thesisError)
},
)?;
let dense_var = region.assign_advice(
|| "dense",
cols.dense,
row,
|| {
dense_val
.map(|v| F::from_u64(v as u64))
.ok_or(Error::SynthesisError)
},
... | Rust | 0 |
import torch
def print_dataloader_summary(dataloader):
def get_channel_stats(data):
channel_means = []
channel_stds = []
channel_mins = []
channel_maxs = []
for c in range(data.size(1)):
channel_data = data[:, c, :, :]
channel_means.appe... | Python | 1 |
def show_name(first_name,last_name):
print(f"{first_name} {last_name}")
show_name(last_name="Getachew",first_name="Demis") | Python | 1 |
'=')
.map(|value| value.trim())
.collect::<Vec<&str>>();
(config_map[0], config_map[1])
}
pub fn extract_value_from(line: &str) -> Option<String> {
let (_key, value) = extract_config_from(line);
if value.is_empty() {
None
} else {
Some(value.into())
}
}
#[cfg(tes... | Rust | 0 |
_name_str, #method_name_str, data).await?;
let response = ::serde_json::from_slice(&output)
.map_err(|e| ::webwire::ConsumerError::DeserializerError(e))?;
Ok(response)
}
})
}
stream
}
fn gen_consumer_method_signature(method: &schema::Metho... | Rust | 0 |
import chainladder as cl
import numpy as np
import pandas as pd
def test_constant_cdf(raa):
dev = cl.Development().fit(raa)
xp = dev.ldf_.get_array_module()
link_ratios = {
(num + 1) * 12: item for num, item in enumerate(dev.ldf_.values[0, 0, 0, :])
}
dev_c = cl.DevelopmentConstant(pattern... | Python | 1 |
**56_346 us** | **177_085 us** |
//! | 500_000 | **3_663 us** | **12_927 us** | | 100_000_000 | **119_500 us** | **366_164 us** |
//! | 1_000_000 | **6_596 us** | **24_879 us** | | 200_000_000 | **231_974 us** | **798_497 us** |
//! | 10_000_000 | **79_342 us** | **263_105 us** | | | | |
//!
//! ### For **`u64`** (Dist... | Rust | 0 |
f.std)
if target is None:
return image, None
target = target.copy()
h, w = image.shape[-2:]
if "boxes" in target:
boxes = target["boxes"]
boxes = box_xyxy_to_cxcywh(boxes)
boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)
... | Python | 1 |
import os
import xml.etree.ElementTree as xml
import json
data = {
"name": "Brais Moure",
"age": 36,
"birth_date": "29-04-1987",
"programming_languages": ["Python", "Kotlin", "Swift"]
}
xml_file = "mouredev.xml"
json_file = "mouredev.json"
"""
Ejercicio
"""
# XML
def create_xml():
root = xml.... | Python | 1 |
_arrangements[suit] = self.arrangement_values[suit];
}
for value in 0..7 {
if self.in_hand_by_type[tile_id] != 4 {
self.kokushi
.draw(tile_id as u32, self.concealed_tiles[tile_id] as u32);
self.chiitoi.draw(self.concealed_tiles[tile_id]);
... | Rust | 0 |
tokens = UnsentStakedTokens::load(&deps.storage)?;
if unsent_tokens.0 != Uint128::zero() {
messages.push(send_msg(
treasury,
unsent_tokens.0,
None,
None,
None,
258,
stake_config.staked_tok... | Rust | 0 |
= Path(dl_manager.download_and_extract(urls))
data_files = {"train": base_dir}
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": data_files["train"],
"split": "train",
... | Python | 1 |
Tray16 = 35,
// Tray 17.
Tray17 = 36,
// Tray 18.
Tray18 = 37,
// Tray 19.
Tray19 = 38,
// Tray 20.
Tray20 = 39,
// Roll 1.
Roll1 = 40,
// Roll 2.
Roll2 = 41,
// Roll 3.
Roll3 = 42,
// Roll 4... | Rust | 0 |
0.0 {
return -1;
}
let solution = -a/b;
if solution == (solution as i64) as f64 {
return -1;
}
let i = 2.0;
let mut ak = a * i;
let mut bk = b * i;
while a.fract() != 0.0 || b.fract() != 0.0 {
a = ak;
b = bk;
ak = ak * i;
bk = bk * i;
}
if a == (a as i64) as f64 && b == (b as i64) as f64 {
let a... | Rust | 0 |
#!/usr/bin/python3
"""Defines the FileStorage class."""
import json
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.place import Place
from models.amenity import Amenity
from models.review import Review
class FileStorage:
... | Python | 1 |
#!/usr/bin/env python
import socket, struct, time, math, errno
import fgFDM
class udp_socket(object):
'''a UDP socket'''
def __init__(self, device, blocking=True, input=True):
a = device.split(':')
if len(a) != 2:
print("UDP ports must be specified as host:port")
sys.ex... | Python | 1 |
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PORTA`"]
#[inline(always)]
pub fn is_porta(&self) -> bool {
*self == EXTIPSEL11_A::PORTA
}
#[doc = "Checks if the value of the field is `PORTB`"]
#[inline(always)]
pub fn is_portb(&self) -> bool {
... | Rust | 0 |
from decimal import Decimal
from unittest import TestCase
from faz.bot.wynn.util.ingredient_drop_probability import IngredientDropProbability
class TestIngredientUtil(TestCase):
def test_ingredient_util(self) -> None:
# PREPARE
ingutil = IngredientDropProbability(Decimal(0.1), 50, 50)
# A... | Python | 1 |
]
fn xor_works() {
// Data is twice as long as the key.
let data : Vec<u8> = vec![0b11111111u8, 0b11111111u8, 0b00001111u8, 0b10101010u8, 0b11111111u8, 0b11111111u8, 0b00001111u8, 0b10101010u8];
let key : Vec<u8> = vec![0b11111111u8, 0b00000000u8, 0b11110000u8, 0b01010101u8];
le... | Rust | 0 |
el\xf4[\xb3\xd1WVl\xf4\xab\xed\x0f\xc0\xb6\xc0\
\x9d\xd1A\xd4(\xc7\x03\x7f\x8c\x0e\xd10\x07\x01[F\
\x87X\x88\x03\x0cr\xeaNk\xf6U\xca\x8a/\xc8\xea\
\x9b\x06\xec\x08\x5c\x12\x1dD\x8dp\x0a>|[\xb61\
\xc0\xbfG\x87X\x84\x8d\xbe\x1c\xd1o\xcd\x11}e\xc5\
F\xbf\x1e\x9e\x22\xcd\xdd\xfdnt\x10\xd5\xda\xa5\xc0\xfb\
\xa3C4\xd0\x01\xc... | Python | 1 |
32)[:, :, ::-1] / 127.5 - 1
prepare_vision_frame = prepare_vision_frame.transpose(0, 3, 1, 2)
region_mask : Mask = face_parser.run(None,
{
face_parser.get_inputs()[0].name: prepare_vision_frame
})[0][0]
region_mask = numpy.isin(region_mask.argmax(0), [ FACE_MASK_REGIONS[region] for region in face_mask_regions ])... | Python | 1 |
defaults to `True`):
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
Returns:
[`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is
True, otherwise a `tuple. When returning a t... | Python | 1 |
from __future__ import annotations
import abc
import dataclasses
import typing
import pydantic
from microbootstrap.helpers import merge_pydantic_configs
if typing.TYPE_CHECKING:
from microbootstrap.console_writer import ConsoleWriter
InstrumentConfigT = typing.TypeVar("InstrumentConfigT", bound="BaseInstrumen... | Python | 1 |
it is possible for a
//! process to escape a process group by simply calling `setpgid(2)`. Thus,
//! such a solution would need to be aware of all calls to `setpgid` and
//! `setsid` to perform proper bookkeeping and maintain an internal set of
//! process groups.
//! 5. We could fork off a child proc... | Rust | 0 |
ntry.black}")
wplayer = players[matchentry.white]
bplayer = players[matchentry.black]
match = Match(wplayer, bplayer, time=4*60*1000, verbose=True)
match.finish_game()
print(match._board)
print(decode_match_end(*match._status))
matchentry.set_result(match._status... | Python | 1 |
tityManager::new();
manager.generations[0] = 0;
let entity = Entity::new(0, 0);
assert_eq!(true, manager.is_alive(entity));
}
#[test]
fn entity_manager_new_returns_expected() {
let manager = EntityManager::new();
// Make sure all generations are set to 0
l... | Rust | 0 |
the subset, only for bin_involved
pro2best_hit_in_this_bin = {} # # Store all the proteins that have best hits in this bin
for pro in pro2best_hit:
if pro2bin[pro] == bin_name2:
pro2best_hit_in_this_bin[pro] = pro2best_hit[... | Python | 1 |
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_variant_attribute")
frappe.db.sql(
"""
UPDATE `tabItem Variant Attribute` t1
INNER JOIN `tabItem` t2 ON t2.name = t1.parent
SET t1.variant_of = t2.variant_of
"""
)
| Python | 1 |
a = int(input("enter la valeur de a ="))
b = int(input("enter la valeur de b ="))
if a*b>0:
print(a ,"et ",b ,"meme sign")
else:
print(a ,"et ",b ," sign deferent") | Python | 1 |
ot(plt)
plt.figure(figsize=(5, 5))
plt.plot(frequencies, spectrum_amplitude_AP, 'k')
plt.xlabel('Frequência Temporal (Hz)')
plt.ylabel('Magnitude de aceleração AP (g)')
plt.xlim(0, 6)
plt.ylim(0, lim/10)
st.... | Python | 1 |
print("Once upon a time...")
######
# TREENODE CLASS
######
class TreeNode:
def __init__(self, story_piece):
self.story_piece = story_piece
self.choices = []
def add_child(self, node):
self.choices.append(node)
def traverse(self):
story_node = self
print(story_nod... | Python | 1 |
{
for (peer, _) in list {
self.floodsub.add_node_to_partial_view(peer);
}
}
MdnsEvent::Expired(list) => {
for (peer, _) in list {
self.floodsub.remove_node_from_partial_view(&peer);
}... | Rust | 0 |
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixels")
plt.xlim([min, max])
for index in tqdm(sample_list):
sample = functor(index)
if (cutoff):
masked = sample.img_data[np.where((sample.img_data < max) & (sample.img_dat... | Python | 1 |
mut _) };
work[0].re as i32
}
fn xgeev(jobvl: u8,
jobvr: u8,
n: i32,
a: &mut [Self],
lda: i32,
w: &mut [Self],
vl: &mut [Self],
ldvl: i32,
vr: &mut [Self],
ldvr: i32,
work: &mut [Self],
lwork: i32,
info: &mut i32)
... | Rust | 0 |
() {
write!(f, ",\n")?;
}
write!(f, "]")
}
}
impl<'s, T> LowerHex for SliceVec<'s, T>
where
T: LowerHex,
{
#[allow(clippy::missing_inline_in_public_items)]
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
write!(f, "[")?;
if f.alternate() {
write!(f, "\n ")?;
}
for... | Rust | 0 |
dress(&who);
let info = T::Runner::call(
source,
source,
target,
input,
value,
gas_limit,
storage_limit,
T::config(),
)?;
let used_gas: u64 = info.used_gas.unique_saturated_into();
Ok(PostDispatchInfo {
actual_weight: Some(T::GasToWeight::convert(used_gas)),
pays_f... | Rust | 0 |
#!/usr/bin/env python
#coding=utf8
import glob, os
from optparse import OptionParser
from filterShell import FilterShell
from getFileTime import getFileTime
from scanShell import *
from createHtml import createHtml
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-p", "--path", dest="path",
h... | Python | 1 |
# Set the total loss
total_loss = 0.0
# Set the progress bar
pbar = tqdm(test_loader, total=len(test_loader), ncols=160, colour="yellow", file=sys.stdout)
# Set the models to evaluation
model.eval()
with torch.no_grad():
for i, (image, mask, text_descrip... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Tests for the debug utils.
"""
from mu.debugger.utils import is_breakpoint_line
def test_is_breakpoint_line_valid_code():
"""
A simple check to ensure a valid line of Python returns True.
"""
code = 'print("Hello")'
assert is_breakpoint_line(code)
def test_is_breakpoi... | Python | 1 |
ith(".ems"):
if line.startswith("#FORMAT") or \
(("EMSA" in line) and ("Spectral" in line)):
return True
except Exception:
pass
return False
def test(filename):
if isThermoEMSFile(filename):
sf=ThermoEMSFileParser(filename)
else:
print(... | Python | 1 |
unsafe { &mut UNVISITED_SIZE };
if *unvisited_size == unvisited.len() {
Err(Error::NoMem)?;
}
// insert at end
unvisited[*unvisited_size] = (x, y, h);
*unvisited_size += 1;
// maintain heap invariant
let mut i = *unvisited_size-1;
while i > 0 {
let p = (i-1) / 2;
... | Rust | 0 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import unittest
from collections.abc import Iterable
from io import StringIO
from pathlib import Path
from typing import... | Python | 1 |
async fn stop_pod_sandbox(
&self,
request: Request<criapi::StopPodSandboxRequest>,
) -> Result<Response<criapi::StopPodSandboxResponse>, Status> {
self.handle_stop_pod_sandbox(request).await
}
async fn remove_pod_sandbox(
&self,
request: Request<criapi::RemovePodSa... | Rust | 0 |
Some(registration) => registration.update(poll, token, interest, opts),
None => Err(io::Error::new(io::ErrorKind::Other, "receiver not registered")),
}
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
match self.registration.borrow() {
Some(registration) => regist... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class ContrastiveLoss(nn.Module):
def __init__(self, temperature=0.07, noise_text_ratio=0.0, normalize=False):
super(ContrastiveLoss, self).__init__()
self.temperature = temperature
self.noise_text_ratio = ... | Python | 1 |
itedList { offset } => {
let mut addr = addr + offset;
println!(
"{}(0x{:08x}) {}: [{}; N] = [",
indent,
addr.0,
field.name,
field.desc.name(),
);
loop {
print!("{} (0x{:08... | Rust | 0 |
, timeseries_fields, centroid_radec)
scr_data['target_position'] = data['target_position']
scr_data['quarter_timestamps'] = data['quarter_timestamps']
data = scr_data
if invert: # inverts light curve for inverted group runs
data['all_flux'] = [flux - 2 * np.median(flux) for flux ... | Python | 1 |
x + overpower_offset,len(renewable_power)):
overcharge_end_index = i
not_leaving: bool = i<vehicle_leave_index
not_fully_charged: bool = energy_left-sum(overcharge_power)/60>0
min_charging_power_possible: bool = renewable_power[i]>=1000
... | Python | 1 |
#!/usr/bin/env python3
# used to generate models:
# where_op.onnx
# where_op_broadcast.onnx
# where_op_scalar_x.onnx
# where_op_scalar_y.onnx
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, condition, x, y):
... | Python | 1 |
\Lambda} A_\lambda \neq \emptyset"#,
r#"A = \left\{z \in \mathbb{C} \;\middle|\; \zeta \left( z \right) = 0 \; \text{and} \; \Re z \neq \frac12 \right\}"#,
r#"\# \mathbb{N} = \aleph_0"#,
r#"\lnot ( P \lor Q) \Leftrightarrow ( \lnot P ) \land ( \lnot Q )"#,
r#"0 \longrightarrow L \overse... | Rust | 0 |
abel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(valid['Close'])
plt.plot(valid['Predictions'])
plt.legend(['Actual', 'Prediction'], loc='upper right')
plt.show()
st.pyplot()
st.subheader("100days and 200days Moving Average")
ma100 = data.Close.rolling(1... | Python | 1 |
self?.filter(|v| if *v > maximum {
Err(Box::new(ValidatorError::AboveMaximum(format!("{}", maximum))))
} else {
Ok(())
}
)
}
/// Makes sure that the configuration value is within a specified range.
///
/// Uses an implementaiton of the
/// [`range`](https://doc.rust-lang.org/std/ops/struct.Range... | Rust | 0 |
import os
def facturacion(usuario):
os.system("cls")
print("*************FACTURACION**************")
print("1............................Vender")
print("2..................Imprimir Factura")
print("3....................Anular Factura")
print("4..........Volver al menu principal")
opcion = i... | Python | 1 |
bel=y_va, reference=dtrain)
model = lgb.train(
params, dtrain,
num_boost_round=args.num_boost_round,
valid_sets=[dtrain, dvalid], valid_names=["train","valid"],
early_stopping_rounds=args.early_stopping_rounds, verbose_eval=False
)
yhat_te = model... | Python | 1 |
AstLikeWrapper::new(node, ImplItemTag))
}
fn flat_map_foreign_item(
&mut self,
node: P<ast::ForeignItem>,
) -> SmallVec<[P<ast::ForeignItem>; 1]> {
self.flat_map_node(node)
}
fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
self.fl... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2020 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 |
es: Vec<MatchAttribute>,
rules: Vec<Rule>,
}
impl Policy {
/// Constructs an 'empty' Policy
pub fn new() -> Self {
Policy {
attributes: Vec::new(),
rules: Vec::new(),
}
}
/// Constructs a Policy that matches and allows any request
pub fn allow_any() -> S... | Rust | 0 |
inputs and outputs of both the vertex and fragment shaders are equally matched.
gl::attach_shader(shader_program_yellow, vertex_shader);
gl::attach_shader(shader_program_yellow, fragment_shader_yellow);
gl::link_program(shader_program_yellow);
// set up vertex data (and buffer(s)) and ... | Rust | 0 |
1.0, (1.486719514734297707908E-6f64).ln(), ln_pdf(0.0));
test_case(0.0, 10.0, (0.03520653267642994777747f64).ln(), ln_pdf(-5.0));
test_case(0.0, 10.0, (0.03866681168028492069412f64).ln(), ln_pdf(-2.5));
test_case(0.0, 10.0, (0.03989422804014326779399f64).ln(), ln_pdf(0.0));
test_case(0.... | Rust | 0 |
else:
print("Single-GPU training")
# Configure trainer for TorchElastic
trainer = pl.Trainer(
max_epochs=args.epochs,
accelerator="gpu",
devices=local_world_size, # Number of GPUs per node
num_nodes=num_nodes, # Number of nodes
strategy=strategy,
p... | Python | 1 |
rce {
fn id(&self) -> &str;
fn path(&self) -> &Path;
fn path_mut(&mut self) -> &mut PathBuf;
fn last_updated(&self) -> SystemTime;
async fn get_download_url(&self, api: &Api) -> Result<Url>;
}
#[async_trait(?Send)]
impl<T: SimpleDownloadableResource> Resource for T {
fn id(&self) -> &str {
... | Rust | 0 |
tx(hash, rpc_client.clone(), tps_counter.clone()).await;
}
}
use assert2::{assert, let_assert};
use tokio_seqpacket::UnixSeqpacket;
/// Test a simple send and recv call.
#[tokio::test]
async fn send_recv() {
let_assert!(Ok((a, b)) = UnixSeqpacket::pair());
assert!(let Ok(12) = a.send(b"Hello world!").await);
l... | Rust | 0 |
del ea9oyhg7zvm
assert sb4f_3mwgnv, None
0.0[0j]: mohl5j_mokh = z0vex63u8ar
False[0] /= kfr0vh8jpow
@fih6w_ybl3e(0j, yp7dg9_5w20, None, low6_k5sk1b=gyj5fyz5ksc, q7e8n2rwpck=0, hf_pw71n1g8=x5og55o93j3, b9pr9g_wgy0=z805wizkakw, ka_pvxbm7rs=b'')
@{cufxkleabhs}
@0.0 << y2vytna8rzf
def tl5iw_2nsm8(thijfv1e8... | Python | 1 |
# some calibration files
for i in range(2):
data = np.random.random((10, 10))
fits_image(
data,
dict(JD=i, TELESCOP="A", IMAGETYP="dark"),
path.join(destination, f"A-bis-test_d{i}.fits"),
)
for i in range(2):
data = np.random.random((10, 10))
... | Python | 1 |
elf, DataId):
self._DataId = DataId
@property
def TaskId(self):
return self._TaskId
@TaskId.setter
def TaskId(self, TaskId):
self._TaskId = TaskId
def _deserialize(self, params):
self._DataId = params.get("DataId")
self._TaskId = params.get("TaskId")
... | Python | 1 |
by-area.txt', RedirectView.as_view(url='/wg/1wg-summary.txt', permanent=True)),
url(r'^summary-by-acronym.txt', RedirectView.as_view(url='/wg/1wg-summary-by-acronym.txt', permanent=True)),
url(r'^1wg-summary.txt', views.wg_summary_area),
url(r'^1wg-summary-by-acronym.txt', views.wg_summary_acronym),
url... | Python | 1 |
.map_err(|_| ParserError::parser_unexpected_buffer_end)?;
let recipient = self.encoded_address()?;
check_canary!();
zxformat::pageString(out_value, recipient.as_ref(), page_idx)
}
2 => {
writer_key
.write_s... | Rust | 0 |
use crate::EvtxRecord;
use encoding::all::WINDOWS_1252;
use encoding::EncodingRef;
use std::cmp::max;
use std::fmt;
use std::fmt::Debug;
use std::iter::{IntoIterator, Iterator};
use std::path::Path;
use std::sync::Arc;
pub const EVTX_CHUNK_SIZE: usize = 65536;
pub const EVTX_FILE_HEADER_SIZE: usize = 4096;
// Stable... | Rust | 0 |
let mut nested_bits = vec![];
let mut bits_iter = bits.iter();
while let Some(thing) = bits_iter.next() {
match thing {
ScriptBit::OpCode(v @ (OpCodes::OP_IF | OpCodes::OP_NOTIF | OpCodes::OP_VERIF | OpCodes::OP_VERNOTIF)) => nested_bits.push(ScriptBit::If {
... | Rust | 0 |
,128) should convert to hsl (5.23598766, 1.0, 0.25)
let (r, g, b) = (0.5, 0.0, 0.5);
let actual = convert_rgb_to_hsl_to_rgb(r, g, b);
assert!(compare_rgb_pairs((r, g, b), actual));
}
#[test]
fn rgb_to_hsl_silver() {
// silver rgb (191,191,191) should convert to hsl (0.0, 0.0, 0.75)
let (r, g, b) = ... | Rust | 0 |
t else button_color, resumeBtn_rect)
background_image.blit(resumeBtn_text,resumeBtn_text_rect )
pygame.draw.rect(background_image, button_highlight_color if saveBtn_highlight else button_color, saveBtn_rect)
background_image.blit(saveBtn_text, saveBtn_text_rect)
pygame.draw.rec... | Python | 1 |
O: handle the None value of insert block
self.builder.get_insert_block(),
);
}
self.builder.create_br_instr(end_block);
}
pub fn get_branch_target(&self, depth: u32) -> &BranchTarget<'ll> {
&self.branch_target_stack[self.branch_target_stack.len() - depth as ... | Rust | 0 |
from secrets import token_hex
from bot import (
LOGGER,
download_dict,
non_queued_dl,
queue_dict_lock,
download_dict_lock,
)
from bot.helper.ext_utils.bot_utils import sync_to_async
from bot.helper.aeon_utils.nsfw_check import is_nsfw, is_nsfw_data
from bot.helper.ext_utils.task_manager import (
... | Python | 1 |
from pyscript import display,HTML
def click_handler1():
display(HTML('''<br/><h1>Example1</h1><p>Simple example showing <script type="py" >.
<script type="py" terminal> has both print and display where as <script type="py" > has only display </p>
<h6>index.html</h6>
<pre style="backgr... | Python | 1 |
import logging
import simpy
from leaf.application import Task
from leaf.infrastructure import Node
from leaf.power import PowerModelNode, PowerMeasurement, PowerMeter
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s\t%(message)s')
def main():
"""Simple example ... | Python | 1 |
/mp4",
"png": "image/png",
"gif": "image/gif",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"txt": "text/plain",
"svg": "image/svg+xml",
"avi": "video/x-msvideo",
"mov": "video/quicktime",
"flv": "video/x-flv",
"wmv": "video/x-ms-wmv",
... | Python | 1 |
let (left, right) = data.split_at_address(addr);
if let Some(data) = right {
new_chunk.push_data(data, addrs_out);
}
// There was some leftover data
if let Some(data) = left {
cur_max_addr =
... | Rust | 0 |
pt 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, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | Rust | 0 |
op application");
// Apply the new operation.
self.doc = Op::apply(&self.doc, op);
// TODO Generate an "undo" version of the operation and store it.
// This should come from the Op::apply above.
// Combine operation with previous queued operations.
self.local_op = Op:... | Rust | 0 |
let dst_path = &dst_dir.path();
create_src_structure_in_dir(src_path);
map_directory(src_path, dst_path, &SETTINGS);
check_that_dst_structure_is_correct_if_videos(dst_path, true);
}
fn check_that_dst_structure_is_correct_if_videos(dst_path: &Path, videos: bool) {
check_dir1(dst_path);
che... | Rust | 0 |
import argparse
import sys
sys.path.append(".")
from base_classes import IPAdapterTextToImageBenchmark # noqa: E402
IP_ADAPTER_CKPTS = {
# because original SD v1.5 has been taken down.
"Lykon/DreamShaper": ("h94/IP-Adapter", "ip-adapter_sd15.bin"),
"stabilityai/stable-diffusion-xl-base-1.0": ("h94/IP-A... | Python | 1 |
("Unexpected character {}", status),
}
}
fn days_in_month(month: usize) -> usize {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => panic!("Unexpected month {}", month),
}
}
fn minutes_since_year_start(month: usize, day: usize, hour: usiz... | Rust | 0 |
OCTOBER = 10,
NOVEMBER = 11,
DECEMBER = 12,
}
impl ::protobuf::ProtobufEnum for Month {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<Month> {
match value {
0 => ::std::option::Option::Some(Month::MONTH_UNSPECIFIED),
... | Rust | 0 |
, ',')
.map(|x| x.parse().unwrap())
.collect::<Vec<i32>>()
.try_into()
.unwrap();
Vector2D::new(x, y)
})
.collect::<Vec<Vector2D>>()
.try_into()
... | Rust | 0 |
hyper::uri::RequestUri;
use hyper::method::Method;
use hyper::header::{Headers, Host, Referer};
// use common;
pub fn logger_fn<'mw>(req: &mut Request, res: Response<'mw>) -> MiddlewareResult<'mw> {
let uri: String = get_uri(&req.origin.uri);
let method: String = get_method(&req.origin.method);
println!... | Rust | 0 |
# 0-1 Knapsack with Duplicate Items
def knapSack(N, W, val, wt):
dp = [0 for i in range(W + 1)]
for i in range(W + 1):
for j in range(N):
if wt[j] <= i:
dp[i] = max(dp[i], dp[i - wt[j]] + val[j])
return dp[W]
N = 4
W = 8
val = [1, 4, 5, 7]
wt = [1, 3, 4, 5]
print(knapSac... | Python | 1 |
import pandas as pd
import numpy as np
def boolean():
print("boolean.py")
# Read csv
df = pd.read_csv("D:\csv_files\diabetes.csv")
pd.reset_option("max_columns")
# print(df.head())
# print("Rows and columns:",df.shape)
# df.info()
# change to boolean type
df1 = df.copy()
df1['... | Python | 1 |
val as i64;
let res: i64 = _val >> shift;
res as u64
}
#[inline(always)]
pub fn set_nth_bit_u64(value: u64, index: usize, set_value: u8) -> u64 {
value ^ (((-(set_value as i64) as u64) ^ value) & (1 << index))
}
/// returns true if the nth bit (count from least significant bit) is the same as val (as boo... | Rust | 0 |
, "label": "no"})
examples.append({"text": "Tell gpt the output should still be latex code.", "label": "no"})
examples.append({"text": "Hint: convert pdfs to text and then answer questions based on them.", "label": "yes"})
examples.append(
{"text": "To create a good PPT, include enou... | Python | 1 |
LLIN as i32) as usize;
pollfds.set_len(nfds);
// Place the fd that indicates shutdown last, so that it's ignored by
// sioctl_revents() which will only look at first nfds.
pollfds.push(pollfd {
fd: close_rx,
events: POLLIN,
revents: 0,
});
... | Rust | 0 |
ontrolled by: - The FRMFILT0 and FRMFILT1 registers - The PAN_ID, SHORT_ADDR, and EXT_ADDR values in RAM"]
pub mod frmfilt1;
#[doc = "Source address matching and pending bits\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`wri... | Rust | 0 |
("ReferenceRoleARNUpdate").string(var_224);
}
Ok(())
}
pub fn serialize_structure_crate_model_mapping_parameters(
object: &mut aws_smithy_json::serialize::JsonObjectWriter,
input: &crate::model::MappingParameters,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
if let Some(var_225... | Rust | 0 |
/5.5.1/zsh/stat.so
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
pub enum Perm {
Read,
Write,
Execute,
Private,
Shared,
Nil,
}
impl Perm {
const ALL: [Perm; 6] = [
Perm::Read,
Perm::Write,
Perm::Exe... | Rust | 0 |
# Copyright (c) 2018, Frappe Technologies and Contributors
# License: MIT. See LICENSE
import unittest
class TestBraintreeSettings(unittest.TestCase):
pass
| Python | 1 |
bool>;
#[doc = "Write proxy for field `GPIO_FUNC68_IN_INV_SEL`"]
pub struct GPIO_FUNC68_IN_INV_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_FUNC68_IN_INV_SEL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the fi... | Rust | 0 |
n, m = map(int, input().split())
a_array = []
b_array = []
for _ in range(n):
a_array.append(list(map(int, input()))[:m])
for _ in range(n):
b_array.append(list(map(int, input()))[:m])
def reverse(x, y, array):
for i in range(x, x + 3):
for j in range(y, y + 3):
array[i][j] = 1 if a... | Python | 1 |
Engine<NativeLink>,
usercode: userlib::Game<NativeLink>,
_snd: NativeAudioEngine,
current_size: peridot::math::Vector2<usize>,
ri_handler: self::input::RawInputHandler
}
impl GameDriver {
fn new(window: HWND, init_size: peridot::math::Vector2<usize>) -> Self {
let nl = NativeLink {
... | Rust | 0 |
f neighbor.get_parent().get_resname() == 'CYS' and neighbor.get_name() == 'SG':
bonded_cys = neighbor.get_parent()
disulfide_bonds.append((cysteine, bonded_cys))
disulfide_bonds = list(set(tuple(sorted(pair)) for pair in disulfide_bonds))
disulfide_list = []
... | Python | 1 |
hbor(test_rrt_star):
# access the test_rrt_star object
planner = test_rrt_star.planner
motion_model = test_rrt_star.motion_model
# create some nodes
state_1 = (125, 225, 0)
state_2 = (100, 275, 0)
state_3 = (150, 300, 0)
state_4 = (150, 275, 0)
node_1 = Node(motion_model, state_1, pl... | Python | 1 |
# This file is part of Indico.
# Copyright (C) 2002 - 2025 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.settings.converters import DatetimeConverter, SettingConverter
from indico.modules.events... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.