text string | label_name string | labels int64 |
|---|---|---|
import xml.etree.ElementTree as ET
import urllib.request
import json
from bibliothecula import *
from bibliothecula.models import *
# Run this in the django shell!
# python3 manage.py shell
# exec(open('standardebooks.py').read())
# Max books to download
MAX_BOOKS = 30
# Download this from https://standardebooks.org/... | Python | 1 |
nome = 'José'
idade = 33
print(f'O {nome} tem {idade} anos.') # python 3.6+
print('O {} tem {} anos.'.format(nome, idade)) # python 3 | Python | 1 |
PU memory)'
)
parser.add_argument(
'--benchmark',
action='store_true',
help='Benchmark GPU vs CPU performance and exit'
)
parser.add_argument(
'--gpu-info',
action='store_true',
help='Show GPU infor... | Python | 1 |
YES" || state == *"NO" {
break state;
}
println!("Please write either yes or no.");
};
return matches!(state.as_str(), "YES");
}
// Copyright (c) 2017, <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is h... | Rust | 0 |
q!(
result.unwrap_err().iter().nth(0).unwrap().description(),
"Failed to render \'child\' (error happened in 'parent')."
);
}
#[test]
fn error_location_in_parent_block() {
let mut tera = Tera::default();
tera.add_raw_templates(vec
/// to increme... | Rust | 0 |
# Copyright (C) 2018-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.front.common.partial_infer.utils import reverse_bypass_infer
from openvino.tools.mo.graph.graph import Graph
from openvino.tools.mo.ops.op import Op
class Reverse(Op):
op = 'Reverse'
... | Python | 1 |
# BGRABitmap Assistant: https://chat.openai.com/g/g-FO7aiutRx-bgrabitmap-assistant
# This program extracts method signatures in BGRABitmap to help provide accurate examples
import os
import re
def gather_method_signatures(source_dir):
print("Source directory:", source_dir)
regexMethod = r"(?P<proc_or_fun>proc... | Python | 1 |
get_addon:
return {"CANCELLED"}
preferences = context.preferences.addons["amaranth"].preferences
if preferences.use_framerate:
framedelta = scene.render.fps
else:
framedelta = preferences.frames_jump
if self.forward:
scene.frame_current ... | Python | 1 |
executable name \"{}\" use env \"{}\" to specify otherwise",
executable,
LIBREOFFICE_ENV,
),
},
LibreOfficeError::ExecutionFailed(input, output, err) => write!(
f,
"couldn't convert {} to {}, {}",
... | Rust | 0 |
import unittest
from ..src.the_observed_pin import get_pins
class TestGetPins(unittest.TestCase):
def test_get_pins_with_single_digit(self):
observed = '1'
expected = ['1', '2', '4']
self.assertEqual(sorted(get_pins(observed)), sorted(expected))
def test_get_pins_with_two_digits(self... | Python | 1 |
import logging
from utils.scan.menu import scan_menu
from mcp.server.fastmcp import FastMCP
from utils.scan.desktop import scan_desktop
logger = logging.getLogger('扫描统计')
def scan_statistics(mcp: FastMCP):
@mcp.tool()
def scan_statistics(file_or_program: str) -> dict:
"""用于扫描桌面以及菜单的程序跟目录,当需要查询桌面或菜单文件或... | Python | 1 |
> {
writeln!(
f,
"{:#x} {}",
process_create_time,
format_time_t(process_create_time),
)?;
}
None => writeln!(f, "(invalid)")?,
}
write!(f, " process_user_time ... | Rust | 0 |
# solvers_p5/p5_components.py
import numpy as np
from pymoo.core.problem import ElementwiseProblem
from pymoo.core.sampling import Sampling
from pymoo.core.repair import Repair
class AssignmentProblem(ElementwiseProblem):
def __init__(self, evaluator):
self.evaluator = evaluator
# 15个决策变量 (5架无人机 *... | Python | 1 |
]
# replace shifts with unsigned shifts (as only unsigned shift happen)
content = content.replace(">>", "@")
# if the function returns declare our res variable
if prefix == "return":
content = "res = "+content
# just run the modified C l... | Python | 1 |
reate();
if (*(*tp).worker_threads.offset(i as isize)).cond.is_null() {
opj_mutex_destroy((*(*tp).worker_threads.offset(i as isize)).mutex);
(*tp).worker_threads_count = i;
bRet = 0 as libc::c_int;
break;
} else {
(*(*tp).worker_threads.offset(i as isize)).marked_as_w... | Rust | 0 |
color=color, line_thickness=tl)
# Draw image filename labels
if paths is not None:
label = os.path.basename(paths[i])[:40] # trim to 40 char
t_size = cv2.getTextSize(
label, 0, fontScale=tl / 3, thickness=tf)[0]
cv2.putText(mosaic, label, (block_... | Python | 1 |
import numpy as np
import pandas as pd
def sort_matrix(score_matrix,interact_matrix):
sort_index = np.argsort(-score_matrix,axis=0)
score_sorted = np.zeros(score_matrix.shape)
y_sorted = np.zeros(interact_matrix.shape)
for i in range(interact_matrix.shape[1]):
score_sorted[:,i] = score_matrix... | Python | 1 |
= CLK_RTC/128"]
#[inline(always)]
pub fn div128(self) -> &'a mut W {
self.variant(DEBF_A::DIV128)
}
#[doc = "CLK_RTC_DEB = CLK_RTC/256"]
#[inline(always)]
pub fn div256(self) -> &'a mut W {
self.variant(DEBF_A::DIV256)
}
#[doc = r"Writes raw bits to the field"]
#[inl... | Rust | 0 |
et --hard")
if commit != head:
run_cmd(f"{git_cmd} fetch --depth 1 origin {commit}")
run_cmd(f"{git_cmd} checkout FETCH_HEAD")
return 0
# Arguments can be
# - family name
# - specific deps path
# - all
if __name__ == "__main__":
status = 0
deps = list(deps_mandatory.keys())
# get ... | Python | 1 |
{
break;
}
n += 1;
}
(n_min, n_peak, n, total)
}
#[cfg(not(feature = "leading-order-only"))]
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Write;
use rand::prelude::*;
use rand_xoshiro::*;
use super::*;
#[test]
fn partial_rates() {
l... | Rust | 0 |
// Verify that a request to reserve space that is not available triggers a buffer resize.
#[kani::proof]
pub fn reserve_more_capacity_still_works() {
// Start with a default VecDeque object (default capacity: 7).
let mut vec_deque = VecDeque::<u8>::new();
let old_capacity = vec_deque.cap... | Rust | 0 |
k_or(Error)
}
}
impl FastFloat for f32 {}
impl FastFloat for f64 {}
/// Parse a decimal number from string into float (full).
///
/// # Errors
///
/// Will return an error either if the string is not a valid decimal number
/// or if any characters are left remaining unparsed.
#[inline]
pub fn parse<T: FastFloat, ... | Rust | 0 |
.rust-lang.org/std/convert/trait.TryFrom.html
[`TryInto`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html
**/
pub trait TryConv: Sized {
/// Attempts to convert `self` into a target type.
///
/// This method runs `<Self as TryInto<T>>::try_into` on `self` to produce
/// the desired output. The only differ... | Rust | 0 |
class Solution:
def minSwaps(self, s: str) -> int:
d1 = {'0': 0, '1': 0}
d2 = {'0': 0, '1': 0}
temp = 1
for i in s:
if int(i) != int(temp):
d1[i] += 1
else:
d2[i] += 1
temp = not temp
# print(d1)
# p... | Python | 1 |
microseconds()
// .to_string()?;
// // simple spec pass
// // let control = get_approval_file(TEST_NAME);
// assert!(actual.contains("µs)"), format!("actual: {:?}", actual));
// Ok(())
// }
// #[test]
// fn nano() -> ReportResult {
// fn return_one() -> i32 {
// 1
// }
// ... | Rust | 0 |
te_random_vec(*input_bytes);
group
.throughput(Throughput::Bytes(*input_bytes as u64))
.bench_with_input(
BenchmarkId::new("encode", input_bytes),
input_data.as_slice(),
do_encode_benchmark,
)
.bench_with_input(
... | Rust | 0 |
utter Likelihood Alphanumeric Block
# # Reflectivity
# 111, # Clutter Likelihood Alphanumeric Block
# # Doppler
# 112-131,# Reserved for Future Products
# 136, # SuperOb Adaptable Latitude, Longitude
# # (ICD packet code 27)
# 139, #... | Python | 1 |
S IN THE
* SOFTWARE.
*
*
* @author <NAME> <<EMAIL>>
* @copyright <NAME> 2020
*/
pub enum Work {
NoWork,
Placement,
Update,
Delete,
Replacement,
}
pub enum Type {
NoType,
Component,
Basic,
Host,
Root,
Fragment,
ErrorBoundary,
ContextProvider,
ContextConsumer,
Text,
}
pub enum Hook {... | Rust | 0 |
.as_str());
// // //create a local v2 token
//let token = Paseto::<V2, Public>::build_token(header, message, &key, None);
let token = Paseto::<V2, Public>::default()
.set_payload(message.clone())
.set_footer(footer.clone())
.try_sign(&private_key)?;
// //validate the test vector
... | Rust | 0 |
#!/usr/bin/env python3
from parameterized import parameterized
import unittest
from cereal import log, messaging
from openpilot.selfdrive.car.car_helpers import FRAME_FINGERPRINT, can_fingerprint
from openpilot.selfdrive.car.fingerprints import _FINGERPRINTS as FINGERPRINTS
class TestCanFingerprint(unittest.TestCase... | Python | 1 |
::new(),
}
}
/// Push a face to the faces.
///
/// If `face.len() < 3`, the face is ignored with warning.
/// # Examples
/// ```
/// use truck_polymesh::*;
/// let mut faces = Faces::<StandardVertex>::default(); // empty faces
/// faces.push(&[[0, 0, 0], [1, 1, 1], [2, 2, 2]]);
/// faces.push(&[[3, 3, 3], ... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
from torchtune.utils import create_optim_in_bwd_wrapper, register_optim_in_bwd_hooks... | Python | 1 |
# 布局器-抽屉布局
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QDesktopWidget, QGroupBox, QHBoxLayout, \
QLineEdit, QGridLayout, QFormLayout, QLabel, QStackedLayout
from ming.init_ming import plugin_path
class Window1(QW... | Python | 1 |
,centers,on_data,ts_range=tsrange)
# vtktool = vtkgen()
## vtkgen.set_draw_mode(0)
# vtktool.add_swc('out_test.swc')
# for ts in tsrange:
# vtktool.add_datafile(anim_dir+'datafile'+str(ts)+'.dat')
# vtktool.write_vtk(anim_dir+'simple'+str(ts)+'.vtk')
# vtktool.clear_datafile()
##
# if write_stimulatio... | Python | 1 |
mem;
pub(crate) const UNUSED: u32 = u32::max_value();
pub(crate) const NULL_REG: u32 = UNUSED - 1;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub(crate) enum Ty {
Int = 0,
Float = 1,
Str = 2,
MapIntInt = 3,
MapIntFloat = 4,
MapIntStr = 5,
MapStrInt = 6,
MapStrFloat = 7,
Map... | Rust | 0 |
if len(self.adjusted_dts) < 2:
raise FinError("Schedule has two dates only.")
prev_dt = self.adjusted_dts[0]
for dt in self.adjusted_dts[1:]:
# if the first date lands on the effective date then remove it
if dt == prev_dt:
self.adjusted_dts.p... | Python | 1 |
format_none(point.value2)
)?;
}
}
}
Ok(())
}
}
pub struct DiffHeader();
impl fmt::Display for DiffHeader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(
f,
... | Rust | 0 |
a = input()
b = input()
c = a + " majors in " + b + '.'
print(c) | Python | 1 |
= FAKE_SAMPLE_ID;
FAKE_SAMPLE_ID += 1;
ret
}
}
impl Action for ActionTakeSample {
implement_name!("TakeSample");
fn apply(&mut self, gs: &mut GameState) {
let sample = Sample {
sample_id: unsafe { ActionTakeSample::next_id() },
carried_by: self.robot_idx as i32,
... | Rust | 0 |
class Solution:
def isPalindrome(self, s: str) -> bool:
new = ''
for a in s:
if a.isalpha() or a.isdigit():
new += a.lower()
return (new == new[::-1]) | Python | 1 |
ector. So, the final poll when there are no more tasks must
// take a while.
poll_resps.push_back(
async {
sleep(Duration::from_secs(10)).await;
unreachable!("Long poll")
}
.boxed(),
);
let mut calls_map = HashMap::<_, i32>::new();
mock_client
... | Rust | 0 |
AM0_0_MIN_R {
CORE_0_AREA_DRAM0_0_MIN_R::new(self.bits as u32)
}
}
impl W {
#[doc = "Bits 0:31 - reg_core_0_area_dram0_0_min"]
#[inline(always)]
pub fn core_0_area_dram0_0_min(&mut self) -> CORE_0_AREA_DRAM0_0_MIN_W {
CORE_0_AREA_DRAM0_0_MIN_W { w: self }
}
#[doc = "Writes raw bi... | Rust | 0 |
(Vector3::new(1., 0., 0.)), 45.0_f32.to_radians()));
}
}
<filename>src/rust/crates/framework/base/icecap-backtrace/cli/icecap-show-backtrace/src/main.rs
use std::fs::File;
use addr2line::Context;
use clap::{App, Arg};
use fallible_iterator::FallibleIterator;
use gimli::read::Reader;
use memmap::Mmap;
use icecap_b... | Rust | 0 |
# Code generated by sqlc. DO NOT EDIT.
# versions:
# sqlc v1.29.0
# source: batch_update_heartbeat_on_executors.sql
import dataclasses
from typing import List
import uuid
import sqlalchemy
import sqlalchemy.ext.asyncio
from . import models
BATCH_UPDATE_HEARTBEAT_ON_EXECUTORS = """-- name: batch_update_heartbeat_o... | Python | 1 |
from os.path import dirname as up
from pyCGM2.Nexus import eclipse
from pyCGM2.Nexus import vskTools
from pyCGM2 import enums
DATA_PATH = "C:\\Users\\fleboeuf\\Documents\\DATA\\pyCGM2-flow-data\\Nantes\\MAIGNAN Olympe\\Session 1\\"
# read a patient enf file
patientDir = up(up(DATA_PATH))+"\\"
enfPatientFile = ecl... | Python | 1 |
dd_argument("-vg", action="store_true",
help = "whether to get vector by index group")
parser.add_argument("-vec", nargs=3,
help = "get vector by your input, eg. -vec 6 6 6")
parser.add_argument("-select", nargs="*",
help = "select the groups, eg. -select ring1 ring2")
a... | Python | 1 |
test, y_pred_test
print("TEST RMSE:", rmse(y_test_orig, y_pred_test_orig))
print("TEST R2:", r2_score(y_test_orig, y_pred_test_orig))
# ---------- 9. Cross-validation ----------
cv_scores = cross_val_score(model, X, y_trans, scoring='neg_mean_squared_error', cv=5, n_jobs=-1)
cv_rmse = np.sqrt(-cv_scores)
print("CV RM... | Python | 1 |
# #!/usr/bin/env python
# Copyright (c) 2019. ShiJie Sun at the Chang'an University
# This work is licensed under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.
# For a copy, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.
# Author: shijie Sun
# Email: shijieSun@... | Python | 1 |
ex
hi $I'm latex3$ alice hi $I'm latex4$ bob
";
let (_, latexes) = extract_latex(s);
assert_eq!(
latexes,
[
"$I'm latex0$",
"$I'm latex1$",
"$I'm latex2$",
"$I'm latex3$",
"$I'm la... | Rust | 0 |
#!/usr/bin/python
# coding: utf8
import re
import requests
import logging
from geocoder.base import OneResult, MultipleResultsQuery
from geocoder.keys import tgos_key
class TgosResult(OneResult):
def __init__(self, json_content, language):
super(TgosResult, self).__init__(json_content)
self.lan... | Python | 1 |
js, int), # total number of trajs sampled over the course of training
('nsa', self.total_num_sa, int), # total number of state-action pairs sampled over the course of training
('ent', self.policy._compute_actiondist_entropy(sampbatch.adist.stacked).mean(), float), # entropy of action distributio... | Python | 1 |
|| (c >= '\u{00}' && c <= '\u{1F}')
|| (c >= '\u{7F}' && c <= '\u{9F}')
{
true
} else {
self.state.insert(pos, c);
false
}
}
}
#[cfg(test)]
mod tests {
use std::mem;
use unicode_width::UnicodeWidthChar;
use crate::cl... | Rust | 0 |
es(right_length)) if allow_bytes => {
return Ok(Type::Bytes(std::cmp::max(*left_length, *right_length)));
}
_ => (),
}
let (left_len, left_signed) = get_int_length(l, l_loc, false, ns, diagnostics)?;
let (right_len, right_signed) = get_int_length(r, r_loc, false, ns, diagnostic... | Rust | 0 |
trim() {
assert_eq!("".trim(), "");
assert_eq!("a".trim(), "a");
assert_eq!(" ".trim(), "");
assert_eq!(" blah ".trim(), "blah");
assert_eq!("\nwut \u3000 ".trim(), "wut");
assert_eq!(" hey dude ".trim(), "hey dude");
}
#[test]
fn test_is_whitesp... | Rust | 0 |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
"""
Version 4.1
what's new:
- add regularization enum
"""
import numpy as np
#import minpy.numpy as np
#from minpy.context import set_context, gpu
from enum import Enum
... | Python | 1 |
r),
Val(i64),
Plus(LBox<Expr<'t>>,LBox<Expr<'t>>), // LBox replaces Box for recursive defs
Times(LBox<Expr<'t>>,LBox<Expr<'t>>),
Divide(LBox<Expr<'t>>,LBox<Expr<'t>>),
Minus(LBox<Expr<'t>>,LBox<Expr<'t>>),
Negative(LBox<Expr<'t>>),
Letexp(&'t str,LBox<Expr<'t>>,LBox<Expr<'t>>),
Seq(Vec<LBox<Exp... | Rust | 0 |
, PartialMapWithStr},
};
/// Parse result of `Name`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum ParseResult<T> {
/// Completely parsed.
Complete(T),
/// Empty value.
Empty,
/// Local part is empty, i.e. the last character was colon.
EmptyLocalPart(Partial<T>),
... | Rust | 0 |
ause since libarchive-2.7.0
// they are implemented identically and know which kind of
// archive struct they deal with.
// The documentation suggests not calling close(),
// because free() calls it automatically, but actually
// free() doesn't call it for fat... | Rust | 0 |
usize,
concat!("Alignment of ", stringify!(RenderModel_Vertex_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RenderModel_Vertex_t>())).vPosition as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RenderModel_Vertex_t),
... | Rust | 0 |
ZERO WIDTH JOINER (ZWJ), or
/// General_Category = Spacing_Mark
/// ```
Extend {
abbr => Extend,
long => Extend,
human => "Extend",
}
/// ```text
/// U+0085 NEXT LINE (NEL)
/// U+2028 LINE SEPARATOR
/// U+2029 PARAGRAPH... | Rust | 0 |
is ignored when moving.
/// Use this for entities that should try to snap
/// to the nearest integer position.
#[derive(Component, Default, Deserialize, Clone)]
#[storage(NullStorage)]
#[serde(deny_unknown_fields)]
pub struct NonPreciseMovement;
<reponame>goto-bus-stop/wasm-pack
use std::env;
use std::fs;
use tempfile;... | Rust | 0 |
from airflow import DAG
from airflow.providers.apache.spark.operators.spark import SparkSubmitOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2024, 1, 1),
'email_on_failure': False,
'email_on_retry': False,
... | Python | 1 |
:
@property
def _then(self) -> type[SparkLikeThen]:
return SparkLikeThen
def __call__(self, df: SparkLikeLazyFrame) -> Sequence[Column]:
self.when = df._F.when
self.lit = df._F.lit
return super().__call__(df)
def _window_function(
self, df: SparkLikeLazyFrame, w... | Python | 1 |
(path) = log_to {
machine
.runtime_env
.recorder
.to_file(path, machine.get_total_gas_usage().to_u64().unwrap())
.unwrap();
}
Ok(true)
}
#[test]
fn test_arbowner() {
match _evm_test_arbowner(None, false) {
Ok(()) => {}
Err(e) => panic... | Rust | 0 |
g after {timeout}")
return False
def wait_live(self, timeout: timedelta):
curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
try_until = datetime.now() + timeout
while datetime.now() < try_until:
check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/... | Python | 1 |
M_VPSLLQ_XMMu64_MASKmskw_XMMu64_IMM8_AVX512 = 5201,
XED_IFORM_VPSLLQ_XMMu64_MASKmskw_XMMu64_MEMu64_AVX512 = 5202,
XED_IFORM_VPSLLQ_XMMu64_MASKmskw_XMMu64_XMMu64_AVX512 = 5203,
XED_IFORM_VPSLLQ_YMMqq_YMMqq_IMMb = 5204,
XED_IFORM_VPSLLQ_YMMqq_YMMqq_MEMdq = 5205,
XED_IFORM_VPSLLQ_YMMqq_YMMqq_XMMq = 520... | Rust | 0 |
}
}
if col_rem == 0 {
return
}
let c_chunk = c.get_chunk(stripes, pillars, p_stride);
for block in (0 .. blocks).step_by(MINIBLOCKM) {
let a_rows = a.get_chunk(stripes, block, m_stride);
let b_cols = b.get_chunk(block, pillars, ... | Rust | 0 |
ions}")
prompt = f"""Continue writing {len(paragraph_descriptions)} more paragraphs of the novel using the information below.
Novel title:
{self.title}
How the novel is written (its writing style):
{self.extra_context}
Novel characters:
{self.characters}
Novel settings:
{self.settings}
Novel synopsis... | Python | 1 |
from typing import List, Optional, Union, Literal, Dict
from pydantic import BaseModel, HttpUrl
class AudioURL(BaseModel):
url: str # Can be data: URI or remote URL
class InputAudio(BaseModel):
data: str # Base64 encoded audio data
format: str # Audio format (e.g., "wav", "mp3", "flac")
class ContentB... | Python | 1 |
, Deserialize, Insertable)]
#[table_name = "users"]
pub struct UserForm {
pub internal_permissions: i64,
pub eth_address: Option<String>,
pub signature: Option<String>,
pub created_at: SystemTime,
pub deleted_at: Option<SystemTime>,
}
impl UserForm {
pub fn insert(mut self, conn: &PgConnection)... | Rust | 0 |
nd;
#[test]
fn name() {
assert_eq!(
super::name("operation(#ambient, #read)"),
Ok(("(#ambient, #read)", "operation"))
);
}
#[test]
fn symbol() {
assert_eq!(super::symbol("#ambient"), Ok(("", builder::s("ambient"))));
}
#[test]
fn string(... | Rust | 0 |
unc_thresh:
# valid_seg_list.append(seg.clamp(max=vid_len, min=0))
# # some weird bug here if not converting to size 1 tensor
# valid_label_list.append(label.view(1))
# segments = torch.stack(valid_seg_list, dim=0)
# ... | Python | 1 |
ult_color_code)
else:
return HC + FCYN + str(msg) + RS
def green( msg ):
""" Print GREEN Colored String """
if os.name == 'nt' or sys.platform.startswith('win'):
windows_user_default_color_code = windows_default_colors()
set_text_attr(FGRN | BBLK | HC | BHC)
sys.stdout.write(str(msg))
resto... | Python | 1 |
-41.22777,
122.32875,
14.285113402275739,
-7.57291,
130.37946,
10.805303085187369,
3812686.035106021,
34.34330804743883,
3588703.8812128856,
0.82605222593217889,
0.82572158200920196,
... | Rust | 0 |
)
### Old MTEB format ###
else:
is_multilingual = any(x in res_dict for x in EVAL_LANGS)
langs = res_dict.keys() if is_multilingual else ["en"]
for lang in langs:
... | Python | 1 |
"""
Defines CHAOS exception classes grouped by failure mode.
"""
class ChaosError(Exception):
"""Base error for all CHAOS exceptions."""
class ChaosSyntaxError(ChaosError):
"""Raised during tokenization or parsing issues."""
class ChaosRuntimeError(ChaosError):
"""Raised during interpretation or execu... | Python | 1 |
bbox_mode,
minmax_normalize=False,
use_text_encoder_init=True,
after_proj=True,
sample_id=True, # CHANGED
# new
num_heads=8,
mlp_ratio=4.0,
qk_norm=True,
enable_flash_attn=False and global_flash_attn,
enable_xformers=True and global_xform... | Python | 1 |
# MIT License
# Copyright (c) 2024 Henrik Hose
# 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, pu... | Python | 1 |
lts, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
#[builder(default)]
pub after: Option<helix::Cursor>,
/// Cursor for backward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cur... | Rust | 0 |
okupEntry): lookup_key), None)
.await?
.ok_or_else(|| MongoStorageError::Other {
description: format!("addressing hash not found using lookup key \"{}\"", lookup_key),
})?
.value;
Ok(addressing_hash)
}
.boxed... | Rust | 0 |
#Using twillo api get notified of a transaction via SMS
import json
import asyncio
import websockets
from twilio.rest import Client
# Set your Twilio credentials
account_sid = ''# Replace with your Twilio account SID
auth_token = ''# Replace with your Twilio auth token
client = Client(account_sid, auth_token)
ALCH... | Python | 1 |
rankScore = 1/popRank
elif p['select_rankWeight'] == 'lin':
rankScore = 1+abs(popRank-len(popRank))
else:
print("Invalid rank weighting (using linear)")
rankScore = 1+abs(popRank-len(popRank))
specId = np.asarray([ind.species for ind in pop])
# Best and Average Fitness of Each Sp... | Python | 1 |
tent'})
for ch in channels:
link =ch.find('a')['href']
title= ch.find('strong').string.encode('utf-8').replace('\n', '').strip()
img='http://torrent-tv.ru/'+ch.find('img')['src']
if __addon__.getSetting('logopack') == "true":
logo_path = os.path.join(PLUGIN_DATA_PATH, 'lo... | Python | 1 |
from unittest import TestCase, mock
from unittest.mock import Mock
from redditrepostsleuth.core.db.databasemodels import Post
from redditrepostsleuth.core.model.repostmatch import RepostMatch
from datetime import datetime
from redditrepostsleuth.core.model.search.search_match import SearchMatch
from redditrepostsleut... | Python | 1 |
#!/usr/bin/env python3
"""
表格提取器
实现各种格式的表格提取逻辑
"""
import re
from typing import List, Dict, Any
from abc import ABC, abstractmethod
from core.utils import setup_logger
class BaseTableExtractor(ABC):
"""表格提取器基类"""
def __init__(self):
self.logger = setup_logger(self.__class__.__name__)
@... | Python | 1 |
from model.da.database_manager import *
from model.entity.user import User
class UserDa(DatabaseManager):
def find_by_username(self, username):
self.make_engine()
entity = self.session.query(User).filter(User.username == username).all()
return result
def find_by_username_and_password... | Python | 1 |
sStream::Done)
}
};
return Ok(Some((logs, next)));
}
}
async fn init(builder: LogFilterBuilder<T>) -> Result<Self, ExecutionError> {
let from_block = builder.from_block.unwrap_or(BlockNumber::Latest);
let to_block = builder.to_block.unwrap_or(Bloc... | Rust | 0 |
= filter(lambda i : i != 1,dim)
return a.reshape(dim), newshape
# =========================================================
def writeout(tmp, cl, labels, outpath, thres):
l, cnt = md(cl.flatten())
l = np.squeeze(l)
if cnt/len(cl.flatten()) > thres:
outfile = id_generator()+'.jpg'
fp = outpa... | Python | 1 |
at.participants_count
channels.append([title, about, link, subscibers])
except FloodWaitError as error:
print(error)
await asyncio.sleep(SLEEP_ERROR)
wb = Workbook()
sheet = wb[wb.sheetnames[0]]
update_table = int(len(c... | Python | 1 |
let p1 = part1(&instr);
let p2 = part2(&instr);
(p1, p2)
}
fn main() {
let input = get_input("d12.txt");
let start = Instant::now();
let (r1, r2) = solve(input.as_slice());
let t = start.elapsed().as_micros() as f64 / 1000.0;
println!("Part 1: {}", r1);
println!("Part 2: {}", r2... | Rust | 0 |
datomnum = res.evoef2_env.md_envset.atoms.len();
let mut atom_level_energy:Vec<f64> = vec![0.0;mdatomnum];
let ene:f64 = res.calc_energy(&mut atom_level_energy);
if top_x > 0{
if top_x_structures.len() >= top_x{
top_x_structures.sort_by(|a,b| (a.0).partial_cmp(&b.0).u... | Rust | 0 |
#!/usr/bin/python3
"""__summary__
- Write a Python script that takes in a URL,
- sends a request to the URL
- displays the body of the response (decoded in utf-8).
"""
if __name__ == "__main__":
import sys
from urllib import request, error
try:
with request.urlopen(sys.argv[1]) as resq:
... | Python | 1 |
cuments
def _write_documents(documents: Iterable[CaseDocument], path: Path) -> None:
with path.open("w", encoding="utf-8") as handle:
for doc in documents:
payload = {
"id": doc.id,
"source": "TCMLM_real_clinical_cases",
"doc_type": "clinical_cas... | Python | 1 |
"""Constants for the Firmata component."""
from typing import Final
from homeassistant.const import (
CONF_BINARY_SENSORS,
CONF_LIGHTS,
CONF_SENSORS,
CONF_SWITCHES,
Platform,
)
CONF_ARDUINO_INSTANCE_ID = "arduino_instance_id"
CONF_ARDUINO_WAIT = "arduino_wait"
CONF_DIFFERENTIAL = "differential"
CO... | Python | 1 |
_int;
pub fn glp_netgen(G: *mut Graph, v_rhs: c_int, a_cap: c_int,
a_cost: c_int, parm: [c_int, ..16u]) -> c_int;
pub fn glp_netgen_prob(nprob: c_int, parm: [c_int, ..16u]);
pub fn glp_gridgen(G: *mut Graph, v_rhs: c_int, a_cap: c_int,
a_cost: c_int, parm: [c_int... | Rust | 0 |
he
`IntoIterator<Item=T>` bound. What that means is that `I` must satisfy the
`IntoIterator` trait. If you look at the documentation of the
[`IntoIterator` trait](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html),
then we can see that it describes types that can build iterators. In this
case, w... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.