text
string
label_name
string
labels
int64
t="kitty %command%") """ exec_string = re.sub(r"%\S*", "", self.exec_string) custom_env = os.environ.copy() # Disable Python virtual environment custom_env.pop("VIRTUAL_ENV", None) custom_env.pop("PYTHONHOME", None) custom_env.pop("PYTHONPATH", None) cmd...
Python
1
failed if query_id in monitor.current_query_data: monitor.current_query_data[query_id]["response_validation_passed"] = False raise finally: if query_id in monitor.current_query_data: monitor.finish_query_tracking(query_id) @contextmanager def track_component_opera...
Python
1
cator('form:invalid')).to_have_count(0) expect(placeholder_field).to_have_text("") formset.locator('input[value="d"]').check() spy = mocker.spy(FormView, 'post') formset.evaluate('elem => elem.submit()') request = json.loads(spy.call_args.args[1].body) assert request['formset_data']['choices'] =...
Python
1
validate_opcode!(program, 19, "muli"); validate_opcode!(program, 20, "gtrr"); validate_opcode!(program, 21, "addr"); validate_opcode!(program, 22, "addi"); validate_opcode!(program, 23, "seti"); validate_opcode!(program, 24, "addi"); validate_opcode!(program, 25, "seti"); validate_opcode...
Rust
0
ndimension() == 3 assert source_control_points.size(1) == self.num_points assert source_control_points.size(2) == 2 target_height= x.shape[2] target_width = x.shape[3] # create target cordinate matrix HW = target_height * target_width target_coordinate = list(iter...
Python
1
""" 问题描述:给定一个无序单链表的头结点head,实现单链表的选择排序 要求:额外空间复杂度为O(1) 思路:选择排序是从未排序的部分找到最小值,放到排好序部分的末尾 (区分选择和冒泡排序,冒泡是比较并交换,而选择是移动指针,每次指 针都是指向最小值,一趟过程后把当前指针指向的值放到排好序的尾部) """ from linkedlist.toolcls import Node, PrintMixin class SortList(PrintMixin): @classmethod def sort_list(cls, head): cur = head new_head =...
Python
1
nPool>(&auction_pool_pubkey) .await .unwrap(); assert_eq!( auction_pool.pool.len(), INITIAL_AUCTION_POOL_LEN as usize + 1 ); assert_eq!(auction_pool.max_len, new_max_len); assert_eq!(auction_pool.pool, vec![[0; 32], [1; 32], [2; 32], [3; 32]]); // Invalid use case ...
Rust
0
else if result == base { return Ok(E::Fr::one()); } let mut cur_guess = base; for exponent in 2..2_u64.pow(SAVER_BLOCK_SIZE) { cur_guess += &base; if result == cur_guess { return Ok(<E::Fr as From<u64>>::from(exponent)); } }...
Rust
0
hex_digit(), skip_many(( optional(char('_')), skip_many1(hex_digit()), )), ).map(|t| t.0) )).and_then(|s: &str| i64::from_str_radix(&s.replace("_", ""), 16)) .message("While parsing a hexadecimal Integer") }); // oct-int = "0o" digit0-7 *( digi...
Rust
0
=======*/ gl.bind_vertex_array(&state.vao); if gl.is_webgl2 { if let Some(_) = self.bound_prog.borrow().upgrade() { return Ok(()); } } // Bind vertex buffer object // "aVertexPosition" bind_buffer( gl, ...
Rust
0
{ type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pu_fbdv_buf_lotx` writer - "] pub struct PU_FBDV_BUF_LOTX_W<'a> { w: &'a mut W, } impl<'a> PU_FBDV_BUF_LOTX_W<'a> { #[doc = r"Sets the field bit"] #[inlin...
Rust
0
teslac", mqtt_config.host, mqtt_config.port); if let (Some(username), Some(password)) = (mqtt_config.username, mqtt_config.password) { options.set_credentials(username, password); } options.set_keep_alive(Duration::from_secs(10)); let (client, mut connection) = Client::new(o...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 完整测试支撑位价格问题修复方案 验证后端计算逻辑和前端验证逻辑 """ import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'backend_api')) from stock.stock_analysis import KeyLevels import logging # 设置日志 logging.basicConfig(level=logging.INFO) logger = logging.getLogger...
Python
1
import os from launch import LaunchDescription from launch_ros.actions import Node from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from ament_index_python.packages import get_package_share_directory from launch_ros.substitutions import Find...
Python
1
if path.is_some() { return Err(syn::Error::new_spanned( attr, "`typed_path` specified more than once", )); } else { path = Some(attr.parse_args()?); } } } Ok(Attrs { path: path.ok_or_...
Rust
0
self) -> &str { match self { &InitError::Io(..) => "IO error while initializing", &InitError::SetLoggerError(..) => "global logger already initialized", } } fn cause(&self) -> Option<&error::Error> { match self { &InitError::Io(ref e) => Some(e), ...
Rust
0
import os.path import urllib.request import zipfile BASE_URL = 'https://figshare.com/collections/Aerial_imagery_object_identification_dataset_for_building_and_road_detection_and_building_height_estimation/3290519' FILE_URL_FORMAT = "https://ndownloader.figshare.com/articles/{}/versions/1" FILE_METADATA_LIST = [ { ...
Python
1
out_custom = custom_fuc(*inputs_gpu) t_forward_custom += get_end_time(t0) loss = torch.sum((1.0 - out_custom)**2) t0 = get_start_time() loss.backward() t_backward_custom += get_end_time(t0) # forward only with torch.no_grad(): t0 = get_start_t...
Python
1
ne): return func(self, request, queryset_or_obj, form_data) wrapper.modal_header = modal_header wrapper.modal_description = modal_description wrapper.permissions = permissions wrapper.form_class = form_class wrapper.skip_confirmation = skip_confirmation retur...
Python
1
import pyb import upcd8544 from machine import SPI,Pin from pyb import UART leds = [pyb.LED(i) for i in range(1,5)] SPI = pyb.SPI(1) #DIN=>X8-MOSI/CLK=>X6-SCK #DIN =>SPI(1).MOSI 'X8' data flow (Master out, Slave in) #CLK =>SPI(1).SCK 'X6' SPI clock RST = pyb.Pin('X20') CE = pyb.Pin('X19') DC = pyb.Pin('X1...
Python
1
} // } /// Creates a Response containing an error, with the Response variant corresponding to the /// Request variant. pub fn error(&self, error: Error) -> CmdError { CmdError::Auth(error) } /// Returns the type of authorisation needed for the request. pub fn authorisation_kin...
Rust
0
from swampdragon.testing.dragon_testcase import DragonTestCase from .models import TextModel, ParentModel, ChildModel from swampdragon import model_tools class TestModelTools(DragonTestCase): def test_get_property(self): text_model = TextModel.objects.create(text='test') val = model_tools.get_prop...
Python
1
'left' - decrease wavelength delay by 0.05λ 'right' - increase wavelength delay by 0.05λ 'up' - increase frequency by 10 Hz 'down' - decrease frequency by 10 Hz 'q' - quit frequency: {:.2}Hz phase shift: {:.2...
Rust
0
nonce[..].as_ptr(), // nonce nonce.len(), // nonce_len buf.as_ptr(), // inp in_len, // in_len extra_in_ptr, // extra_in extra_in_len, // extra_in_...
Rust
0
ecked(1)) * ClearFloat::from(0.5); ans } #[inline(always)] pub fn sinh(self) -> Self { let e2 = self.exp_2(); let ans = (&*e2.get_unchecked(0) - &*e2.get_unchecked(1)) * ClearFloat::from(0.5); ans } #[inline(always)] pub fn tanh(self) -> Self { let e2 = se...
Rust
0
fire) # try to submit weekly without specifying days of week self.assertUpdateSubmit( update_url, {"start_datetime": datepicker_fmt(today), "repeat_period": "W"}, form_errors={"repeat_days_of_week": "Must specify at least one day of the week."}, object_un...
Python
1
dataOut.Check_Output() if count>1: subset = dataOut.Create_NC_file(ofile,primary='SIT') df = Functions.Append_to_NC(df, subset) else: df = dataOut.Create_NC_file(ofile,primary='SIT', datasource='Airborne E...
Python
1
try: import cupy as cp except ImportError: import numpy as cp import copy from numtorch.autograd import Tensor from typing import Union, List from numtorch.nn.relu import ReLU from numtorch.nn.sequential import Sequential from numtorch.nn.linear import Linear from numtorch.nn.base import Module class MLP(Modu...
Python
1
CE_SIZE.is_power_of_two()); // Must adhere to architectural restrictions. assert!(AS_SIZE >= arch_mmu::MIN_ADDR_SPACE_SIZE); assert!(AS_SIZE <= arch_mmu::MAX_ADDR_SPACE_SIZE); assert!((AS_SIZE % arch_mmu::AddrSpaceSizeGranule::SIZE) == 0); AS_SIZE } } /// Raw mapping of vi...
Rust
0
from fir_artifacts.artifacts import AbstractArtifact import re class Phone(AbstractArtifact): key = "phone" display_name = "Phone Numbers" regex = r"""(?P<search> \+\d{1,3} # country code [ \t.\-()]* # optional separators (no ...
Python
1
find_fn = True break if(find_fn ==False): print ("!!!ERROR: cannot find the connection layer fn") self.connection_layer_fn_lst_dec = [] for layer_name in self.connection_layer_lst_dec: layer_name = "_"+layer_...
Python
1
sick" library. TODO: - use pickle and unpickle support for `self.autom` """ def __init__(self, ignore_case=True, titles=None, extra_titles=None): """ :param ignore_case if True, lower case job titles are also added :param titles: if given, overrides default `load_titles()` valu...
Python
1
olidated: bool durationFrom: datetime durationTo: datetime unit: str roleType: str docId: str docType: Literal["Annual", "Quarterly", "SemiAnnual"] docSubmissionDate: datetime class PLConcept(FinancialStatementConcept): def __init__( self, root_concepts: list[ModelConce...
Python
1
"""Provides a version of the Distutils "build_py" command that knows about PTL files. """ import os from glob import glob from distutils.command.build_py import build_py class qx_build_py(build_py): def find_package_modules(self, package, package_dir): self.check_package(package, package_dir) mod...
Python
1
"Dormant Users": (0.8, 1.0), } response_data = [] for category, (lower_bound, upper_bound) in churn_categories.items(): # Count users in each category user_count = ( db.query(func.count(ResultsDB.id)) .filter( ResultsDB.churn_probability > lower_bo...
Python
1
annel { Channel{period: 0, sample_number: 0, effect: 0} } pub fn is_empty(&self) -> bool { self.period == 0 && self.sample_number == 0 && self.effect == 0 } } /// A single row in a Pattern. /// Normally there are 4 channels per Row. #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct Row { /...
Rust
0
inline] fn add_round_key(state: &mut State, rkey: &[u32]) { debug_assert_eq!(rkey.len(), 8); for (a, b) in state.iter_mut().zip(rkey) { *a ^= b; } } #[inline(always)] fn add_round_constant_bit(state: &mut [u32], bit: usize) { state[bit] ^= 0x0000c000; } #[inline(always)] fn ror(x: u32, y: u32)...
Rust
0
"""Functions for calculating steps in exchaning currency.""" def exchange_money(budget, exchange_rate): return budget / exchange_rate def get_change(budget, exchanging_value): return budget - exchanging_value def get_value_of_bills(denomination, number_of_bills): return denomination * number_of_bills ...
Python
1
""" Sources: Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland """ from django.utils.translation import ugettext_lazy as _ IE_COUNTY_CHOICES = ( ('antrim', _('Antrim')), ('armagh', _('Armagh')), ('carlow', _('Carlow')), ('cavan', _('Cavan')), ('clare', _('Clare')), ('cork...
Python
1
t.P_OUTPUT_TRANSFORMER: self.filename('transformer.pkl'), } self.runalg(algFit, parametersFit) # forward transform alg1 = TransformRasterAlgorithm() alg1.initAlgorithm() parameters = { alg1.P_RASTER: enmap_potsdam, alg1.P_TRANSFORMER: parametersFi...
Python
1
self.matcher_vo = VersionOrder(vspec_str) matcher = self.operator_match is_exact = True else: matcher = self.exact_match is_exact = True return vspec_str, matcher, is_exact def merge(self, other): assert isinstance(other, self.__class__) ...
Python
1
"n_agents": 4, "n_enemies": 18, "limit": 200, "a_race": "P", "b_race": "Z", "unit_type_bits": 2, "map_type": "stalkers_and_zealots_vs_zergling", }, "3s1z_vs_zg_easy": { "n_agents": 4, "n_enemies": 18, "limit": 200, "a_race":...
Python
1
&'a mut W, } impl<'a> EXTMEM_ICACHE_TAG_MEM_FORCE_ON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } ...
Rust
0
izePolicy.Policy.Maximum, QSizePolicy.Policy.Minimum) self.bottom_horizontalLayout.addItem(self.horizontalSpacer_3) self.verticalLayout.addLayout(self.bottom_horizontalLayout) self.retranslateUi(search_base) QMetaObject.connectSlotsByName(search_base) # setupUi def retransl...
Python
1
from flask import Blueprint, jsonify, current_app import psutil, shutil, time ov_bp = Blueprint("overview", __name__) # Global buffer to simulate real-time traffic history traffic_data = [] @ov_bp.route("/stats", methods=["GET"]) def stats(): cpu = psutil.cpu_percent(interval=0.5) mem = psutil.virtual_memory...
Python
1
from distutils.core import setup from setuptools import find_packages import os # User-friendly description from README.md current_directory = os.path.dirname(os.path.abspath(__file__)) try: with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() except E...
Python
1
create_device(&device); let gbm_surface = gbm::surface_create( gbm_device, mode_info.hdisplay as u32, mode_info.vdisplay as u32, GBM_FORMAT, gbm_bo_flags::GBM_BO_USE_SCANOUT | gbm_bo_flags::GBM_BO_USE_RENDERING, ); let egl_display = egl::get_display(gbm_device as *mut c_void)....
Rust
0
description=input_description, num_res=num_res) msa_features = make_msa_features( msas=parsed_msas, deletion_matrices=parsed_delmat) return {**sequence_features, **msa_features} ##################MAIN####################### #Parse args args = parser.parse_args() #Data input_fasta_path ...
Python
1
rn self.forward_pre(output, memory, segms, #query, key, value, segms, pos=pos) return self.forward_post(output, memory, segms, #query, key, value, segms, pos=pos)#output:分别为形状同quries的0向量;memory:backbone出来的特征;tgt_mask:None;memory_mask:手物query数量的mask([4,...
Python
1
'prefix': 'D', 'weight': 0, 'is_hot': 0, }, { 'id': 318, 'pid': 25, 'name': '文昌', 'level': 2, 'pinyin': 'wenchang', 'prefix': 'W', 'weight': 0, 'is_hot': 0, }, { ...
Python
1
elled}, tags::Plicit, vec1::Vec1, }; use crate::syntax::pat::{Copat, Pat}; /// Surface syntax: Parameter. /// /// It's a part of a pi-type expression. #[derive(Debug, Clone, Eq, PartialEq)] pub struct Param { pub licit: Plicit, /// This field can be empty -- which indicates the parameter to be ///...
Rust
0
d|dS(Ns</%s>(R+(R"R-((s saxutils.pyt endElementscCs|jd|j|xN|jD]C\}}|rS|jjd||fq$|jjd|q$Wg|_x@|jD]2\}}|jd|j|t|fqW|jddS(...
Python
1
subshell(label) max_electrons[ishell] = maxele ret = [] if self.previous_inert() is not None: inert = self.__class__(self.previous_inert()) ret.append(inert.symbol) inert_remain = inert.atomic_number # Consume the shells up to the previous ine...
Python
1
transfer::derive_ibc_denom) from the [`ibc`] module. Derives the denom on `ChainB` based on a denom on `ChainA` that has been transferred to `ChainB` via IBC. Accepts the following arguments: - A `PortId` on `ChainB` that corresponds to a channel connected to `ChainA`. - A `ChannelId` on `Cha...
Rust
0
tect_wakeup_word 메소드 def detect_wakeup_word(self, predicted_text): messages = [ {"role": "system", "content": self.WAKEUP_WORD_PROMPT}, {"role": "user", "content": predicted_text}, ] return self.chat_completion("gpt-3.5-turbo", 0, messages) == "Yes" # STT_Agent의 ...
Python
1
new(); canvas.set_face_color("None").set_edge_color("magenta"); canvas.draw_circle(0.5, 0.8, grid.radius); canvas.draw_circle(0.1, 0.4, grid.radius); canvas.draw_circle(0.5, 0.0, grid.radius); canvas.draw_circle(0.1, 1.6, grid.radius); canvas.set_e...
Rust
0
is similar in feel (and encryption) to /// [SIGMA-I](http://webee.technion.ac.il/~hugo/sigma-pdf.pdf), albeit with /// MAC instead of a digital signature. pub trait HandshakePattern: Display { /// Get the pattern name as a static string, e.g. "IX" fn name() -> &'static str; /// Get the initiator's pre-mess...
Rust
0
from virtual_shell import start_shell def main(): print("Welcome to Virtual OS Simulator!") start_shell() if __name__ == "__main__": main()
Python
1
_bits = other.bits(); // Check for division by 0 assert!(your_bits != 0); // Early return in case we are dividing by a larger number than us if my_bits < your_bits { return U256(ret); } // Bitwise long division let mut shift = my_bits - your_bits; ...
Rust
0
} // Board plugin app.add_plugin(BoardPlugin { running_state: AppState::InGame, }) .add_state(AppState::Out) .add_startup_system(setup_board) // Startup system (cameras) .add_startup_system(setup_camera) // UI .add_startup_system(setup_ui) // State handling .add_sy...
Rust
0
ranks[j] +=1 #print("ranks",ranks) #Computes CMC Scores from ranks cmcScores = ranks / nb_test_class return cmcScores def drawTriplets(tripletbatch, nbmax=None): """display the three images for each triplets in the batch """ labels = ["Anchor", "Positive", "Negative"] if ...
Python
1
.unwrap(); let sum_y = metrics.iter().map(|m| m.y).sum::<f64>(); let sum_u = metrics.iter().map(|m| m.u).sum::<f64>(); let sum_v = metrics.iter().map(|m| m.v).sum::<f64>(); Ok(PlanarMetrics { y: log10_convert(sum_y, 1. / metrics.len() as f64), u: log10_convert(sum...
Rust
0
ment_table: *const u16; 0x0046E0C7 => upgrade_requirement_table: *const u16; 0x0046DE76 => tech_use_requirement_table: *const u16; 0x0046DF96 => tech_research_requirement_table: *const u16; 0x0046DD6D => order_requirement_table: *const u16; 0x0045CA0C => aiscript_default_switch_table: [u32; 0x71]; ...
Rust
0
util_requirement=self.skip_root_kmutil_requirement ) source_files_path = str(self.constants.payload_local_binaries_root_path) required_patches = self._preflight_checks(required_patches, source_files_path) for patch in required_patches: logging.info("- 安装补丁集: " + patch) ...
Python
1
ence = float('inf'), 0, 40 best_wts = None MAX_EPOCHS = 5000 # 用于绘图的损失记录列表 train_losses, val_losses = [], [] # ---------- 4. 训练循环 ---------- for epoch in range(1, MAX_EPOCHS + 1): model.train() total_reg, n = 0., 0 for X, a, Y in train_loader: optimizer.zero...
Python
1
!( r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self } } impl Default for RtcStatsReportInternal { fn default() -> Self { Self::new() } } // This file is part of the SORA network and Polkaswap app. // Copyr...
Rust
0
.get_raw() .image .texture_def() .extents; let dst_offset_pixels = glam::Vec2::new( dst_uv_min.x * dst_image_extents.width as f32, dst_uv_min.y * dst_image_extents.height as f32, ); let dst_size_pixels = glam::Vec2::new( ...
Rust
0
pe)> { match (exp, sig) { (exp, _) if exp >= Float::<T>::exp_max() => { let infinite = if round_inc == T::BaseType::from(0) { Float::<T>::new(sign, Float::<T>::exp_max() - T::BaseType::from(1), Float::<T>::sig_max()) } else { Fl...
Rust
0
(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { let old_enabled = self.cfg.enabled(); self.cfg.update(offset, data); let new_enabled = self.cfg.enabled(); if !old_enabled && new_enabled { return Some(InterruptUpdateAction::EnableMsi); } ...
Rust
0
lake2_128Concat, T::AccountId, Balance, ValueQuery >; #[pallet::storage] #[pallet::getter(fn allowance)] pub (super) type Allowances<T:Config> = StorageDoubleMap< _, Blake2_128Concat, T::FungibleTokenId, Blake2_128Concat, //(owner,operator) (T::AccountId,T::AccountId), Balance, ValueQuery, >; #[pallet::event] #[...
Rust
0
.Fs / f for f in fs_list] params.fs_list = fs_list params.inputs_lengths = [len(s) for s in signals_list] # Write parameters of run to a text file with open(os.path.join(params.output_folder, 'log.txt'), 'w') as f: f.write(''.join(["%s = %s\n" % (k, v) for k, v in params.__dict__.items()])) if params.run_mode == ...
Python
1
}<gh_stars>1000+ use crate::fmt::display; use crate::kind::Trivial; use crate::string::CxxString; use crate::weak_ptr::{WeakPtr, WeakPtrTarget}; use crate::ExternType; use core::ffi::c_void; use core::fmt::{self, Debug, Display}; use core::marker::PhantomData; use core::mem::MaybeUninit; use core::ops::Deref; /// Bin...
Rust
0
ck_json_load): mock_json_load.return_value = {'baz': 13, 'boo': {'a': 1, 'b': 2}} actual = json_ref.resolve_refs( {'foo': 1, 'bar': {'$ref': 'another.json#', 'boo': {'b': ...
Python
1
oOutputParameterHandler) return nbFile pos = len(sMovieTitle) sYear, pos = getYear(sMovieTitle, pos) sMovieTitle = sMovieTitle[:pos] # ajout des fichiers nbFile = 0 oOutputParameterHandler = cOutputParameterHandler() for file in content['files']: sFileName = file['titl...
Python
1
from typing import * def prod_signs(arr): if not arr: return None prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr))) return prod * sum([abs(i) for i in arr])
Python
1
.__name__, "description": description, "parameters": { "type": "object", "properties": parameters, }, "required": required, } def check_session_token(self, session_token: str) -> dict: """ Retrieves a user from ...
Python
1
_nth_unstable_by(index, compare) } /// Reorder the slice with a key extraction function such that the element at `index` is at its /// final sorted position. #[unstable(feature = "slice_partition_at_index", issue = "55300")] #[rustc_deprecated(since = "1.49.0", reason = "use the select_nth_unstable...
Rust
0
_name] = web_dir if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: for name in module.NODE_CLASS_MAPPINGS: if name not in ignore: NODE_CLASS_MAPPINGS[name] = module.NODE_CLASS_MAPPINGS[name] if hasattr(m...
Python
1
ate::vendor_prefix::VendorPrefix; use crate::declaration::DeclarationList; use super::flex::{BoxAlign, FlexLinePack, BoxPack, FlexPack, FlexAlign, FlexItemAlign}; use crate::targets::Browsers; use crate::prefixes::{Feature, is_flex_2009}; use crate::printer::Printer; use crate::compat; use crate::error::{ParserError, P...
Rust
0
metadata.height_of_longest_chain; } match node .find_and_accept_constitutions(base_node_client.clone(), last_tip) .await { Ok(()) => info!("Contracts accepted"), ...
Rust
0
from django.template.defaultfilters import urlencode from django.test import SimpleTestCase from ..utils import setup class UrlencodeTests(SimpleTestCase): @setup({"urlencode01": "{{ url|urlencode }}"}) def test_urlencode01(self): output = self.engine.render_to_string("urlencode01", {"url": '/test&"/...
Python
1
enumerate(obj['edges']): if obj['edges'][i]['source'] not in [None,''] and obj['edges'][i]['target'] not in [None,''] and obj['edges'][i]['label'] not in [None,'']: dot.edge( tail_name=str(obj['edges'][i]['sourc...
Python
1
type AnswerPreCheckoutQuery: Request<Payload = AnswerPreCheckoutQuery, Err = Self::Err>; /// For Telegram documentation see [`AnswerPreCheckoutQuery`]. fn answer_pre_checkout_query<P>( &self, pre_checkout_query_id: P, ok: bool, ) -> Self::AnswerPreCheckoutQuery where ...
Rust
0
i_fd_t, fs_rights_base: wasi::__wasi_rights_t, fs_rights_inheriting: wasi::__wasi_rights_t, ) -> Result<()> { trace!( "fd_fdstat_set_rights(fd={:?}, fs_rights_base={:#x?}, fs_rights_inheriting={:#x?})", fd, fs_rights_base, fs_rights_inheriting ); let fe = wasi_ctx.ge...
Rust
0
import json import boto3 from boto3.dynamodb.conditions import Key from boto3.dynamodb.conditions import Attr from decimal import Decimal dynamodb_resource = boto3.resource("dynamodb") follows_table = dynamodb_resource.Table("tastehub-follows") posts_table = dynamodb_resource.Table("tastehub-posts") # Used to JSON d...
Python
1
import pygame, time ################################# LOAD UP A BASIC WINDOW AND CLOCK ################################# pygame.init() pygame.font.init() font = pygame.font.SysFont('Calibri',40) DISPLAY_W, DISPLAY_H = 480, 270 canvas = pygame.Surface((DISPLAY_W,DISPLAY_H)) window = pygame.display.set_mode(((DISPLAY_W,...
Python
1
import pandas as pd # Load the predictions file_path = '../../reports/predictions_2019.csv' pred_df = pd.read_csv(file_path) # Melt the dataframe to have one row per runner melted_df = pred_df.melt(id_vars=['School'], var_name='Runner', value_name='Time') # Rank runners by time in ascending order melted_df = melted_...
Python
1
ering> { other.partial_cmp(self) } } impl PartialEq<String> for Bytes { fn eq(&self, other: &String) -> bool { *self == &other[..] } } impl PartialOrd<String> for Bytes { fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> { self.as_slice().partial_cmp(other.as_bytes...
Rust
0
t for things that are already quoted path = quote(parts.path, safe="%!$&'()*+,/:;=@") query = quote(parts.query, safe="%!$&'()*+,/:;=?@") fragment = quote(parts.fragment, safe="%!#$&'()*+,/:;=?@") if parts.hostname: netloc = parts.hostname.encode("idna").decode("ascii") else: netloc...
Python
1
g7_1(&self) -> bool { *self == ADC14IFG7_A::ADC14IFG7_1 } } #[doc = "ADC14MEM8 interrupt flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADC14IFG8_A { #[doc = "0: No interrupt pending"] ADC14IFG8_0 = 0, #[doc = "1: Interrupt pending"] ADC14IFG8_1 = 1, } impl Fro...
Rust
0
executor; #[cfg(cortex_m)] pub mod interrupt; pub mod io; #[cfg(feature = "time")] pub mod time; pub mod util; pub use embassy_macros::*; pub use embassy_traits as traits; #[doc(hidden)] /// Implementation details for embassy macros. DO NOT USE. pub mod export { pub use atomic_polyfill as atomic; } // Copyright ...
Rust
0
import os import os.path import shutil import stat from contextlib import contextmanager from tempfile import NamedTemporaryFile # NOTE: retrying is not annotated in typeshed as on 2017-07-17, which is # why we ignore the type on this import. from pip._vendor.retrying import retry # type: ignore from pip._vendo...
Python
1
let entries_str = fs::read_to_string(config_path).expect("cannot read entries-define.yaml"); let entries: EntryDefines = serde_yaml::from_str(&*entries_str).unwrap(); entries.entries } mod gameoflife; mod reversi; mod tsp; use crate::base::iters::DevTreeIter; use crate::base::{DevTree, DevTreeNode}; use c...
Rust
0
from clint.rules.base import Rule class DoNotDisable(Rule): DO_NOT_DISABLE = {"B006"} def __init__(self, rules: set[str]) -> None: self.rules = rules @classmethod def check(cls, rules: set[str]) -> "DoNotDisable": if s := rules.intersection(DoNotDisable.DO_NOT_DISABLE): r...
Python
1
""" Copyright (c) 2018-2024 Intel Corporation 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 applicable law or agreed to in wri...
Python
1
ck(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.r...
Python
1
er(), inline_vars(Default::default())), $name, $src, $expected ); }; } macro_rules! to_fn { ($name:ident, $src:expr, $expected:expr) => { to!( $name, &format!( "function wtf(){{ {} }}", ...
Rust
0
erverBoundPacket { ServerBoundChatMessage(ServerBoundChatMessage), ServerBoundKeepAlive(ServerBoundKeepAlive), ServerBoundAbilities(ServerBoundAbilities), } pub enum GameClientBoundPacket { ClientBoundChatMessage(ClientBoundChatMessage), JoinGame(JoinGame), ClientBoundKeepAlive(ClientBoundKeepA...
Rust
0
########################################################################## # # Copyright (c) 2007, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
Python
1
ializationError> { let mut out = String::new(); #[allow(unused_mut)] let mut writer = aws_smithy_query::QueryWriter::new( &mut out, "CreateVpcEndpointConnectionNotification", "2016-11-15", ); #[allow(unused_mut)] let mut scope_1556 = writer.prefix("DryRun"); if let So...
Rust
0