text
string
label_name
string
labels
int64
import math def day_of_the_week(d,m,y): days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] m = m-2 if m <= 0: m=m+12 y = y-1 c = y//100 a = y%100 #print(d,m,y,c,a) f = int((2.6*m)-0.2)+d+a+int(a/4)+int(c/4)-(2*c) return days[int(f%7...
Python
1
let mut i = 0x3; i |= opcode5 << 2; i |= rd << 7; i |= funct3 << 12; i |= rs1 << 15; i |= (imm << 20) as u32; sink.put4(i); } /// U-type instructions. /// /// 31 11 6 /// imm rd opcode /// 12 7 0 /// /// Encoding bits: `opcode[6:2] | (funct3 << 5)` fn put_u<CS: CodeSink + ?S...
Rust
0
### feature PE condition = self.FeaturePositionalEncoding(condition) condition = condition.permute(1,0,2).contiguous() condition = self.CLalignEmbedding(condition) # torch.Size([T, BS, 512]) condition = self.PositionalEmbedding(condition...
Python
1
""" Simple Bar Chart ================ This example shows a basic bar chart created with Altair. """ # category: simple charts import altair as alt import pandas as pd source = pd.DataFrame({ 'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 'b': [28, 55, 43, 91, 81, 53, 19, 87, 52] }) alt.Chart(source).mark...
Python
1
th respect to the line through `c` and `b`. //! In Rust, this condition can be written as //! ``` //! # use geometry_predicates::orient2d; //! # let a = [1.0, 2.0]; //! # let b = [3.0, 4.0]; //! # let c = [5.0, 6.0]; //! assert_eq!(orient2d(a,c,b).signum(), orient2d(c,b,a).signum()); //! ``` //! //! Mathematically, pre...
Rust
0
lfio::constant::ET_REL => println!("Object ELF file"), //! elfio::constant::ET_EXEC => println!("Executable ELF file"), //! elfio::constant::ET_DYN => println!("Shared library ELF file"), //! elfio::constant::ET_CORE => println!("Core ELF file"), //! _ => println!("ELF type is not recogn...
Rust
0
import time import keyboard import pyautogui import cv2 import numpy as np import mouse ''' START EDITABLE PARAMETERS ''' # color of target to aim for target_color = (149, 195, 232) # target of save score button save_score_color = (255, 209, 84) # minimum size (pretty arbitrary) to ensure contour is large enough con...
Python
1
# Gracin Goff # UWYO COSC 1010 # 11/05/2024 # HW 03 # Lab Section: 10 # Sources, people worked with, help given to: # your # comments # here day_in_month = [31,28,31,30,31,30,31,31,30,31,30,31] days_of_week = {'0':'Sunday','1':'Monday','2':'Tuesday','3':'Wednesday','4':'Thursday','5':'Friday','6':'Saturday'} def fi...
Python
1
for BulkResponse<TIndex, TType, TId> { type Item = <Self::IntoIter as Iterator>::Item; type IntoIter = ResultIntoIter<TIndex, TType, TId>; fn into_iter(self) -> Self::IntoIter { ResultIntoIter(self.items.into_iter()) } } /** An owning iterator for a bulk item that may have succeeded or failed...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Optional, Union import torch from torch import nn from mmpretrain.models import BaseSelfSupervisor, CosineEMA from mmpretrain.registry import MODELS from mmpretrain.structures import DataSample @MODELS.register_module() class DINO(BaseSelfSupe...
Python
1
""" Flask server for emotion detection API. This module provides a REST API endpoint for detecting emotions in text using the emotion_detection module. """ from flask import Flask, request, jsonify from emotion_detection import emotion_detector app = Flask(__name__) @app.route('/emotionDetector', methods=['POST']...
Python
1
import math def read_data(file="input.txt"): with open(file) as f: data = f.readlines() # basic clean up here return data def part_1(data): time, distance = [map(int, string.split(':')[1].strip().split()) for string in data] data = zip(time, distance) number_of_ways = [] for r...
Python
1
#!/usr/bin/env python # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), e...
Python
1
3D6, 'M', 'π'), (0x3D7, 'V'), (0x3D8, 'M', 'ϙ'), (0x3D9, 'V'), (0x3DA, 'M', 'ϛ'), (0x3DB, 'V'), (0x3DC, 'M', 'ϝ'), (0x3DD, 'V'), (0x3DE, 'M', 'ϟ'), (0x3DF, 'V'), (0x3E0, 'M', 'ϡ'), (0x3E1, 'V'), (0x3E2, 'M', 'ϣ'), (0x3E3, 'V'), (0x3E4, 'M', 'ϥ'), (0x3E5, 'V'),...
Python
1
ssions on the data object. self.assert_permissions_on_data_object_for_user(no_access_user.username, logical_path, not_found_string) finally: self.admin.assert_icommand(['ils', '-Al', logical_path], 'STDOUT') # Debugging # Make sure that the data object can be removed by mar...
Python
1
def msg(name, ending="Thank you"): print(f"Take care {name} ,{ending}") msg("Harsh") msg("Atif","Get lost")
Python
1
from abc import ABC class Discretization(ABC): """Holds discretization information about a Component. Attributes: ----------- time_step: int The time step with which to run the Component """ def __init__( self, time_step: int, ): """Initialize a Discretiza...
Python
1
/// length. #[prost(bytes = "vec", tag = "2")] pub value: ::prost::alloc::vec::Vec<u8>, /// Labels applied to the cell by a [RowFilter][google.bigtable.v2.RowFilter]. #[prost(string, repeated, tag = "3")] pub labels: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Specifies a con...
Rust
0
= Tag::from_bytes(b"zero"); <filename>src/cli/display.rs use std::convert::From; use std::error::Error; use std::fmt::Display; use prettytable::{cell, row, Row}; use super::table::ToRow; use crate::api::rpc::{LearnedRoute, PeerSummary}; pub const EMPTY_VALUE: &str = ""; pub fn display_cell<T>(value: Option...
Rust
0
syms.insert("Arabic_hamza_above", 0x1000654); keysyms.insert("Arabic_hamza_below", 0x1000655); keysyms.insert("Arabic_jeh", 0x1000698); keysyms.insert("Arabic_veh", 0x10006a4); keysyms.insert("Arabic_keheh", 0x10006a9); keysyms.insert("Arabic_gaf", 0x10006af); keysyms.insert("Arabic_noon_ghunna", 0x10006ba)...
Rust
0
_Decryptor_decrypt(self, encrypted, destination) } #[inline] pub unsafe fn invariant_noise_budget( &mut self, encrypted: *const seal_Ciphertext, ) -> ::std::os::raw::c_int { seal_Decryptor_invariant_noise_budget(self, encrypted) } #[inline] pub unsafe fn new(context: ...
Rust
0
""" Determine if an attack has been successful in targeted Classification ----------------------------------------------------------------------- """ from .classification_goal_function import ClassificationGoalFunction class TargetedClassification(ClassificationGoalFunction): """A targeted attack on classifica...
Python
1
_started_at( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); ...
Rust
0
Some(HashAlgorithm::SHA512) } else if oid.eq(&ID_SHA512_224) { Some(HashAlgorithm::SHA512_224) } else if oid.eq(&ID_SHA512_256) { Some(HashAlgorithm::SHA512_256) } else if oid.eq(&ID_SHA3_224) { Some(HashAlgorithm::SHA3_224) } else if oid....
Rust
0
"""pdf utility functions""" import PyPDF2 ## Read and extract text from a PDF file def read_pdf(file_path: str) -> str: """ Reads a PDF file and extracts the text content. """ pdf_text = "" try: pdf_reader = PyPDF2.PdfReader(file_path) for page in pdf_reader.pages: pdf_text += page.extract_text...
Python
1
# Original Code # https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py # See https://github.com/graykode/matorage/blob/0.1.0/NOTICE # modified by TaeHwan Jung(@graykode) # Copyright 2020-present Tae Hwan Jung # # Licensed under the Apache License, Version 2.0 (the "License");...
Python
1
per!_", "road_rai", "rockbox_", "rok_____", "roman", "roman___", "rot13", "rotated", "rounded", "rowancap", "rozzo", "runic", "runyc", "sans", "sansb", "sansbi", "sansi", "santa_clara", "sblood", "sbook", "sbookb", "sbookbi", "sbooki", "script", "script__", "serifcap", "shadow", "shimrod", "short", "skateord", "skatero...
Python
1
from .app import app from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) from . import routes
Python
1
import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))) import asyncio from sphero_sdk import SpheroRvrAsync from sphero_sdk import Colors from sphero_sdk import RvrLedGroups from sphero_sdk import SerialAsyncDal loop = asyncio.get_event_loop() rvr = SpheroRvrAsyn...
Python
1
Ok(None), }) .collect::<Result<Vec<Option<T>>, String>>() } #[test] fn cache_set_get() { #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Foo(String); set_hash_items("__test", &[ ("key1", Foo("val1".into())), ("key3", Foo("val3".into())), ]) .expect("Error...
Rust
0
{review[1]}") ui.separator() def display_user_games(container, user_id): username = queries.get_user_name(user_id) games = queries.get_games_by_user_id(user_id) with container: ui.markdown(f"# {username[0]}'s games") ui.separator() if games is None: ui.l...
Python
1
!("(?, {})", y) } } struct Point<T> { x: T, y: T } struct Line<T> { start: Point<T>, end: Point<T> } pub fn generics() { let a:Point<f32> = Point{x: 0.0, y: 4.0}; // explicit type let b = Point{x: 1.2, y: 3.4}; // type deduction let my_line = Line{start: a, end: b}; }extern crate pro...
Rust
0
value((_, value1): &(usize, &u32), (_, value2): &(usize, &u32)) -> Ordering { value1.cmp(value2) } fn highest_to_lowest(a: &u32, b: &u32) -> Ordering { b.cmp(a) } // //! Copyright 2020 Alibaba Group Holding Limited. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use th...
Rust
0
s`` subclasses during class creation. Subclasses of ``PropertyDescriptorFactory`` are responsible for implementing this function to return descriptors specific to their needs. """ raise NotImplementedError("make_descriptors not implemented") #----------------------------------...
Python
1
ETH_INTR_RING_SIZE: u32 = 1024; pub const RTE_EVENT_CRYPTO_ADAPTER_MAX_INSTANCE: u32 = 32; pub const RTE_EVENT_ETH_TX_ADAPTER_MAX_INSTANCE: u32 = 32; pub const RTE_RAWDEV_MAX_DEVS: u32 = 64; pub const RTE_LIBRTE_IP_FRAG_MAX_FRAG: u32 = 4; pub const RTE_MAX_LCORE_FREQS: u32 = 64; pub const RTE_SCHED_PORT_N_GRINDERS: u32...
Rust
0
, 0, 0, 0, 1, 1]; assert_eq!(&p.iter().map(|&p| d.inverse(p)).collect::<Vec<_>>(), &x); } #[test] fn kurtosis() { assert_eq!(new!(0.5).kurtosis(), -2.0); } #[test] fn mass() { let d = new!(0.25); assert_eq!( &(0..3).map(|x| d.mass(x)).collect::<Vec<_...
Rust
0
s://api.github.com/repos/BaseMax/GameNetSystemPHP/downloads', 'issues_url': 'https://api.github.com/repos/BaseMax/GameNetSystemPHP/issues{/number}', 'pulls_url': 'https://api.github.com/repos/BaseMax/GameNetSystemPHP/pulls{/number}', 'milestones_url': 'https://api.github.com/repos/BaseMax/GameNetSystemPHP/milestones{/n...
Python
1
['refresh_token'] expires_in = r['expires_in'] headers['Authorization'] = 'Bearer %s' % r['access_token'] r = requests.get('https://osu.ppy.sh/api/v2/me/fruits', headers=headers) user_data = r.json() print('Success! %s has successfully signed in with osu oauth.' % user_data['us...
Python
1
import pygame from pygame.locals import * from gl import Renderer from buffer import Buffer from shaders import * from model import Model width = 600 height = 600 pygame.init() screen = pygame.display.set_mode( (width, height), pygame.OPENGL | pygame.DOUBLEBUF) clock = pygame.time.Clock() renderer = Renderer(s...
Python
1
nt.set_client_identification( 'node', 'session' ) ns_client.on_warning = self.report_warning try: # output = execAny( ns_client, 'REREAD ' + jobID ) raise Exception( "Expected exception, got none (case 1)" ) except Exception as exc: if "Cannot re...
Python
1
} else { v.len() / 1024 } }; let pivot = frac / 2; let lo = v.len() / 2 - pivot; let hi = lo + frac; let gap = (v.len() - 9 * frac) / 4; let mut a = lo - 4 * frac - gap; let mut b = hi + gap; for i in lo..hi { let k = ninther( v, ...
Rust
0
"Happy", "Confident", "Curious", "Excited"]) negative_moods = sum(mood_vector.get(mood, 0) for mood in [ "Sad", "Anxious", "Frustrated", "Angry"]) sentiment_score = positive_moods - negative_moods ...
Python
1
uat"] gtk::RadioButton { label: "Uat", hexpand: true, mode: false, toggled => Msg::EnvironmentSelected(EnvironmentType::EnvUat), }, #[name="radio_prd"] gtk::RadioButton { label: "Prod", ...
Rust
0
s = get_or_create( session, Conditions, wind_speed=row["Wind Speed"], wind_direction=row["Wind Direction"], wind_gust=row["Wind Gust"] ) # Fact table: prevent duplicates by checking existing combination existing_fact = session.query(Fa...
Python
1
Talk( 0x101, "#00009F#4P哈哈,拜托你了。\x02", ) CloseMessageWindow() OP_6C(0x42CC, 0x5DC) FadeToDark(1000, 0, -1) OP_0D() Sound(9, 0, 100, 0) SetChrName("") OP_5B(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) AnonymousTalk( 0xFF, ( scpstr(0x7, 0x5), ...
Python
1
node.connection_messages.extend(connection_message.clone()); pending_connection_notifications.retain(|(addr_b, connection_message)| { if *addr_b == addr { node.telemetry_connection_notifier .push(connection_message.clone()); false } else { true } }); } }...
Rust
0
ect> { let js_this = ctx.this_unchecked::<JsObject>(); let store_ref: &mut napi::Ref<()> = ctx.env.get_instance_data()?.unwrap(); let store: JsObject = ctx.env.get_reference_value(store_ref)?; let ctor: JsFunction = store.get_named_property("ConstantSourceNode")?; ctor.new_instance(&[js_this]) } ...
Rust
0
import logging from sqlalchemy.orm import Session from evizent.api.data import db_session from evizent.models import Event, Venue # Assuming your Event model is in evizent.models import os from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() def update_single_venue_skybox_id(venue...
Python
1
use super::query::*; #[derive(Default)] pub struct QueriesCache { queries: DashMap<QueryId, QueryState>, } impl QueriesCache { pub fn add_query(self: &Arc<Self>, query_id: QueryId) -> PendingAdnlQuery { let barrier = Arc::new(Barrier::new(2)); let query = QueryState::Sent(barrier.clone()); ...
Rust
0
IPNDMScheduler(num_train_timesteps=steps) generator = torch.manual_seed(seed) noise = torch.randn([1, 2, config.sample_size], generator=generator).to(device) t = torch.linspace(1, 0, steps + 1, device=device)[:-1] step_list = get_crash_schedule(t) pipe = DanceDiffusionPipeline(unet=diffusers_mod...
Python
1
# Translates entries of RSS 2.0 (or ATOM) feed into different locale. # # Requires Python 3.10+. # # Make sure to have all dependencies installed: # pip3 install googletrans-py lxml bs4 httpx httpcore asyncio --upgrade # # You must provide raw RSS 2.0 (or ATOM) UTF-8 feed XML data as input, for example with curl: # ...
Python
1
xfb\xad\xbf\xc4C\x9f\xf8E\xe0\xde\ \xa3p9G\xa3\xd9\xbdi\xffS^\xf2\xb3\xbf\xc2w\ \xfc\xcc\xb7\x8c\xa8\x1a\xeb\x80q\x00\xeb\xf8\x81\xb2o\xf0\ \xd8\xf3\xcdD\xaf\xf2\xf77\x15O\xe8\x8a\xd6h$\x8d\ 4\xd2\xc8\x11\x95\xe7\xbc\xec\xd9\xcc\x9ez>\x9f}\xcf\ *\xea>\xdaX\xc8WWn\xe3\xa6;\xde\xc8\xf7\xfd\ \xde\xab\xb7|\xc1\x85\xe5\xcc&...
Python
1
black_list = ['j'] ochered=['a','g','j','k','x','n'] # for name in range(len(ochered)): # if len(ochered)==0: # break # else: # ochered.pop(0) # time+=1 # print(ochered, time) # print(time) def queque(ochered,time=0): time-=len(black_list) while True: if len(oche...
Python
1
sync def get_raw_event_by_id(self, event_id: str) -> Union[RawEvent, None]: """Get raw event by ID. Args: event_id: Raw event ID to retrieve Returns: RawEvent if found, None otherwise """ try: async with aiosqlite.connect(str(self.database_pa...
Python
1
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([...
Python
1
, HashValue::zero(), AccountAddress::ZERO, ), }; // Run prologue by genesis account session .as_mut() .execute_function( &account_config::TRANSACTION_MANAGER_MODULE, &PROLOGUE_NAME, ...
Rust
0
f._wakeup_thread() return # we're now either in limbo state waiting for thread to setup, # or no thread has been started if self._state == 'playing': # in limbo, just wait for thread to setup player return elif self._state == 'paused': # i...
Python
1
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class VideoTestimonio(models.Model): TIPO_VIDEO_CHOICES = [ ('local', 'Video Local'), ('youtube', 'YouTube'), ('vimeo', 'Vimeo'), ] titulo = models.CharField(max_length=200) ...
Python
1
ranted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, ...
Rust
0
ava::lang::String>>) -> __jni_bindgen::std::result::Result<__jni_bindgen::Local<'env, crate::org::w3c::dom::DOMException>, __jni_bindgen::Local<'env, crate::java::lang::Throwable>> { // class.path == "org/w3c/dom/DOMException", java.flags == PUBLIC, .name == "<init>", .descriptor == "(SLjava/lang/String;)V"...
Rust
0
)?)) } } pub struct IntPoint; impl IntPoint { pub fn pack(point: &[i32]) -> Vec<u8> { assert!(!point.is_empty()); let mut packed = vec![0u8; point.len() * 4]; for dim in 0..point.len() { IntPoint::encode_dimension(point[dim], &mut packed[dim * 4..]); } ...
Rust
0
ics::llvm_numeric("pow", kind, false); use crate::ast::ScalarKind::{F32, F64}; let c_name = match kind { F32 => "powf", F64 => "pow", _ => unreachable!(), }; let ret_ty = self.llvm_type(&Scalar(ki...
Rust
0
") # 步骤2:处理文档并创建向量存储 vector_store = process_documents(documents) # 步骤3:测试查询 test_queries = [ "什么是机器学习?", "人工智能的伦理考虑有哪些?", "自然语言处理的主要技术是什么?" ] all_results = [] for i, query in enumerate(test_queries, 1): print(f"\n{'='*60}") print(f"...
Python
1
IRECTIONS : [Direction; 6] = [ YZ, XZ, XY, ZY, ZX, YX ]; static ALL_ANGLES : [Angle; 6] = [ Forward, Right, RightBack, Back, LeftBack, Left]; /// Angle, relative to a Direction #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Ord, PartialOrd)] #[cfg_attr(feature="serde-serde", derive(Serialize, Deserialize))] pub enu...
Rust
0
import openai from openai import OpenAI client = OpenAI(api_key="") try: # API Key response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "system", "content": "hi!"}]) print("API Key is valid") except openai.AuthenticationError: print("API Key is not valid") except o...
Python
1
import time import pyautogui pyautogui.PAUSE = 0.70 time.sleep(3) # Importação for _ in range(1051): pyautogui.click(x=42, y=69) # clia em icon importr time.sleep(3) pyautogui.click(x=206, y=217) # Primeiro Arq time.sleep(3) pyautogui.press('enter') time.sleep(7) pyautogui.press('enter') #...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch class BalancedPositiveNegativeSampler(object): """ This class samples batches, ensuring that they contain a fixed proportion of positives """ def __init__(self, batch_size_per_image, positive_fraction): """ ...
Python
1
)) .call2(&JsValue::NULL, k, value) } #[wasm_bindgen] pub fn co_inject(k: &JsValue, default_value: &JsValue, treat_default_as_factory: &JsValue) -> Result<JsValue, JsValue> { let key = "inject"; util::get_vue_value(key) .dyn_ref::<Function>() .expect(&format!("{} is not a function", ke...
Rust
0
terator[GenerationChunk]: invocation_params = self._invocation_params(stop, **kwargs) for res in self.client.generate_stream(prompt, **invocation_params): # identify stop sequence in generated text, if any stop_seq_found: Optional[str] = None for stop_seq in invocati...
Python
1
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
Python
1
cm, 0.5 * cm)) # Set the title p = Paragraph( '<para align="center"><strong>%(description)s</strong></para>' % {'description': routine}, styleSheet['HeaderBold'], ) elements.append(p) elements.append(Spacer(10 * cm, 1.5 * cm)) # Iterate through the Workout and render the traini...
Python
1
} if success { Ok(()) } else { Err(AnimatePropertyError::NoValidProperties) } } <gh_stars>0 use self::super::super::isa::{GeneralPurposeRegisterBank, SpecialPurposeRegister}; use self::super::{MicroOpPerformError, MicroOp}; use self::super::super::vm::{Memory, Ports}; const FLAG_BIT_ZERO...
Rust
0
br = gc.CreateLinearGradientBrush(x1, y1, x2, y2, wx.BLACK, wx.WHITE) gc.SetBrush(br) gc.DrawRectangle(*r) dc.TextForeground = wx.WHITE dc.Font = default_font() j = int(ceil(sqrt(len(bitmaps)))) i = 0 for y in xrange(j): for x in xrange(j): ...
Python
1
node = int(input()) graph = [[0] * node for i in range(node)] for i in range(node): pass
Python
1
ered_incidences.append(row) return filtered_incidences def update_status_bar(self): current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.statusBar().showMessage(f"Fecha y Hora Actual: {current_time}") def apply_styles(self): title_font = QFont("Arial", 14, QFont...
Python
1
use crate::device::internals::RunResult::{Breakpoint, EoF, ProgError}; use crate::device::Dump; use anyhow::{Error, Result}; use chrono::{Local, Timelike}; use random_fast_rng::{FastRng, Random}; use std::cmp::Ordering; use std::fs::{File, OpenOptions}; use std::io::{Read, Seek, SeekFrom, Write}; use std::ops::{BitAnd...
Rust
0
_equivalent; let to_subaccount = Subaccount({ let mut sha = Sha256::new(); sha.write(b"my_account"); sha.finish() }); gov.disburse_neuron( &id, &from, &Disburse { amount: Some(Amount { e8s: 100000000 }), to_account: Some(AccountIdenti...
Rust
0
el, predicted_label in zip(test_corpus, test_labels, svm_tfidf_predictions): if label == 0 and predicted_label == 15: print 'Actual Label:', class_names[label] print 'Predicted Label:', class_names[predicted_label] print 'Document:-' print re.sub('\n', ' ', document) print ...
Python
1
} impl<'a> IntoRenderer<'a, ()> for InputObjectTypeRef { fn into_renderer(&'a self) -> Box<dyn Renderer<'a, ()> + 'a> { Box::new(DMMFObjectRenderer::Input(Weak::clone(self))) } } impl<'a> IntoRenderer<'a, ()> for ObjectTypeRef { fn into_renderer(&'a self) -> Box<dyn Renderer<'a, ()> + 'a> { ...
Rust
0
ed<String>, /// URL encoded contents of the Cookie header. #[metastructure(pii = "true", bag_size = "medium")] #[metastructure(skip_serialization = "empty")] pub cookies: Annotated<Cookies>, /// HTTP request headers. #[metastructure(pii = "true", bag_size = "large")] #[metastructure(skip_s...
Rust
0
ixStream; use {TlsMode, Error, BoxedFuture}; use error; use tls::TlsStream; pub type PostgresStream = Framed<Box<TlsStream>, PostgresCodec>; pub fn connect( host: Host, port: u16, tls_mode: TlsMode, handle: &Handle, ) -> Box<Future<Item = PostgresStream, Error = Error> + Send> { let inner = match...
Rust
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from functools import update_wrapper, wraps from django.db import models as m from django.utils.encoding import force_bytes import six from . import WeChatApp def create_shortcut(model): def method(func_or_name): def decorator(func): ...
Python
1
Debug, nested::{Display, Debug}}; impl Debug<|> for Foo { } ", ); } #[test] fn test_replace_split_common_target_longer() { check_assist( replace_qualified_name_with_use, " use std::fmt::Debug; impl std::fmt::nested::Display<|> for Foo { } ", " use std::...
Rust
0
.as_raw_handle() } } #[cfg(windows)] impl AsHandle for ArrayWriter { #[inline] fn as_handle(&self) -> BorrowedHandle<'_> { self.file.as_handle() } } #[cfg(windows)] impl AsRawHandleOrSocket for ArrayWriter { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { sel...
Rust
0
PINIT', 1)] + defs, include_dirs = include_dirs, libraries = libs, library_dirs = added_lib_dirs, ) self.extensions.append(ext) # XXX handle these, but how to detect? # *** Uncomment and edit for PIL...
Python
1
self.display_welcome() while True: try: user_input = input("> ").strip() if not user_input: continue result = self.process_input(user_input) if ...
Python
1
urn self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image ...
Python
1
(k - 1, 1); } } (basis, mapping) } #[cfg(test)] mod tests { use super::*; use approx::assert_abs_diff_eq; use ndarray::arr2; use ndarray_linalg::{error::LinalgError, InverseInto}; #[test] fn gram_schmidt_process() { let ortho = _gram_schmidt_process(&arr2(&[[...
Rust
0
import telebot import sqlite3 API_TOKEN = '7073988924:AAGlr3M6iIkFkZdFp-s3KN-NUh-781_a9MQ' bot = telebot.TeleBot(API_TOKEN) conn = sqlite3.connect('db/AUTO.db', check_same_thread=False) cursor = conn.cursor() def db_table_val_car(marka: str, model: str, year: int, power: int, liter: int, transmission: str, drive: s...
Python
1
from django.urls import path from . import views urlpatterns = [ path("available_slots/", views.available_slots_week, name="available_slots_week"), path("book_slot/", views.book_slot, name="book_slot"), path("cancel_bookin/", views.cancel_booking, name="cancel_booking"), path("my_bookings/", views.my_b...
Python
1
RequestCount.lock(); *remoteRecvRequestCount += count; // println!( // "CongestionControl +{}, *remoteRecvRequestCount: {}", // count, *remoteRecvRequestCount // ); self.ProcessRequestsInQueue(remoteRecvRequestCount); } } f...
Rust
0
# Copyright 2012-2015 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Handling of MAAS API credentials. The API client deals with credentials consisting of 3 elements: consumer key, resource token, and resource secret. These are in OAuth, b...
Python
1
# ============================================================================== # MIT License # # # Copyright 2022 Institute for Automotive Engineering of RWTH Aachen University. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
Python
1
= all_results[:cvemap_config["max_entry"]] with open(cvemap_json_path, "w", encoding="utf-8") as f: json.dump(all_results, f, indent=2) return all_results # ''' Second Search # 1. GitHub searcher for CVEs # 2. DocHandler for same directory as step 1, but different summary prompt and query. # Output: ...
Python
1
| s.len()) .unwrap_or(0); let mut i = 0; while i < min_len && strs .iter() .all(|s| s.chars().nth(i) == strs[0].chars().nth(i)) { i = i + 1; } strs[0][..i].to_string() } } #[cfg(test)] mod tests { use s...
Rust
0
plejwt.tokens.AccessToken',), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, } CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True # Only if HTTPS EMAIL_BACKEND = 'django.core.mail.backends.smtp.Email...
Python
1
edSample<T1,T2> { /// Constructor. pub fn new(label:Label, behavior:&T1, src:&T2) -> Self { let event = src.clone_ref(); let behavior = watch_stream(behavior); let definition = SampleData {behavior,event}; Self::construct_and_connect(label,src,definition) } } impl<T1:...
Rust
0
s2) .status() .expect("netns setup fail"); cmd!("ip", "link", "add", &name1, "type", "veth", "peer", "name", &name2, "netns", &ns2) .status() .expect("veth pair setup fail"); // Assign IP addresses and routes cmd!("ip", "addr", "add", ip1, "dev", ...
Rust
0
import gradio as gr def greet(nama): return "Halo " + nama + ", Selamat bergabung di IBM Academy!" demo = gr.Interface(fn=greet, inputs="text", outputs="text") demo.launch(server_name="0.0.0.0", server_port= 7860, share=True)
Python
1
t and converts it into a recipe :param file: ByteIO or any file like object, depends on provider :return: Recipe object """ raise NotImplementedError('Method not implemented in integration') def split_recipe_file(self, file): """ Takes a file that contains multiple r...
Python
1