text string | label_name string | labels int64 |
|---|---|---|
import simplejson as json
from .telegram_field import TelegramField
class TelegramHeader(object):
def __init__(self):
self._startField = TelegramField([0x68])
self._lField = TelegramField([0x00])
self._cField = TelegramField()
self._aField = TelegramField()
self._crcField =... | Python | 1 |
n(benchmark_dir, problem_file)):
self._exec_args = [os.path.join(benchmark_dir, problem_file)]
else:
raise RuntimeError("Input file not found: " + problem_file)
if not num_epochs is None:
self._exec_args.append(str(num_epochs))
if cores_per_node is None:
... | Python | 1 |
'''Escreva um programa que leia uma quantidade indeterminada de números inteiros, terminada pela leitura de um número 0 (zero). Depois, leia um valor inteiro constante. O programa deve mostrar uma nova lista onde cada valor da lista original é a multiplicado pelo valor da constante.
IMPORTANTE: Crie uma função chamada... | Python | 1 |
} else {
(1_000_000_000.0, "s")
};
if let Some(stddev) = stddev {
format!("{:.1}±{:.2}{}", nanos / div, stddev / div, label)
} else {
format!("{:.1}{}", nanos / div, label)
}
}
fn throughput(bytes_per_second: Option<f64>) -> String {
const MIN_KB: f64 = (2 * (1 << 10) as u64... | Rust | 0 |
from typing import List
# brut force approch
class Solution:
def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]:
if len(nums)==1:
return True
def isIntervalSpecial(start, end):
for i in range(start,end):
... | Python | 1 |
import os
import numpy
# numpy.show_config()
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import time
import numba
from numba import jit
from pyscf.lib.numpy_helper import zdot
def local_energy_generic_cholesky_opt_rhf(Ghalfa, rchola):
# Element wise multiplication.
nalpha = Gha... | Python | 1 |
// I don't think we have reason to believe the choice makes much of a
// difference in practice, we choose stable:
// - There are more users who use the stable version of Rust than on a
// nightly build, so we care more what the error messages look like on
// that version.
... | Rust | 0 |
tems['v'], items['m'])
def save(self, volume: vx.Volume, filename: os.PathLike) -> None:
"""
Write volume to a pytorch file.
Args:
volume (Volume): The volume to save.
filename (PathLike): The path to the pytorch file to write.
"""
features = volume.... | Python | 1 |
ANDELA),
("₩", &*SOUTH_KOREAN_WON),
("fluid_ounce", &*FLUID_OUNCE),
("ft", &*FOOT),
("BTU/lb", &*BTU_PER_POUND),
("LRD", &*LIBERIAN_DOLLAR),
("₪", &*NEW_ISRAELI_SHEKEL),
("R$", &*BRAZILIAN_REAL),
("₮", &*TUGRIK),
("bahamian_dollar", &*BAHAMIAN_DOLL... | Rust | 0 |
[0m", vu, vd, self.vids);
//self.validate(format!("after swapping vd:{:?} with vu:{:?}", vd, vu).as_str());
let mut work:Vec<(WID, Q)> = vec![];
// tell anyone waiting on rd that they can resume work
debug_assert!(!alarm.contains_key(&vd), "alarm should never be placed on a downward-moving row.");
... | Rust | 0 |
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from PyQt6.QtCore import Qt
class AboutDialog(QDialog):
def __init__(self, settings=None, parent=None):
super().__init__(parent)
self.setObjectName("SettingsDialog")
self.setWindowTitle("About FFMigo")
... | Python | 1 |
import numpy as np
import tensorflow as tf
import os
from sklearn.model_selection import train_test_split
import pickle
import matplotlib.pyplot as plt
import time
import datetime
import model.movie_nn as movie_nn
import model.user_nn as user_nn
tf.reset_default_graph()
train_graph = tf.Graph()
features = pickle.... | Python | 1 |
5MHz-5% use GMII mode
).Else(
mode.eq(0)
),
NextState("IDLE")
)
class LiteEthPHYGMIIMII(Module, AutoCSR):
def __init__(self, clock_pads, pads, clk_freq):
# Note: we can use GMII CRG since it also handles tx clock pad used for MII
self.sub... | Python | 1 |
et = crate::W<MISC_POR_1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<MISC_POR_1_SPEC>> for W {
#[inline(always)]
... | Rust | 0 |
#[doc = "< Path nodes"]
pub n: [*mut ::std::os::raw::c_char; 1usize],
}
#[test]
fn bindgen_test_layout__JBL_PTR() {
assert_eq!(
::std::mem::size_of::<_JBL_PTR>(),
24usize,
concat!("Size of: ", stringify!(_JBL_PTR))
);
assert_eq!(
::std::mem::align_of::<_JBL_PTR>(),
... | Rust | 0 |
event_seal {
pub trait Seal {
#[doc(hidden)]
fn as_web_sys_ui_event(&self) -> &web_sys::UiEvent;
}
}
pub trait UiEvent: ui_event_seal::Seal {
fn view(&self) -> Option<Window> {
self.as_web_sys_ui_event().view().map(|w| w.into())
}
}
macro_rules! impl_ui_event_traits {
($tpe... | Rust | 0 |
from sympy.core import sympify, Symbol
x = Symbol('x')
def timeit_sympify_1():
sympify(1)
def timeit_sympify_x():
sympify(x)
| Python | 1 |
ls[gts['model_list'][j]].astype(np.float32)
# all_pts.append(torch.FloatTensor(instance_pts))
# all_rgb.append(torch.FloatTensor(instance_rgb))
# all_nocs.append(torch.FloatTensor(instance_nocs))
# all_models.append(torch.FloatTensor(model))
# ... | Python | 1 |
= grasps[keep], conf[keep]
if args.k is not None and grasps.shape[0] > args.k:
indices = torch.topk(conf, args.k).indices
grasps, conf = grasps[indices], conf[indices]
print(f"Total grasps visualised: {grasps.shape[0]} (mask_thresh={args.mask_thresh})")
# # ── visualise ------------------... | Python | 1 |
&self.file)?;
}
if !self.country_code.is_empty() {
os.write_string(2, &self.country_code)?;
}
os.write_unknown_fields(self.special_fields.unknown_fields())?;
::std::result::Result::Ok(())
}
fn s... | Rust | 0 |
er;
//!
//! fn main() {
//! let nds_parser = match NDSParser::try_from("path/to/some.nds") {
//! Ok(parsed) => parsed,
//! Err(err) => println!("Houston, we've got a problem: {}", err),
//! };
//! }
//! ```
use std::convert::{TryFrom, TryInto};
use std::fs::File;
use std::io::Read;
// == Error... | Rust | 0 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import UserViewSet
from .views import FriendRequestViewSet, FriendshipViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'friend_requests', FriendRequestViewSet)
router.register(r'f... | Python | 1 |
_arr.get(0)? {
Val::Sym(QUESTION_MARK_SYM) => {
ensure_at!(span, (param_arr.len() == 2 || param_arr.len() == 3) &&
param_arr.get::<Val>(1)?.is_sym() &&
param_arr.get::<Val>(1)? != Val::Sym(UNDERSCORE_SYM),
"invalid param {} in (fn) special form", &pa... | Rust | 0 |
Encode, Decode, FullCodec};
use sp_std::prelude::*;
use frame_support::{
RuntimeDebug, weights::Weight, Twox64Concat,
storage::types::{StorageMap, StorageValue},
traits::{GetPalletVersion, PalletVersion},
};
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq)]
struct SeatHolder<AccountId, Balance> {
... | Rust | 0 |
aps']
all_vis = []
for i, img in enumerate(imgs):
img = img.astype(np.uint8)
this_img_boxes = pred_bounding_boxes[i] * img.shape[0]
this_img_boxes = this_img_boxes.astype(np.int32)
this_img_cls_heatmap = np.tile(pred_cls_heatmaps[i][..., None], (1, 1, 3)) ... | Python | 1 |
eateOrUpdateOrgSecret::from_json(body)?),
method: "PUT",
headers: vec![]
};
let request = GitHubRequestBuilder::build(req, self.auth)?;
// --
let github_response = crate::adapters::fetch_async(request).await?;
// --
if github_response.is_succe... | Rust | 0 |
8hw\xa2bYl\xd8\xb0at\
\xb4\xe8\xc2\xd8e1\xa7Sr\xa8\x99\xba\x8d\xd3\x92\xb6\
x\xcd\xa1V\x8a\xf4\x0a(\xc8:]J@\x06|4\
\x81\x92\xcas\xe7\xce\x95zaN3\xcao\x81\xea\x96\
(\xc6\xf6_Th\xa3\xd9\x1d\xd74T,\xd3B>\
F'n\xab!3\xb1\x13\xcf\xa9V\x90\x0am\xa5P\
\xd9\xb6m\x1b\xb5\xc2\xc3o\x02s\x90\xc5w\x82\xee\x5c\
\x0d\x13\xc1\xd2d\xa3F... | Python | 1 |
ce','damageDealtToBuildings','damageSelfMitigated','goldEarned','totalDamageDealtToChampions','totalDamageShieldedOnTeammates','totalDamageTaken','totalHealsOnTeammates','totalMinionsKilled','visionScore','dragonTakedowns'])
with open(file_namekr, mode='w', newline='', encoding='utf-8') as file:
writer = ... | Python | 1 |
torque on body_b in n*m.
fn get_reaction_torque(&self, inv_dt: f32) -> f32;
/// dump this joint to the log file.
fn dump(&self) {
//b2Log("// dump is not supported for this joint type.\n");
}
/// Shift the origin for any points stored in world coordinates.
fn shift_origin(&mut self, new_origin: B2vec2) {
b2... | Rust | 0 |
# Настраиваем после файла file_handing
"""файл со словарем соответствий команд и запросов отображаемым текстам. То есть, например,
если пользователь отправил команду /start - ему должен прийти обратно какой-то текст.
Этот текст может меняться со временем или в зависимости от языка пользователя.
Удобно хранить такие соо... | Python | 1 |
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"BUY" => Ok(ComboAction::Buy),
"SELL" => Ok(ComboAction::Sell),
"SSELL" => Ok(ComboAction::ShortSell),
&_ => Err(ParseEnumError)
}
}
}
impl Decodable for ComboAction { }
#[derive(Debug,Clone... | Rust | 0 |
count", "Number of service restarts").expect("Failed to create prometheus metric");
}
#[derive(Clone, Debug)]
struct AverageTracker {
total: u64,
count: u64,
}
#[derive(Clone, Debug)]
struct StatefulGauge<T: Clone> {
gauge: Gauge,
data: Arc<RwLock<T>>,
}
#[derive(Clone, Debug)]
struct BtcBalance {
... | Rust | 0 |
# How do you prevent a python print() function to print a new line at the end.
print("Harsh")
print("Dev")
print("Rahul",end="")
print("Sachin", end="") | Python | 1 |
".join(c for c in TASK_MAPPING.keys())
)
)
def round_stsb_target(label):
"""STSB maps two sentences to a floating point number between 1 and 5
representing their semantic similarity. Since we are treating all tasks as
text-to-text tasks we need to convert this floating point number to ... | Python | 1 |
b = spawn_local(async { block_on(async { ready(2).await }) }).await;
let c = block_on(async { block_on(async { ready(1).await }) });
a + b + c
});
assert_eq!(x, 3 + 2 + 1);
let y = block_on(async {
let a = block_on(async { block_on(async { ready(3).await }) });
let b = spa... | Rust | 0 |
args.led1.set_high();
args.led2.set_low();
args.timer.wait(1);
args.led1.set_low();
args.led2.set_high();
args.timer.wait(1);
}
}
<gh_stars>0
use crate::graphics::WindowContext;
use crate::world::GameWorld;
pub struct Context {
pub window: WindowContext,
pub world: GameWorld,
}
im... | Rust | 0 |
{
conn.query(format!("INSERT INTO Cats (id) VALUES ({})", i))
.unwrap();
sleep();
}
{
let deleted = conn
.query("DELETE FROM Cats WHERE Cats.id = 1 OR Cats.id = 2")
.unwrap();
assert_eq!(deleted.affected_rows(), 2);
sleep();
}
... | Rust | 0 |
source}/{operation}.
:paramtype name: str
:keyword display: The object that represents the operation.
:paramtype display: ~azure.mgmt.resource.features.v2015_12_01.models.OperationDisplay
"""
super().__init__(**kwargs)
self.name = name
self.display = display
cla... | Python | 1 |
from maascommon.enums.scriptresult import ScriptStatus
from maasservicelayer.builders.scriptresult import ScriptResultBuilder
from maasservicelayer.context import Context
from maasservicelayer.db.filters import QuerySpec
from maasservicelayer.db.repositories.scriptresults import (
ScriptResultClauseFactory,
Scr... | Python | 1 |
SystemState {
archetype_accesses: Vec<ArchetypeAccess>,
commands: Commands,
}
/// Converts `Self` into a Query System
pub trait IntoQuerySystem<Commands, R, Q> {
fn system(self) -> Box<dyn System>;
}
macro_rules! impl_into_query_system {
(($($commands: ident)*), ($($resource: ident),*), ($($query: ide... | Rust | 0 |
new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here ar... | Rust | 0 |
core::{
algebra::{Matrix4, Point3, Vector2, Vector3},
arrayvec::ArrayVec,
math::{
aabb::AxisAlignedBoundingBox, ray::Ray, ray_rect_intersection, Rect, TriangleDefinition,
},
pool::Handle,
visitor::{prelude::*, PodVecView},
},
resource::texture::{Tex... | Rust | 0 |
(0xBA, 0x06, 0x00),
Rgb(0x8C, 0x17, 0x00),
Rgb(0x5C, 0x2F, 0x00),
Rgb(0x10, 0x45, 0x00),
Rgb(0x05, 0x4A, 0x00),
Rgb(0x00, 0x47, 0x2E),
Rgb(0x00, 0x41, 0x66),
Rgb(0x00, 0x00, 0x00),
Rgb(0x05, 0x05, 0x05),
Rgb(0x05, 0x05, 0x05),
Rgb(0xC7, 0xC7, 0xC7),
Rgb(0x00, 0x77, 0xFF),
... | Rust | 0 |
bounds[0], bounds[1]);
Ok(())
}
fn has_same_adjacent_digits(mut val: u32, larger_group_allowed: bool) -> bool {
let mut last_digit = None;
let mut group_len = 1;
while val > 0 {
let digit = val % 10;
if let Some(prev) = last_digit {
if prev == digit {
if la... | Rust | 0 |
ef p) = closest_path {
if p.len() >= 2 {
Some(p[1] - p[0])
} else {
None
}
} else {
None
};
}
if periphery[0].len() > maxdist {}
... | Rust | 0 |
rsStr = "" # 变量string
self.varsPool = {} # 变量dict 变量池,包括varsPre的和varsPost的
self.headerDict = {} # header json字符串转换成的dict
@catch_exception
def generateByCaseStepDebugData(self):
"""
根据步骤debug表的id获取步骤
Returns:
无
"""
if self.caseStepDe... | Python | 1 |
();
assert_no_error(JsGetGlobalObject(&mut global));
let console_string = CString::new("console").unwrap();
let mut console_prop_id = ptr::null_mut();
assert_no_error(JsCreatePropertyId(
console_string.as_ptr(),
console_string.as_bytes().le... | Rust | 0 |
import ctypes, typing, collections.abc as abc
from . import SDL_FUNC, SDL_BINARY
SDL_CACHELINE_SIZE: int = 128
SDL_GetNumLogicalCPUCores: abc.Callable[..., typing.Any] = SDL_FUNC["SDL_GetNumLogicalCPUCores", ctypes.c_int, [], SDL_BINARY]
SDL_GetCPUCacheLineSize: abc.Callable[..., typing.Any] = SDL_FUNC["SDL_GetCPUCa... | Python | 1 |
"blue ", aver::colors::reset(), aver::colors::on_blue(), "on blue", aver::colors::reset(), "\n");
log!(aver::colors::magenta(), "magenta ", aver::colors::reset(), aver::colors::on_magenta(), "on magenta", aver::colors::reset(), "\n");
log!(aver::colors::white(), "white ", aver::colors::reset(), av... | Rust | 0 |
4,
}
impl NlAttrType for Nl80211Ac {}
/// nl80211ChannelType
///
/// Enumeration from nl80211/nl80211.h:3464
#[neli_enum(serialized_type = "u16")]
pub enum Nl80211ChannelType {
ChanNoHt = 0,
ChanHt20 = 1,
ChanHt40minus = 2,
ChanHt40plus = 3,
}
impl NlAttrType for Nl80211ChannelType {}
/// nl80211Cha... | Rust | 0 |
# %%
"""
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Visualization/image_color_palettes.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a t... | Python | 1 |
s: vec![],
auto_ty: AutoTy::Tuple { fields: vec![] },
source_origin: SourceOrigin {
rule_id: rule_id,
rule_pos: vec![rhs_start_pos],
}
}
}
}
impl FlattenRhsAst {
fn new(lhs: Name, rule_id: u32) -> Self {
FlattenRhsAst {
... | Rust | 0 |
0,
#[doc = "Divide-by-12."]
_1011,
#[doc = "Divide-by-13."]
_1100,
#[doc = "Divide-by-14."]
_1101,
#[doc = "Divide-by-15."]
_1110,
#[doc = "Divide-by-16."]
_1111,
}
impl OUTDIV1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
... | Rust | 0 |
, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use sp_std::{prelude::*};
use sp_runtime::{DispatchResult, DispatchError};
use frame_support::{decl_module, decl_storage, decl_event, decl_error, ensure};
use frame_support::traits::Get... | Rust | 0 |
defined(ENABLE_PURECFMA_SCALAR)
let w = s;
}*/
let q = vsel_vi_vd_vi(s, Ix::splat(2));
s = s.abs();
let q = vsel_vi_vd_vd_vi_vi(ONE, s, q + Ix::splat(1), q);
s = ONE.lt(s).select(s.recpre(), s);
let mut t = s * s;
le... | Rust | 0 |
, u128));
// Converting from signed types. These are straight conversions.
signed_to_unsigned!(u8, (i8));
signed_to_unsigned!(u16, (i8, i16));
signed_to_unsigned!(u32, (i8, i16, i32));
signed_to_unsigned!(u64, (i8, i16, i32, i64));
signed_to_unsigned!(u128, (i8, i16, i32, i64, i128, isize));
signed_to_unsigned!(usiz... | Rust | 0 |
"""
Set covering in cpmpy.
Example 9.1-2, page 354ff, from
Taha 'Operations Research - An Introduction'
Minimize the number of security telephones in street
corners on a campus.
This cpmpy model was written by Hakan Kjellerstrand (hakank@gmail.com)
See also my cpmpy page: http://hakank.org/cpmpy/
"""
from cpmpy i... | Python | 1 |
from audio_recorder import AudioRecorder
from google_meet_connector import GoogleMeetConnector
from speech_rec import SpeechRecognition
from summarizer import Summarizer
import threading
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class MeetBot:
def ... | Python | 1 |
-87.3 1 0.00 438.4 438.4 438.4
84.5 17200 -54.5 -87.5 1 0.00 443.0 443.0 443.0
75.3 17932 -59.5 -90.5 1 0.00 447.3 447.3 447.3
70.0 18390 -58.7 -89.7 1 0.00 458.5 458.5 458.5
68.7 18507 -59.3 -90.3 ... | Rust | 0 |
op: DataValueLogicOperator,
}
impl LogicFunction {
pub fn register(factory: &mut FunctionFactory) {
factory.register("and", LogicAndFunction::desc());
factory.register("or", LogicOrFunction::desc());
factory.register("not", LogicNotFunction::desc());
}
pub fn try_create_func(o... | Rust | 0 |
import timeit # used to measure times
mode = int(input("Select mode: \n\t0 to generate for N\n\t1 to generate for range 2 to N\nMode: "))
if mode == 1:
start = 2 # starting N value, change this to limit your generation range
end = int(input("ending bit length: "))+1 # ending N value, user input
else:
start ... | Python | 1 |
class Solution:
def getAverages(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
size = 2 * k + 1
ans = [-1] * n
if size > n:
return ans
summ = sum(nums[:size])
for i in range(k, n - k):
ans[i] = summ // size
if i + k + 1 < n:
summ += nums[i + k + 1] - num... | Python | 1 |
let maybe_block = self.blocked.lock().clone();
if let Some(block) = maybe_block {
block.notified().await;
}
// maybe panic
if self.panic.lock().remove(&k) {
panic!("test");
}
k.to_string()
}
... | Rust | 0 |
schema_type,
} => {
update_schema(
id,
name,
insert_destination,
query_address,
schema_type,
args.registry_addr,
)
.await
... | Rust | 0 |
#!/usr/bin/env python
##########################################################################
# mycroft-systemd_messagebus.py
#
# 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://... | Python | 1 |
import importlib
#################################################
## MAIN TRAINING ROUTINE
#################################################
def learn_model(config, dset, epoch=1, seed=None, verbose=1):
model_module = importlib.import_module("plugins.models.{}".format(config["train"]["model"]["name"]))
crop... | Python | 1 |
}
Some(Self::new(
"s",
v[4],
v[5],
&format!("/{}", v[6..].join("/")),
))
}
}
<filename>components/tidb_query_codegen/src/aggr_function.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use ::darling::FromDeriveInput;
use quote::qu... | Rust | 0 |
from typing import TYPE_CHECKING
import numpy
from .. import registry
from .numpy_ops import NumpyOps
from .ops import Ops
if TYPE_CHECKING:
# Type checking does not work with dynamic base classes, since MyPy cannot
# determine against which base class to check. So, always derive from Ops
# during type c... | Python | 1 |
FFBRLL
BFFBFFBRRL
BFBBBBBRLR
BBFBBBFLLL
FFBFFFBLLR
FFBFFBFRLL
FFFBBBFLLR
FFBFBBBRLR
BFBFBBBRLL
BFFBBBBRLR
FBBBBFFRRL
FFFBBFFRLR
BBFFBFBLLL
BBBFFBFLLR
FFBBBBFRLL
BBFFBFBLLR
BFBFBBBRLR
FFBFFFFRRL
BFBFFFFRLL
BBBFFFFLLL
BFFBBFFLLR
FBBFBFFLLR
FFBFBFBRLR
FBBBBBFRLL
FBBFFFBRLR
BBFFFBBLLR
BFFBFBBRLR
FFFBFBBRLL
BFBBFFFRRL
BBFBF... | Rust | 0 |
{}", &opts.cron);
for datetime in schedule.upcoming(Utc) {
info!("check certificate of {} at {}", opts.domain_names, datetime);
loop {
if Utc::now() > datetime {
break;
} else {
tokio::time::sleep(Duration::from_millis(999)).await;
... | Rust | 0 |
t operation = if let Some(Input::Character(input)) = self.get_input() {
self.current_processor_mut().borrow_mut().decode(input)?
} else {
Operation::maintain()
};
if let Some(notification) = self.explorer.borrow_mut().receive_notification() {
self.pane.borrow... | Rust | 0 |
ars().enumerate() {
match ch {
'F' => {
let res = rem / 2;
range.1 -= res + 1;
rem = res;
}
'B' => {
let res = rem / 2;
range.0 += res + 1;
... | Rust | 0 |
se super::*;
#[test]
fn test_intersect() {
let sphere = Sphere::new(
Point3::new(1.0, 1.0, 1.0),
1.0,
Diffuse::new(Color::new(1.0, 1.0, 1.0), 1.0).into(),
);
let ray = Ray {
source: Point3::new(0.0, 0.0, 0.0),
direction: Vector... | Rust | 0 |
:protobuf::ProtobufEnum for IPFamily {
fn value(&self) -> i32 {
*self as i32
}
fn from_i32(value: i32) -> ::std::option::Option<IPFamily> {
match value {
0 => ::std::option::Option::Some(IPFamily::v4),
1 => ::std::option::Option::Some(IPFamily::v6),
_ => ... | Rust | 0 |
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from .models import Choice, Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pu... | Python | 1 |
vm-config path.
#[structopt(long)]
pub use_llvm: Option<CMakeSetting>,
/// Enable TVM's stackvm in the runtime.
#[structopt(long)]
pub use_stackvm_runtime: Option<bool>,
/// Build with graph runtime, defaults to ON.
#[structopt(long)]
pub use_graph_runtime: Option<bool>,
/// Build wi... | Rust | 0 |
DeserializeOwned};
use failure::{Fail, Backtrace};
use crate::serde_polyfill::MessagePolyfill;
use crate::{Proposal, Answer, MachineCore};
#[derive(Debug, Serialize, Deserialize)]
pub enum TransportItem<M: MachineCore, A: Address> {
#[serde(bound(deserialize = "Proposal<M>: Deserialize<'de>"))]
#[serde(bound(... | Rust | 0 |
lize)]
#[serde(tag = "type")]
pub enum Idp2pAgreementKey {
Idp2pX25519 {
#[serde(with = "encode_vec")]
public: Vec<u8>,
},
}
impl Idp2pKey {
pub fn new(code: u64, public: &[u8]) -> Result<Self> {
match code {
ED25519_CODE => Ok(Idp2pKey::Idp2pEd25519 {
pu... | Rust | 0 |
+ 4]);
let t10 = t0 + t3;
let t12 = t0 - t3;
let t11 = t1 + t2;
let t13 = t1 - t2;
let t0 = i32::from(samples[y0]) - i32::from(samples[y0 + 7]);
let t1 = i32::from(samples[y0 + 1]) - i32::from(samples[y0 + 6]);
let t2 = i32::from(samples[y0 + 2]) - i32::from(sa... | Rust | 0 |
in game.messages.iter().rev() {
let msg_height = measure_text(msg, TILE_HEIGHT) as f32 / (MSG_WIDTH * TILE_WIDTH) as f32;
let msg_height = msg_height.ceil() as i32;
y -= msg_height;
if y < 0 {
break;
}
let color: Color = color.into();
d.draw_text(
... | Rust | 0 |
default(), Single).await?;
Ok(())
}
// We read stream events by batch. We also test if we can properly read a
// stream thoroughly.
async fn test_read_stream_events(client: &Client) -> Result<(), Box<dyn Error>> {
let stream_id = fresh_stream_id("read_stream_events");
let events = generate_events("es6-rea... | Rust | 0 |
family = family_name.to_wide_null();
let family = family.as_ptr();
let mut idx = 0;
let mut exists = 0;
let hr = self.ptr.FindFamilyName(family, &mut idx, &mut exists);
if SUCCEEDED(hr) && exists != 0 {
Some(idx)
} else {
... | Rust | 0 |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pickle
fn = '100_samples.pkl'
with open(fn, 'r') as f:
results = pickle.load(f)
reinf_fs, reinf_cs, rep_cs, zlaxs = results
min_val = -3#np.min(np.concatenate([reinf_fs, reinf_cs, rep_cs, zlaxs]))
max_val = 3#np.max(np.concatenat... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path("", views.indice, name="indice"),
path("iniciarSesion", views.iniciarSesion, name="iniciar_sesion"),
path("cerrarSesion", views.cerrarSesion, name="cerrar_sesion"),
path("registrarse", views.registrarse, name="registrarse"),
pat... | Python | 1 |
lice_epub, tag = rspns[0], rspns[1:34], rspns[34:]
if bytes([hver]) != hs.handshake_version:
raise HandshakeFailed("unexpected handshake version: {}".format(hver))
# act 2
hs.update(alice_epub)
ss = get_ecdh(epriv, alice_epub)
ck, temp_k2 = get_bolt8_hkdf(hs.ck, ss)
... | Python | 1 |
t.
pub fn into_inner(self) -> Result<U, T> {
// We don't need to inspect `self.initialized` since `self` is owned
// so it is guaranteed that no other threads are accessing its data.
match unsafe { self.value.into_inner().unwrap() } {
ThisOrThat::This(t) => Err(t),
Th... | Rust | 0 |
: Duration,
) -> Result<(), Error> {
setsockopt_duration(
self.as_mut_ptr(),
SocketOption::HeartbeatInterval,
duration,
)
}
pub(crate) fn set_heartbeat_timeout(
&self,
duration: Duration,
) -> Result<(), Error> {
setsockopt_dur... | Rust | 0 |
io0_9;
#[doc = "I/O configuration for pin SWCLK/PIO0_10/ SCK0/CT16B0_MAT2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [A... | Rust | 0 |
r().map(|x| x.as_ref()).collect(), output.as_ref()))
.collect();
let all_unpaired: Vec<Vec<&str>> = examples
.clone()
.into_iter()
.map(|(row, _)| row)
.chain(unpaired.into_iter())
.collect();
let graph = InputDataGraph::new(&all_unpaired);
let dag = Dag::lear... | Rust | 0 |
n = int(input())
line = list(map(int, input().split()))
sum_left = 0
sum_right = sum(line)
state = False
index = 0
for i in range(n):
sum_left += line[i]
sum_right -= line[i]
if sum_left == sum_right:
state = True
index = i+1
break
if state:
print(index)
else:
print('Andr... | Python | 1 |
tern(name= 'Q1a')
modelSpace.setCurrentLoadPattern(q1a.name)
trackCrossSection= trackAxis.getTrackCrossSection()
nodalLoads= trackAxis.defDeckCentrifugalLoadOnRailsThroughLayers(trainModel= trainLoadModel, relativePosition= 0.5, v= v, Lf= Lf, r= r, trackCrossSection= trackCrossSection, spreadingLayers= spreadingLayers,... | Python | 1 |
msg.hostname, parsed.hostname));
assert_eq!(msg.appname, parsed.appname);
assert_eq!(msg.procid, parsed.procid);
assert_eq!(msg.msgid, parsed.msgid);
assert_eq!(msg.structured_data, parsed.structured_data);
assert_eq!(msg.msg, parsed.msg);
// Do we still have the same message?
quickcheck::T... | Rust | 0 |
# Copyright HeteroCL authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from hcl_mlir.exceptions import HCLNotImplementedError
class Pass:
"""Base class for all intermediate pass.
A pass is a visitor that can mutate the Intermediate Layer.
"""
def __init__(self, name):
self... | Python | 1 |
fle', 'ice cream', 'ice lolly', 'French loaf', 'bagel', 'pretzel', 'cheeseburger', 'hotdog', 'mashed potato', 'head cabbage', 'broccoli', 'cauliflower', 'zucchini', 'spaghetti squash', 'acorn squash', 'butternut squash', 'cucumber', 'artichoke', 'bell pepper', 'cardoon', 'mushroom', 'Granny Smith', 'strawberry', 'orang... | Python | 1 |
# Generated by Django 5.0.3 on 2024-03-04 16:32
import os
from pathlib import Path
from django.db import migrations, transaction
from django.db.models import F
from decks.exceptions import MalformedDeckException
@transaction.atomic
def create_new_deck(user, deck_form: dict):
decklist = deck_form["decklist"]
... | Python | 1 |
import ctypes
class WhisperFullParams(ctypes.Structure):
_fields_ = [
("strategy", ctypes.c_int),
#
("n_max_text_ctx", ctypes.c_int),
("n_threads", ctypes.c_int),
("offset_ms", ctypes.c_int),
("duration_ms", ctypes.c_int),
#
("translate", ctypes.c_bo... | Python | 1 |
Add => Operation::Add,
Token::Sub => Operation::Sub,
Token::Div => Operation::Div,
Token::Mod => Operation::Mod,
Token::Mul => Operation::Mul,
Token::BitAnd => Operation::BitAnd,
Token::BitLShift => Operation::BitLShift,
Token::BitOr =>... | Rust | 0 |
/ times from `FrameStream::wait` and `Action::state` instead.
#[inline]
#[cfg(windows)]
pub fn now(&self) -> Result<Time> {
unsafe {
let mut now = MaybeUninit::uninit();
winapi::um::profileapi::QueryPerformanceCounter(now.as_mut_ptr());
let now = now.assume_init()... | Rust | 0 |
# Copyright (c) 2010-2017 Samuel Abels
#
# 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, d... | Python | 1 |
16 => i32}
impl_signed_cmp! {u16 => i64}
impl_signed_cmp! {u16 => i128}
impl_signed_cmp! {u32 > i8}
impl_signed_cmp! {u32 > i16}
impl_signed_cmp! {u32 > i32}
impl_signed_cmp! {u32 => i64}
impl_signed_cmp! {u32 => i128}
impl_signed_cmp! {u64 > i8}
impl_signed_cmp! {u64 > i16}
impl_signed_cmp! {u64 > i32}
impl_signed_c... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.