text
string
label_name
string
labels
int64
from __future__ import print_function import torch import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from util import ncc, input_param, init_rtvec_test, gradncc from util_plot import plot_example_regi from module import ProST device = torch.device("cuda") PI = 3.1415926 NUM_PHOTON = 10000...
Python
1
############################################################## ## ROBÔ DE PREENCHIMENTO AUTOMÁTICO DE FORMULARIO DO CHROME ## ############################################################## from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from se...
Python
1
ing_if = "Option::is_none")] pub ID: Option<String>, #[serde(rename = "Namespace", skip_serializing_if = "Option::is_none")] pub namespace: Option<String>, #[serde(rename = "Target", skip_serializing_if = "Option::is_none")] pub target: Option<::std::collections::HashMap<String, String>>, #[serd...
Rust
0
self.run_query_insert(context)?; let execution_time = stopwatch.stop(); let task_metrics = TaskMetricsUpdateByTask::new(context.task(), execution_time); let metrics = MetricsUpdateByTaskExecution::new( task_metrics, in_queue_metrics.map_or_else(Vec::new, |m| vec![m]), ...
Rust
0
= "generated by AutoRust"] #[cfg(feature = "profile-hybrid-2020-09-01")] pub mod profile_hybrid_2020_09_01; #[cfg(all(feature = "profile-hybrid-2020-09-01", not(feature = "no-default-tag")))] pub use profile_hybrid_2020_09_01::{models, operations, operations::Client, operations::ClientBuilder}; #[cfg(feature = "packag...
Rust
0
write_js(&mut file, &str).await; } pub async fn write_sswhite_r(ipv4: &BTreeMap<Ipv4Addr, u8>, domains: &BTreeSet<String>) { const FILENAME: &str = r"ss_white_r.pac"; println!("正在生成 {}...", FILENAME); let mut file = get_file(FILENAME); let str = WHITE_R_TEMPLATE; let str = str.replace(r"__cnIpRang...
Rust
0
sort coding""" # This function raises UnicodeDecodeError with position in the extended. # Caller should add the offset. char = 0x80 pos = -1 bias = 72 extpos = 0 while extpos < len(extended): newpos, delta = decode_generalized_number(extended, extpos, ...
Python
1
filesystem_encoding() _get_windows_console_stream = lambda *x: None _wrap_std_stream = lambda *x: None def term_len(x): return len(strip_ansi(x)) def isatty(stream): try: return stream.isatty() except Exception: return False def _make_cached_stream_func(src_func, wrapper_func)...
Python
1
r. """ config = self.config for name, module in tqdm( tuple(pretrained_model.named_modules()), tqdm_desc, leave=False, dynamic_ncols=True, ): if isinstance(module, self._linear_layer_cls): self._upscale_linear_la...
Python
1
::sync::oneshot::{channel, Sender}; use tokio::time::interval; #[derive(Clone)] pub struct RateLimitWatcher { wait_until: Arc<Mutex<Option<SystemTime>>>, _stop_tx: Arc<Sender<()>>, } impl RateLimitWatcher { pub fn new(window: Window<Wry>) -> Self { let wait_until: Arc<Mutex<Option<SystemTime>>> = ...
Rust
0
list); } else { let md = fs::metadata(&args[1]).unwrap(); if md.is_dir() { // 想解码直接双击运行就行了,所以拖入文件夹大概率是加密 s_dir_str = args[1].clone(); enc_flag = true; } } } let watch_header_jpeg: Vec<u8> = vec![1,2,3,6]; le...
Rust
0
from lxml import etree from odoo import api, fields, models, _ from odoo.exceptions import UserError class TaskCloseWizard(models.TransientModel): _name = 'task.close.wizard' _description = 'Task Wizard: Close' task_id = fields.Many2one('task.task', string='Task', required=True, ondelete='cascade') r...
Python
1
import os from aphrodite import LLM, SamplingParams # creates XLA hlo graphs for all the context length buckets. os.environ["NEURON_CONTEXT_LENGTH_BUCKETS"] = "128,512,1024,2048" # creates XLA hlo graphs for all the token gen buckets. os.environ["NEURON_TOKEN_GEN_BUCKETS"] = "128,512,1024,2048" # Quantizes neuron mod...
Python
1
import telegram.ext as tg from telegram import Update import haruka.modules.sql.antispam_sql as sql CMD_STARTERS = ('/', '!') class CustomCommandHandler(tg.CommandHandler): def __init__(self, command, callback, **kwargs): if "admin_ok" in kwargs: del kwargs["admin_ok"] super().__init_...
Python
1
ash::PasswordHash::from_encoded(&hash)?; let password = pwhash::Password::from_slice(pass.as_ref())?; return Ok(pwhash::hash_password_verify(&stored_hash, &password)?); } Err(orion::errors::UnknownCryptoError) } pub fn create_user(id: &str, password: &str) -> Result<(),...
Rust
0
in parser { let e = e.unwrap(); match e { XmlEvent::StartElement { name, attributes, .. } => { let mut attrs = BTreeMap::new(); for attribute in attributes { attrs.insert(attribute.name.local_name, attribute.valu...
Rust
0
X: # range 1-11 absolute_change = 0.1 if attr_name == ATTR_WEATHER_PRESSURE: # local variation of around 100 hpa if (unit := new_attrs.get(ATTR_WEATHER_PRESSURE_UNIT)) is None or unit in ( UnitOfPressure.HPA, UnitOfPressure.MBAR, # 1hPa = 1mbar ...
Python
1
3[0] = alpha3[0] # Update largest time step - CFL condition hcl.update(delta_t, lambda x: step_bound()) def returnDerivative(V_array, Deriv_array): with hcl.Stage("ComputeDeriv"): with hcl.for_(0, V_array.shape[0], name="i") as i: with hcl.for_(0, V_array.shap...
Python
1
!( "Invalid map record: {}.", CStr::from_ptr(map_name).display() ); } else { (*opt).charcoll = new((strlen(p).wrapping_add(1)).wrapping_mul(::std::mem::size_of::<i8>()) as _) as *mut i8; strcpy((*opt).charcol...
Rust
0
dict(status=400), ) try: result = self.xray_backend.get_trace_ids(trace_ids) except AWSError as err: raise err except Exception as err: return ( json.dumps({"__type": "InternalFailure", "message": str(err)}), ...
Python
1
odeGenes[gene_index].activation: activation = choice(Activations.enabled_functions) self.NodeGenes[gene_index].activation = activation def __str__(self) -> str: string: str = "Link Genes:\nbegin\t|\tend\t |\tenabled\t| innovation\n" string += "".join(f" {gene.begin : <7} {g...
Python
1
else ''}") def _unique(seq): seen = set() out = [] for item in seq: if item not in seen: seen.add(item) out.append(item) return out reason_str = ", ".join(_unique(reasons)) if reasons else "unknown" safety_str = "; ".join(_unique(...
Python
1
class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: if str2>str1: str1,str2=str2,str1 if str1==str2: return str2 if str1+str2!=str2+str1: return "" return self.gcdOfStrings(str1[len(str2):],str2) s=input("Enter string 1:") t=input(...
Python
1
}) .unwrap(), }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: TWD_TOKEN.to_string(), msg: to_binary(&Cw20ExecuteMsg::IncreaseAllowance { spender: TWD_POOL.to_string(), amount: Uint128::f...
Rust
0
""" This part was modified based on Willy's LSTM architecture. Reference: https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html """ import torch import torch.nn as nn import torch.optim as optim import numpy as np from torch.utils.data import DataLoader, TensorDataset from sklearn.preprocessing import MinMaxSc...
Python
1
# -*- coding: utf-8 -*- import struct import sys import time # Import nacl libs import libnacl import libnacl.encode import libnacl.secret import libnacl.public import libnacl.sign import libnacl.dual def load_key(path_or_file, serial='json'): ''' Read in a key from a file and return the applicable key obje...
Python
1
rs.into_iter().enumerate() { grid.set(&Entity::Cell(0, i), Settings::new().text(text)); } row = 1; } for fields in rows.into_iter() { // don't show off a empty data array if fields.is_empty() { continue; } for (column, field) in fields.i...
Rust
0
f objects, they are supposed to appear)') self.assertEqual( shNode.GetItemChildWithName(segmentationShItemID, 'Body'), 0) self.assertEqual( self.inputSegmentationNode.GetSegmentation().GetNumberOfSegments(), 2) shNode.RemoveItem(tumorItemID) qt.QApplication.processEvents() self.assertEqual( self.in...
Python
1
assword": "pass", "framerate": 20, } await help_setup_mock_config_entry(hass, options) client = await hass_client() resp = await client.get("/api/camera_proxy/camera.config_test") assert resp.status == HTTPStatus.OK assert respx.calls.call_count == 1 assert await resp.read() == fa...
Python
1
, m.v.1)).collect(); let state_z: Vec<_> = moons.iter().map(|m| (m.p.2, m.v.2)).collect(); if !past_x.insert(state_x) && turn_x.is_none() { turn_x = Some(turn); } if !past_y.insert(state_y) && turn_y.is_none() { turn_y = Some(turn); ...
Rust
0
from .instance import Monadking __all__ = ["Monadking"]
Python
1
Err(parse_error) => { error!("{}", parse_error); Err(String::from("Invalid guild id")) } }, None => Ok(main_guild_id()), }, Channel::Guild(guildchan) => Ok(guildchan.guild_id), _ => Err(String::from("This doesn't work in this channel")), } } pub fn discord...
Rust
0
(sub, gid) { Err(err) => return Ok(err.into_response()), Ok(token) => token, }; Ok(json_response(&TokenResponse { token }, StatusCode::OK)) } fn is_valid_id(s: &str, n: usize) -> bool { !s.is_empty() && s.len() <= n && s.chars().all(|c| c.is_ascii_alphanumeric()) } fn create_jwt(sub: Stri...
Rust
0
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): frappe.db.sql("""update `tabStock Entry` set purpose='Manufacture' where purpose='Manufacture/Repack' and ifnull(work_ord...
Python
1
((n, 2)) return v_rees, r_rees, m_rees, a_i, w_i, a_i_th def guardar_datos(k, n, r_rees, v_rees): if k % (n*100) == 0: np.savetxt(file_posiciones, r_rees, delimiter=",") np.savetxt(file_velocidades, v_rees, delimiter=",") file_posiciones.write("\n") file_velocidades.write...
Python
1
s: Some("↑↑↑"), keywords: &["↑↑↑"], }, #[cfg(feature = "es_US")] crate::Annotation { lang: "es_US", tts: Some("↑↑↑"), keywords: &["↑↑↑"], }, #[cfg(feature = "et")] crate::Annotation { lang: "et", tts:...
Rust
0
let child2 = task::spawn(unsafe_run_session(cont, ctx3, sender1)); let _ = join!(child1, child2).await; }) } /// An error type describing what can happen when parsing Modbus data from bytes #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ModbusSerializationError { /// The input ...
Rust
0
"] #[inline(always)] pub fn variant(self, variant: LCTL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "LED off"] #[inline(always)] pub fn lctl_0(self) -> &'a mut W { self.variant(LCTL_A::LCTL_0) } #[doc = "LED on"] #[inline(always)] pub fn lctl_1(self) -> &'a mut W { ...
Rust
0
ONF0_SPEC>; #[doc = ""] pub mod ch6conf0; #[doc = "CH6CONF1 register accessor: an alias for `Reg<CH6CONF1_SPEC>`"] pub type CH6CONF1 = crate::Reg<ch6conf1::CH6CONF1_SPEC>; #[doc = ""] pub mod ch6conf1; #[doc = "CH7CONF0 register accessor: an alias for `Reg<CH7CONF0_SPEC>`"] pub type CH7CONF0 = crate::Reg<ch7conf0::CH7C...
Rust
0
# Sphinx configuration for SPDB documentation import os import sys sys.path.insert(0, os.path.abspath("../..")) project = "SPDB" author = "Kamil Urbanek" release = "0.1.0" # Use README.md from root as main page master_doc = "index" extensions = [ "myst_parser", "sphinx.ext.autodoc", "sphinx.ext.napoleo...
Python
1
se: model_class.properties[t_property.attr_property] = self.create_annotation(val) else: model_class.properties[f"ext::{t_property.attr_property}"] = self.create_annotation(value) else: if prop.name not in []: # ...
Python
1
import serial from cam import * ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1, dsrdtr=True, rtscts=True) ser.reset_input_buffer() manager = multiprocessing.Manager() sensor_one = manager.Value("i", -1.0) sensor_two = manager.Value("i", -1.0) sensor_three = manager.Value("i", -1.0) sensor_four = manager.Value(...
Python
1
e })) ) ]), false )), )? .try_cast_str("to json") }) } pub fn into_indexable(self) -> Result<IndexableVal> { Ok(match self { Val::Str(s) => IndexableVal::Str(s), Val::Arr(arr) => IndexableVal::Arr(arr), _ => throw!(ValueIsNotIndexable(self.value_type())), }) } } const...
Rust
0
C296"); let g_y = Elem::from_hex("4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); let _g_g = g_x * g_y; } #[test] fn test_secret_nat_mod() { nat_mod!( type_name: Elem, type_of_canvas: P256Canvas, bit_size_of_field: 256, modulo_value: "ffffffff000000010000...
Rust
0
# import sys # sys.stdin = open("input.txt","r") def dfs(battery,cnt,index): # 현재 내 배터리, 카운트, 인덱스 global ans if cnt > ans: return if battery == 0: return if index + battery >= goal: # 현재 내 인덱스 + 배터리 >= 목표지점인덱스 ans = min(cnt,ans) return dfs(arr[index+1],cnt+...
Python
1
} } #[async_trait::async_trait] impl<M: 'static + Send, E: Send> Route<M> for BoundedHandle<E> where E: std::convert::TryFrom<M>, E::Error: Send, { async fn try_send_msg(&self, message: M) -> anyhow::Result<Option<M>> { // try to reserve permit match self.inner.try_reserve() { O...
Rust
0
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: # transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层...
Python
1
from_module_generators(absolute_order_module_gens, check_integral=False, check_is_ring=False, check_rank=check_rank, ...
Python
1
_size` bytes. /// /// This function will optionally copy the GOT and data segment into memory as /// well as zero out the BSS section. It also optionally performs relocation on /// the GOT and on variables named in the relocation section of the binary. /// /// Note: If we are doing the relocation, we place the stack at...
Rust
0
BinaryColor::On) .background_color(BinaryColor::Off) .build(); TextBox::new("word", Rectangle::new(Point::zero(), Point::new(54, 15))) .into_styled(style) .draw(&mut display) .unwrap(); assert_eq!( display, MockDisplay...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the `pypath` python module # # Copyright 2014-2023 # EMBL, EMBL-EBI, Uniklinik RWTH Aachen, Heidelberg University # # Authors: see the file `README.rst` # Contact: Dénes Türei (turei.denes@gmail.com) # # Distributed under the GPLv3 License. #...
Python
1
esnet34.gluon_in1k', 'gluon_resnet50_v1b': 'resnet50.gluon_in1k', 'gluon_resnet101_v1b': 'resnet101.gluon_in1k', 'gluon_resnet152_v1b': 'resnet152.gluon_in1k', 'gluon_resnet50_v1c': 'resnet50c.gluon_in1k', 'gluon_resnet101_v1c': 'resnet101c.gluon_in1k', 'gluon_resnet152_v1c': 'resnet152c.gluon_i...
Python
1
: u64, store_id: u64, ) -> Result<()> { let mut ident = StoreIdent::default(); if !is_range_empty(&engines.kv, CF_DEFAULT, keys::MIN_KEY, keys::MAX_KEY)? { return Err(box_err!("kv store is not empty and has already had data.")); } if !is_range_empty(&engines.raft, CF_DEFAULT, keys::MIN_KEY...
Rust
0
url(href) and href not in explored_urls and href not in exploring_urls and is_same_domain(href, domain) ): await queue.put(href) exploring_urls.add(href) if document_callback: ...
Python
1
import time from queue import Queue from threading import Thread, Event import cv2 from ultralytics import YOLO class ObjectDetectionThread(Thread): def __init__(self, thread_index, model_path, video_source, stop_event, result_queue, confidence_threshold=0.7, detect_every=3): super(Objec...
Python
1
} } #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] #[allow(missing_docs)] /// A compressed normal format. pub struct Normal { pub x: Fraci8, pub y: Fraci8, pub z: Fraci8, } impl Normal { /// Turn a normalized floating-point normal into a packed format. pub fn of_float_normal(normal:...
Rust
0
s.clone()); let w1 = TxInWitness::TreeSig( schnorr_sign(&secp, &msg, &sk1).0, merkle.generate_proof(raw_public_keys[0].clone()).unwrap(), ); let txa = PlainTxAux::TransferTx(tx, vec![w1].into()); let mut encoded: Vec<u8> = txa.encode(); let mut data: &[u8...
Rust
0
""" Input tools for micro:bit MCP server. This module contains tools for handling input from the micro:bit (buttons, etc.). """ import json import mcp.types as types def get_input_tools() -> list[types.Tool]: """Get all input-related MCP tools.""" return [ types.Tool( name="wait_for_butt...
Python
1
self.mouse_pos = position.to_physical(device_dim.dpi_factor()); } } } if let Some(raycast) = raycast_from_camera(raycast_data, self.mouse_pos, self.max_steps) { let mut maybe_ray_info: Option<VoxelRayInfo> = N...
Rust
0
x = if self.p.x { 1 } else { 0 }; // Execute opcodes, utilize macros and op_funcs in common cases match opcode { op::ADC_61 => op!(dir_x_ptr16, op_adc, 2, 7 - m + dl_zero), op::ADC_63 => op!(stack, op_adc, 2, 5 - m), op::ADC_65 => op!(dir, op_adc, 2, 4 - m + dl_zero...
Rust
0
"0.4.1": "http://download.pytorch.org/whl/cu80/torch-0.4.1-cp27-cp27mu-linux_x86_64.whl", "0.3.1": "torch==0.3.1", "0.3.0.post4": "torch==0.3.0.post4", "0.1.2.post1": "torch==0.1.2.post1", "0.1.2": "torch==0.1.2", ...
Python
1
data_root = '/data/data' data = dict(type='InternalData', root='images', image_list_json=['data_info.json'], transform='default_train', load_vae_feat=True) image_size = 256 # the generated image resolution train_batch_size = 32 eval_batch_size = 16 use_fsdp=False # if use FSDP mode valid_num=0 # take as valid a...
Python
1
second_leader = solana_ledger::leader_schedule_utils::slot_leader_at( slot + NUM_CONSECUTIVE_LEADER_SLOTS, &bank, ) .unwrap(); let mut expected_leader_sockets = vec![ recent_peers.get(&first_leader).unwrap(), recent_pee...
Rust
0
# import the libraries from datetime import datetime # Import the datetime module from datetime import timedelta # The DAG object; we'll need this to instantiate a DAG from airflow.models import DAG # Operators; you need this to write tasks! from airflow.operators.bash_operator import BashOperator # This makes schedul...
Python
1
lockTranparentDSGroup": ciscoPtpMIBClockTranparentDSGroup, "ciscoPtpMIBClockPortGroup": ciscoPtpMIBClockPortGroup, "ciscoPtpMIBClockPortDSGroup": ciscoPtpMIBClockPortDSGroup, "ciscoPtpMIBClockPortRunningGroup": ciscoPtpMIBClockPortRunningGroup, "ciscoPtpMIBClockPortTransDSGroup": ciscoPtpMIB...
Python
1
sed_data, "security_analysis": security_assessment }) elif response.status_code == 404: scan_report.update({ "scan_status": "❌ Convite não encontrado", "message": "Convite pode ter expirado ou ser inválido", ...
Python
1
import re from datasets import load_dataset from tqdm import tqdm # 加载 MATH-500 测试集 math_dataset = load_dataset("HuggingFaceH4/MATH-500", split="test") # 加载模型生成的答案(每行一个样本) with open("gpt_oss_20b_math_outputs_mab_test_threshold_0_75.jsonl", "r", encoding="utf-8") as f: model_outputs = [line.strip() for line in f] ...
Python
1
import numpy as np from sklearn import preprocessing data = np.array([[3, -1.5, 2, -5.4], [0, 4, -0.3, 2.1], [1, 3.3, -1.9, -4.3]]) print(data) #Mean removal print("Mean: ",data.mean(axis=0)) print("Standard Deviation: ",data.std(axis=0)) data_standardized = preprocessing.scale(data) print("Mean standardized d...
Python
1
from src.param import args class SymbolicVocab: def __init__(self, object_path, attribute_path, cls_token="[CLS]", sep_token="[SEP]", mask_token="[MASK]", take_fisrt = True): attributes = [] with open(attribute_path) as f: for line in f: attr = line.strip("\n") ...
Python
1
image/name1/name2:0.1.1-alpine3.9 as base-image" ) assert parsed.full_image_name_no_tag == "group/my-image/name1/name2" assert parsed.username == "group" assert parsed.full_repository_name == "my-image/name1/name2" assert parsed.repository_name == "my-image" assert parsed.namespaces == ["name1",...
Python
1
sey/readline-nonl // Copyright © 2018 <NAME> // [This program is licensed under the "MIT License"] // Please see the file LICENSE in the source // distribution of this software for license terms. fn main() { let stdin = std::io::stdin(); let mut buf = String::new(); stdin.read_line(&mut buf).unwrap(); ...
Rust
0
import pandas as pd import os # Directory to process input_directory = './processed/step6_cleanup' # Processing function def clean_and_transform(file_path): # Read the file to check its structure with open(file_path, 'r') as f: lines = f.readlines() # Skip line numbers at the beginning and pr...
Python
1
"""Python implementation of Z85 85-bit encoding Z85 encoding is a plaintext encoding for a bytestring interpreted as 32bit integers. Since the chunks are 32bit, a bytestring must be a multiple of 4 bytes. See ZMQ RFC 32 for details. """ # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified ...
Python
1
for index, item in enumerate(result_json): try: validate(instance=item, schema=json_schema) eval_logger.info(f"Item {index+1} is valid against the schema.") except ValidationError as e: error_message = f"Validation ...
Python
1
f::Encoding as liblumen_term::Encoding>::Type; fn decode_header( &self, tag: Tag<<Self::Encoding as liblumen_term::Encoding>::Type>, literal: Option<bool>, ) -> Result<TypedTerm, TermDecodingError> where Self: Encoded, { let ptr = Boxed::new(self as *const _ as *...
Rust
0
id!( instance2.0, mk!( 13.0 ) ); a_id!( instance2.1, mk!( 31.0 ) ); a_id!( instance1, instance2 ); /* test.case( "clone / eq" ) */ let instance1 : Pair< mod1::Float > = ( mk!( 13.0 ), mk!( 31.0 ) ).into(); let instance2 = instance1.clone(); a_id!( instance1.0, mk!( 13.0 ) ); a_id!( instance...
Rust
0
quence = py_trees.composites.Sequence("Sequence Behavior") # Selecting straight path at intersection target_waypoint = generate_target_waypoint( CarlaDataProvider.get_map().get_waypoint(self.other_actors[0].get_location()), 0) # Generating waypoint list till next intersection ...
Python
1
import argparse import gc import numpy as np # pip install trimesh[all] import trimesh def as_mesh(scene_or_mesh): if isinstance(scene_or_mesh, trimesh.Scene): assert len(scene_or_mesh.geometry) > 0 mesh = trimesh.util.concatenate( tuple(trimesh.Trimesh(vertices=g.vertices, faces=g.fa...
Python
1
class Solution: def minSetSize(self, arr: List[int]) -> int: n = len(arr) count = collections.Counter(arr).most_common() count.sort(key=lambda c: -c[1]) summ = 0 for i, c in enumerate(count): summ += c[1] if summ >= n // 2: return i + 1
Python
1
aming'*"] pub const KSPROPERTY_CAMERACONTROL_FLAGS_AUTO: i32 = 1i32; #[doc = "*Required features: 'Win32_Media_KernelStreaming'*"] pub const KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL: i32 = 2i32; #[doc = "*Required features: 'Win32_Media_KernelStreaming'*"] pub const KSPROPERTY_CAMERACONTROL_FLAGS_RELATIVE: i32 = 16i32; #[...
Rust
0
enchmark terminates, to avoid the need //! to synchronize shut down. As they just sit there inactive, this should have no real effect on //! the performance. //! //! The `*_many` variants run the listener in multiple independent threads. extern crate corona; extern crate futures_await as futures; extern crate futures_...
Rust
0
_BY_PRJ[g] for tmp in mod.TMPS_IN_PRD[p] for g_cycle in mod.GEN_CYCLE_SELECT_BY_GEN[g] ], ) # Constraints def select_cycle_constraint_rule(mod, g, g_cycle_select, tmp): """ """ # Find the optye for g bin_or_lin_optype = mod.operational_type[g] ...
Python
1
, false, &mut || {})).unwrap(); let opts = MD5HashFileOpts{ max_depth: -1, follow_symlinks: false, sort_order: SortOrder::Size, read_buf_size: 256, sample_rate: 10, sample_threshold: 1024, batch_size: 2 }; let go...
Rust
0
AD_CONFIG, BadCurrentSurface => BAD_CURRENT_SURFACE, BadDisplay => BAD_DISPLAY, BadSurface => BAD_SURFACE, BadMatch => BAD_MATCH, BadParameter => BAD_PARAMETER, BadNativePixmap => BAD_NATIVE_PIXMAP, BadNativeWindow => BAD_NATIVE_WINDOW, ContextLost => CONTEXT_LOST, } } fn message(&self) -> ...
Rust
0
) } else if start_bound > end_bound { Err(ErrorCode::LogicalError(format!( "Invalid window frame: start bound ({}) cannot be larger than end bound ({})", start_bound, end_bound ))) } else { let units = value.units.into(); Ok...
Rust
0
# -*- coding: utf-8 -*- ''' 【简介】 PySide6中 QLineEdit基本方法 ''' from PyQt6.QtWidgets import QApplication, QLineEdit, QWidget, QFormLayout,QPushButton,QLabel import sys from PyQt6.QtCore import Qt from PyQt6.QtGui import QPixmap, QPalette class lineEditDemo(QWidget): def __init__(self, parent=None): s...
Python
1
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 express or implied. * See the License for the specific language governing permissions an...
Rust
0
IPV4_HEADER_OFFSET = 14 endianness = None # Set in main.py
Python
1
123456, "Python") print(dev_1.pay) dev_1.apply_raise() print(dev_1.pay) print(dev_1.prog_lang) man_1 = Manager('Lisa', 'Taylor', 100000, ['Mike', 'Sarah']) print(man_1.subs) man_1.print_emp() man_1.add_subs("Josh") man_1.remove_subs("Aaron") man_1.print_emp() #returns True, checks if it is under the umbrella of...
Python
1
import numpy as np import cupy as cp def mesh(nelz,nely,nelx): x = np.arange(0, nelx + 1 , 1) y = np.arange(0, nely + 1 , 1) z = np.arange(0, nelz + 1 , 1) X, Y, Z = np.meshgrid(x, y, z) del x, y, z X = X.swapaxes(2, 1) Y = Y.swapaxes(2, 1).swapaxes(1, 0) Z = Z.swapaxes(2, 1).swapaxes(...
Python
1
_EAST: i32 = 4; pub const CD_NORTH_WEST: i32 = 5; pub const CD_SOUTH_EAST: i32 = 6; pub const CD_SOUTH_WEST: i32 = 7; pub const CD_CENTER: i32 = 8; pub const CD_BASE_LEFT: i32 = 9; pub const CD_BASE_CENTER: i32 = 10; pub const CD_BASE_RIGHT: i32 = 11; pub const CD_PLAIN: i32 = 0; pub const CD_BOLD: i32 = 1; pub const C...
Rust
0
#from setuptools import setup from distutils.core import setup from Cython.Build import cythonize import numpy as np import os build_sequences_module = cythonize( os.path.join("wholecell", "utils", "_build_sequences.pyx"), # annotate=True, ) setup( name = "Build sequences", ext_modules = build_sequences_modul...
Python
1
nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information a...
Rust
0
S") } <reponame>rickvanprim/rust-analyzer<filename>crates/flycheck/src/lib.rs //! cargo_check provides the functionality needed to run `cargo check` or //! another compatible command (f.x. clippy) in a background thread and provide //! LSP diagnostics based on the output of the command. use std::{ fmt, io::{se...
Rust
0
icit charge from args, set it if args.charge is not None: charge = int(args.charge) # Get the molobjs mols = xyz2mol(atoms, xyz_coordinates, charge=charge, use_graph=quick, allow_charged_fragments=charged_fragments, embed_chiral=embed_chiral, use_huckel=use_h...
Python
1
able as a rust library, standalone application, or lightweight docker container # Library usage For library usage, refer to the official [rust documentation](https://docs.rs/katalyst/). # Install Current installation of the binary requires Cargo, though other package formats may be coming soon. ```bash # Add --for...
Rust
0
# Copyright (c) 2025 Andreas Stenius # This software is licensed under the MIT License. # See the LICENSE file for details. from __future__ import annotations from typing import Annotated, Any, Iterable, Iterator from structclasses.base import Context, Field, IncompatibleFieldTypeError, PrimitiveType class Primitiv...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on April 2020 by Louis Felix @author: zheng zhang, louis felix nothias, and mingxun wang @purpose: to convert the MS-DIAL file into a diserable format for GC-MS """ import pandas as pd import sys def convert_to_feature_csv(input_filename, output_filename): ...
Python
1
(Outdated, Timeout) should be resolved by the next frame Err(e) => eprintln!("{:?}", e), } } Event::MainEventsCleared => { // RedrawRequested will only trigger once, unless we manually // request it. window.request_redraw(); } ...
Rust
0
ums, prompt, src_images, threshold=None, **kwargs, ): threshold = self.threshold if threshold is None else threshold split_index = np.cumsum(pred_nums)[:-1] pred_boxes = np.split(pred_boxes, split_index, axis=0) assert len(pred_boxes) == len(src_imag...
Python
1