text
string
label_name
string
labels
int64
split_once(&header, |&b| b == b' ') .ok_or_else(|| invalid_data_err("no space in git object header"))?; // Convert size from `&[u8]` to `&str` let size = str::from_utf8(size) .map_err(|_| invalid_data_err("git object size is not valid UTF-8"))?; // Convert size from `&...
Rust
0
import tweepy import pandas as pd import json from datetime import datetime import s3fs def run_twitter_etl(): access_key = "" access_secret = "" consumer_key = "" consumer_secret = "" # Twitter authentication auth = tweepy.OAuthHandler(access_key, access_secret) auth.set_access_t...
Python
1
float(node.get('width')) image_h = float(node.get('height')) newpath.set('d', str(Path(self.drawfunction(image_w, image_h, file)))) newpath.set('title', 'Line_Shading') node.getparent().append(newpath) newpath.set('x', x) def export_png(self, nod...
Python
1
uchar, b: c_uchar, a: c_uchar); pub fn IupGetAttribute(ih: *mut Ihandle, name: *const c_char) -> *mut c_char; pub fn IupGetInt(ih: *mut Ihandle, name: *const c_char) -> c_int; pub fn IupGetInt2(ih: *mut Ihandle, name: *const c_char) -> c_int; pub fn IupGetIntInt(ih: *mut Ihandle, name: *const c_char, i...
Rust
0
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets import cv2 import numpy as np class Ui_PracticeWindow(object): def __init__(self): self.main_window_width = 960 self.main_window_height = 720 ### 設定物件布局 def setupUi(self, MainWindow): ### 設定主視窗 MainWindow.s...
Python
1
RequestId(self): """唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :rtype: str """ return self._RequestId @RequestId.setter def RequestId(self, RequestId): self._RequestId = RequestId def _deserialize(self, params): if params.get("Job") is not None: ...
Python
1
AsyncRead` which will read /// at most `limit` bytes, after which it will always return EOF /// (`Ok(0)`). Any read errors will not count towards the number of /// bytes read and future calls to [`read()`][read] may succeed. /// /// # Examples /// /// [`File`][cra...
Rust
0
import time # Pausas no script / Script pauses import ctypes # Manipula funções do SO / Handles OS functions import threading # Permite verificar a opção de saída sem interromper o loop principal / Allows exit option check without interrupting main loop from datetime import datetime, timedelta # Exibe a hora exata ...
Python
1
han the ref ligand SDF.") conformer = ref_mol.GetConformer() xyz_predicted = np.array(this_mol.GetConformer().GetPositions()) for atom_index_in_mol in range(len(xyz_predicted)): conformer.SetAtomPosition(atom_index_in_mol, xyz_predicted[atom_index_in_mol]) output_sdf_block = Chem.MolToMolBloc...
Python
1
return Ok(None); } let b2 = get!(2, 0x80, 0xC0) as u32; let c = ((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F); (unsafe { char::from_u32_unchecked(c) }, 3) } else if b0 < 0xF8 { let b1lim = if b0 == 0xF0 { 0x90 } else { 0x80 }; ...
Rust
0
[Seed] = None): rng = np.random.default_rng(seed) values = rng.integers(0, rng.integers(10, 100), 10) return np.sum(values) map_reduce_job = MapReduceJob( None, map_func=_sum_of_random_integers, reduce_func=np.mean, parallel_backend=parallel_backend, ) ...
Python
1
(target_arch = "wasm32"))] fn debug_read_depthbuffer(&mut self, framebuffer: &str) -> Vec<f32> { let (framebuffer_width, framebuffer_height) = { let framebuffer = self .framebuffers .get(framebuffer) .unwrap_or_else(|| panic!("Framebuffer '{}' not ...
Rust
0
import time import numpy as np from argparse import ArgumentParser from scipy.sparse import load_npz from scipy.sparse.linalg import eigsh def load_matrix(path): start_time = time.time() sparse_matrix = load_npz(path) end_time = time.time() print(sparse_matrix.nnz) print(f"Matrix loaded from: {path...
Python
1
# stream_extreme_temp.py import asyncio, time, math import httpx from collections import defaultdict from datetime import datetime, timezone # Example watchpoints (lat, lon, label). Add more or generate a grid. WATCHPOINTS = [ (48.2082, 16.3738, "Vienna"), (51.5074, -0.1278, "London"), (40.7128, -74.0060, ...
Python
1
ontent_lengths rlrHeadersMixin.content_length3**4+>+>?%-tF3~3FFrwrvrurwrrrsrtrur frozensetATTRSr.rrrurrvrrGrwr#rFr~propertyrWrrrrvrjrwrlrqrq% P QE3#'M8C='.2M8DcN+28@...
Python
1
Key(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] proxyOverride = str(winreg.QueryValueEx(internetSettings, ...
Python
1
) -> Self { assert!(vec.len() >= 2); Collision(Box::new(vec.into())) } pub fn from_box(b: Box<[(K, V)]>) -> Self { assert!(b.len() >= 2); Collision(Box::new(b)) } pub fn len(&self) -> usize { self.0.len() } pub fn iter(&self) -> slice::Iter<'_, (K, V)> { ...
Rust
0
# Finite-Difference Time-Domain (FDTD) Simulation of Electromagnetic Wave Propagation import numpy as np # Import NumPy for numerical operations from matplotlib import pyplot as plt # Import Matplotlib for plotting # Define the number of spatial points ke = 200 # Initialize electric field (Ex) and magnetic field (...
Python
1
#!/usr/bin/env python # coding=utf-8 import json import numpy as np # from constant import cam2idx,idx2cam from math import radians, cos, sin, asin, sqrt #!/usr/bin/env python # coding=utf-8 #cam2idx={ # 'SQ0931':0, # 'SQ0927':1, # 'SQ0928':2, # 'SQ0924':3, # 'SQ0929':4, # 'SQ0930':5, # 'SQ0932':6...
Python
1
ariant_names)] #![allow(clippy::match_like_matches_macro)] use crate::{ ast::*, SyntaxKind::{self, *}, SyntaxNode, SyntaxResult, SyntaxToken, T, }; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct JsUnknownStatement { pub(crate) syntax: SyntaxNode, } impl JsUnknownStatement { pub fn syntax_element(&self) ->...
Rust
0
#! /usr/bin/env python # # Copyright 2022 Spotify AB # # Licensed under the GNU Public License, Version 3.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.gnu.org/licenses/gpl-3.0.html # # Unless required by applicable law...
Python
1
commit_strategy, CommitEncodeWithStrategy, Conceal, }; use bitcoin::{OutPoint, Txid}; use core::convert::TryFrom; pub type Confidential = OutpointHash; /// Convenience type name useful for defining new seals pub type SealDefinition = Revealed; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Display...
Rust
0
Selector<'a> { /// The extents of the current level extents: (i32, i32), /// The big tileset big_set: Tileset<'a>, /// The small tileset small_set: Tileset<'a>, } impl<'a> TilesetSelector<'a> { const THRESHOLD: i32 = 40; /// Creates a new instance. pub fn new(big_set: Tileset<'a>, ...
Rust
0
from itertools import combinations a=list(map(int,input().split())) b=list(map(int,input().split())) count=0 for al,bl in combinations(zip(a,b),2): ali,alc=al bli,blc=bl if (ali>bli and alc<blc) or (ali<bli and alc>blc): count+=1 print(count)
Python
1
JigEPzgINDAYdxNvpeWrEh3QTZk5tIK9 75p5hXFKpSKVBtwRnfOaNHPV+ap8QSiWn0yS7tsUao8dUzJQXbVaT9Al8uaj2MLz vFFiBsq7J4svBn6Q41xpFBW5vdQsNXP5Qg+0depSxyvuzaavaMaZNynzB4r0KKxX d9W8qNFcWb/7BWFYgmw7TmJjIn0F/6pKrG75MUrj5Jc6cQMRfNuJrSjEYpsBkG2e LWy5QBTboDtNnldB6vMR8X25ja25UqiMuvP1HY4OGPX3hYvDVX2IP67BY7i/hb/9 3SwQYWjH38lfSdHlC14FcOWVzWk...
Rust
0
model((sample_hat + 1) / 2, sigma_hat / 2).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev step_output = self.scheduler.step(model_output, sigma_hat, sigma_prev, sample_hat) if sigma_prev != 0: # 6. Apply 2nd order ...
Python
1
sAnt({:?} -> color: {:?}, dir: {:?})", self.pos, self.color, self.dir ) } } <gh_stars>10-100 //! TinKV command line app. use clap_verbosity_flag::Verbosity; use std::path::PathBuf; use std::process; use structopt::{self, StructOpt}; use tinkv::{self, Store}; #[derive(Debug, StructOpt)] enum Sub...
Rust
0
ic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [flctl_bank1_rdctl](flctl_bank1_rdctl) module"] pub type FLCTL_BANK1_RDCTL = crate::Reg<u32, _FLCTL_BANK1_RDCTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FLCTL_BANK1_RDCTL; #[doc = "`r...
Rust
0
get_input_commitment_ids<'a>(process: &ProcessAddress) -> Cow<'a, Vec<CommitmentAddress>> { get_linked_addresses_with_foreign_key_as_type(process, PROCESS_COMMITMENT_INPUTS_LINK_TYPE, PROCESS_COMMITMENT_INPUTS_LINK_TAG) } fn get_output_commitment_ids<'a>(process: &ProcessAddress) -> Cow<'a, Vec<CommitmentAddress>...
Rust
0
ChrTurnDirection(0x00FE, 0x0008, 0) Yield() Jump('lambda_2526') DispatchAsync2(0x0101, 0x0001, lambda_2526) @scena.Lambda('lambda_2537') def lambda_2537(): ChrTurnDirection(0x00FE, 0x0008, 0) Yield() Jump('lambda_2537') DispatchAsync2(0x00F7, 0x0001, ...
Python
1
#!/usr/bin/env python3 import sys import struct import os from scapy.all import sniff, sendp, hexdump, get_if_list, get_if_hwaddr from scapy.all import Packet, IPOption from scapy.all import ShortField, IntField, LongField, BitField, FieldListField, FieldLenField from scapy.all import IP, UDP, Raw from scapy.layers.in...
Python
1
e if isinstance(message, MessageSegment) else Message(message) for ms in message: # 处理文本 if ms['type'] == 'text': res += str(ms['data']['text']).strip() continue # 处理图片 if ms['type'] == 'image': file = ms['data']['file'] try: ...
Python
1
th = os.path.expanduser(file_path) if not os.path.exists(expanded_path): return {"success": False, "message": f"File does not exist: {expanded_path}", "error": "file_not_found", "details": {"path": expanded_path}} file_ext = os.path.splitext(expanded_pat...
Python
1
ce, 0x34, 0x5c, 0xd1, 0xc5, 0xdb, 0x79, 0x49, 0x28, 0x23, 0x13, 0xef, 0x3e, 0xe0, 0xca, 0xf1, 0xef, 0x62, ]); let expected_ct = ByteSeq::from_public_slice(&[ 0xf6, 0x26, 0xd5, 0x8f, 0xf, 0x42, 0xc7, 0xc2, 0x7a, 0xa1, 0xd1, 0x40, 0xb, 0x1, 0xb8, 0xc2, 0x1a, 0x5, 0x3f, 0x65, 0x23, 0xb4, 0...
Rust
0
案提取 query_words = set(query.lower().split()) best_answer = "" best_score = 0 for doc in context.relevant_docs: doc_text = doc.content.lower() score = 0 # 计算查询词在文档中的出现频率 for word in query_words: if len(word) > 1: # 忽略单字符词...
Python
1
onding to a batch of N inputs :param labels: shape=[N, C], labels of inputs, ``labels[i][k] == 1`` means the i-th input belongs to the k-th category and vice versa. Multi-label input is allowed. :param str kernel_type: Type of kernel function used when calculating inner products. The inner product is the simila...
Python
1
,fuse::session=error,info"; const DEFAULT_CONFIG: &str = r#" ### This is the configuration file that GCSF uses. ### It should be placed in $XDG_CONFIG_HOME/gcsf/gcsf.toml, which is usually ### defined as $HOME/.config/gcsf/gcsf.toml # Show additional logging info? debug = false # Perform a mount check and fail early...
Rust
0
} } impl<T: Float> Div<Self> for Complex<T> { type Output = Self; fn div(self, other: Self) -> Self { let re = self.re * other.re + self.im * other.im; let im = self.re * other.im - self.im * other.re; Self::Output { re, im } } } #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)]...
Rust
0
ome(HashingAlgorithm::Sha256)) /// .expect("Failed to create RSA scheme"), /// RsaKeyBits::Rsa2048, /// RsaExponent::default(), /// ) /// .expect("Failed to create rsa public area"); /// /// // Execute context methods using the session /// context.exec...
Rust
0
tiveValue { fn from(value: $typ) -> Self { PrimitiveValue::$variant(C::from_slice(&value[..])) } } }; } macro_rules! impl_from_array_for_primitive_1_to_8 { ($typ: ty, $variant: ident) => { impl_from_array_for_primitive!([$typ; 1], $variant); impl_...
Rust
0
pub fn glUniformMatrix2fv_is_loaded() -> bool { !glUniformMatrix2fv_p.load(RELAX).is_null() } /// [glUniformMatrix2x3fv](http://docs.gl/es3/glUniform)(location, count, transpose, value) /// * `value` len: count*6 #[cfg_attr(feature = "inline", inline)] #[cfg_attr(feature = "inline_always", inline(always)...
Rust
0
wx.ALL, 5) freeze_box_sizer.Add(freeze_grid, 0, wx.ALL | wx.EXPAND, 5) # 添加下载链接和功能按钮 link_buttons_sizer = wx.BoxSizer(wx.HORIZONTAL) # 下载链接 self.download_link = wx.adv.HyperlinkCtrl(self, -1, "下载 pssuspend64", "https://download.sysinternals.com/files/PS...
Python
1
), }; let mut rl = Editor::with_config(config); rl.set_helper(Some(h)); rl.bind_sequence(KeyEvent::alt('n'), Cmd::HistorySearchForward); rl.bind_sequence(KeyEvent::alt('p'), Cmd::HistorySearchBackward); if rl.load_history("pua_history.txt").is_err() { println!("No previous history."); ...
Rust
0
elf.lcd_control.bits(), LCDStatusRegister => self.lcd_status.bits(), ScrollY => self.scroll_y, ScrollX => self.scroll_x, CurrentScanline => self.rendering_state.line, ComparisonScanline => self.comparison_scanline, BackgroundPalette => self.backgro...
Rust
0
하는지 확인 for col in df.columns: if col.startswith('MA_') or col == 'RSI' or col.startswith('Volatility_'): if df[col].dtype in ['float64', 'int64']: # 급격한 점프가 있는지 확인 diff = df[col].diff().abs() if len(diff.dropna()) > 0: ...
Python
1
# Copyright 2020 The JAX Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
Python
1
""" If you have issues about development, please read: https://github.com/knownsec/pocsuite3/blob/master/docs/CODING.md for more about information, plz visit http://pocsuite.org """ from collections import OrderedDict from urllib.parse import urljoin from pocsuite3.api import POCBase, Output, register_poc, logger, req...
Python
1
enerate!("ncnn::Option") generate!("_ncnn_option_t") generate!("ncnn_option_create") // generate!("ncnn_option_destroy") generate!("_ncnn_net_t") generate!("ncnn_net_load_param") generate!("ncnn_net_load_model") generate!("ncnn_net_create") generate!("init_tengine") generate!("r...
Rust
0
-> Result<Ex> { Ok(Ex(ex.to_string())) } } impl FromStr for DockerEnv { type Err = Error; fn from_str(env: &str) -> Result<DockerEnv> { Ok(DockerEnv(env.to_string())) } } #[derive(Debug, Clone)] pub struct Dest(PathBuf); impl FromStr for Dest { type Err = Error; fn from_str(...
Rust
0
[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] pub enum CrowdfundingStatus { // Incomplete -> Ready -> Active Incomplete, Ready, Active, // Active -> Payout -> Raise -> RaiseDone Payout, Raise, RaiseDone, // A...
Rust
0
# colors.py Micropython GUI library for TFT displays: colors and shapes # Released under the MIT License (MIT). See LICENSE. # Copyright (c) 2019-2023 Peter Hinch from hardware_setup import SSD from gui.core.writer import CWriter # Code can be portable between 4-bit and other drivers by calling create_color def creat...
Python
1
t[int], float]: loop = asyncio.get_running_loop() async with aiofiles.open(playlist_path, encoding='utf8') as file: content = await file.read() playlist = await loop.run_in_executor(None, m3u8.loads, content) duration = Decimal() timestamps: List[int] = [] for seg in play...
Python
1
("{}", s), Expr::Let(var, val, body) => format!( "(let (({} {}))\n{})", var, val, pp(body, lvl+1) ), Expr::Lambda(var, None, body) => format!("(λ ({})\n{})", var.join(" "), pp(body, lvl+1)), Expr::Lambda(var,...
Rust
0
t(); NTILES]; ips.iter_mut().for_each(|p| *p = rng.gen()); jps.iter_mut().for_each(|p| *p = rng.gen()); for i in 0..NTILES { for j in 0..NTILES { kernel.p2p(THRESHOLD, THRESHOLD, &mut ips[i], &mut jps[j]); } } ...
Rust
0
ery/current_now') if isinstance(reg, str) and "No such file or directory"==reg: logger.debug("can't get current from file /sys/class/power_supply/battery/current_now") elif reg: current = reg return current def _get_powerinfo_dic(self, out): ''' :par...
Python
1
'include_context']: assert self._context is not None, 'context is None' to_exec = f'{self._context}\n{code_str}' to_log = f'{self._context}\n{user_query}\n{code_str}' else: to_exec = code_str to_log = f'{user_query}\n{to_exec}' to_log_...
Python
1
{ ($kind:ident, $value:tt) => { Argument::Register(Register { kind: RegisterKind::$kind, position: 0, high: false, raw_value: Some($value), }) }; ($kind:ident, $pos:tt, $high:tt) => { Argument::Register(Register { kind: Reg...
Rust
0
import time, pytest, inspect from utils import * def test_inputs(run_brave): run_brave() check_brave_is_running() assert_inputs([]) # Create input, and can set the id add_input({'type': 'test_video', 'id': 99}) time.sleep(2) assert_inputs([{'type': 'test_video', 'id': 99, 'uid': 'input99'...
Python
1
import csv import subprocess import argparse import os import sys #Motive: take an input file of the format geneFamily \t genome and output a roary style gene_presence_absence.csv. #Parse arguemnts to get input file for reading parser = argparse.ArgumentParser() parser.add_argument("--input", "-i", type=str, required...
Python
1
ut IWXSTR) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn iwxstr_user_data_detach(xstr: *mut IWXSTR) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn iwxstr_clear(xstr: *mut IWXSTR); } #[doc = " @brief JSON document in compact binary format [Binn](https://github.com/liteserver/binn)"] #[repr(C)] #[d...
Rust
0
(1.0) ); assert!((distance_curve.point_at_pos(0.0).x() - -4.0).abs() < 0.0001); assert!((distance_curve.point_at_pos(1.0).x() - 4.0).abs() < 0.0001); } #[test] fn clip_line_1() { // Horizontal line, with a y range of 2.0 to 7.0 let fat_line = FatLine::new((Coord2(0....
Rust
0
mask |= value; } option_mask } } /// Core model in XGBoost, containing functions for training, evaluating and predicting. /// /// Usually created through the [`train`](struct.Booster.html#method.train) function, which /// creates and trains a Booster in a single call. /// /// For more fine grained...
Rust
0
import csv import sqlite3 import os from ..config import HostConfig as Config def main(): """ Exports all scraped host guidebooks into a CSV file. """ conn = sqlite3.connect(Config.CONFIG_DB_FILE) cur = conn.cursor() # Query the host_guidebooks table cur.execute(""" SELECT ...
Python
1
""" Домашнее задание №1 Цикл for: Продажи товаров * Дан список словарей с данными по колличеству проданных телефонов [ {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, {'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141,...
Python
1
""" Generic alphametic solver in cpmpy. This is a generic alphametic solver. Usage: python alphametic.py -> solves SEND+MORE=MONEY in base 10 python alphametic.py 'SEND+MOST=MONEY' 11 -> solver SEND+MOST=MONEY in base 11 python alphametic.py TEST <base> -> solve some test probl...
Python
1
en(|x| usize::from_str_radix(x, 16).ok()) .unwrap_or(0); let uid = pieces.skip(2).next() .and_then(|x| x.parse::<u32>().ok()) .unwrap_or(0); return Socket { local_address: local.into(), remote_address: remote.into(), state: status.into(), tx_queue: tx, ...
Rust
0
pResult { let jobset_cfg = load_config(config_path); let creds = Creds { username: String::from(user), password: String::from(password), }; client.login(creds)?; client.jobset_create(project_name, jobset_name, &jobset_cfg)?; ok_msg("jobset__create") } extern crate alloc; use c...
Rust
0
b'M', b'1', b'N', b'1', b'O', b'1', b'P', b'1', b'Q', b'1', b'R', b'1', b'S', b'1', b'T', b'1', b'U', b'1', b'V', b'1', b'W', b'1', b'X', b'1', b'Y', b'2', b'0', b'2', b'1', b'2', b'2', b'2', b'3', b'2', b'4', b'2', b'5', b'2', b'6', b'2', b'7', b'2', b'8', b'2', b'9', b'2', b'A', b'2', b'B', b'2', b'C', b'...
Rust
0
# Programmer: limodou # E-mail: limodou@gmail.com # # Copyleft 2006 limodou # # Distributed under the terms of the GPL (GNU Public License) # # NewEdit is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
Python
1
tr, data: &HoliumCbor, ) -> Result<Option<String>> { // Write data in local context local_context .data .insert(node_typed_name, data.to_vec()) .context(DbOperationFailed)?; // Try to export with portation let mut portation_file_path: Option<String> = None; let res_porta...
Rust
0
-> Result<DOMElement, glib::Error>; #[cfg_attr(feature = "v2_22", deprecated)] #[cfg(any(feature = "v2_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_16")))] #[doc(alias = "webkit_dom_document_fragment_query_selector_all")] fn query_selector_all(&self, selectors: &str) -...
Rust
0
"""Say we have a data abstraction for cities. A city has a name, a latitude coordinate, and a longitude coordinate. Our data abstraction has one constructor: make_city(name, lat, lon): Creates a city object with the given name, latitude, and longitude. We also have the following selectors in order to get the informat...
Python
1
_state_machine(&mut context, &resource); expect(context.response.status).to(be_equal_to(204)); expect(context.response.headers.get("A").unwrap().clone()).to(be_equal_to(vec!["B".to_string()])); expect(context.response.headers.get("C").unwrap().clone()).to(be_equal_to(vec!["D;E=F".to_string()])); } #[test] fn exe...
Rust
0
"""Tests for the bob_emploi.data_analysis.importer.deployments.uk.unemployment_rate module.""" from os import path import os import tempfile import unittest import requests_mock from bob_emploi.data_analysis.importer.deployments.uk import unemployment_rate @requests_mock.mock() class TestCareerChangers(unittest.Te...
Python
1
, WalletKind::Basic) .is_ok()); let staking_address = wallet.new_staking_address(name, passphrase).unwrap(); let synchronizer = ManualSynchronizer::new( storage.clone(), MockClient { staking_address }, MockBlockHandler, ); synchronizer ...
Rust
0
import base64 import json import os import glob import os.path as osp import numpy as np import PIL.Image from labelme import utils def process_json_files(json_dir: str, jpgs_path: str, pngs_path: str) -> None: json_files = glob.glob(os.path.join(json_dir, '*.json')) for json_file in json_files: wit...
Python
1
title>", username); println!("<link>{}</link>", user_url); println!("<description>{}</description>", user_url); for node in document.find(Class("tweet")) { println!("<item>"); let timestamp = node.find(Class("tweet-timestamp")).next().unwrap(); let text = node.find(Class("tweet-text...
Rust
0
"""Реализуйте класс ReversibleString, описывающий строку. При создании экземпляра класс должен принимать один аргумент: string — значение строки Экземпляр класса ReversibleString должен иметь следующее неформальное строковое представление: <значение строки> Также экземпляр класса ReversibleString должен поддерживать ...
Python
1
ount_config::AccountSequenceInfo, on_chain_config::ON_CHAIN_CONFIG_REGISTRY, PeerId, }; use channel::{aptos_channel, message_queues::QueueStyle}; use enum_dispatch::enum_dispatch; use event_notifications::EventSubscriptionService; use futures::{ channel::mpsc::{self, unbounded, UnboundedReceiver}, FutureExt, St...
Rust
0
elf, node): for k, v in node.parent.children.items(): if v == node: break del node.parent.children[k] self.evictable_size_ -= len(node.key) def _total_size_helper(self): total_size = 0 stack = [self.root_node] while stack: curr...
Python
1
.unwrap(), url); } #[test] fn test_authorize_url_with_param() { let config = Config::new("aaa", "bbb", "http://example.com/auth?foo=bar", "http://example.com/token"); let url = config.authorize_url(); assert_eq!(Url::parse("http://example.com/auth?foo=bar&client_id=aaa&scope=&response_type=code").unwrap(...
Rust
0
import numpy as np import imutils import pickle import time import cv2 embeddingModel="Attendence-System-Face-Recognition/openface.nn4.small2.v1.t7" embeddingFile='Attendence-System-Face-Recognition/output/embeddings.pickle' recognizerFile='Attendence-System-Face-Recognition/output/recognizer.pickle' labelEncFile='At...
Python
1
aux: (N, num_classes, H_out, W_out), Auxillary classification logits """ # Preprocess images x = self.preprocess(images) # Extract features result = OrderedDict() features = self.model.backbone(x) result['features'] = features['features'] feat_sh...
Python
1
::new("CASDOMUXEN_B", 1)); port.insert(Port::new("CASOREGIMUXA", 1)); port.insert(Port::new("CASOREGIMUXB", 1)); port.insert(Port::new("CASOREGIMUXEN_A", 1)); port.insert(Port::new("CASOREGIMUXEN_B", 1)); port.insert(Port::new("ADDRARDADDR", 14)); port.insert(Port::new("A...
Rust
0
cl( event, name, ty_param_list_opt, left_brace, fields, right_brace_opt, comma_opt, px, ) } fn parse_variant_decl(parent: VariantParentKind, px: &mut Px) -> Option<AfterVariantDecl> { let event = px.start_element(); let name = parse_unqualifia...
Rust
0
wait(); }).unwrap(); } #[bench] fn load_usize(b: &mut test::Bencher) { let a = AtomicCell::new(0usize); let mut sum = 0; b.iter(|| sum += a.load()); test::black_box(sum); } #[bench] fn store_usize(b: &mut test::Bencher) { let a = AtomicCell::new(0usize); b.iter(|| a.store(1)); } #[bench] ...
Rust
0
'input>, usize), (_, __0, _): (usize, Type, usize), ) -> Type { (__0) } fn __action50< 'input, >( (_, h, _): (usize, ::std::vec::Vec<VarTy>, usize), (_, t, _): (usize, ::std::option::Option<VarTy>, usize), ) -> Vec<VarTy> { { let mut h = h; h.extend(t); h } } fn __a...
Rust
0
impl Future<Output = T> + 'static>) -> JoinAll<T> { let fut = fut .into_iter() .map(|f| JoinFuture::Future(Box::pin(f))) .collect(); JoinAll { fut } } enum JoinFuture<T> { Future(Pin<Box<dyn Future<Output = T>>>), Result(Option<T>), } impl<T> Unpin for JoinAll<T> {} impl<T> F...
Rust
0
NOTIFICATION_DATA = 1 << 38, VIRTIO_NET_F_GUEST_HDRLEN = 1 << 59, VIRTIO_NET_F_RSC_EXT = 1 << 61, VIRTIO_NET_F_STANDBY = 1 << 62, // INTERNAL DOCUMENTATION TO KNOW WHICH FEATURES HAVE REQUIREMENTS // // 5.1.3.1 Feature bit requirements // Some networking feature bits require other networking feature bits ...
Rust
0
config.no_tld_query = true; config.sortlist = vec![ Network::V4( Ipv4Addr::new(130, 155, 160, 0), Ipv4Addr::new(255, 255, 240, 0), ), // This fails currently Network::V4(Ipv4Addr::new(130, 155, 0, 0), Ipv4Addr::new(255, 255, 0, 0)), ]; assert_eq!(confi...
Rust
0
let py_server_tuple = PyTuple::new( py, server_addresses .into_iter() .map(|addr| (addr.ip().to_string(), addr.port())), ); scope_dict.set_item("server", py_server_tuple) }) } } use super::*; mod che...
Rust
0
from shutil import copyfile from .attachments import copy_attachments from ....path_model import dst_model from ....path_model import src_model from ....typehint import * def main(conf: TConf): src_model.assert_ready() dst_model.assert_ready() print( ':l', 'model paths overview', (sr...
Python
1
.Swm.html pub fn assign<P, S>( mut self, mut pin: Pin<P, S>, swm: &mut Handle, ) -> ( Function<T, Assigned<P>>, <Pin<P, S> as AssignFunction<T, T::Kind>>::Assigned, ) where T: FunctionTrait<P>, P: pins::Trait, S: pins::State, Pin<P,...
Rust
0
eError hf_token = os.environ['HF_TOKEN'] huggingface_hub.login(hf_token) if args.use_4bit: print("Using 4-bit inference") tokenizer = AutoTokenizer.from_pretrained(model_name, token=hf_token) tokenizer.pad_token_id = tokenizer.eos_token_id # for open-ended generation ...
Python
1
b(s[y], 1), nyb(s[y], 2), nyb(s[y], 3), ]); rows.push(vec![ f(xprime), f(yprime), f(top_bit), nyb(y_xor_xprime, 4), nyb(y_xor_xprime, 5), nyb(y_xor_xprime, 6), nyb(y_xor_xprime, 7), ny...
Rust
0
""" Classifies: CHEBI:82744 aliphatic aldoxime """ from rdkit import Chem def is_aliphatic_aldoxime(smiles: str): """ Determines if a molecule is an aliphatic aldoxime based on its SMILES string. An aliphatic aldoxime contains an aliphatic chain and an aldehyde group converted to an oxime (R-C=NOH). ...
Python
1
construct the weights W_est = self.dequantize_Wq_aten(W_q, meta) # Cleanup for key in del_keys: del meta[key] return W_est def forward_aten(self, x: Tensor) -> Tensor: W_est = self.dequantize_aten() out = torch.matmul(x, W_est.t()) if self.bias ...
Python
1
e(), |&l, &r| l.cmp(&r), |&c| c.to_digit(10).map(|v| v as isize)) } /// Compares two strings case-insensitively. /// It skips any Unicode whitespaces and handles a series of decimal digits. pub fn compare_ignore_case(left: &str, right: &str) -> Ordering { // XXX what we really wan...
Rust
0
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" message = f"Hello, {full_name.title()}!" print(message)
Python
1
E_R = crate::R<u8, u8>; #[doc = "Reader of field `SENSITIVE_BACKUP_BUS_PMS_MONITOR_VIOLATE_STATUS_HTRANS`"] pub type SENSITIVE_BACKUP_BUS_PMS_MONITOR_VIOLATE_STATUS_HTRANS_R = crate::R<u8, u8>; #[doc = "Reader of field `SENSITIVE_BACKUP_BUS_PMS_MONITOR_VIOLATE_INTR`"] pub type SENSITIVE_BACKUP_BUS_PMS_MONITOR_VIOLATE_I...
Rust
0