text string | label_name string | labels int64 |
|---|---|---|
for i in range(comboBox.count()):
columns.append(comboBox.itemText(i))
for b in dlg_buttons:
if b.text() == 'Cancel':
qtbot.mouseClick(b, QtCore.Qt.LeftButton)
break
break
columnCountBeforeI... | Python | 1 |
}
}
<gh_stars>0
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
pub search_fn: for <'r, 's> fn(&'r str, &'s str) -> Vec<&'s str>,
}
impl Config {
pub fn new(mut args: std::e... | Rust | 0 |
crate::semantica::globales::*;
/// Función auxiliar para actualizar el cuadruplo de gotof de la decisión y crear el goto del sino.
///
/// # Ejemplo
///
/// ```ignore
/// generar_goto_sino();
/// ```
fn generar_goto_sino() {
let mut cuadruplos = CUADRUPLOS.lock().unwrap();
let mut saltos = PILA_SALTOS.lock().un... | Rust | 0 |
());
}
#[test]
fn test_shred_reference_tick() {
let keypair = Arc::new(Keypair::new());
let slot = 1;
let parent_slot = 0;
let shredder = Shredder::new(slot, parent_slot, 5, 0).unwrap();
let entries: Vec<_> = (0..5)
.map(|_| {
let keypair0... | Rust | 0 |
/// must also guarantee that all other users of the given chunk of memory are using volatile
/// accesses.
pub unsafe fn new(addr: *mut u8, size: u64) -> VolatileSlice<'a> {
VolatileSlice {
addr,
size,
phantom: PhantomData,
}
}
/// Gets the addre... | Rust | 0 |
# 我们使用Titanic(泰坦尼克号的救援记录)这个数据集来实践一个预测某乘客是否获救的分类器。
# 这里为了处理数据方便,我们引入一个新的工具包pandas
import pandas as pd
import numpy as np
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
#瞧瞧数据,什么数据特征的都有,有数值型的、类别型的,字符串,甚至还有缺失的数据等等。
print (titanic.head())
# 使用pandas,数据都转入pandas独有的dataframe格... | Python | 1 |
(GMLAN_RD)
def GMLAN_RD_get_log(self):
# type: (Packet) -> Tuple[str, Any]
return self.sprintf("%GMLAN.service%"), \
(self.dataFormatIdentifier, self.memorySize)
@Ecu.extend_pkt_with_logging(GMLAN_TD)
def GMLAN_TD_get_log(self):
# type: (Packet) -> Tuple[str, Any]
return self.sprintf("%GMLAN.s... | Python | 1 |
# coding: utf-8
"""
Hostinger API Python SDK
API Version: 0.1.16
NOTE: This file is auto-generated, DO NOT EDIT THIS FILE MANUALLY!
If you want to contribute or request a new feature, please create an issue or pull request on https://github.com/hostinger/api
""" # noqa: E501
import unittest
from ... | Python | 1 |
{WriteProcessMemory, ReadProcessMemory},
Memory::{VirtualProtectEx, PAGE_READWRITE},
},
};
#[allow(dead_code)]
pub unsafe fn WriteMemory(
hProc: HANDLE,
lpAddress: *const c_void,
lpBuf: *const c_void,
nSize: usize,
lpNumOfBytesWritten: *mut usize,
)
{
let mut new = PAGE_READWRITE;
... | Rust | 0 |
available_tasks or 'play' not in available_tasks:
self.control_bar.play_pause_button.hide()
else:
self.control_bar.play_pause_button.clicked.connect(self.play_pause_button_clicked)
@Slot()
def play_pause_button_clicked(self) -> None:
self.send_task.emit('pause' if self.... | Python | 1 |
WS_STORAGE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = os.getenv('AWS_S3_ENDPOINT_URL')
AWS_S3_CUSTOM_DOMAIN = os.getenv('AWS_S3_CUSTOM_DOMAIN')
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
if AWS_ACCESS_KEY_ID is not None:
STORAGES = {
"default": {
"BACKEND": "storages.backends... | Python | 1 |
#!/usr/bin/python3
"""3-is_kind_of_class
"""
def is_kind_of_class(obj, a_class):
""" Compare is obj is an instance of a_class """
return isinstance(obj, a_class)
| Python | 1 |
# Django Imports
from django.shortcuts import get_object_or_404
from django.urls import reverse
# NetBox Imports
from netbox.views import generic
from utilities.views import register_model_view
# ProxBox Imports
from netbox_proxbox.models import NetBoxEndpoint
from netbox_proxbox.tables import NetBoxEndpointTable
fro... | Python | 1 |
(s) => s.into_py(py),
Self::Simple { value, comma } => {
let libcst = PyModule::import(py, "libcst").expect("libcst cannot be imported");
let kwargs = [
Some(("value", value.into_py(py))),
comma.map(|x| ("comma", x.into_py(py))),
... | Rust | 0 |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the F... | Python | 1 |
,
frame_id: u64,
is_main_frame: bool,
url: ultralight_sys::ULString,
description: ultralight_sys::ULString,
error_domain: ultralight_sys::ULString,
error_code: i32,
) where
F: FnMut(View, u64, bool, ULString, ULString, ULString, i32),
{
let closure... | Rust | 0 |
.599, 335.1, 165.0, 110.929, 1950., 61.187],
&[328.975, 209.9, 309.9, 112.075, 1951., 63.221],
&[346.999, 193.2, 359.4, 113.270, 1952., 63.639],
&[365.385, 187.0, 354.7, 115.094, 1953., 64.989],
&[363.112, 357.8, 335.0, 116.219, 1954., 63.761],
&[397.469, 290.... | Rust | 0 |
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let result = func();
// Clean up before running unwrap on test result
child.kill().unwrap();
result.unwrap();
}
<gh_stars>0
use crate::utils::consts::OPTIONS;
use crate::utils::n... | Rust | 0 |
}
#[weight = T::WeightInfo::withdraw()]
pub fn withdraw(origin, _who: T::AccountId, amount: BalanceOf<T>) -> dispatch::DispatchResult {
let sender = ensure_signed(origin)?;
let owner = T::OwnerAddress::get();
ensure!(owner == sender, Error::<T>::PermissionDenied);
... | Rust | 0 |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | Python | 1 |
.len()), false);
for i in 0..mask.len() {
if mask[i] {
tmp_state.used_bits[i] = true;
tmp_state.values[i] = entry[i];
}
}
output.push(format!("\t{}", tmp_state.debug_string(&[])));
}
format!("{}", output.join("\n"))
}
fn decode_le... | Rust | 0 |
_frame = self.interval;
}
Ok(AsyncPlaybackBuffer::new(
self.frame_size,
&mut self.buffer,
&mut self.buffer_drop,
)?)
}
}
/// No-op control for `NoopStream`s.
#[derive(Default)]
pub struct NoopStreamControl;
impl NoopStreamControl {
pub fn new() -> Se... | Rust | 0 |
import os
import unittest
from dragon.data.ddict import DDict
from dragon.native.machine import System, Node
from dragon.infrastructure.policy import Policy
from dragon.telemetry.analysis import AnalysisClient
class TestRuntimeReboot(unittest.TestCase):
def test_reboot(self):
is_a_restart = bool(os.env... | Python | 1 |
ce62efec1913cd8093c2/ref/blake2bp-ref.c#L55
.inner_hash_length(OUTBYTES);
let leaf_words = |worker_index| {
base_params
.clone()
.node_offset(worker_index)
.node_depth(0)
// Note that setting the last_node flag here has no e... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
OpenScrapers Module
"""
import json
import re
def json_load_as_str(file_handle):
return byteify(json.load(file_handle, object_hook=byteify), ignore_dicts=True)
def json_loads_as_str(json_text):
return byteify(json.loads(json_text, object_hook=byteify), ignore_dicts=True)
def bytei... | Python | 1 |
INIT: Encoding = Encoding {
name: "windows-1251",
variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1251, 0x0410, 64, 64),
};
/// The windows-1251 encoding.
///
/// This is the Cyrillic encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1251.html),
/... | Rust | 0 |
}
fn finish(&mut self, overflow: bool) -> std::io::Result<Option<Bytes>> {
let buffer = self.decoder.finish()?;
let line = match buffer.iter().position(|b| *b == b'\n') {
Some(pos) => Some(buffer.slice_to(pos)),
None if !overflow => Some(buffer),
None => No... | Rust | 0 |
, code, url);
}
}
Err(_) => println!("{}: Error accessing {}", dt, url),
}
}
}
});
}
pub fn init(&self) {
let metrics_name = self.config["pinger"]["metric-name"]
.as_str()
.unwrap_or("pinger_metrics");
let counter_rate_suffix =... | Rust | 0 |
import math
import numpy as np
import target
def sort_targets(targets):
# 按距离排序
targets.sort(key=lambda x: x.distance)
return targets | Python | 1 |
direction_history.append(current_direction)
if len(direction_history) > args.history_size:
direction_history.pop(0)
# 统计各方向出现次数
direction_counts = {
"Left Curve": direction_history.count("Left Curve"),
"Right Curve": direction_history.count("Right ... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import machine_learning as ml
from plot import color_pick, marker_pick
G_INS = ['P300', 'R300']
G_CS = ['ABA', 'CFR', 'ECO', 'EFA', 'KOX', 'KPN', 'PMA', 'SAU', 'SHO', 'SMA']
def plot_3D_scatter(data: np.array, labels: np.array, fig_size=(7, 5), f... | Python | 1 |
of its variants
enumdef
.variants
.iter()
.for_each(|variant| check_ident(cx, &variant.ident, self.upper_case_acronyms_aggressive));
},
_ => {},
}
}
}
<filename>src/tools/clippy/clippy_lints/src/misc.rs
use c... | Rust | 0 |
exists())
}
}
impl fmt::Display for PathExists {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let PathExists(path) = self;
write!(f, "PATH EXISTS {}", path.to_string_lossy())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::{tempdir, NamedTempFile}... | Rust | 0 |
it would be mutually shared in `transfer` while simultaneously would be
// immutable shared in `assert_eq`.
let mut msg_sending = msg_send;
// Transfer the content of the array via SPI and receive it's output.
// When MOSI and MISO pins are connected together, `msg_received` should receive the content.... | Rust | 0 |
pattern_chars[j as usize] == pattern_chars[m-k-1] {
j -= 1;
k += 1;
suffix[k] = j + 1;
}
if j == -1 { prefix[k] = true; }
}
(suffix, prefix)
}
fn move_by_gs(bad_char_start_index: usize, pattern_len: usize, suffix: &Vec<i32>, prefix: &Vec<bool>) -> i32 {
... | Rust | 0 |
dings,
) -> sspilib.SecChannelBindings:
"""Gets the raw byte value of the SEC_CHANNEL_BINDINGS structure."""
return sspilib.SecChannelBindings(
initiator_addr_type=int(channel_bindings.initiator_addrtype),
initiator_addr=channel_bindings.initiator_address,
accepto... | Python | 1 |
ged the threshold boundary
last_update_value: bool,
last_change_timestamp: u64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_button_keys() {
let mut button = Button::new();
assert_eq!(button.keys.len(), 0);
button.add_key(Scancode::A);
... | Rust | 0 |
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse` namespace for importing the functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'dia_matrix',
'isspmatrix_dia',
'spmatrix',
]
def __dir__():... | Python | 1 |
"from the input buffer, because they arrived too late to "
"be processed in a given time step. Try increasing the "
"time_scale_factor located within the .spynnaker.cfg file "
"or in the pynn.setup() method.")
else:
db.... | Python | 1 |
, val: T, wakeup_count: usize) {
{
let mut obj_page_tree = self.lock_page_tree();
let page_number = PageNumber::from_address(VirtAddr::new(offset as u64));
let page_offset = offset % PageNumber::PAGE_SIZE;
if let Some((page, _)) = obj_page_tree.get_page(page_numb... | Rust | 0 |
o all but last element
if idx == len(results) - 1:
bbord = u''
else:
bbord = u'bbord'
with li(cls='title bold'):
span(title, cls='name', title=title)
with span(cls=... | Python | 1 |
#!/usr/bin/python3
'''Initializes the package'''
# from models.base_model import BaseModel
from models.engine import file_storage
storage = file_storage.FileStorage()
storage.reload()
| Python | 1 |
import sys
import antlr
import codecs
import ident_l,ident_p
def warn(msg):
print >>sys.stderr,"warning:",msg
sys.stderr.flush()
def error(msg):
print >>sys.stderr,"error:",msg
sys.stderr.flush()
sys.exit(1)
### Unicode handling depends very much on whether
### your terminal can handle (print) u... | Python | 1 |
home_point = \
{
"J": [1.327,-130.671,139.899,-101.789,87.985,89.265],
}
spiral_1 = \
{
"J1": [20.669, -81.99, 86.739, -5.889, 61.649, 88.616],
"J2": [15.185, -81.715, 86.319, -5.892, 56.158, 128.796],
"J3": [13.007, -82.429, 87.249, -6.059, 53.998, 128.809]
}
spiral2 = \
{ ... | Python | 1 |
access;
mod reset;
mod seek;
use crate::register_access::{BitFlags, Register};
pub use crate::reset::{
reset_and_select_i2c_method1, reset_and_select_i2c_method1_with_gpio3,
reset_and_select_i2c_method2,
};
mod tune;
mod types;
use crate::types::OperationState;
pub use crate::types::{
ic, marker, Band, Chan... | Rust | 0 |
"""Fixtures for the trend component tests."""
from collections.abc import Awaitable, Callable
from typing import Any
import pytest
from homeassistant.components.trend.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
ComponentSetup = Callable[[dict[str, Any]],... | Python | 1 |
్రో', 'th': 'ชามอร์โร', 'ti': 'ቻሞሮ', 'tk': 'çamorro', 'to': 'lea fakakamolo', 'tr': 'Çamorro dili', 'ug': 'چامورروچە', 'uk': 'чаморро', 'ur': 'چیمارو', 'uz': 'chamorro', 'uz-Cyrl': 'чаморро', 'uz-Latn': 'chamorro', 'vec': 'ciamoro', 'vi': 'Tiếng Chamorro', 'xnr': 'कमोरो', 'yo': 'Èdè S̩amoro', 'yrl': 'xamuru', 'yue': '查... | Python | 1 |
, str>>,
{
let sql = stmt.into();
protocol::write_sql_batch(&mut self.0.transport, &sql)?;
Ok(())
}
fn simple_exec_internal<'a, Q, R: StmtResult<I>>(mut self, query: Q) -> ResultSetStream<I, R>
where
Q: Into<Cow<'a, str>>,
{
let result = self.queue_sql_batch(... | Rust | 0 |
}
/// Outputs values sampled from the standard uniform distribution.
pub fn standard_uniform<T: ArrayLike>(shape: &T) -> Tensor
{
let shape = shape.as_tensor();
Tensor::builder()
.set_input(&shape)
.set_shape(shape)
.build(random_ops::StandardUniform)
}
/// Outputs values sampled from... | Rust | 0 |
class Programmer:
company = "Microsoft"
def __init__(self , name, salary, pin):
self.name = name
self.salary = salary
self.pin = pin
p = Programmer("Aakarshit", 2400000, 226017)
print(p.name, p.salary , p.pin , p.company)
r = Programmer("Rahul", 2400000, 226017)
print(r.name, r.salary... | Python | 1 |
= []
labels = []
labels_id = []
scores = []
landmarks = []
for i, det in enumerate(pred): # detections per image
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img_size, det[:, :4], image_rgb.shape).ro... | Python | 1 |
"""From Fig. 1 of [bocquet2010a][]."""
import numpy as np
import dapper.mods as modelling
from dapper.mods.Lorenz96 import step
tseq = modelling.Chronology(0.05, dko=1, T=4**3, BurnIn=20)
Nx = 10
Dyn = {
"M": Nx,
"model": step,
"noise": 0,
}
X0 = modelling.GaussRV(M=Nx, C=0.001)
jj = np.arange(0, Nx, ... | Python | 1 |
next_frame, Runtime, RuntimeIsDone};
async fn count_up(w: Rc<RefCell<impl Write>>) {
for i in 0..300 {
{
let mut w = w.borrow_mut();
queue!(w, MoveTo(2, 5)).unwrap();
queue!(w, Print(format!("COUNT UP: {:3}/299", i))).unwrap();
w.flush().unwrap();
}
... | Rust | 0 |
import pytest
from ase.atoms import Atoms
def test_h2o_getitem():
w = Atoms('H2O',
positions=[[2.264, 0.639, 0.876],
[0.792, 0.955, 0.608],
[1.347, 0.487, 1.234]],
cell=[3, 3, 3],
pbc=True)
with pytest.raises(IndexEr... | Python | 1 |
#!/usr/bin/env python3
import rclpy
import time
from rclpy.node import Node
from sensor_msgs.msg import Imu
imu_pub = None
def imuCallback(imu):
global imu_pub
imu.header.frame_id = "base_footprint_ekf"
imu_pub.publish(imu)
def main(args=None):
global imu_pub
rclpy.init(args=args)
node = Nod... | Python | 1 |
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
# carry = 0
# len_digits = len(digits)-1
# for i in range(len_digits, -1, -1):
# if i == len_digits:
# if digits[i] + 1 > 9:
# digits[i] = 0
# carry = 1
... | Python | 1 |
#!/usr/bin/env python
#
# Copyright (c) 2012 Ralph Meijer <ralphm@ik.nu>
# See LICENSE.txt for details
"""
Print Tweets on a user's timeline in real time.
This connects to the Twitter User Stream API endpoint with the given OAuth
credentials and prints out all Tweets of the associated user and of the
accounts the us... | Python | 1 |
pt"][0],
generation_config=prompt_dict_chat["parameters"],
safety_settings=DEFAULT_SAFETY_SETTINGS,
stream=False,
)
mock_vertexai_call.assert_awaited_with(
content=prompt_dict_chat["prompt"][1],
generation_config=prompt_dict_chat["parameters"],
safety_settings=DEF... | Python | 1 |
#[inline]
pub fn new(ptr: *mut c_void) -> Self {
UContext {
context: unsafe { (ptr as *mut ucontext_t).as_mut().expect("non-null context") },
}
}
pub fn as_ptr(&mut self) -> UContextPtr {
UContextPtr::new(self.context as *mut _ as *mut _)
}
}
impl Into<UContext... | Rust | 0 |
import os
import re
def listdir(path, mask=None, includeFiles=True, includeDirs=True, maskFlags=re.IGNORECASE):
path = os.path.normpath(path)
files = os.listdir(path)
if (not includeFiles):
for f in files:
if os.path.isfile(os.path.join(path, f)):
files.remove(f)
if... | Python | 1 |
= 0;
for i in w {
w_sum += i;
}
if w_sum == p && w_size > sum_len {
prime = p;
sum_len = w_size;
break 'outer;
} else if w_sum >= p {
... | Rust | 0 |
prob.model.connect("AS_point_0.fuelburn", "fuel_diff.fuelburn")
comp = om.ExecComp("fuel_diff_25 = (fuel_mass - fuelburn) / fuelburn", units="kg")
prob.model.add_subsystem("fuel_diff_25", comp, promotes_inputs=["fuel_mass"], promotes_outputs=["fuel_diff_25"])
prob.model.connect("AS_poi... | Python | 1 |
builder().max_size(15).build(manager)?;
Ok(ConnPool { pool })
}
pub fn acquire_connection(&self) -> impl Future<Output = Fallible<Conn>> {
let pool = self.pool.clone();
poll_fn_01(move || blocking(|| pool.get()))
.then(|result| match result {
Ok(Ok(conn)) => ... | Rust | 0 |
from flask_openapi3 import Tag
from flask_openapi3 import APIBlueprint
from pydantic import BaseModel, Field
from swingmusic.api.apischemas import GenericLimitSchema
from swingmusic.lib.home.recentlyadded import get_recently_added_items
from swingmusic.lib.home.get_recently_played import get_recently_played
from swing... | Python | 1 |
# -*- coding: utf-8 -*-
try:
import cv2
except:
import sys
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2
import numpy as np
import os
import time
def TIF_algo(p1, p2, median_blur_value=3, mean_blur_value=35):
"""
通过TIF方法融合图像
:param p1_path: 图像1路径
:param p... | Python | 1 |
de: *mut ID3D11LinkingNode, SrcParameterIndex: INT, pSrcSwizzle: LPCSTR,
pDstNode: *mut ID3D11LinkingNode, DstParameterIndex: INT, pDstSwizzle: LPCSTR
) -> HRESULT,
fn GetLastError(&mut self, ppErrorBuffer: *mut *mut ID3DBlob) -> HRESULT,
fn GenerateHlsl(&mut self, uFlags: UINT, ppBuffer: *mut *mut ... | Rust | 0 |
n>().expect("");
if code != LZ4_COMPRESSION_METHOD {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
DriverError::BadCompressedPacketHeader,
));
}
if comp_size == 0
|| comp_size as usize > crate::MAX_BLOCK_SIZE_BYTES
|| raw_size as usize > cra... | Rust | 0 |
aquete)
if ruta and not error:
# Actualizar coordenadas si la ruta se calculó exitosamente
paquete.direccion_envio_lat = ruta.destino_lat
paquete.direccion_envio_lng = ruta.destino_lng
paquete.save()
... | Python | 1 |
# Define the phrase you're searching for
phrase = "I WILL NOT BE SNEAKY"
# Initialize an empty string to store differing letters
all_differing_letters = ""
# Open the text file
with open("chalkboardgag.txt", "r") as file:
# Iterate through each line in the file
for line in file:
# Remove leading/trail... | Python | 1 |
# Generated by Django 3.2.16 on 2022-11-09 04:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dojo', '0189_finding_effort_and_remediation_for_fixing'),
]
operations = [
migrations.AddField(
model_name='system_settings',
... | Python | 1 |
ersion] Translated %s into untyped function:\n%s" % (fn, repr(fundef))
_currently_processing.remove(fn)
_known_python_functions[fn] = fundef
return fundef
import threading
_lock = threading.RLock()
def translate_function_value(fn):
if fn in _known_python_functions:
return _known_pyt... | Python | 1 |
= VisGroupChain(obj)
return chain[-1]
#from Part-o-magic... over-engineered, but proven to work
def ContainerChain(feat):
'''ContainerChain(feat): container path to feat (not including feat itself).
Last container directly contains the feature.
Example of output: [<document>,<SuperPart>,<Part>,<Body... | Python | 1 |
"""
Functions to rebase Gadgets in the loc_db (Miasm per default extracts gadgets
as offset, not accounting for the load_address). To work with libraries,
we need to rebase all gadgets to their actual address.
"""
from typing import Dict, List
import copy
from miasm.core.locationdb import LocationDB
from .config impo... | Python | 1 |
import paddle
from paddle.io import DataLoader
from typing import Union, List
__all__ = [
"no_scaling",
"mean_std_scaling",
"rmsd_scaling",
"custom_scaling",
]
def no_scaling(
train_loader: DataLoader,
target: Union[str, List[str]],
**kwargs
):
return 0.0, 1.0
de... | Python | 1 |
from typing import Any
import pytest
from ikea_api import ItemFetchError
from ikea_api.constants import Constants
from ikea_api.endpoints.ingka_items import IngkaItems
from tests.conftest import EndpointTester, MockResponseInfo
def test_ingka_items_passes(constants: Constants):
item_codes = ["11111111", "222222... | Python | 1 |
bounds(&self, data: &[P::Scalar], value: P::Scalar) -> Option<usize> {
let mut first = 0usize;
let mut step;
let mut count = data.len() as isize;
while count > 0 {
step = count / 2;
let it = first + step as usize;
if !value.lt(&data[it]) {
... | Rust | 0 |
import time
import pytest
from pages.main_page import MainPage
from pages.profile_page import ProfilePage
@pytest.mark.smoke
def test_go_to_login_page(browser):
link = 'http://34.141.58.52:8080/#/'
page = MainPage(browser, link)
page.open()
page.go_to_login_page()
browser.save_screenshot('main_pag... | Python | 1 |
.into_iter())
}
}
impl<'a, T: Clone> IntoParallelStream for &'a LinkedList<T>
where
T: Send + 'static,
{
type ParStream = IterParStream<iter::Cloned<linked_list::Iter<'a, T>>>;
type Item = T;
#[inline(always)]
fn into_par_stream(self) -> Self::ParStream
where
Self: Sized,
{
IterParStream(self... | Rust | 0 |
ion: None,
waiting_read_op: None,
pending_read_ops: None,
messages_consumed_counter: None,
cursor_ledger: None,
cursor_ledger_last_entry: None,
individually_deleted_messages: None,
last_ledger_switch_timestamp: None,
state: ... | Rust | 0 |
def model_info(model, verbose=False, imgsz=640):
n_p = sum(x.numel() for x in model.parameters())
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad)
if verbose:
print(
f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}"
... | Python | 1 |
en the Cholesky decomposition of a matrix `M`, a scalar `sigma` and a vector `v`,
/// performs a rank one update such that we end up with the decomposition of `M + sigma * (v * v.adjoint())`.
#[inline]
pub fn rank_one_update<R2: Dim, S2>(&mut self, x: &Vector<N, R2, S2>, sigma: N::RealField)
where
... | Rust | 0 |
factory_get_list())
}
}
}
unsafe impl Send for TypeFindFactory {}
unsafe impl Sync for TypeFindFactory {}
/// Echart module
///
/// # TODO move to server-api
///
/// * [ ] appending data on fly https://www.echartsjs.com/examples/en/editor.html?c=linesGL-ny&gl=1
///
/// ```
/// myChart.appendData({
/// se... | Rust | 0 |
import pygame
import sys
import game_methods
# Initialize Pygame
pygame.init()
# Screen dimensions
width = 1000
height = 750
screen = pygame.display.set_mode((width, height))
# Define colors
white = (255, 255, 255)
blue = (41, 86, 143)
# Load and scale background image
background_image = pygame.image.load('images/bl... | Python | 1 |
pub subscribe_disable: SUBSCRIBE_DISABLE,
#[doc = "0x94 - Subscribe configuration for task RSSISTART"]
pub subscribe_rssistart: SUBSCRIBE_RSSISTART,
#[doc = "0x98 - Subscribe configuration for task RSSISTOP"]
pub subscribe_rssistop: SUBSCRIBE_RSSISTOP,
#[doc = "0x9c - Subscribe configuration for... | Rust | 0 |
import time
from app.libs.error_code import AddMockException, EditMockException
from app.libs.init import mongo
class Mock:
def __init__(self, method=None, url=None, request_header=None, request_body=None, response_header=None,
response_body=None, status_code=None, msg=None):
self.mid = ... | Python | 1 |
std::hash::{Hash, Hasher};
use std::borrow::Cow;
// #[deprecated = "This is a compatability macro for conversion to Nuclear"]
macro_rules! match_gcell {
(mut $p:expr, $($rest:tt)*) => {
match_gcell!(@mut (*$p).type_of(), $p, $($rest)*)
};
($p:expr, $($rest:tt)*) => {
match_gcell!(@emit (*$... | Rust | 0 |
mport is there (mentally, as I can't check current file state without reading it again)
# Assuming: from .scraper import start_link_discovery, scrape_selected_pages
try:
# We pass session_name_base to help name the directory within ROOT_OUTPUT_DIR
# scrape_selected_pages will call create_sessio... | Python | 1 |
or: String,
pub description: String,
pub external_url: String,
pub image: String,
pub name: String
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Asset {
pub erc_data: ERC721,
pub metadata: Metadata
}
<reponame>NZXTCorp/native-windows-gui<filename>native-windows-gui/src/winnls/locale.rs
use winapi::... | Rust | 0 |
8::new_fp4s(
&FP4::new_fp2s(
&FP2::new_bigs(
&BIG::new_ints(&rom::CURVE_PYAAA),
&BIG::new_ints(&rom::CURVE_PYAAB),
),
&FP2::new_bigs(
&BIG::new_ints(&rom::CURVE_PYABA),
... | Rust | 0 |
impl<R: Rule> RuleEdges<R> {
pub fn entry_for(&self, dependency_key: &R::DependencyKey) -> Option<&Entry<R>> {
self
.dependencies
.get(dependency_key)
.and_then(|entries| entries.first())
}
pub fn all_dependencies(&self) -> impl Iterator<Item = &Entry<R>> {
self.dependencies.values().f... | Rust | 0 |
filename>src/join.rs
// From the specs-rs project:
// https://github.com/slide-rs/specs/
// Appache 2.0 License
#![allow(missing_docs)]
use tuple_utils::Split;
use hibitset::{BitSetAnd, BitSetLike};
/// BitAnd is a helper method to & bitsets togather resulting in a tree
pub trait BitAnd {
type Value: BitSetLike... | Rust | 0 |
_space=add_prefix_space,
**kwargs,
)
pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
... | Python | 1 |
#[test]
fn encr_keying() {
let (skey, _) = make_deterministic_keys(b"testing");
let my_cloaking_seed = "diddly";
let encr_key = encrypt_key(my_cloaking_seed, &skey.to_bytes());
assert!(encr_key.payload != skey.to_bytes());
let recovered_skey =
decrypt_key(my_... | Rust | 0 |
x1b' {
if let Some((_, '[')) = iter.next() {
is_color = true;
}
} else if visible_len < MAX_COLS {
truncated_len = i;
visible_len += 1;
} else {
truncated_len = i;
visible_len = MA... | Rust | 0 |
查新密碼強度
strength = check_password_strength(request.new_password)
if not strength["is_strong"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"密碼強度不足: {', '.join(strength['feedback'])}"
)
# 生成新密碼哈希
new... | Python | 1 |
r=True)[0]
cfg = load_cpac_pipe_config(pipe_config)
cfg.pipeline_setup['output_directory']['path'] = \
os.path.join(test_dir, 'out')
cfg.pipeline_setup['working_directory']['path'] = \
os.path.join(test_dir, 'work')
cfg.pipeline_setup['log_directory']['path'] = \
os.path.join(te... | Python | 1 |
ile_path(existing_file, schemas_dir)
assert schema_file.exists()
assert schema_file in schemas_before
existing_file.unlink()
time.sleep(0.5)
filewatcher.dispatch.assert_any_call( # type: ignore
FileDeletedEvent(
src_path=str(existing_file),
is_synthetic=False,
... | Python | 1 |
import numpy as np
import scipy.misc
import tensorflow as tf
import tensorflow.contrib.slim as slim
import slim_net
NUM_CLASSES = 2
COLOR_SET = [
[255, 255, 255], [125, 135, 185], [190, 193, 212], [214, 188, 192],
[187, 119, 132], [142, 6, 59], [74, 111, 227], [133, 149, 225],
[181, 187, 227], [230, 175... | Python | 1 |
| Schema::Enum { .. }
| Schema::Record { .. }
| Schema::Map(..)
| Schema::Array(..)
| Schema::Union(..) => q.push_back(&**sc),
// ... Not nested, can be pushed to the result stack
_ => push_unique(&mut deps, ... | Rust | 0 |
}
(Block(an, a), Block(bn, b)) => {
if a == b {
Block(an + bn, a)
} else {
let mut res = Vec::with_capacity(an as usize * a.len() + bn as usize * b.len());
for _ in 0..an {
res.extend(a.iter(... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.