text
string
label_name
string
labels
int64
live_delta = Some(delta); } } if let Some(live_delta) = live_delta { let delta = live_delta.total_seconds() as f32; if delta > draw_info.max_delta { draw_info.max_delta = delta; } else if delta < draw_info.min_delta { draw_info.min_delta = delta; ...
Rust
0
头 ''' result = b'' cls = self.__class__ while cls != StructHeaderBase: if cls.__header__ != cls.__base__.__header__: values = tuple(self.get_values(cls)) try: result = struct.pack(cls.header_format, *values) + result ...
Python
1
'a> { fn activated_by(&mut self, (root_pkg_name, feature): RootFeature<'a>) { if let Optionality::Optional { activated_by_features, } = self { activated_by_features.insert((root_pkg_name, feature)); } } fn to_expr(&self, root_features_var: &str) -> Bo...
Rust
0
oves //! //! For the generation type, moves can either be generated to be Legal, Or Pseudo-Legal. A Legal //! move is, for as the name implies, a legal move for the current side to play for a given position. //! A Pseudo-Legal move is a move that is "likely" to be legal for the current position, but cannot //! be guara...
Rust
0
e_loss(logits, label, ignore_mask) return avg_loss def multi_bce_loss(logits, label, ignore_mask=None): if isinstance(logits, tuple): avg_loss = 0 for i, logit in enumerate(logits): logit_label = fluid.layers.resize_nearest(label, logit.shape[2:]) logit_mask = (logit_lab...
Python
1
import argparse import requests import io import os import pandas as pd from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta # Import the datetime module BASE_PORTAL_API_SEARCH_URL = 'https://www.ebi.ac.uk/ena/portal/api/search' #FIELDS = ['run_accession', 'sample_accession', 'in...
Python
1
0u8, 0, 0, 0, 0, 0, 0]), value: TestValue(*b"valueA"), }, Trie::Leaf { key: TestKey([1u8, 0, 0, 0, 0, 0, 0]), value: TestValue(*b"valueB"), }, Trie::Leaf { key: TestKey([2u8, 0, 0, 0, 0, 0, 0]), value: TestValue(*b"valueC"), }, Trie::Leaf { key: Te...
Rust
0
from pylayers.antprop.antenna import * from pylayers.antprop.antvsh import * import matplotlib.pylab as plt from numpy import * import pdb """ This test : 1 : loads a measured antenna 2 : applies an electrical delay obtained from data with getdelay method 3 : evaluate the antenna vsh coefficient with a dow...
Python
1
unkedArray<CategoricalType> { self.cast::<UInt32Type>().unwrap().reverse().cast().unwrap() } } macro_rules! impl_reverse { ($arrow_type:ident, $ca_type:ident) => { impl ChunkReverse<$arrow_type> for $ca_type { fn reverse(&self) -> Self { self.into_iter().rev().collec...
Rust
0
from django.urls import path, include from rest_framework import routers from challenges.apps import ChallengesConfig from challenges.views import (ChallengeViewSet, ChallengeInProgressListAPIView, FinishedChallengeListAPIView,) app_name = ChallengesConfig.n...
Python
1
noise_down, size=(noise.shape[-2], noise.shape[-1]), mode="bilinear", align_corners=True, antialias=True ) high_freqs = noise - noise_up noisy_latent = rearrange(noisy_latent, "b c f h w -> (b f) c h w") noisy_latent_down = F.interpolate( noisy_latent, size=(new_h, new_w), mode="bilinear", ali...
Python
1
ObjType, ) -> Result<ExId, AutomergeError>; /// Insert a value into a list at the given index. fn insert<O: AsRef<ExId>, V: Into<ScalarValue>>( &mut self, obj: O, index: usize, value: V, ) -> Result<(), AutomergeError>; /// Insert an object into a list at the given...
Rust
0
{ "placeholder": "AWS Console Sign-In", "key": "redirect_uri", "type": "button", "icon": "sign-in", "content": "Sign-In", "onClick": {"action": "redirect"}, ...
Python
1
::Err(FieldError::from(err)), } } } /// Assumes that the given condition is true. /// /// This macro allows the expression of invariants in code. For example, one might `assume!` that /// an index is in bounds prior to indexing into a slice - this would allow the optimizer to remove /// the bounds checking ...
Rust
0
qk_scale, attn_drop=attn_drop, drop=drop, in_rpe_dim=in_rpe_dim, k_rpe=k_rpe, q_rpe=q_rpe, v_rpe=v_rpe, heads_share_rpe=heads_share_rpe) # Queries will be built from input parent feature self.q = nn.Linear(q_in_dim, qk_...
Python
1
import os import time class Config(object): # Get a bot token from botfather TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "") # Get from my.telegram.org (or @UseTGXBot) API_ID = int(os.environ.get("API_ID", 12345)) # Get from my.telegram.org (or @UseTGXBot) API_HASH = os.environ.get("API_...
Python
1
if bytes.len() != 4 { return None; } Some(i32::from_be_bytes(bytes[0..4].try_into().unwrap())) }) } } impl AsRef<FitnessInner> for Fitness { fn as_ref(&self) -> &FitnessInner { &self.0 } } impl Ord for Fitness { fn cmp(&self, other: &Self) -> Ord...
Rust
0
lf.optim, self.sched # ) start_epoch, sd = resume_from_checkpoint( path, self.model.tuner, self.optim, self.sched ) return start_epoch, sd def load_model(self, directory, epoch=None): if not directory: print("Note that load_model() is skipped as no ...
Python
1
import pytest import pandas as pd import pandas._testing as tm class TestDatetimeIndexFillNA: @pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"]) def test_fillna_datetime64(self, tz): # GH 11343 idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"]) exp = p...
Python
1
track!(self.channel.as_mut().expect("never fails").poll_send()) { self.channel = Err(e); } break; } Ok(Async::NotReady) } } <filename>src/test/ui/parser/shebang/shebang-and-attrib.rs<gh_stars>1000+ #!/usr/bin/env run-cargo-script // check-pass #![allow(unused...
Rust
0
ariant of [`xcb_input_touch_mode_t`]. pub const XCB_INPUT_TOUCH_MODE_DEPENDENT: xcb_input_touch_mode_t = 2; /// The `Input::ButtonClass` struct. /// /// The following fields can be accessed via accessor functions: /// /// - `state` /// - `labels` #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_input_button_cla...
Rust
0
"Elzrttrnr" => "ɻ", "Elzrvbull" => "◘", "Elzsqspne" => "⋥", "Elztrnmlr" => "ɰ", "Elzvrecto" => "▯", "Leftarrow" => "⇐", "accurrent" => "⏦", "angleubar" => "⦤", "approxeqq" => "⩰", "backprime" => "‵", "backsimeq" => "⋍", "ba...
Rust
0
: Typ::from_ast(typ) }; Expr::App { fun: Box::new(cont.clone()), arg: Box::new(con) } }, // TODO change this _ => Expr::App { fun: Box::new(Value::Var {id: "TODO".to_string(), typ: Typ::Bool }), arg: Box::new(Value::Var {id: "TODO".to_string(), typ: Typ::Bool }) } // Axpr::Lambda { args, body, typ } => ...
Rust
0
byte_index: r.start, offset: l as isize + 2 - str[6..].parse::<isize>().unwrap(), filename: None } } }) .collect::<Vec<_>>(); let mut current = 0..0; let mut fi...
Rust
0
Type { fn default() -> Self { IfType::IF_API_TYPE_HARDWARE } } #[derive(Debug, Clone, Serialize_repr, Deserialize_repr)] #[repr(u8)] pub enum Direction { RX=0, TX=1, } impl Default for Direction { fn default() -> Self { Direction::RX } } pub type InterfaceIndex=u32; //! Parent module for all STM32F2 devic...
Rust
0
ey).unwrap()) } pub fn pw(l: i32, matches: &ArgMatches) -> BoxResult<String> { let numbers = matches.value_of("numbers"); let symbols = matches.value_of("symbols"); let n: i32 = match numbers { Some(v) => match v.parse() { Ok(v) => v, _ => return Err(Box::try_from("Number q...
Rust
0
Vector { _handler: USB_UBM }, Vector { _handler: TIMER0_A1, }, Vector { _handler: TIMER0_A0, }, Vector { _handler: ADC12 }, Vector { _handler: USCI_B0 }, Vector { _handler: USCI_A0 }, Vector { _handler: WDT }, Vector { _handler: TIMER0_B1, }, Vect...
Rust
0
ds the start_marker in heading elements only and the end_marker at the beginning of a paragraph element. """ # keep everything until "part B" if state.step == "before": if isinstance(elem, Header) and start_marker in str(elem): state.step = "deleting" # delete everything until pa...
Python
1
); } else { // Player 2 wins. player2.push_back(card2); player2.push_back(card1); } let mut hasher = DefaultHasher::new(); player1.hash(&mut hasher); player2.hash(&mut hasher); let hash = hasher.finish(); // Player 1 wins (we'...
Rust
0
"""Concerns figure 4 of [todter2015a][].""" import numpy as np import dapper.mods as modelling import dapper.tools.randvars as RVs from dapper.mods.Lorenz96 import step from dapper.tools.localization import nd_Id_localization t = modelling.Chronology(0.05, dko=2, T=4**5, BurnIn=20) Nx = 80 Dyn = { "M": Nx, ...
Python
1
{ ($json:expr, $item_name:expr) => {{ let items: &Vec<json::Json> = pick_item!($json, $item_name, as_array, "Array"); items .iter() .map(|j| { let result: Result<String, DecoderError> = j .as_string() .ok_or(DecoderError...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from collections import defaultdict class ContractHistory(models.Model): _inherit = 'hr.contract.history' time_credit = fields.Boolean('Credit time', readonly=True, help='T...
Python
1
"enable_time", feature = "enable_profiler"))] pub fn milliseconds(value: std::time::Duration) -> f64 { (value.as_secs() * 1000) as f64 + value.subsec_nanos() as f64 / 1_000_000.0 } // Copyright 2015-2021 Swim Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file ex...
Rust
0
D, 1) for mib in mibs: Items.UseItem(mib) Misc.Pause(250) scrolls = Items.FindAllByID(SCROLL_ITEM_ID, -1, SOURCE_CONTAINER_ID, 1) for scroll in scrolls: for prop in scroll.Properties: match = re.match(r"(.*){1}\:\s\((\d+){1}, (\d+){1}\)", prop.ToString()) if match is not None: f...
Python
1
import os import logging from binance_sdk_derivatives_trading_usds_futures.derivatives_trading_usds_futures import ( DerivativesTradingUsdsFutures, ConfigurationRestAPI, DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL, ) # Configure logging logging.basicConfig(level=logging.INFO) # Create configurati...
Python
1
-> (Vec<String>, Vec<RefCell<Cart>>) { let f = File::open(filename).expect("input file not found"); let f = BufReader::new(f); let lines:Vec<String> = f.lines().map(|l| l.expect("Failed to parse line!")).collect(); let carts = get_carts_from_grid(&lines); (lines, carts) } fn get_carts_from_grid...
Rust
0
account for the // margin, and then go up to account for the floor height. let mut current_origin = Point::new( (surf_width / 2 - self.width / 2) as i32, surf_height as i32 - self.height as i32 - floor_height as i32, ); for floor in isomap.0.axis_iter(Axis(2)) ...
Rust
0
} } } pub struct QueryOutput { pub rows: Vec<MySqlRow>, } pub struct DCliColumn<'a> { pub col: &'a MySqlColumn, pub val_ref: MySqlValueRef<'a>, } pub struct QueryOutputMapSer<'a>(pub &'a QueryOutput); struct DcliRowMapSer<'a>(&'a MySqlRow); struct QueryOutputListSer<'a>(&'a QueryOutput); struct DcliR...
Rust
0
(datamodel) } fn migration_persistence<'a>(&'a self) -> Box<dyn MigrationPersistence + 'a> { Box::new(SqlMigrationPersistence { connector: self }) } fn database_migration_inferrer<'a>(&'a self) -> Box<dyn DatabaseMigrationInferrer<SqlMigration> + 'a> { Box::new(SqlDatabaseMigrationInfe...
Rust
0
runtime::get_blocktime() != BlockTime::new(0) { runtime::revert(Error::GetBlockTime); } if runtime::get_caller() != source_account { runtime::revert(Error::GetCaller); } } #[no_mangle] pub extern "C" fn calls_do_nothing_level1() { let contract_package_hash = runtime::get_key(HASH_KEY_...
Rust
0
_TYPE_INT24 => { if unsigned { Ok(Int(try!(self.read_le_u32()) as i64)) } else { Ok(Int(try!(self.read_le_i32()) as i64)) } }, ColumnType::MYSQL_TYPE_LONGLONG => { if unsigned { ...
Rust
0
"""Model for simulation of an SPDC Lens. This module defines the SPDCLens class for creation of entangled photons. """ from copy import deepcopy from ..kernel.entity import Entity class SPDCLens(Entity): """Lens to create entangled photons (via SPDC). Attributes: name (str): label for SPDCLens ins...
Python
1
else: samples_to_lose = 0 command2 = [sox_cmd, "-D", "-R", of1, of2, "speed", str(speed)] subprocess.call(command1) subprocess.call(command2) command_concat.append(of2) command_concat.append(out_wav) ...
Python
1
Default for ScriptWorld { fn default() -> Self { Self::new() } } pub const NONE_SCRIPT_WORLD: Option<&ScriptWorld> = None; pub trait ScriptWorldExt: 'static { #[cfg(any(feature = "v2_22", feature = "dox"))] fn get_name(&self) -> Option<GString>; #[cfg(any(feature = "v2_2", feature = "dox...
Rust
0
modulo q.) // * For ECDSA ... // // If r turns out to be zero, a new k should be selected and r // computed again (this is an utterly improbable occurrence). let r = self.params.g.modpow(&k, &self.params.p) % &self.params.q; if r.is_z...
Rust
0
// The clone here is sound as AnyUserData just holds a reference let all_args = (tmp_as_userdata.clone(), args); let call_res = method.call(all_args)?; // the function call might have mutated the `this` value... ...
Rust
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re, sys, os # absolute_path = os.path.dirname(os.path.abspath(__file__)) try: sys.path.append(absolute_path) from modules.common.gxPinYing import pypinyin, pinyin except: from modules.common.gxPinYing import pypinyin, pinyin if os.path....
Python
1
); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WAR...
Rust
0
static"); cmd.arg("--enable-fast-install"); cmd.arg("--with-included-gettext"); cmd.arg("--with-included-glib"); cmd.arg("--with-included-libcroco"); cmd.arg("--with-included-libunistring"); if target.contains("windows") { // FIXME: should pthread support be optional? // It is n...
Rust
0
ion, mode: fd.mode, user_attributes: vec![], file_attributes: vec![], final_: false, is_xhp: false, has_xhp_keyword: false, kind: ClassKind::Cnormal, name: Id(p.clone(), make_closure_name(env, st)), tparams: class_tparams, extends: vec![Hin...
Rust
0
derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)] #[allow(non_snake_case)] #[repr(C)] pub struct WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER { pub AsUINT64: UINT64, } bitfield!(WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER AsUINT64: UINT64[ NmiNotification set_NmiNotification[0..1], InterruptNoti...
Rust
0
""" GravMag: Forward modeling of the gravitational potential and its derivatives using tesseroids """ import time # 3rd imports import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap # local imports from geoist import gridder from geoist.inversion.geometry import Tesseroid from geoist.pfm import polyp...
Python
1
s = ["Lucas", "Mia", "Henry"] # Merge the old list with the new student list to make one combined list. # #Write the code here old_students = ["Lucas", "Mia", "Henry"] # old student list studentList.extend(old_students) print(studentList) # 1️⃣2️⃣ The school needs at least 10 students for the comp...
Python
1
components::*; /// # use wasm_bindgen_test::*; /// # fn ui() -> Node { /// let vec = StateVec::new(); /// vec.insert(0, StateAtomic::new(0)); /// /// vec.view(ul!(), |x| li!(x)) /// # .into() /// # } /// # wasm_bindgen_test_configure!(run_in_browser); /// # #[wasm_bindgen_test] ...
Rust
0
import random print("let me think of a number between 0 and 50!") random_number = random.randint(1, 50) difficulty_level = input("choose level of difficulty...Type 'easy' or 'hard': ") def winner_decider(yg, rg): if yg == rg: print(f"your guess {yg} is right") print("you won") if yg > rg: ...
Python
1
set_state(Gst.State.NULL) self.button.set_label("Start") elif t == Gst.MessageType.ERROR: err, debug = message.parse_error() print "Error: %s" % err, debug self.player.set_state(Gst.State.NULL) self.button.set_label("Start") def on_sync_message(se...
Python
1
# Interact with simple Register.sol smart Contract from web3 import Web3 # Infura URL for the AVAX Testnet infura_url = "https://api.avax-test.network/ext/bc/C/rpc" # https://www.infura.io/blog/post/deploy-an-erc721-smart-contract-and-mint-accounting-nfts-with-infura-and-avalanche-c-chain # Infura is a Web3 developm...
Python
1
ficient=mem_efficient) elif exp_name == "CoinGame": def run(env): from lola.train_cg import train train(env, num_episodes=num_episodes, trace_length=trace_length, batch_size=batch_size, bs_mul=bs_mul, ...
Python
1
::new(name.as_ref()); let name_ptr = name.as_ptr() as usize; let size = size as usize; let flags = flags as usize; syscall5(SYS_SETXATTR, filename_ptr, name_ptr, value, size, flags).map(drop) } /// Attach the System V shared memory segment. /// /// ``` /// let size = 4 * nc::PAGE_SIZE; /// let flags = ...
Rust
0
src_grid = jt.cat([src_grid[..., :1, :] / (Ws - 1) * 2 - 1, src_grid[..., 1:, :] / (Hs - 1) * 2 - 1], dim=-2) # x, y src_grid = src_grid.permute(0, 2, 1) # (B*S, D*Hb*Wb, 2) src_grid = src_grid.view(BS, D, h * w, 2) # (B*S, D, Hb*Wb, 2) # Actual grid sample cost_volume = nn.grid_sample(feat, src_gri...
Python
1
_id let value = config.chain_id(BlockTag::Tag(Tag::Pending)).unwrap(); assert_eq!(value, 1); // Test operator let value = config.operator(BlockTag::Tag(Tag::Pending)).unwrap(); assert_eq!(value, "test-operator"); // Test website let value = config.website(BlockT...
Rust
0
# # COPYRIGHT: # The Leginon software is Copyright under # Apache License, Version 2.0 # For terms of the license agreement # see http://leginon.org # import time class Timer(object): def __init__(self, message=''): self.message = message print 'Timer Start: %s' % (self.message,) self.t...
Python
1
y_ram_to_flash(flash_dst as u32, FLASH_BUFFER.as_ptr() as usize, FLASH_BUFFER.len(), MAIN_CLOCK_FREQ / 1024); if err != 0 { return 1; } FLASH_CUR_IDX += 0x200; FLASH_BUFFER[..data.len() - buffer_cap].copy_from_slice(&data[buffer_cap..]); FLASH_...
Rust
0
::BluetoothAdapter; use blurz::bluetooth_device::BluetoothDevice; use blurz::bluetooth_session::BluetoothSession; use env_logger::Builder; use env_logger::Env; use std::error::Error; use std::time::Duration; type Result<T = ()> = std::result::Result<T, Box<Error>>; #[derive(Deserialize)] struct Config { adapter_a...
Rust
0
"]' 2 #[doc(cfg(unix))] pub mod unix_only { // @has doc_cfg/unix_only/fn.unix_only_function.html \ // '//*[@id="main"]/*[@class="item-info"]/*[@class="stab portability"]' \ // 'This is supported on Unix only.' // @count - '//*[@class="stab portability"]' 1 pub fn unix_only_function() { con...
Rust
0
}, ); self.pc += 4; } 3 => { let input = input_queue.pop_front().unwrap_or(-1); self.store(self.mem[self.pc + 1], mode_op1, input); self.pc += 2; ...
Rust
0
置 "Path": "./data/image/Zombie/Burn/Burn%d.svg", # 僵尸燃烧状态图片路径 "ImageCount": 11, # 僵尸燃烧状态图片数量 "Size": (60, 60), # 僵尸燃烧状态图片尺寸 "Pos": (40, 45) # 僵尸燃烧状态图片位置偏移 }, }, # 阴影相关设置 "shadow":{ "name": "shadow", # 阴影名称 "path": "./data...
Python
1
types delegate to their components. impl<R, T0, T1> Rewrite<R> for (T0, T1) where T0: Rewrite<R>, T1: Rewrite<R>, { #[inline(always)] fn rewrite(&self, plan: &RewritePlan<R>) -> Self { (self.0.rewrite(plan), self.1.rewrite(plan)) } } impl<R, T> Rewrite<R> for Arc<T> where T: Rewrite<R>, { ...
Rust
0
""" Binary Search The Binary Search algorithm searches through an array and returns the index of the value it searches for. Binary Search is much faster than Linear Search, but requires a sorted array to work. The Binary Search algorithm works by checking the value in the center of the array. If the target value is l...
Python
1
<usize>()) ); } else { panic!() } world.try_add_unique(0usize).unwrap(); } #[test] fn not_unique_storage() { let world = World::new(); match world.try_run(|_: UniqueView<usize>| {}).err() { Some(error::Run::GetStorage(get_storage)) => assert_eq!( get_storage, ...
Rust
0
d::Hash { type Strategy = strategies::HashFixedBytes; } impl<T> Strategy for sha256t::Hash<T> where T: sha256t::Tag, { type Strategy = strategies::HashFixedBytes; } impl Strategy for sha512::Hash { type Strategy = strategies::HashFixedBytes; } impl Strategy for hash160::Hash { type Strategy = strate...
Rust
0
= jax.random.PRNGKey(42) xp = jax.random.uniform(key, (n, dim), minval=0., maxval=L) key = jax.random.PRNGKey(43) xe = jax.random.uniform(key, (n, dim), minval=0., maxval=L) hf, logpsi = make_hf() E, mo_coeff = hf(xp) print("energy:", E) print("mo_coeff:\n", mo_coeff) # print(logpsi(mo...
Python
1
s: `\"Win32_Devices_ImageAcquisition\"`*"] pub const WIA_LIST_VALUES: u32 = 2u32; #[doc = "*Required features: `\"Win32_Devices_ImageAcquisition\"`*"] pub const WIA_LONG_DOCUMENT_DISABLED: u32 = 0u32; #[doc = "*Required features: `\"Win32_Devices_ImageAcquisition\"`*"] pub const WIA_LONG_DOCUMENT_ENABLED: u32 = 1u32; #...
Rust
0
((&mut u32s, &mut u16s, &mut f32s), (0, 0, 0.)); entities.add_entity((&mut f32s, &mut u16s, &mut u32s), (0., 0, 0)); assert!((&mut u32s, &mut u16s).iter().count() > 0); } #[test] fn builder() { let world = World::new(); let _entity = world .try_entity_builder() .unwrap() .try_...
Rust
0
import yfinance as yf indices = { # North America "USA": {"name": "S&P 500", "ticker": "^GSPC"}, "USA-NASDAQ": {"name": "NASDAQ", "ticker": "^IXIC"}, "USA-DOW": {"name": "Dow Jones", "ticker": "^DJI"}, "CANADA": {"name": "S&P/TSX", "ticker": "^GSPTSE"}, "MEXICO": {"name": "IPC", "ticker": "^MXX...
Python
1
] fn panic_async() { tokio_unit_test(async { panic!("Ow! Something went wrong!") }) } #[test] fn spawn_async() { tokio_unit_test(async { let _ = tokio_old::spawn(future::lazy(|| Ok(()))); }) } #[test] fn spawn_async_new_tokio() { tokio_unit_test(...
Rust
0
vmm_sys_util; /// use vmm_sys_util::signal::{block_signal, get_blocked_signals, unblock_signal}; /// /// block_signal(1).unwrap(); /// assert!(get_blocked_signals().unwrap().contains(&(1))); /// unblock_signal(1).unwrap(); /// ``` pub fn unblock_signal(num: c_int) -> SignalResult<()> { let sigset = create_sigset(&...
Rust
0
GGGUGA", ).unwrap(); let aas = super::Sequence::from(&rna); assert_eq!(aas.to_string(), "MAMAPRTEINSTRING"); } } use std::{convert, fmt, ops}; use super::AminoAcid; use super::RnaSequence; #[derive(Debug, Eq, PartialOrd, Ord, PartialEq)] pub struct...
Rust
0
(tag("<"), ctx.parse_uri(), tag(">")), )), map(ctx.parse_uri_no_params(), |uri| (None, "", uri)), )), move |(name, _, uri)| Self { name: name.map(|name| BytesStr::from_parse(ctx.src, name)), uri, ...
Rust
0
(|_| Error::UnexpectedMembershipElement(idx + 1)) }, )?; // At this point, we could check that implied_root.range.to = // proof.highest_index, or that -1, or something, but I'm not sure at this // moment what exactly the right test is, and I don't think we really need this, // it would be m...
Rust
0
sb) = hsl_to_rgb(hspin, s, l); rgb_to_hex(sr, sg, sb) } fn normalize_degrees(degrees: i32) -> i32 { match degrees { d if d < 0 => (degrees % CIRCLE_DEGREES) + CIRCLE_DEGREES, _ => degrees % CIRCLE_DEGREES, } } fn normalize_spin(h: i32, degrees: i32) -> i32 { (h + degrees) % CIRCLE_DEG...
Rust
0
request( "PATCH", url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeou...
Python
1
omputes the size of a `xcb_sync_change_alarm_request_t` object. #[inline] pub unsafe fn xcb_sync_change_alarm_sizeof(&self, _buffer: *const c_void) -> c_int { sym!(self, xcb_sync_change_alarm_sizeof)(_buffer) } /// Returns `true` iff the symbol `xcb_sync_change_alarm_sizeof` could be loaded. ...
Rust
0
ize, Vec<f64>); // Bin may be float resolution fn bin_to_freq(&self, bin: f64, sample_rate: f64) -> f64; fn freq_to_bin(&self, freq: f64, sample_rate: f64) -> f64; fn name(&self) -> &'static str; } use anyhow::Result; use colored::Colorize; use heim::process::processes; use notify_rust::Notification; ...
Rust
0
LineEdit(txt, self) text_field.setFont(monospace_font) text_field.setReadOnly(True) text_field.setStyleSheet('background-color: #ffffff;') # Add the label and text field to the horizontal layout horizontal_layout.addWidget(label) horizontal_layout...
Python
1
it MainLogic { fn main_logic(self); } impl<S> MainLogic for S where S: StateMachine, { fn main_logic(self) { self.execute().main_logic(); } } struct FirstState; struct LastState; impl StateMachine for FirstState { type Next = LastState; fn execute(self) -> Self::Next { unimpl...
Rust
0
t::skip] const NONRESIDUE: Fq2 = field_new!(Fq2, field_new!(Fq, BigInteger384([0, 0, 0, 0, 0, 0])), field_new!(Fq, BigInteger384([ 202099033278250856u64, 5854854902718660529u64, 11492539364873682930u64, 8885205928937022213u64, 5545221690922...
Rust
0
""" Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. """ #!/usr/bin/env python3 import logging from sylph.config.config import CfgNode as CN from sylph.runner.default_configs imp...
Python
1
ew("uart").unwrap(); /// # let name1 = CString::new("uart10").unwrap(); /// # let name2 = CString::new("uart11").unwrap(); /// let mut uart1 = uart_open(name1.as_ptr(), conn.as_ptr(), bus.as_ptr(), 5); /// let mut uart2 = uart_open(name2.as_ptr(), conn.as_ptr(), bus.as_ptr(), 5); /// /// uart_putc(uart1, 7u8); /// /// ...
Rust
0
from collections import deque from copy import deepcopy def get_moves(state): moves = [] for i, tube in enumerate(state): if not tube: continue for j, target in enumerate(state): if i == j: continue if not target or tube[-1] == target[-1] and...
Python
1
rt target to binary variable p_STt = [((key[0], key[1] == t), val) for key, val in p_ST.to_dict().items()] # aggregate identical states p_STt = reduce(lambda d, x: d.update({x[0]: d.get(x[0], 0) + x[1]}) or d, p_STt, {}) p_SxTt.append(p_STt) # ...
Python
1
826045602989947510129, 185089342855265166563915858025522983409, 300544292992993952360719000252205715076, 284751400376525550861233017183497639371, 62365388436267647533064120634464266870, 243579355010018669877160932197352017974, 93028746118909893246237533845189074002, ...
Rust
0
# -*- coding: utf-8 -*- # Автор: Гусев Илья # Описание: Модуль загрузки корпусов. from typing import List import nltk from pymorphy2 import MorphAnalyzer from russian_tagsets import converters from rnnmorph.data_preparation.grammeme_vectorizer import GrammemeVectorizer from rnnmorph.data_preparation.word_vocabulary ...
Python
1
import json import os import toml from invoke import task @task def install_hooks(c): """Install git hooks.""" c.run("pre-commit install") c.run("pre-commit install -t pre-push") @task(aliases=["format"]) def black(c): """Format modules using black.""" c.run("black klaxon/ tests/ tasks.py") @...
Python
1
fn trans_multi_param_lam() { let code = r"let l = \a b a . b a;"; let lam_expr = parse_str_err_printed(code).unwrap().remove(0).body; let lam_abs = trans_expr(lam_expr, &[], &mut Default::default(), &Default::default()).unwrap(); println!("{}", lam_abs); let abs_lam_ba = must_be_lam(lam_abs); le...
Rust
0
*curr_strain *= computed_decay.powf((current.strain_time / *avg_strain_time).max(1.0)); *curr_strain += (1.0 + 0.5 * current.snap_probability()) * strain_value * TAP_STRAIN_MULTIPLIER; strains.push(*curr_strain * rhythm_complexity)...
Rust
0
from django.urls import path from . import views app_name = 'videos' urlpatterns = [ # Video management path('', views.VideoListView.as_view(), name='video-list'), path('<int:pk>/', views.VideoDetailView.as_view(), name='video-detail'), path('create/', views.VideoCreateView.as_view(), name='video-crea...
Python
1
text = open('para.txt', 'r') s = text.read() # reads all the content of the file and returns it as a single string a = s pig_latin = a.split() #makes the input into a list for i in range(len(pig_latin)): pig_latin[i] = [pig_latin[i]] #breaks down that list into another list for i in range(len(pig_latin)):...
Python
1
nc def send_mntner_migrate_initiate_mail( session_provider, request: Request, new_auth_mntner: AuthMntner, affected_mntner: RPSLMntner ): """ Send the mntner migration initiation mail. Looks at admin-c of the existing mntner, and then looks up all emails of all contacts, and mails them the token. ...
Python
1
86Reg::CS).unwrap() as u32), ss: Some(vcpu.read_register(&x86Reg::SS).unwrap() as u32), ds: Some(vcpu.read_register(&x86Reg::DS).unwrap() as u32), es: Some(vcpu.read_register(&x86Reg::ES).unwrap() as u32), fs: Some(vcpu.read_register(&x86Reg::FS).unwrap() as u32), gs: Some(vcpu.read_register(&x86Reg::GS)...
Rust
0