text
string
label_name
string
labels
int64
l_user, to, msg.as_string()) mailServer.close() #creates a file containing a daily sum def dailySum(newData,fileName,extent): todayData = loadtxt(os.path.join(getCurrentDirectory(),'DailySums',timeStr[-15:-7]),'float',delimiter =',') summedData=todayData + newData if '-S233000-' in fileName: rotatedSum = np.rot9...
Python
1
ts.append([name, f'{t_forward/num_steps:.6f}s']) else: ts.append([name, f'{t_forward:.4f}s']) if backward: if per_step: ts[-1].append(f'{t_backward/num_steps:.6f}s') ts[-1].append(f'{(t_forward + t_backward)/num_steps:.6f}s') els...
Python
1
te::{web::auth::Authorization, ServerState}; pub async fn revoke(route: Route<ServerState>, auth: Authorization, code: SmolStr) -> Response { ().into_response() } <filename>src/lib.rs<gh_stars>1-10 #[derive(Debug)] pub struct Attribute { pub name: &'static str, pub value: AttributeValue, } #[derive(Debug)]...
Rust
0
= self.block1(out) out = self.block2(out) out = self.block3(out) out = self.relu(self.bn1(out)) out = F.avg_pool2d(out, 8) out = out.view(-1, self.num_channels) return self.fc(out) def wideresnet(conf): net_depth = int(conf.arch.replace('wideresnet', '')) datas...
Python
1
done for convenience purposes, so that we do not have to pass on the `VkLib` instance. Since there is a function for every vulkan command, this also includes commands, that are not supported on the system. In this case calling the function will panic even after instance/device creation. The same will happen if the vku...
Rust
0
e_tags(input: &str) -> IResult<&str, &str, ()> { let tail_space = input.len(); let maybe_tags = input.trim_end_matches(|c: char| c.is_ascii_whitespace()); let tail_space = tail_space - maybe_tags.len(); // I verified that org-element and org-mode don't respect Unicode whitespace // here. This inclu...
Rust
0
Valid, InvalidStringEscapes(Box<[StrSlice]>), InvalidNumber(StrSlice), IllegalChar(StrSlice), NotTokenized(StrSlice), } impl<I> ParseError<I> for NotFoundError { fn from_error_kind(_: I, _: nom::error::ErrorKind) -> Self { NotFoundError } fn append(_: I, _: nom::error::ErrorKin...
Rust
0
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
Python
1
usize, style_opt: Option<&StyleOpt>) { let mut s = cell.to_string(); if let Some(style_opt) = style_opt { s = stylize(cell, style_opt); } let col_width = self.max_widths.borrow()[col_idx]; let pad = GridPrinter::pad(col_width - cell.len() + self.col_spacing); ...
Rust
0
) -> &Self::Target { &self.0 } } impl From<crate::R<RTC_WEEKDAY_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<RTC_WEEKDAY_SPEC>) -> Self { R(reader) } } #[doc = "Register `RTC_WEEKDAY` writer"] pub struct W(crate::W<RTC_WEEKDAY_SPEC>); impl core::ops::Deref for W { type T...
Rust
0
production| BoxChartValue { max: production.max.to_f64().unwrap(), min: production.min.to_f64().unwrap(), p25: production.p25.to_f64().unwrap(), p50: production.p50.to_f64().unwrap(), p75: production.p75.to_f64().unwrap(), }), }) .collect::<Vec<_>>(), title: Some("quantiles...
Rust
0
) -> Tuple[Tensor, Tensor]: """ Returns (Y_train, Y_real) as [N,D] on device/dtype. For "mnist_pixels": Y_train is drawn from the MNIST training split, Y_real is drawn from the MNIST test split (both flattened to [N, 784]). """ device = device or torch.device("cuda" if torch.cuda.is_available(...
Python
1
if matchlen < nlen && ((*name.offset((matchlen) as isize)) as i32) == 32 { c_runtime::preInc(&mut matchlen); if (stbtt_CompareUTF8toUTF16_bigendian_internal( ((((name).offset((matchlen) as...
Rust
0
)) .select([col("values").sum()]) .collect()?; assert_eq!(df.column("values")?.get(0), AnyValue::Int32(130)); Ok(()) } //! Tests auto-converted from "sass-spec/spec/non_conformant/sass/mixins.hrx" use ash::{extensions::ext::DebugReport, version::EntryV1_0}; use ash::{vk, Entry, Instance}; use std::{ ...
Rust
0
x = (*{ let _old = s; s = s.offset(1isize); _old } as (i32) - b'A' as (i32)) as (u8); if x as (i32) <= b'Z' as (i32) - b'A' as (i32) { x = (x as (i32) + b'a' as (i32)) as (u8); } else { x = (x as (i32) + b'A' a...
Rust
0
# Rui Santos & Sara Santos - Random Nerd Tutorials # Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-micropython-ebook/ from machine import Pin, I2C from time import sleep import BME280 # Initialize I2C communication i2c = I2C(id=0, scl=Pin(5), sda=Pin(4), freq=10000) while True: ...
Python
1
flist.pyshell # handle remaining options: if debug: shell.open_debugger() if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): shell.interp.execfile(filename) if shell an...
Python
1
Error::GenericString(err.to_string()))?; Ok(ExtendedKey { private_key: PrivateKey(esk.secret_key()), public_key: PublicKey(esk.public_key()), public_key_compressed: PublicKeyCompressed(esk.public_key_compressed()), address: address.to_string(), }) } /// Get extended key from pr...
Rust
0
for s in (b"10", b"abcdef", b"AB1234", b"fed", b"123467890"): self.assertIs(True, http._ishexdigits(s)) def test_decodes(self): """ L{_hexint()} returns the integer equivalent of the input. """ self.assertEqual(10, http._hexint(b"a")) self.assertEqual(0x10, h...
Python
1
$span_info); #[cfg(feature = "trace")] let __ = span.enter(); } pub(crate) macro trace_error_span($span_info:expr) { #[cfg(feature = "trace")] let span = ::tracing::span!(::tracing::Level::ERROR, $span_info); #[cfg(feature = "trace")] let __ = span.enter(); } pub(crate) macro trace_expr (...
Rust
0
me): if name in read_env_flags: read_env_flags.remove(name) sysstr = platform.system() if 'Darwin' in sysstr: remove_flag_if_exists('use_pinned_memory') if core.is_compiled_with_ipu(): # Currently we request all ipu available for training and testing # finer c...
Python
1
ilities)) .set_image_array_layers(1) .set_present_mode(surface_props.present_mode) .set_clipped(true) .set_image_color_space(VkColorSpaceKHR::SRGB_NONLINEAR_KHR) .set_image_usage(VkImageUsageFlagBits::COLOR_ATTACHMENT_BIT); // TODO: non exclusive / queue family indices let swapchain = vkCreateSw...
Rust
0
&dtor_self_type, self_type_did)); ensure_drop_predicates_are_implied_by_item_defn(tcx, drop_impl_did, ...
Rust
0
cias de los siguientes resúmenes:\n{summaries}") analysis = trend_response.content # Mostrar resultados - si en caso quieres usar esto más adelante, ¡puedes descomentar las siguientes 2 líneas para obtener los resúmenes también! # st.subheader("Resúmenes de Noticias") ...
Python
1
_types[i - 1]).count() == 0; } } can_bow_list } /// Returns char_length of same category type from given offset fn get_char_category_continuous_length( char_category_types: &Vec<CategoryTypes>, c_offset: usize, ) -> usize { let mut continuous_cat = c...
Rust
0
import numpy as np import time def GenSignal(power, freq, period, fs): omega = freq / fs * (2*np.pi) num_sample = period * fs sample = np.arange(num_sample).reshape(-1, 1) phase = np.dot(sample, omega.reshape(1, -1)) phase_initial = np.random.randn(1, len(omega)) phase_initial = np.tile(phase_...
Python
1
"""add processed fuel raster table Revision ID: a1553ead7fde Revises: 128156e36f67 Create Date: 2025-05-26 15:42:34.221962 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from wps_shared.db.models.common import TZTimeStamp # revision identifiers, used by Alembic. revisi...
Python
1
rator[str]: ... @overload def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ... def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]: if not dirname: if isinstance(dirname, bytes): dirname = os.curdir.encode('ASCII') else: dirname = os.curdir try: n...
Python
1
inbound_map.remove(&in_key); } { let mut outbound_map = self.outbound_map.lock().await; outbound_map.remove(&out_key); } } let inbound_map = self.inbound_map.lock().await; if let Some(m) = inbound_map.get(i_key) { ...
Rust
0
For information about available fields see [rdlr](rdlr) module"] pub type RDLR = crate::Reg<u32, _RDLR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RDLR; #[doc = "`read()` method returns [rdlr::R](rdlr::R) reader structure"] impl crate::Readable for RDLR {} #[doc = "CAN_RDL0R"] pub mod rdlr; #[doc = "CAN_RDH0R\n...
Rust
0
import pygame import sys from config import * from .Collisions import * from .PoolTable import draw_background from .Player import * def player_turn_switch(turn): """ Chuyển đổi lượt chơi giữa hai người chơi. Tham số: - turn: Đối tượng của người chơi hiện tại. Trả về: Đối tượng của người chơi ...
Python
1
e: {file_info['path']}") except Exception as e: logger.error(f"Failed to delete {file_info['path']}: {e}") return { "total_files_checked": len(matching_files), "old_files_found": len(old_files), "deleted_count": deleted_count, ...
Python
1
r i in range(1, len(path)): # print(path[i-1][2], path[i][2]) assert np.abs(path[i-1][2] - path[i][2]) <= np.pi one_object_metric = imacs.SO2DistanceSq(G, 3, 2) print("Baseline path length:", Metric.path_length(path)) times = [t_scaling * np.sqrt(np.max([one_object_metric(path[i-1][j-2:j+1], path[i][j-2:j+1])[...
Python
1
'b; fn try_nonblocking_guarded_mut_borrow_mut( &mut self, ) -> Result<Self::MutGuardMut<'_>, Self::MutBorrowMutError<'_>> { Ok(self) } } impl<T: ?Sized> NonBlockingGuardedBorrow<T> for RefCell<T> { type Guard<'a> = Ref<'a, T> where T: 'a,; type BorrowError<'a> = BorrowError...
Rust
0
`Array` must be built with an `ArrayBuilder`. The array trait provides several /// unified interface on an array, like `len`, `get` and `iter`. /// /// The `Builder` associated type is the builder for this array. /// The `Item` is the item you could retrieve from this array. /// /// For example, `PrimitiveArray` could...
Rust
0
ard(board) if turn == AI and not game_over: col, minimax_score = minimax(board, difficulty, -math.inf, math.inf, True) if is_valid_location(board, col): row = get_next_open_row(board, col) drop_piece(board, row, col, AI_PIECE) if winning_move(board, AI_PIECE): ...
Python
1
edTerm::HeapBinary(bin_ptr) => bin_ptr.as_ref().try_into(), TypedTerm::SubBinary(bin_ptr) => bin_ptr.as_ref().try_into(), TypedTerm::ProcBin(bin_ptr) => bin_ptr.as_ref().try_into(), TypedTerm::MatchContext(bin_ptr) => bin_ptr.as_ref().try_into(), _ => Err(TypeError.into()...
Rust
0
assert_eq!(iter.next().expect("next"), 'b'); assert_eq!(iter.next().expect("next"), 'c'); assert_eq!(iter.next().expect("next"), 'd'); assert_eq!(iter.next().expect("next"), 'e'); assert!(iter.next().is_none()); let mut iter = ::iter_short("-a").expect("Iter"); assert_e...
Rust
0
""" Text processing utilities for API interactions. """ import re def sanitize_api_queries(text: str, max_length: int = 200) -> str: """ Clean text for API queries by removing problematic characters and formatting. Args: text: The text to clean max_length: Maximum allowed length (default...
Python
1
append({"role": "user", "parts": [PROMPTS["source_identification"]]}) response = self.gemini.get_answer( messages=messages, stream=False, model=model, temperature=0 ) self.last_usages = response["usages"] try: extracted_sourc...
Python
1
/")? .join("v4/")? .join("merge_requests?scope=all")?; self.client .get(url) .send() .await? .error_for_status()? .json() .await? }: Result<_>) .map_err(|err| ...
Rust
0
ory* sm.st .opcodes .extend_from_slice(&[Opcode::PUSHLP, Opcode::INCLP, Opcode::RET]); // Execute the instructions sm.execute(0, GasLimit::Limited(100)).unwrap(); assert_eq!(sm.st.number_stack, vec![321]); assert_eq!(sm.st.loop_stack, vec![(1, 39483)]); } #[test] fn test_execute_a...
Rust
0
)) } } fn type_attr(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_dom_html_param_element_get_type_attr( self.as_ref().to_glib_none().0, )) } } fn value(&self) -> Option<glib::GString> { unsafe { ...
Rust
0
used_imports)] use witx_bindgen_rust; }; let mut content = input.content.unwrap(); content.1.extend(exports); content.1.push(use_witx_bindgen_rust); input.content = Some(content); // Need to allow dead_code since the generated code doesn't always directly // read the fields of user...
Rust
0
_single_clause() { let rng = XorShiftRng::from_seed([0xde, 0xad, 0xbe, 0xef]); let (facts, program, samples) = program::<MaxFloat64>(r#" types(0) :- a(0), b(0) sample b(1) output a(1). "#) .unwrap() .0; let m...
Rust
0
1, true), (p42, true), (p43, false), ]; for &mut (ref mut p, _) in pts.iter_mut() { p.x.0 += offset_x.0; p.y.0 += offset_y.0; } pts } /// Calculates and returns the points for a rectangle, given a horizontal and vertical scale, /// and an offset into the page from the lower left corne...
Rust
0
ing.Optional[network.ErrorReason] #: Response code if intercepted at response stage. response_status_code: typing.Optional[int] #: Response headers if intercepted at the response stage. response_headers: typing.Optional[typing.List[HeaderEntry]] #: If the intercepted request had a corresponding Netw...
Python
1
_a_grid( grid_size, self.interp_shape, device=video_chunk.device ) queries = torch.cat( [torch.ones_like(grid_pts[:, :, :1]) * grid_query_frame, grid_pts], dim=2, ) if add_support_grid: ...
Python
1
ve to wait // for the request to have it complete, we will just not read the response. let response_btc = pending_btc.try_wait(deadline).map_err(|_| http::Error::DeadlineReached)??; let response_eth = pending_eth.try_wait(deadline).map_err(|_| http::Error::DeadlineReached)??; let response_dot = pending_dot.try_...
Rust
0
ri); let inner = Factory::create(uri.clone())?; let exec = Quoter { name: name.clone(), uri, inner, }; QUOTERS.insert(name, exec.clone()); Ok(exec) } pub fn get(name: &str) -> Option<Quoter> { if let Some(exec) = QUOTERS.get(name) { return Some(exec.value().clon...
Rust
0
label="Click an example to ask (will automatically clear chat and continue)" ) # --- Event Listeners and Bindings --- # Show/hide corresponding setting groups when switching model source def toggle_model_source_ui(source): return { local_model_group: gr.update(visib...
Python
1
'unconcern', 'ambiguous-agitation': 'agitation', 'ambiguous-fear': 'fear', 'ambiguous-expectation': 'expectation'}.get(categ, categ).title()) def clean_term(t): return(re.sub("\(.*\)$", "", t.lower())) f = open('wnaffect.tsv', 'w') rows = set() print('term', 'pos', 'category', 'emotion',...
Python
1
low.my_model"]), fqn=["snowplow", "my_model", "test_my_model_null_handling"], config=UnitTestConfig(), schema="test_schema", ) expected.build_unit_test_checksum() assertEqualNodes(unit_test, expected) def test_expected_promote_non_none_row_dct(self): ...
Python
1
orderbook.price_data.get(&price).expect("order at this price doesn't exist"); let order = price_data.orders.get(&order_id).expect("order with this id doesn't exist or is already canceled"); assert!(env::predecessor_account_id() == order.creator, "not this user's order"); /* Cancel the order, this returns how muc...
Rust
0
message")) class Template(tornado.web.RequestHandler): def get(self): items = ["Item 1", "Item 2", "Item 3"] self.render("template.html", title="My title", items=items) class urlhttp(tornado.web.RequestHandler): @tornado.web.asynchronous ...
Python
1
import httpx from ..schemas import CRED from ..exception import RequestException app_code = "4ca99fa6b56cc2ba" class SklandLoginAPI: _headers = { "User-Agent": ("Skland/1.32.1 (com.hypergryph.skland; build:103201004; Android 33; ) Okhttp/4.11.0"), "Accept-Encoding": "gzip", "Connection":...
Python
1
{self, StreamExt}, }; use libecc::{types::*, *}; use tokio::task::spawn_blocking; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #[derive(Debug, Clone)] pub struct BitGD<C> where C: Code + BitUnitCode + Clone, { pub code: C, pub basis_di...
Rust
0
n_correct) > 0 else 0.0, 'response_length/mean_when_wrong': np.mean(response_length_when_wrong) if len(response_length_when_wrong) > 0 else 0.0, } response_zero_adv_count_by_data_source = defaultdict(int) for prompt_str, count in response_non_zero_diff_count_by_prompt_str.items(): ...
Python
1
); let (info, mut reader) = decoder.read_info().unwrap(); let mut buf = vec![0; info.buffer_size()]; // Read the next frame. Currently this function should only called once. reader.next_frame(&mut buf).unwrap(); Image::from_buffer(info.widt...
Rust
0
"""Speech detection using TEN VAD model.""" import numpy as np from ten_vad import TenVad class SpeechDetector: """Wraps TEN VAD mode with a chunk size of 512 samples.""" CHUNK_SIZES = {16000: 512} def __init__(self, rate: int = 16000): if rate not in self.CHUNK_SIZES.keys(): raise V...
Python
1
from panda3d.core import * from direct.showbase.PythonUtil import Functor from toontown.toonbase import ToontownGlobals from direct.directnotify import DirectNotifyGlobal class FactoryCameraViews: notify = DirectNotifyGlobal.directNotify.newCategory('FactoryCameraViews') def __init__(self, factory): s...
Python
1
dth in bytes/sec") parser.add_argument('-m', "--num_machines_in_first_level", type=int, default=None, help="Number of machines in first level") parser.add_argument('-s', "--memory_size", type=float, default=16000000000, help="Amount of memory available on each mac...
Python
1
import unittest import uuid from titus_isolate.crd.model.resource_usage_prediction import ResourceUsagePredictions test_task_id = str(uuid.uuid4()) test_job_id = str(uuid.uuid4()) test_raw_prediction = { 'model_version': '0.2', 'model_instance_id': '523d600d-c83b-4e53-9a63-97e6257b8c89', 'prediction_ts_ms...
Python
1
raise RemoteError('413 content too large') # Succeed for subsequent chunks return original_query(*args, **kwargs) with ( patch('rotkehlchen.externalapis.defillama.DEFILLAMA_CHUNK_SIZE', 2), patch.object(session_defillama, '_query', side_effect=mock_query), ): # T...
Python
1
""" Parts of the U-Net model """ import torch import torch.nn as nn import torch.nn.functional as F import functools class Down(nn.Module): """Upscaling then double conv""" def __init__(self, outer_nc, inner_nc, input_nc=None, innermost=False, outermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): ...
Python
1
const."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `WebGl2RenderingContext`*"] pub const COPY_WRITE_BUFFER: u32 = 36663u64 as u32; #[doc = "The `WebGL2RenderingContext.COPY_READ_BUFFER_BINDING` const."] #[doc = ""] #[doc = "*This API requires the foll...
Rust
0
int(AT_FDCWD), c_str(oldname), c_int(AT_FDCWD), c_str(newname), c_uint(0), )) } } #[inline] pub(crate) fn linkat( old_dirfd: BorrowedFd<'_>, oldname: &ZStr, new_dirfd: BorrowedFd<'_>, newname: &ZStr, flags: AtFlags, ) -> io::Result<()> { ...
Rust
0
if token["name"]: if token["publicId"]: output.append("""%s<!DOCTYPE %s "%s" "%s">""" % (" " * indent, token["name"], token["publicId"], toke...
Python
1
pub fn deserialize<R: Read>(r: &mut R) -> Result<ClientboundPacket> { Ok(ClientboundPacket::LoginDisconnect(LoginDisconnect { raw_chat: read_String(r).chain_err(|| "while reading field raw_chat")?, })) } /// Serializes the packet into Vec<u8>. You usually won't need to use this....
Rust
0
ttr}'), end=' ') def get_lump_data(self, reader_func, lump_index, num_bytes, header_length=0): lump_info = self.reader.directory[lump_index] count = lump_info['lump_size'] // num_bytes data = [] for i in range(count): offset = lump_info['lump_offset'] + i * num_bytes + h...
Python
1
lgorithms.remove("extra") if legend_map is not None: legend_map = {algo.upper(): value for algo, value in legend_map.items()} if run_times is not None: run_times = {algo.upper(): value for algo, value in run_times.items()} xlabel = "Time (Minutes)" fig = plot_single_task_curve( ...
Python
1
let label = match label_opt { Some(it) => it, None => { error_continue_out_of_loop(PLoc::from_loc(loc), self.logger); return new_error_term(loc).0; } }; self.nodes.push(new_jump_node( label, vec![KTerm::Unit { l...
Rust
0
Config::default()) } /// Prints the result if successful as `[out#]` or the failure message if any. /// Uses the given formatting configuration for the `Kserd` data. /// The return is (<repl in read state>, <maybe <stmt index, data>>) pub fn print_with_formatting( self, conf...
Rust
0
self.shell_window.present() return self.shell_window = gtk.Window() self.shell_window.set_size_request(750,550) self.shell_window.set_resizable(True) scrolled_window = gtk.ScrolledWindow() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMA...
Python
1
ecArena = Arena<StrDec>; #[derive(Debug)] pub enum StrDec { Dec(DecIdx), Structure(Vec<StrBind>), Local(StrDecIdx, StrDecIdx), Seq(Vec<StrDecIdx>), } #[derive(Debug)] pub struct StrBind { pub name: Name, pub str_exp: StrExpIdx, } pub type StrExpIdx = OptIdx<StrExp>; pub type StrExpArena = Arena<StrExp>; ...
Rust
0
es::CompletionResponse; use tower_lsp::lsp_types::CompletionTextEdit; use tower_lsp::lsp_types::CompletionTriggerKind; use tower_lsp::lsp_types::DidChangeTextDocumentParams; use tower_lsp::lsp_types::DidCloseTextDocumentParams; use tower_lsp::lsp_types::DidOpenTextDocumentParams; use tower_lsp::lsp_types::InitializePar...
Rust
0
.sample_with_fixed_number(class_name, sample_group) sampled_boxes = np.stack([x['box3d_lidar'] for x in sampled_dict], axis=0).astype(np.float32) if self.sampler_cfg.get('DATABASE_WITH_FAKELIDAR', False): sampled_boxes = box_utils.boxes3d_kitti_fakelidar_to_lidar(sa...
Python
1
// # Examples /// /// Basic usage: /// /// ``` /// use jobsteal::make_pool; /// /// let mut pool = make_pool(2).unwrap(); /// /// // get a handle to the pool's spawner. /// let spawner = pool.spawner(); /// /// // execute a job which can spawn other jobs. /// spawner....
Rust
0
ap(|line| Ok(line?.parse()?))) { match res { Ok(value) => { if value != Value::Unspecified { println!("{}", value); } } Err(e) => println!("; error: {}", e), } } } else { ...
Rust
0
import boto3 import json s3 = boto3.client("s3") BUCKET_NAME = "audiobook-data-dhivya" # ✅ your bucket def extract_metadata_from_s3_object(key): response = s3.get_object(Bucket=BUCKET_NAME, Key=key) content = response["Body"].read().decode("utf-8") lines = content.strip().split("\n") title = lin...
Python
1
n pub fn srl_reg(reg: &mut u8, flags: &mut u8) { *flags &= 0b10010000; if *reg & 0b00000001 == 1 { *flags |= 0b00010000; } else { *flags &= 0b11101111; } *reg = *reg >> 1; if *reg == 0 { *flags |= 0b10000000; } else { *flags &= 0b01111111; } } pub fn sr...
Rust
0
if size == 0: print pos else: position = list() count = size // 20280 inc = 0 while inc < count: position.append(str(inc * 20280 + pos)) inc += 1 mod = size % 20280 if pos + len(offset) <= mod: position.append(str(inc * 20280 + pos)) print os.linesep.join(position) excep...
Python
1
import datetime from typing import Any, cast, Optional import iso8601 from graphql.language.ast import StringValue, Value from graphql import GraphQLScalarType def typed_parse_date(value: Any) -> datetime.datetime: return cast(datetime.datetime, iso8601.parse_date(value)) def serialize_date(value: datetime.dat...
Python
1
crate smallvec; extern crate string_interner; mod builder; mod helpers; pub mod pattern; mod range; pub mod rule; mod stash; pub use builder::RuleSetBuilder; pub use helpers::BoundariesChecker; use pattern::Pattern; use pattern::TerminalPattern; pub use range::Range; use rule::Rule; use rule::TerminalRule; pub use r...
Rust
0
) with pytest.raises(Exception) as index_error: pc_fusion_wrappers.add_cloud_filtering_msk( [ds0, ds1], elt_remove, "mask", 255 ) assert ( str(index_error.value) == "Index indicated in the elt_pos_infos " "pandas. DataFrame is not coherent " "with the clou...
Python
1
) -> &str { &self.full_path } /// Returns the immediate parent of this realm. async fn parent(&self, context: &Context) -> FieldResult<Option<Realm>> { match self.parent_key { Some(parent_key) => Realm::load_by_key(parent_key, context).await, None => Ok(None) ...
Rust
0
b, producing 2 intermediate signed 32-bit results. Sum these 2 results with the corresponding 32-bit integer in src using signed saturation, and store the packed 32-bit results in dst. /// /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm512_dpwssds_epi32&expand=2228) #...
Rust
0
erwrite::<Self>(clear_lsb(fv.0.ptr_value())) }; let res = x.1.freeze(freezer)?; r.fill(simple(res)); Ok(fv) } fn heap_copy(&self, me: &AValuePtr, tracer: &Tracer<'v>) -> Value<'v> { let (v, r) = tracer.reserve::<Self>(); let mut x = unsafe { me.overwrite::<Self>(clear_ls...
Rust
0
est_pair[0] + best_pair[1] merges[best_pair] = merged_token vocab.append(merged_token) logger.info(f"Merged {best_pair} -> {merged_token} (freq: {max_freq})") logger.info(f"Training complete! Final vocabulary size: {len(vocab)}") return tokenizer, merges, vocab def tokenize_text( ...
Python
1
if matrix.get(x1).and_then(|row| row.get(y1)).is_none() { continue; } let next = State { cost: cost + matrix[x1][y1] as usize, crd: (x1, y1), }; if next.cost < dist[x1][y1] { q.push(next); ...
Rust
0
 :Xc@`sddlmZmZmZddlZddlmZddlmZm Z dj e Z ej de Z d ej fd YZ d ZdS( i(tabsolute_importtdivisiontunicode_literalsNi(tbasei(trcdataElementstspaceCharactersuu[...
Python
1
ctx: NSIContext_t, from: NSIHandle_t, from_attr: *const ::std::os::raw::c_char, to: NSIHandle_t, to_attr: *const ::std::os::raw::c_char, ) { unsafe { NSIDisconnect(ctx, from, from_attr, to, to_attr) }; } #[inline] fn NSIEvaluate( &self, ctx: NSI...
Rust
0
from .printer import BluetoothTransport, PrinterClient, SerialTransport
Python
1
err)); ptr::null() } } } #[no_mangle] #[cfg(feature = "c_api")] pub unsafe extern "C" fn ddlog_run( workers: ::std::os::raw::c_uint, do_store: bool, print_err: Option<extern "C" fn(msg: *const ::std::os::raw::c_char)>, init_state: *mut *mut ::differential_datalog::DeltaMap<DDVa...
Rust
0
_name); if !dst_path.parent().unwrap().exists() { std::fs::create_dir_all(dst_path.parent().unwrap())?; } if file.is_dir() { if !dst_path.exists() { std::fs::create_dir_all(dst_path)?; } } else { if dst_path.exists() { ...
Rust
0
Identifier(_, _) => ASN1Class::Universal, &ASN1Block::UTF8String(_, _) => ASN1Class::Universal, &ASN1Block::PrintableString(_, _) => ASN1Class::Universal, &ASN1Block::TeletexString(_, _) => ASN1Class::Universal, &ASN1Block::IA5String(_, _) => ASN1Class::Universal, ...
Rust
0
import sys import os from utils import read_parameters, create_folder, SetBoundaries, create_job_script import numpy as np import pickle try: param_path = sys.argv[1] except FileNotFoundError: print("Parameter file is not found or specified.") sys.exit() Param = read_parameters(param_path) folder_name = c...
Python
1
ter") .unwrap() } } fn set_property_proposals_batch_size(&self, proposals_batch_size: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"proposals-batch-size\0".as_ptr() as *const ...
Rust
0
type Item = F; type Iter = InitIter<F, S::Iter>; fn stream(&self) -> Self::Iter { let iterator = self.stream.stream(); let x = self.x; let y = self.y; // let x2 = self.x.square(); // let index = F::from(self.stream.len() as u64); Self::Iter { x, ...
Rust
0
= " The current state of the ECN controller for the path"] pub enum EcnState { #[non_exhaustive] #[doc = " ECN capability is being actively tested"] Testing {}, #[non_exhaustive] #[doc = " ECN capability has been tested, but not validated yet"] Unknown {}, #[...
Rust
0