text
string
label_name
string
labels
int64
stars>100-1000 #![allow(unused)] #![deny(explicit_outlives_requirements)] use std::fmt::{Debug, Display}; // These examples should live in edition-lint-infer-outlives.rs, but are split // into this separate file because they can't be `rustfix`'d (and thus, can't // be part of a `run-rustfix` test file) until rust-lan...
Rust
0
EventMgr; use kas::macros::impl_singleton; use kas::widgets::{EditField, RowSplitter, TextButton}; use kas::{Widget, Window}; #[derive(Clone, Debug)] enum Message { Decr, Incr, } fn main() -> kas::shell::Result<()> { env_logger::init(); let panes = (0..2).map(|n| EditField::new(format!("Pane {}", n +...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2015,掌阅科技 All rights reserved. 摘 要: test_manager.py 创 建 者: WangLichao 创建日期: 2015-08-21 """ import sys import os import time import logging.config sys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0])) import unittest from zyred...
Python
1
Ord(t) < Card(t) - Card(iS) + 2] = ( Sum(iS, chiS[t.lead(Ord(iS))]) <= 1 ) # indicate if the plant left the idle state eq. (30) PPstarted[t] = chiI[t] >= delta["m1", t - 1] - delta["m1", t] # control the minimum idle time period: # it has to be at least Nk2 time periods long eq. (31) P...
Python
1
xplore.pop(0) i, j = currentNode[0], currentNode[1] # If the current node has already been visited, continue to the next iteration if visited[i][j]: continue # Mark the current node as visited visited[i][j] = True # If the current node is land (0), continue...
Python
1
EN: u8 = $max; fn into_payload(self) -> Result<Option<Vec<u8>>, Error> { // macros are kind of dumb #[allow(unused_mut)] let mut payload: Vec<u8> = Vec::new(); $(serializer(&mut payload, &self.$arg_name.into())?;)* let len = pay...
Rust
0
} PA04 { /// Pin A1/D1 name: a1 } PA10 { /// Pin A2/D2 name: a2 } PA11 { /// Pin A3/D3 name: a3 } PA08 { /// Pin A4/D4/SDA name: a4 aliases: { ...
Rust
0
ind_target != TextureTarget::CubeMap { Err(Error::from(NativeError::TextureCubeFaceNotCube)) } else { Ok(cube_face as u32) } } None => { if bind_target == TextureTarget::CubeMap { Err(Error::from(NativeError::TextureMiss...
Rust
0
gt_dict.eos() unk = self.tgt_dict.unk() target_mask = target_tokens.eq(bos) | target_tokens.eq( eos) | target_tokens.eq(pad) return target_tokens.masked_fill(~target_mask, unk) if self.args.noise == 'random_delete': return _random_delete(target_t...
Python
1
go let matching: Vec<&matrix_sdk::room::Joined> = rooms.iter().filter(|&joined_room| { println!("canonical alias: {:?}", joined_room.canonical_alias()); joined_room.canonical_alias().map_or(false, |x| x.alias() == room) }).collect(); if matching.len() == 1 { matching[0].clone() } else if m...
Rust
0
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 config_kwargs.u...
Python
1
bool::arbitrary(input)?, module_new: bool::arbitrary(input)?, module_drop: bool::arbitrary(input)?, instance_new: bool::arbitrary(input)?, instance_drop: bool::arbitrary(input)?, call_exported_func: bool::arbitrary(input)?, }) } } /// A call to o...
Rust
0
8, Pg>>::from_sql(bytes).map(DiscordColour) } } impl From<u32> for DiscordColour { fn from(val: u32) -> Self { Self(val.into():i64) } } #[derive(Debug, SqlType)] #[postgres(type_name = "discord_user")] pub struct SQL_DiscordUser; composite_type! { #[derive(PartialEq,Eq,Debug)] #[sql_type ...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, force_fp32 from torch import nn as nn class DGCNNFPModule(BaseModule): """Point feature propagation module used in DGCNN. Propagate the features from one set to another. Args: mlp_...
Python
1
from controller.controladorSistema import ControladorSistema if __name__ == "__main__": controlador_sistema = ControladorSistema() controlador_sistema.inicializar_sistema()
Python
1
import pygame import time import random pygame.init() branco = (255, 255, 255) amarelo = (255, 255, 102) preto = (0, 0, 0) vermelho = (213, 50, 80) verde = (0, 255, 0) azul = (50, 153, 213) largura_tela = 800 altura_tela = 600 tamanho_bloco = 10 velocidade = 15 fonte = pygame.font.SysFont("bahnschrift", 25) fonte_...
Python
1
"Offset of field: ", stringify!(FPDF_BSTR_), "::", stringify!(len) ) ); } #[doc = " Structure for persisting a string beyond the duration of a callback."] #[doc = " Note: although represented as a char*, string may be interpreted as"] #[doc = " a UTF-16LE for...
Rust
0
(&t0); self.x.norm(); self.x.mul(&t1); self.x.dbl(); //(y^2-9bz^2)xy2 self.x.norm(); self.y.copy(&y3); self.y.norm(); return 1; } /* self+=Q - return 0 for add, 1 for double, -1 for O */ pub fn add(&mut self, Q: &ECP8) -> isize { let b = 3 *...
Rust
0
price value. - period: Period of the sinusoidal signal. OUTPUTS: - sinusoidal: Generated fictive stock market dataframe. """ # Initialization of the new stock market dataframe downloader = YahooFinance() DowJones = downloader.getDailyData('DIA', star...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- #__author__ = '1c3z' import urlparse def assign(service, arg): if service == "DVRDVS-Webs": return True, arg def audit(arg): import base64 r = urlparse.urlparse(arg) host = r.hostname url = arg + "PSIA/Custom/SelfExt/userCheck" pass_list = ...
Python
1
Benchmark::new("Decompress a Signature", move |b| { b.iter(|| { black_box(Signature::from_serialized(&s).unwrap()); }) }) .sample_size(10), ); } fn aggregation(c: &mut Criterion) { set_eth_mode(EthModeType::Old); let mut seckey = unsafe { SecretKey:...
Rust
0
ase_percent/100), 0.5), 0.4, color='black') else: shadow = plt.Circle((0.5 - 0.4 * (2 * (phase_percent-50)/100), 0.5), 0.4, color='black') ax.add_patch(shadow) ax.set_xlim(0, 1) ax.set_ylim(0, 1) f...
Python
1
uct ErrorResponse { message: String, } fn stream_body(body: Body) -> impl Stream<Item = Result<Bytes>> { async fn unfold(mut body: Body) -> Option<(Result<Bytes>, Body)> { body.next() .await .map(|chunk| (chunk.map_err(Error::from), body)) } stream::unfold(body, unfold)...
Rust
0
let mut buf = ArrayString::<20>::new(); write!(&mut buf, "{:?}", Response::Connect(1)).expect("Can't write"); assert_eq!(&buf, "Connect(1)"); } fn test_debug_data() { let mut buf = ArrayString::<256>::new(); let data = b"FOO\0BAR"; let mut array = [0u8; super::...
Rust
0
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, modify, merge, publish, ...
Python
1
) pub creator: AccountId, /// Total pending rewards in fees to be distributed between relayers pub pending_rewards: BalanceOf, /// Minimum fee that the quorum accepts for jobs pub min_fee: BalanceOf, /// Who can make oracle job requests pub membership: Membership, } #[cfg_attr(feature = "std", derive(Serialize,...
Rust
0
| CallReply::RArray { .. } | CallReply::RNull { .. } => None, CallReply::RInteger { ptr } => { let integer = unsafe { ffi::RedisModule_CallReplyInteger.unwrap()(*ptr) }; Some(integer) } } } ...
Rust
0
import logging from config import Config from clients.rinnai_client import RinnaiClient from clients.local_client import LocalClient from clients.http_client import RinnaiHttpClient from clients.ha_discovery_client import RinnaiHomeAssistantDiscovery from processors.message_processor import MessageProcessor logging.ba...
Python
1
_Vfmsub231sd_xmm_k1z_xmm_xmmm64_er = 3561, /// `VFNMADD231PS xmm1, xmm2, xmm3/m128` /// /// `VEX.128.66.0F38.W0 BC /r` /// /// `FMA` /// /// `16/32/64-bit` VEX_Vfnmadd231ps_xmm_xmm_xmmm128 = 3562, /// `VFNMADD231PS ymm1, ymm2, ymm3/m256` /// /// `VEX.256.66.0F38.W0 BC /r` /// /// `FMA` /// /// `16/32/64-...
Rust
0
ng.as_ptr() as _)) } } else { Cow::Owned(CString::new(string).unwrap()) } } } #[macro_use] extern crate cli_log; pub mod args; pub mod ask; pub mod dirs; pub mod dup; pub mod dup_report; pub mod ext; pub mod file_pair; pub mod hash; mod json; pub mod removal_report; pub use { args:...
Rust
0
99), PILImage.BOX) return x # mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 def elastic_transform(image, severity=1): c = [(360 * 2, 360 * 0.7, 360 * 0.1), (360 * 2, 360 * 0.08, 360 * 0.2), (360 * 0.05, 360 * 0.01, 360 * 0.02), (360 * 0.07, 360 * 0.01, 360 * 0.02)...
Python
1
from decimal import Decimal import factory from django.conf import settings from oscar.core.loading import get_model from ecommerce.extensions.refund.status import REFUND, REFUND_LINE from ecommerce.extensions.test.factories import create_order from ecommerce.tests.factories import SiteConfigurationFactory, UserFac...
Python
1
监控任务""" import gc import psutil import os import time as time_module process = psutil.Process(os.getpid()) last_gc_time = time_module.time() while True: try: # 每分钟检查一次(更频繁的监控) await asyncio.sleep(60) # 获取内存使用情况 me...
Python
1
#[test] fn hex_vec() { #[serde_as] #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct B(#[serde_as(as = "Vec<Hex>")] Vec<Vec<u8>>); is_equal( B(vec![vec![0, 1, 2, 13], vec![14, 5, 6, 7]]), expect![[r#" [ "0001020d", "0e050607" ...
Rust
0
cleaned.make_ascii_lowercase(); if cleaned.is_empty() { return Err(SectionIdentifierError::Empty); } Ok(SectionIdentifier(cleaned)) } } // fn modifier_to_string(modifier: Modifier) -> &'static str { // match modifier { // Modifier::Chorus => "c-", // ...
Rust
0
"""Functions to prevent a nuclear meltdown.""" def is_criticality_balanced(temperature, neutrons_emitted): return temperature < 800 and neutrons_emitted > 500 and temperature * neutrons_emitted < 500000 def reactor_efficiency(voltage, current, theoretical_max_power): generated_power = voltage * current ...
Python
1
: 192.168.0.1:4442 groups: [] "; let (_tmpf, ci) = load_conf(cont).unwrap(); assert_eq!(2, ci.nodes.len()); { // test `get` let nid1 = "127.0.0.1:4441"; let nid2 = "192.168.0.1:4442"; let n1 = ci.get(nid1).unwrap(); assert_eq!(nid1, n1.node_id); assert_eq!(...
Rust
0
lick class DiffusiveMonteCarlo(_DEMethod): """Diffusive Monte Carlo method for the Lindblad master equation. This method calls [`dq.dssesolve()`][dynamiqs.dssesolve] to compute stochastic trajectories of the unit-efficiency diffusive unraveling of the Lindblad master equation (ME). These trajectories...
Python
1
, target_positions,speed=max_speed) print("moved to zero") def interpolate_move(self,start_positions, target_positions, speed=50, dt=0.01): interpolation_list = self.interpolate_positions_with_speed(start_positions, target_positions, speed, dt) for target_position in interpolation_l...
Python
1
ut inner_map1 = BTreeMap::new(); inner_map1.insert( Key(vec![]), Value { refs0: vec![], refs1: vec![0, 1], }, ); inner_map1.insert( Key(vec![0]), Value { refs0: vec![0, 1, 2], refs1: vec![], }, ); inner_m...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2025 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
och+1周期的参数 save_checkpoint( model=self.net, optimizer=self.opti, scheduler=self.sche, amp=self.amp, exp_name=self.exp_name, current_epoch=curr_epoch + 1, full_net_path=self.path_dict["final_full_n...
Python
1
ns[1] @torch.no_grad() @typechecked def get_decomposed_mlp_contributions( resid_mid: Float[torch.Tensor, "d_model"], resid_post: Float[torch.Tensor, "d_model"], decomposed_mlp_out: Float[torch.Tensor, "hidden d_model"], distance_norm: int = 1, ) -> Tuple[Float[torch.Tensor, "hidden"], float]: """ ...
Python
1
import random import json # ----------------------------- # Quiz Data # ----------------------------- quiz_data = { "General Knowledge": [ { "question": "What is the capital of France?", "options": ["A) London", "B) Paris", "C) Berlin", "D) Rome"], "answer": "B" ...
Python
1
import json import pytest from otaro.parsing import llm_parse_json SAMPLE_DICT = { "foo": "bar", "answer": 42, "hello world": [1, 2, 3.14], "empty": None, } SAMPLE_DICT_STR = json.dumps(SAMPLE_DICT) SAMPLE_ARRAY = ["foo", 1, [3.14], {"hello": "world"}, None] SAMPLE_ARRAY_STR = json.dumps(SAMPLE_ARRA...
Python
1
from matplotlib import pyplot as plt anos = [1950, 1960, 1970, 1980, 1990, 2000, 2010] pib = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3] #crie um gráfico de linhas, anos no eixo x, pib no eixo y plt.plot(anos, pib, color='green', marker='o', linestyle='solid') # adicionando título plt.title("PIB Nomina...
Python
1
m.deep_copy() mm.create_mask_around_density( resolution = 3, molecular_mass = 2100, sequence = "GAVAGA", solvent_content = 0.5, ) mask_mm = mm.get_mask_as_map_manager() assert approx_equal( (mask_mm.map_data().count(0), mask_mm.map_data().count(1), mask_mm.map_d...
Python
1
CriticalSectionSpinLockMutex::new(None); static WATCHDOG1: CriticalSectionSpinLockMutex<Option<watchdog::Watchdog<esp32::TIMG1>>> = CriticalSectionSpinLockMutex::new(None); static TX: CriticalSectionSpinLockMutex<Option<esp32_hal::serial::Tx<esp32::UART0>>> = CriticalSectionSpinLockMutex::new(None); #[entry] f...
Rust
0
else { error!( "GitHub payload -> slack::Message failed. link = {}", &payload.url() ); //error!("payload: {:#?}", &payload); } } Ok(HttpResponse::Ok().body("webhook")) } impl Rule { fn check_match(&self, payload: &github::Payload...
Rust
0
"""Network integration testing.""" from __future__ import annotations import os from ...util import ( ApplicationError, ANSIBLE_TEST_CONFIG_ROOT, ) from ...util_common import ( handle_layout_messages, ) from ...target import ( walk_network_integration_targets, ) from ...config import ( Network...
Python
1
to_alice: Endpoint, to_bob: Endpoint, to_carol: Endpoint ) { let (alice_peer, alice_mb, mut alice_addr ) = CborWF::create_peer( "to_alice", to_alice, 1024, 1024, AsyncStd, None, None ) .expect( "spawn peer" ) ; let (bob_peer , bob_mb , mut bob_addr ) = CborWF::create_peer( "to_bob" , to_bob , 1024, 1024, A...
Rust
0
r(mock_config, 2_000); // make sure 20_000 land unit deploy per period assert_eq!(round_issuance.min, 20_000); assert_eq!(round_issuance.ideal, 20_000); assert_eq!(round_issuance.max, 20_000); assert_eq!(round_issuance.staking_allocation, 4_000); assert_eq!(round_issuance.mining_allocation, 16_000); } } u...
Rust
0
nto')), ('carrera', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='core_alumnos', to='core.carrera', verbose_name='carrera')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='core_alumno', to=settings.AUTH...
Python
1
""" Tool display field generator for web frontend. Generates display fields (action, action_content) based on tool name and parameters without modifying existing tool definitions. Usage Examples: # Register action only ToolDisplayManager.register_action("web_search", { "zh": "正在搜索", "en": "Sea...
Python
1
(b' '*5, foldspaces=True, adobe=False), b'y+9') def test_b85encode(self): eq = self.assertEqual tests = { b'': b'', b'www.python.org': b'cXxL#aCvlSZ*DGca%T', bytes(range(255)): b"""009C61O)~M2nh-c3=Iws5D^j+6crX17#SKH9337X""" b"""AR!_nBqb&%C@Cr{EG...
Python
1
print("No model to save.") class SDFDialog: def __init__(self, system_prompt=gpt4_input): self.messages = [] self.system_prompt = system_prompt def add_user_message(self, content): self.messages.append({"role": "user", "content": content}) def add_assistant_message(self, content)...
Python
1
unsafe { std::slice::from_raw_parts(message, message_size) }; let signature = cryptoxide::ed25519::signature_extended( (&message_slice[..]).try_into().unwrap(), c_pointer_to_rust_array_64(secret_key_extended) ); copy_rust_to_c(&signature, sign, 64); }use std::str::FromStr; use std::string::...
Rust
0
= SCHEDULED assert rule.completion_rate() is None rule.state = ABORTING assert rule.completion_rate() is None rule.state = ABORTED assert rule.completion_rate() is None @pytest.mark.django_db @pytest.mark.parametrize( 'current_state,target_state', [ (NEW, SCHE...
Python
1
# Copyright 2022 The HuggingFace Team. 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 applicabl...
Python
1
dy_type: Box<syn::Type>, } struct DocOnlyAttributes { doc: Vec<WithSpan<String>>, } impl InterfaceDefinition { pub fn visibility(&self) -> &syn::Visibility { &self.visibility } pub fn name(&self) -> &syn::Ident { &self.name } pub fn doc(&self) -> &[WithSpan<String>] { &self.doc } pub f...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 장기요양보험 공단 사이트 다운로드 자동화 테스트 https://longtermcare.or.kr/npbs/r/a/201/selectLtcoSrch.web?menuId=npe0000000650 장기요양기관 검색 및 엑셀 다운로드 기능 """ import asyncio from playwright.async_api import async_playwright from datetime import datetime import os import time class LongTermCar...
Python
1
# Copyright 2015, Pinterest, 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 required by applicable law or agreed to in writ...
Python
1
""" Query Optimizer Implementation - Step 4 (Coming Soon) 查询优化器实现 - 第四步 (即将推出) This module will implement query optimization techniques. 本模块将实现查询优化技术。 Teaching Approach / 教学方法: - Start with query expansion / 从查询扩展开始 - Implement query rewriting / 实现查询重写 - Add multi-query generation / 添加多查询生成 - Optimize for different d...
Python
1
r_sdk::collections::LookupMap; use near_sdk::{near_bindgen, BorshStorageKey}; #[derive(BorshStorageKey, BorshSerialize)] struct StorageKeyStruct { key: String, } #[derive(BorshStorageKey, BorshSerialize)] enum StorageKeyEnum { Accounts, SubAccounts { account_id: String }, } #[near_bindgen] #[derive(Borsh...
Rust
0
original_config = attrs.asdict(model.config) config = PretrainedConfig.from_dict(original_config) # Synchronization with original RBLNDecoderOnlyForCausalLMConfig sync_kwargs = { "n_head": getattr(config, "n_heads"), "num_key_value_heads": getattr(config, "n_kv_...
Python
1
"""Script used to define the paystack Customer class.""" from paystackapi.base import PayStackBase class Customer(PayStackBase): """docstring for Customer.""" @classmethod def create(cls, **kwargs): """ Function defined to create customer. Args: first_name: customer'...
Python
1
######## NUM_EPOCHS = 50 optimizer = torch.optim.Adam(model.parameters(), lr=5e-5) num_steps = NUM_EPOCHS * len(train_loader) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_steps) ######################################### ### 3 Finetuning ######################...
Python
1
ces that are currently being downloaded, and have already been requested. fn pick_blocks(&mut self, peer_have: BitVec<Msb0, u8>, n: usize) -> Vec<(DataIndex, usize)> { if n == 0 { return vec![]; } let mut blocks = Vec::with_capacity(n); // 1) Get next blocks from pieces ...
Rust
0
()) } /* This error occurs when there was a recursive trait requirement that overflowed before it could be evaluated. Often this means that there is unbounded recursion in resolving some type bounds. */ #[cfg(test)] mod tests { #[allow(dead_code)] #[allow(non_snake_case)] #[allow(unused_imports)] #[t...
Rust
0
de at given `index`. /// /// Returns a tuple of indices, the 1st of which is the index of its first children, and the 2nd /// of which is its last children. pub fn get_children(&self, index: usize) -> Option<(usize, usize)> { // It is computed by // // select(false, // for...
Rust
0
ty_2 { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } impl Default for rte_mempool_objhdr { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq)] pub struct rte_mempool_objhdr_list { pub stqh_first: *mut rte_mempool...
Rust
0
class Solution: def scoreOfParentheses(self, s: str) -> int: stack = [0] for b in s: if b == "(": stack.append(0) else: val = max(2*stack.pop(), 1) stack[-1] += val return stack.pop()
Python
1
here F: Function, { let params = function.parameters(); let values = params .iter() .map(|param| { anys.get(param.keyword).map(VmArgument::Any).or_else(|| { args.optional_value(param.keyword) .expect("argument should be a literal") ...
Rust
0
# Copyright 2023 The Qwen team, Alibaba Group. 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...
Python
1
q, k_buffer, v_buffer, o, req_to_token, b_seq_len, attn_logits, num_kv_splits, sm_scale, page_size=1, logit_cap=0.0, ): assert num_kv_splits == attn_logits.shape[2] kv_group_num = q.shape[1] // v_buffer.shape[-2] if kv_group_num == 1: # MHA decode_att...
Python
1
ze, PartialFreeze, TotalTake, PartialTake, Immobile}; use middle::borrowck::ReqMaps; use middle::borrowck::loan; use middle::mem_categorization::{cmt, mem_categorization_ctxt}; use middle::pat_util; use middle::ty::{ty_region}; use middle::ty; use util::common::indenter; use util::ppaux::{expr_re...
Rust
0
ut_ids ) inputs_embeds = merge_multimodal_embeddings( input_ids, inputs_embeds, audio_embeddings, _AUDIO_PLACEHOLDER_TOKEN ) input_ids = None else: inputs_embeds = None hidden_states = self.language...
Python
1
, s1: Group) -> Option<SS2Op> { match (s0, s1) { (SS2Op::Skip(a), Group::Same(_, b)) => return Some(SS2Op::Skip(a + b)), // Skip followed by SetEnd operation. // // Since the SetEnd is stored separately, s0 is the final // operation. We want to ignore the final skip...
Rust
0
#! /usr/bin/env python # # Copyright (c) 2008, Nicolas Rougier # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # noti...
Python
1
RANGE { false } else if x + dx > MAX_X || y + dy > MAX_Y { false } else { true } } } <gh_stars>0 use crate::testing::VoteTestGen; use crate::{ certificate::{TallyDecryptShares, VotePlan}, fee::LinearFee, header::BlockDate, testing::{ ...
Rust
0
name: (first_name.clone() + "'s Den").to_string(), privacy: app_definitions::Privacy::Private, channel_type: app_definitions::ChannelType::Den }; let shared_den = app_definitions::Channel{ //Create shared den - den viewable by people in your pack parent: username_address.clone(), ...
Rust
0
> <h3 style='color: white; margin: 0;'>📈 Analysis Results</h3> </div> """) with gr.Row(): with gr.Column(): activity_box = gr.Textbox( ...
Python
1
ms_sql(self, **kwargs): return "FROM {field}".format(field=self.field.get_sql(**kwargs)) # Null Functions class IsNull(Function): def __init__(self, term, alias=None): super(IsNull, self).__init__("ISNULL", term, alias=alias) class Coalesce(Function): def __init__(self, term, *default_values...
Python
1
res!(unsafe { libc::bind(socket.as_inner(), addr_ptr, addr_len) }); let _ = res!(unsafe { libc::listen(socket.as_inner(), 128) }); Ok(socket) } fn as_inner(&self) -> libc::c_int { self.0 } } <reponame>synek317/cargo-git-registry use cmd_args::ForgetArgs; use failure::Error; use ut...
Rust
0
![allow( unused_parens, clippy::excessive_precision, clippy::missing_safety_doc, clippy::not_unsafe_ptr_arg_deref, clippy::should_implement_trait, clippy::too_many_arguments, clippy::unused_unit, )] //! # Video Analysis //! # Motion Analysis //! # Object Tracking //! # C API use crate::{mod_prelude::*, cor...
Rust
0
four, seven, eight, rest) } fn find_6_3( one: &BTreeSet<SignalWire>, signals: Vec<BTreeSet<SignalWire>>, ) -> ( BTreeSet<SignalWire>, BTreeSet<SignalWire>, Vec<BTreeSet<SignalWire>>, ) { let six = signals .iter() .filter(|signal| signal.len() == 6) .find(|signal| signal...
Rust
0
/ All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. // THE SOURCE CODE IS AVAILABLE UNDER THE ABOVE CHOSEN LICENSE "AS IS", WITH NO WARRANTIES. //! Rust abstractions of the computecore APIs. //! These are Rust idiomatic equivalents of the C bi...
Rust
0
''' Project: Gui Gin Rummy File name: menu_bar.py Author: William Hale Date created: 3/14/2020 ''' # from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .game_frame import GameFrame import tkinter as tk from tkinter import messagebox from .preferences_window...
Python
1
assert_eq!(chip8.memory[0xDC as usize], 1); chip8.execute_cycle(); assert_eq!(chip8.pc, 0xDC); assert_eq!(chip8.memory[chip8.pc as usize], 1); } #[test] fn test_call_subroutine_at_nnn() { // 0x2NNN: calls subroutine at NNN let program: Vec<u8> = vec![0x20, 0x...
Rust
0
# pylint: disable=too-many-arguments, too-many-locals from collections import OrderedDict from itertools import product import dgl import pytest import torch from dgl.nn import CuGraphGATConv, GATConv options = OrderedDict( { "idtype_int": [False, True], "max_in_degree": [None, 8], "num_he...
Python
1
from __future__ import annotations from hist import Stack, axis def test_1D_empty_repr(named_hist): h = named_hist.new.Reg(10, -1, 1, name="x", label="y").Double() html = h._repr_html_() assert html assert "name='x'" in repr(h) assert "label='y'" in repr(h) def test_1D_var_empty_repr(named_hist...
Python
1
""" Plot effective radiative forcings (ERF) for volcanic aerosols and solar. """ import matplotlib.pyplot as plt def read_timeseries_file(filename): solar_years = [] solar_erf = [] solar_zero = [] with open(filename, 'r') as f: f.readline() for line in f: columns = line.sp...
Python
1
isors(s)); let ss = dd.iter().sum::<u64>() - dd.last().unwrap_or(&0) + 1; if x == ss { return Some(s); } None } fn main() { assert_eq!(find_amicable_pair(220), Some(284)); let mut set = HashSet::new(); for x in 1..10_000 { if set.contains(&x) { continue; ...
Rust
0
the Shaiya downloader. This is used to download patches from the OpenShaiya /// archive site, and apply them to an "original" client distribution. #[tokio::main] pub async fn main() -> anyhow::Result<()> { let args = App::new("Shaiya Downloader") .version(VERSION) .author("<NAME> (Cups)") ....
Rust
0
let mut img = if !transposed { RgbaImage::new(width as u32, height as u32) } else { RgbaImage::new(height as u32, width as u32) }; img.pixels_mut().zip(base).zip(mask).for_each(|((pixel, idx)...
Rust
0
.lstrip(".") else: raise ValueError( """ Cannot infer image type from output path '{file}'. Please add a file extension or specify the type using the format parameter. For example: >>> import plotly.io as pio >>> pio.write_image(fig, file_path, format='png') """.format(file=...
Python
1
mp=mock_gmp.gmp_protocol, target_name=target_name, hosts=hosts, ports=ports, port_list_name=port_list_name, ) self.assertEqual(target_id, returned_id) @patch("gvm.protocols.latest.Gmp", new_callable=GmpMockFactory) def test_create_and_start_task(...
Python
1
remote_port = test_source_city_temperature.port() ), ]; let mut config = SpringConfig::default(); config.memory.upper_limit_bytes = upper_limit_bytes; config.memory.severe_to_critical_percent = 60; config.memory.moderate_to_severe_percent = 30; config.memory.critical_to_seve...
Rust
0
_per_symbol, 'completeness': record_count / expected_records_per_symbol if expected_records_per_symbol > 0 else 0, 'min_date': result[1] if result and result[1] else None, 'max_date': result[2] if result and result[2] else None ...
Python
1
let db = connect(&self.db_url).unwrap(); let mut cfg = postgres::transaction::Config::new(); cfg.isolation_level(postgres::transaction::IsolationLevel::ReadUncommitted); let tx = db.transaction_with(&cfg).unwrap(); if self.truncate { let tq = format!("TRUNCATE {}", self.table()); ...
Rust
0