file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
keys.rs |
pub modifier: Modifier,
pub value: Value,
}
bitflags! {
pub struct Modifier: u8 {
const NONE = 0;
const ALT = 1 << 0;
const CTRL = 1 << 1;
const LOGO = 1 << 2;
const SHIFT = 1 << 3;
}
}
impl Default for Modifier {
fn default() -> Self {
Modifier::empty()
}
}
#[derive(Eq, PartialEq, Copy, C... | y { | identifier_name | |
keys.rs | " => F(1); CTRL);
insert!(b"\x1B[1;3P" => F(1); ALT);
insert!(b"\x1B[1;6P" => F(1); LOGO);
insert!(b"\x1B[1;2P" => F(1); SHIFT);
insert!(b"\x1BOP" => F(1));
insert!(b"\x1B[1;5Q" => F(2); CTRL);
insert!(b"\x1B[1;3Q" => F(2); ALT);
insert!(b"\x1B[1;6Q" => F(2); LOGO);
insert!(b"\x1B[1;2Q" => F... | // Check if it's a single escape press.
if input == &[0x1B] {
return (&input[1..], Some(Key {
modifier: Modifier::empty(),
value: Escape, | random_line_split | |
lib.rs | = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 };
let up = if y > 0 { y - 1 } else { 0 };
let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 };
res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap());
res_y.push(-*phi.get(x, do... | {
c + 1
} | conditional_block | |
lib.rs | "mask.png");
//!
//! // level-set segmentation by Chan-Vese
//! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0);
//! utils::save_boolgrid(&seg, "out.png");
//! utils::save_floatgrid(&phi, "phi.png");
//! }
//! ```
extern crate distance_transform;
use distance_transform::dt2d;
use std::f64;
... | };
phi
}
// Compute curvature along SDF
fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> {
// get central derivatives of SDF at x,y
let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = {
let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy)
: (Vec<f64>, Vec... | {
let inv_init_a = {
let mut result = init_a.clone();
for (_, _, value) in result.iter_mut() {
*value = !*value;
}
result
};
let phi = {
let dist_a = bwdist(&init_a);
let dist_inv_a = bwdist(&inv_init_a);
let mut result = FloatGrid::new(in... | identifier_body |
lib.rs | value <= 0. {
res1.push((x, y));
}
else {
res2.push((x, y));
}
}
(res1, res2)
};
let u = upts.iter().fold(0f64, |acc, &(x, y)| {
acc + *img... | let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); | random_line_split | |
lib.rs | idx: &Vec<(usize,usize)>) -> Vec<f64> {
// get central derivatives of SDF at x,y
let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = {
let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy)
: (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = (
Vec::with_capacity(idx.len()), ... | sussman_sign | identifier_name | |
controller.rs | _bank = 5;
}
};
let kempston = if settings.kempston {
Some(KempstonJoy::new())
} else {
None
};
let mut out = ZXController {
machine: settings.machine,
memory: memory,
canvas: ZXCanvas::new(settings.machine),... | fn frame_pos(&self) -> f64 {
let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64;
if val > 1.0 {
1.0
} else {
val
}
}
/// loads rom from file
/// for 128-K machines path must contain ".0" in the tail
/// and s... | out
}
/// returns current frame emulation pos in percents | random_line_split |
controller.rs | = 5;
}
};
let kempston = if settings.kempston {
Some(KempstonJoy::new())
} else {
None
};
let mut out = ZXController {
machine: settings.machine,
memory: memory,
canvas: ZXCanvas::new(settings.machine),
... |
/// check events count
pub fn no_events(&self) -> bool {
self.events.is_empty()
}
/// Returns last event
pub fn pop_event(&mut self) -> Option<Event> {
self.events.receive_event()
}
/// Returns true if all frame clocks has been passed
pub fn frames_count(&self) -> usi... | {
self.events.clear();
} | identifier_body |
controller.rs | = 5;
}
};
let kempston = if settings.kempston {
Some(KempstonJoy::new())
} else {
None
};
let mut out = ZXController {
machine: settings.machine,
memory: memory,
canvas: ZXCanvas::new(settings.machine),
... |
return 0xFF;
}
/// make contention
fn do_contention(&mut self) {
let contention = self.machine.contention_clocks(self.frame_clocks);
self.wait_internal(contention);
}
///make contention + wait some clocks
fn do_contention_and_wait(&mut self, wait_time: Clocks) {
... | {
if clocks % 2 == 0 {
return self.memory.read(bitmap_line_addr(row) + col as u16);
} else {
let byte = (row / 8) * 32 + col;
return self.memory.read(0x5800 + byte as u16);
};
} | conditional_block |
controller.rs | = 5;
}
};
let kempston = if settings.kempston {
Some(KempstonJoy::new())
} else {
None
};
let mut out = ZXController {
machine: settings.machine,
memory: memory,
canvas: ZXCanvas::new(settings.machine),
... | (&mut self, port: u16) {
if self.addr_is_contended(port) {
self.do_contention();
};
self.wait_internal(Clocks(1));
}
/// Returns late IO contention clocks
fn io_contention_last(&mut self, port: u16) {
if self.machine.port_is_contended(port) {
self.do_... | io_contention_first | identifier_name |
storage.rs | _fund_account(&mut swarm, 1000000);
transfer_coins(
&client_1,
&transaction_factory,
&mut account_0,
&account_1,
1,
);
let mut expected_balance_0 = 999999;
let mut expected_balance_1 = 1000001;
assert_balance(&client_1, &account_0, expected_balance_0);
as... | {
let current_version = client.get_metadata()?.into_inner().diem_version.unwrap();
let txn = root_account.sign_with_transaction_builder(
transaction_factory.update_diem_version(0, current_version + 1),
);
client.submit(&txn)?;
client.wait_for_s... | conditional_block | |
storage.rs | , types::LocalAccount,
};
use diem_temppath::TempPath;
use diem_types::{transaction::Version, waypoint::Waypoint};
use forge::{NodeExt, Swarm, SwarmExt};
use rand::random;
use std::{
fs,
path::Path,
process::Command,
time::{Duration, Instant},
};
#[test]
fn test_db_restore() {
// pre-build tools
... | &transaction_batch_size.to_string(),
"--state-snapshot-interval",
&state_snapshot_interval.to_string(),
"--metadata-cache-dir",
metadata_cache_path1.path().to_str().unwrap(),
"local-fs",
"--dir",
backup_path.path().to_str().... | {
let now = Instant::now();
let bin_path = workspace_builder::get_bin("db-backup");
let metadata_cache_path1 = TempPath::new();
let metadata_cache_path2 = TempPath::new();
let backup_path = TempPath::new();
metadata_cache_path1.create_as_dir().unwrap();
metadata_cache_path2.create_as_dir().... | identifier_body |
storage.rs | // pre-build tools
workspace_builder::get_bin("db-backup");
workspace_builder::get_bin("db-restore");
workspace_builder::get_bin("db-backup-verify");
let mut swarm = new_local_swarm(4);
let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>();
let client_1 = swar... | transfer_and_reconfig | identifier_name | |
storage.rs | , types::LocalAccount,
};
use diem_temppath::TempPath;
use diem_types::{transaction::Version, waypoint::Waypoint};
use forge::{NodeExt, Swarm, SwarmExt};
use rand::random;
use std::{
fs,
path::Path,
process::Command,
time::{Duration, Instant},
};
#[test]
fn test_db_restore() {
// pre-build tools
... |
fn wait_for_backups(
target_epoch: u64,
target_version: u64,
now: Instant,
bin_path: &Path,
metadata_cache_path: &Path,
backup_path: &Path,
trusted_waypoints: &[Waypoint],
) -> Result<()> {
for _ in 0..60 {
// the verify should always succeed.
db_backup_verify(backup_pat... | if !output.status.success() {
panic!("db-backup-verify failed, output: {:?}", output);
}
println!("Backup verified in {} seconds.", now.elapsed().as_secs());
} | random_line_split |
lib.rs | Buf,
}
impl Localizer {
pub fn run<P: Into<PathBuf>>(
ids_map: Map<String, i64>,
module_name: &str,
output_dir: P,
force_all: bool,
) {
let output_dir = output_dir.into();
let localizer = Self {
data: Self::construct_language_data(vec![
... | random_line_split | ||
lib.rs | path::{Path, PathBuf},
thread,
time::Duration,
};
mod error;
pub use error::Error;
use error::ProcessingError;
mod utils;
const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36";
static USER_AGENT: Lazy<Cow<'static,... | (output_dir: &Path) -> Cow<'_, Path> {
use std::fs;
use std::os::unix::fs::MetadataExt;
let os_tmp = env::temp_dir();
match (
fs::metadata(output_dir).map(|v| v.dev()),
fs::metadata(&os_tmp).map(|v| v.dev()),
) {
(Ok(num1), Ok(num2)) if num1 =... | get_tmp_dir | identifier_name |
lib.rs | path::{Path, PathBuf},
thread,
time::Duration,
};
mod error;
pub use error::Error;
use error::ProcessingError;
mod utils;
const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36";
static USER_AGENT: Lazy<Cow<'static,... |
}
}
Ok(node.text())
})
});
match result {
... | {
return Err("Not a valid NPC ID".into());
} | conditional_block |
mmio.rs | 0 Vertical: high=top, low=(bottom+1)");
def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)");
def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1");
def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe,... | def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); | random_line_split | |
mmio.rs | ["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)");
def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)");
def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Co... | {
let u = BG_PALETTE.index(bank * 16).as_usize();
unsafe { VolBlock::new(u) }
} | identifier_body | |
mmio.rs | def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)");
def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits");
def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "D... | obj_palbank | identifier_name | |
domain_models.py | idPusher(object):
def | (
self,
orcid,
recid,
oauth_token,
pushing_duplicated_identifier=False,
record_db_version=None,
):
self.orcid = orcid
self.recid = str(recid)
self.oauth_token = oauth_token
self.pushing_duplicated_identifier = pushing_duplicated_identif... | __init__ | identifier_name |
domain_models.py | from flask import current_app
from inspire_service_orcid import exceptions as orcid_client_exceptions
from inspire_service_orcid.client import OrcidClient
from invenio_db import db
from invenio_pidstore.errors import PIDDoesNotExistError
from time_execution import time_execution
from inspirehep.records.api import Lite... |
import re
import structlog | random_line_split | |
domain_models.py | idPusher(object):
def __init__(
self,
orcid,
recid,
oauth_token,
pushing_duplicated_identifier=False,
record_db_version=None,
):
self.orcid = orcid
self.recid = str(recid)
self.oauth_token = oauth_token
self.pushing_duplicated_ident... |
return self.inspire_record.get("deleted", False)
@time_execution
def push(self): # noqa: C901
putcode = None
if not self._do_force_cache_miss:
putcode = self.cache.read_work_putcode()
if not self._is_record_deleted and not self.cache.has_work_content_changed(
... | LOGGER.debug(
"OrcidPusher force delete", recid=self.recid, orcid=self.orcid
)
return True | conditional_block |
domain_models.py | .pushing_duplicated_identifier = pushing_duplicated_identifier
self.record_db_version = record_db_version
self.inspire_record = self._get_inspire_record()
self.cache = OrcidCache(orcid, recid)
self.lock_name = "orcid:{}".format(self.orcid)
self.client = OrcidClient(self.oauth_tok... | LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid)
if not self.cached_author_putcodes:
putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token)
putcodes_recids = list(
putcode_getter.get_all_inspire_putcodes_and_recids_iter()
... | identifier_body | |
lib.rs | lude::future::Executor;
use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt};
error_chain! {
links {
Core(CoreError, CoreErrorKind);
}
foreign_links {
HandlerError(HandlerSettingError);
SpawnError(tokio::executor::SpawnError);
}
}
#[derive(Debug, Deseria... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SubscriptionId::Num(n) => write!(f, "{}", n),
SubscriptionId::String(s) => write!(f, "{}", s),
}
}
}
#[derive(Debug)]
enum SubscriberMsg {
NewMessage(SubscriptionMessage),
NewSubscriber(SubscriptionId, mps... | fmt | identifier_name |
lib.rs | lude::future::Executor;
use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt};
error_chain! {
links {
Core(CoreError, CoreErrorKind);
}
foreign_links {
HandlerError(HandlerSettingError);
SpawnError(tokio::executor::SpawnError);
}
}
#[derive(Debug, Deseria... |
_ => true,
},
}
}
}
impl Future for NotificationHandler {
type Item = ();
type Error = | {
self.current_future = Some(fut);
false
} | conditional_block |
lib.rs | extern crate jsonrpc_client_utils;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate tokio;
#[macro_use]
extern crate log;
#[macro_use]
extern crate error_chain;
use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream};
use jsonrpc_client_core::server::{
types::... | //!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core; | random_line_split | |
boxed.rs |
let garbage = unsafe {
let garbage_ptr = sodium::allocarray::<u8>(1);
let garbage_byte = *garbage_ptr;
sodium::free(garbage_ptr);
vec![garbage_byte; unboxed.len()]
};
// sanity-check the garbage byte in case we have a bug in how we
// ... | #[should_panic(expected = "secrets: releases exceeded retains")]
fn it_doesnt_allow_negative_users() {
Box::<u64>::zero(10).lock();
} | random_line_split | |
boxed.rs | // retain/release code. If an out-of-order `release` causes the
// ref counter to wrap around below zero, the subsequent
// `retain` will panic here.
match refs.checked_add(1) {
Some(v) => self.refs.set(v),
None if self.is_locked() => panic!("secrets: ou... | {
let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]);
let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]);
assert_ne!(boxed_1, boxed_2);
assert_ne!(boxed_2, boxed_1);
} | identifier_body | |
boxed.rs | ,
"secrets: may not call Box::as_ref while locked");
unsafe { self.ptr.as_ref() }
}
/// Converts the [`Box`]'s contents into a mutable reference. This
/// must only happen while it is mutably unlocked, and the slice
/// must go out of scope before it is locked.
///
/// Pani... | (&self) {
// When releasing, we should always have at least one retain
// outstanding. This is enforced by all users through
// refcounting on allocation and drop.
proven!(self.refs.get() != 0,
"secrets: releases exceeded retains");
// When releasing, our protection ... | release | identifier_name |
boxed.rs | ,
"secrets: may not call Box::as_ref while locked");
unsafe { self.ptr.as_ref() }
}
/// Converts the [`Box`]'s contents into a mutable reference. This
/// must only happen while it is mutably unlocked, and the slice
/// must go out of scope before it is locked.
///
/// Pani... |
}
/// Returns true if the protection level is [`NoAccess`]. Ignores
/// ref count.
fn is_locked(& | {
mprotect(self.ptr.as_ptr(), Prot::NoAccess);
self.prot.set(Prot::NoAccess);
} | conditional_block |
route.go | /vpp-agent/v3/pkg/models"
kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
"go.ligato.io/vpp-agent/v3/plugins/netalloc"
netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor"
ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor"
"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plu... | (key string, route *l3.Route) (metadata interface{}, err error) {
err = d.routeHandler.VppAddRoute(context.TODO(), route)
if err != nil {
return nil, err
}
return nil, nil
}
// Delete removes VPP static route.
func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error {
err := d.... | Create | identifier_name |
route.go | /vpp-agent/v3/pkg/models"
kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
"go.ligato.io/vpp-agent/v3/plugins/netalloc"
netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor"
ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor"
"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plu... | Key: l3.VrfTableKey(route.ViaVrfId, protocol),
})
}
// if destination network is netalloc reference, then the address must be allocated first
allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork,
"", "dst_network-")
if hasAllocDep {
dependencies = append(dependencies, allocDep)
}
/... | })
}
if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 {
dependencies = append(dependencies, kvs.Dependency{
Label: viaVrfTableDep, | random_line_split |
route.go | escriptor"
ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor"
"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter"
"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls"
netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc"
interfaces "go.ligato.io/vpp-agent/v3/prot... | {
return addr1 == addr2
} | conditional_block | |
route.go | /vpp-agent/v3/pkg/models"
kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
"go.ligato.io/vpp-agent/v3/plugins/netalloc"
netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor"
ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor"
"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plu... | key := models.Key(route)
expCfg[key] = route
nbCfg[key] = kv.Value
}
// Retrieve VPP route configuration
routes, err := d.routeHandler.DumpRoutes()
if err != nil {
return nil, errors.Errorf("failed to dump VPP routes: %v", err)
}
for _, route := range routes {
key := models.Key(route.Route)
value :=... | {
// prepare expected configuration with de-referenced netalloc links
nbCfg := make(map[string]*l3.Route)
expCfg := make(map[string]*l3.Route)
for _, kv := range correlate {
dstNetwork := kv.Value.DstNetwork
parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork,
"", netalloc_api.IPAddressForm_AD... | identifier_body |
models.py | devices = devices.filter(confirmed=bool(confirmed))
return devices
class Device(models.Model):
"""
Abstract base model for a :term:`device` attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP device... |
@property
def persistent_id(self):
"""
A stable device identifier for forms and APIs.
"""
return '{0}/{1}'.format(self.model_label(), self.id)
@classmethod
def model_label(cls):
"""
Returns an identifier for this Django model class.
This is jus... | try:
user = self.user
except ObjectDoesNotExist:
user = None
return "{0} ({1})".format(self.name, user) | identifier_body |
models.py | devices = devices.filter(confirmed=bool(confirmed))
return devices
class Device(models.Model):
"""
Abstract base model for a :term:`device` attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP device... |
:param str token: The OTP token provided by the user.
:rtype: bool
"""
_now = timezone.now()
if (
(self.token is not None)
and (token == self.token)
and (_now < self.valid_until)
):
self.token = None
self.vali... | random_line_split | |
models.py | devices = devices.filter(confirmed=bool(confirmed))
return devices
class | (models.Model):
"""
Abstract base model for a :term:`device` attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP devices are inherently stateful. For example, verifying a token is
logically a mutating operation on... | Device | identifier_name |
models.py | devices = devices.filter(confirmed=bool(confirmed))
return devices
class Device(models.Model):
"""
Abstract base model for a :term:`device` attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP device... |
device = device_set.first()
except (ValueError, LookupError):
pass
return device
def is_interactive(self):
"""
Returns ``True`` if this is an interactive device. The default
implementation returns ``True`` if
:meth:`~django_otp.models.De... | device_set = device_set.select_for_update() | conditional_block |
NetHandler.ts | ;
private curTryTimes: number = 0;
private tcp: Game.TcpClient = null;
private host: string;
private port: number = 0;
private status: ConnectStatus;
private id = 0;
constructor(id: number) {
this.id = id;
Game.TcpClient.setHandleTimesInFrame(30);
let headsize = 2;
... | his.close();
// 多个url用|分开
this.ips = ips;
this.hostList = ips.split("|");
//先暂时定为一个
this.port = port;
let hostCount: number = this.hostList.length;
// 创建ping
let curSocketCnt: number = this.sockets.length;
for (let i = 0; i < hostCount - curSocke... | ,不能list两次role,所以每次都要断开重连
t | identifier_body |
NetHandler.ts | ;
private curTryTimes: number = 0;
private tcp: Game.TcpClient = null;
private host: string;
private port: number = 0;
private status: ConnectStatus;
private id = 0;
constructor(id: number) {
this.id = id;
Game.TcpClient.setHandleTimesInFrame(30);
let headsize = 2;
... | this.onDisconnectCallback();
}
}
}
private onRecv(id: number, data: any, size: number, busy: boolean) {
if (null != this.workSocket && this.workSocket.Id == id) {
let msgid = G.Dr.msgid(data, size);
if (msgid < 0) {
uts.bugRepo... | if (null != this.onDisconnectCallback) { | random_line_split |
NetHandler.ts | private curTryTimes: number = 0;
private tcp: Game.TcpClient = null;
private host: string;
private port: number = 0;
private status: ConnectStatus;
private id = 0;
constructor(id: number) {
this.id = id;
Game.TcpClient.setHandleTimesInFrame(30);
let headsize = 2;
... | Socket.send(G.Dr.packBuf(), packlen);
// 记录发送时间
if (Macros.MsgID_SyncTime_Request == msgId) {
// 将延迟设置为0
this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup);
}
}
private onConnect(id: number, isSuccess: boolean, reason: number) {
if (null ... | rn;
}
this.work | conditional_block |
NetHandler.ts | private curTryTimes: number = 0;
private tcp: Game.TcpClient = null;
private host: string;
private port: number = 0;
private status: ConnectStatus;
private id = 0;
constructor(id: number) {
this.id = id;
Game.TcpClient.setHandleTimesInFrame(30);
let headsize = 2;
... | s.status = ConnectStatus.closed;
this.host = null;
this.port = 0;
}
send(data: any, size: number) {
this.tcp.send(data, size);
}
private doConnect() {
this.curTryTimes++;
this.tcp.close();
this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds ... | thi | identifier_name |
zsy_3pandas.py | 2['state'])
# print(frame2.year)
# print(frame2.ix['three'])
# frame2['debt'] = 16.5
# print(frame2)
# frame2['debt'] = np.arange(5.)
# print(frame2)
val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])
frame2['debt'] = val
# print(frame2)
frame2['eastern'] = frame2.state == 'Ohio'
# print(frame2)
# del fram... | eturn Series([x.min(), x.max()], index=['min', 'max'])
# print(frame.apply(f))
format = lambda x: '%.2f' % x
# print(frame.applymap(format))
# print(frame['e'].map(format))
# 13
obj = Series(range(4), index=['d', 'a', 'b', 'c'])
# print(obj)
# print(obj.sort_index())
frame = DataFrame(np.arange(8).reshape((2, 4)), ind... | r | identifier_name |
zsy_3pandas.py | 2['state'])
# print(frame2.year)
# print(frame2.ix['three'])
# frame2['debt'] = 16.5
# print(frame2)
# frame2['debt'] = np.arange(5.)
# print(frame2)
val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])
frame2['debt'] = val
# print(frame2)
frame2['eastern'] = frame2.state == 'Ohio'
# print(frame2)
# del fram... | rame.apply(f))
format = lambda x: '%.2f' % x
# print(frame.applymap(format))
# print(frame['e'].map(format))
# 13
obj = Series(range(4), index=['d', 'a', 'b', 'c'])
# print(obj)
# print(obj.sort_index())
frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'],
columns=['d', 'a', 'b', '... | ies([x.min(), x.max()], index=['min', 'max'])
# print(f | identifier_body |
zsy_3pandas.py | 2])
# print(data.ix[:'Utah', 'two'])
# print(data.ix[data.three > 5, :3])
# 10
s1 = Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e'])
s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g'])
# print(s1)
# print(s2)
# print(s1+s2)
df1 = DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'),... | random_line_split | ||
movement.py |
latitude = float(row['latitude'])
longitude = float(row['longitude'])
#Put Data in .csv file into an array
lat.append(latitude)
lon.append(longitude)
desired_lat = lat[count]
desired_lon = lon[count]
return desired_lat, desired_lon
de... | pipeline.stop()
camera()
elif x > 400:
#right of camera, what to do?
print("object on right\r\n")
left()
time.sleep(0.3)
... | depth = frames.get_depth_frame()
for y in range(0,480,40):
for x in range(0,600,40):
dist = depth.get_distance(x,y)
if y == 480:
pipeline.stop()
return
if dist > 0.1 and dist < 1:
... | conditional_block |
movement.py | np.array([0.07,0.07,0.04])
def getB(yaw, deltak):
"""
Calculates and returns the B matrix
3x2 matix -> number of states x number of control inputs
The control inputs are the forward speed and the
rotation rate around the z axis from the x-axis in the
counterclockwise direction.
[v,yaw_ra... | random_line_split | ||
movement.py | near-optimal) estimate of the current state of the robot
print(f'State Estimate After EKF={state_estimate_k}\r\n')
# Return the updated state and covariance estimates
return state_estimate_k, P_k
############################################################################################
#function a... | print("starting manual movement\n")
print("press wasd to control the movement\n")
try:
while True:
key = stdscr.getch()
#Forward
if key == ord('w'):
forward()
#Move Left
elif key == ord('a'):
left()
#... | identifier_body | |
movement.py | (100):
compass_bearing_arr.append(sensor.euler[0])
compass_bearing_std = np.std(compass_bearing_arr)
#if compass standard deviation above 0.5 degrees reinitialize offset
if compass_bearing_std > 0.5:
print("bearing not accurate, reinitializing\r\n")
auto()
else:
prin... | right | identifier_name | |
model.py | output = pattern.sub(' ', input).strip()
return output
def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims):
vectorized_data = []
# probably could be optimized further
ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset]
token_list = [tokenizer.tokenize(s... | Get word embeddings for the training data.
'''
shuffle(dataset)
data = [s['data'] for s in dataset]
#labels = [s['label'] for s in dataset]
labels = [[s['label']] for s in dataset]
#le_encoder = preprocessing.LabelEncoder()
if le_encoder is None:
... | random_line_split | |
model.py | output = pattern.sub(' ', input).strip()
return output
def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims):
vectorized_data = []
# probably could be optimized further
ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset]
token_list = [tokenizer.tokenize(samp... |
def load(path):
print(f'loading model from {path}')
structure_file = os.path.join(path, 'structure.json')
weight_file = os.path.join(path, 'weight.h5')
labels_file = os.path.join(path, 'classes.npy')
with open(structure_file, "r") as json_file:
json_string = json_file.read()
model... | '''
save model based on model, encoder
'''
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
print(f'saving model to {path}')
structure_file = os.path.join(path, 'structure.json')
weight_file = os.path.join(path, 'weight.h5')
labels_file = os.path.join(path, 'classes')
... | identifier_body |
model.py | output = pattern.sub(' ', input).strip()
return output
def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims):
vectorized_data = []
# probably could be optimized further
ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset]
token_list = [tokenizer.tokenize(samp... | (self, dataset, le_encoder=None):
'''
Preprocess the dataset, transform the categorical labels into numbers.
Get word embeddings for the training data.
'''
shuffle(dataset)
data = [s['data'] for s in dataset]
#labels = [s['label'] for s in dataset]
labels ... | __preprocess | identifier_name |
model.py | output = pattern.sub(' ', input).strip()
return output
def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims):
vectorized_data = []
# probably could be optimized further
ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset]
token_list = [tokenizer.tokenize(s... |
new_data.append(temp)
return new_data
def save(model, le, path, history):
'''
save model based on model, encoder
'''
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
print(f'saving model to {path}')
structure_file = os.path.join(path, 'structure.json')
we... | temp = sample | conditional_block |
mod.rs | };
use itc_rpc_client::direct_client::{DirectApi, DirectClient};
use itp_types::{
Balance, ShardIdentifier, TrustedOperationStatus,
TrustedOperationStatus::{InSidechainBlock, Submitted},
};
use log::*;
use rand::Rng;
use rayon::prelude::*;
use sgx_crypto_helper::rsa3072::Rsa3072PubKey;
use sp_application_crypto::sr25... | (
account: sr25519::Pair,
shard: ShardIdentifier,
direct_client: &DirectClient,
) -> Index {
let getter = Getter::trusted(
TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())),
);
let getter_start_timer = Instant::now();
let getter_result = get_state(direct_client, shard, &ge... | get_nonce | identifier_name |
mod.rs | };
use itc_rpc_client::direct_client::{DirectApi, DirectClient};
use itp_types::{
Balance, ShardIdentifier, TrustedOperationStatus,
TrustedOperationStatus::{InSidechainBlock, Submitted},
};
use log::*;
use rand::Rng;
use rayon::prelude::*;
use sgx_crypto_helper::rsa3072::Rsa3072PubKey;
use sp_application_crypto::sr25... |
// Create new account.
let account_keys: sr25519::AppPair = store.generate().unwrap();
let new_account =
get_pair_from_str(trusted_args, account_keys.public().to_string().as_str());
println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT);
println!(" From: {:?}", client.account.public(... | {
random_wait(random_wait_before_transaction_ms);
} | conditional_block |
mod.rs | };
use itc_rpc_client::direct_client::{DirectApi, DirectClient};
use itp_types::{
Balance, ShardIdentifier, TrustedOperationStatus,
TrustedOperationStatus::{InSidechainBlock, Submitted},
};
use log::*;
use rand::Rng;
use rayon::prelude::*;
use sgx_crypto_helper::rsa3072::Rsa3072PubKey;
use sp_application_crypto::sr25... |
output
})
.collect();
println!(
"Finished benchmark with {} clients and {} transactions in {} ms",
self.number_clients,
self.number_iterations,
overall_start.elapsed().as_millis()
);
print_benchmark_statistic(outputs, self.wait_for_confirmation)
}
}
fn get_balance(
account: sr25519::Pa... | break;
}
}
client.client_api.close().unwrap(); | random_line_split |
app.py | ,clf_labels):
scores = cross_val_score(estimator=clf,X=X_train,y=y_train,
cv=10,scoring='roc_auc')
print("roc auc: %0.2f (+/- %0.2f) [%s]"%(scores.mean(),scores.std(),label))
# 由打印的结果可以看出,集成分类器的性能相对于单个的分类器有质的提升
# 绘制评估器的roc曲线,评估模型性能
from sklearn.metrics impo... | 315 of diluted wines',
ha='center',va='center',fontsize=12)
plt.show()
############################AdaBoost算法###############################
#
def function5():
from sklearn.ensemble import AdaBoostClassifier
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'
'mac... | conditional_block | |
app.py | plt.legend(loc='lower right')
plt.plot([0,1],[0,1],linestyle='--',color='gray',lw=2) # 随机猜测roc曲线
plt.xlim([-0.1,1.1])
plt.ylim([-0.1,1.1])
plt.grid(alpha=0.5)
plt.xlabel('false positive rate (fpr)')
plt.ylabel('true positive rate (tpr)')
plt.show()
# 绘制各个评估器的决策边界
sc = StandardScale... | n_estimators=500,
learning_rate=0.1,
random_state=1) | random_line_split | |
app.py | #集成分类器---简单投票分类器##################################
# 使用k-折交叉验证评估各评估器的性能
def function2():
clf1 = LogisticRegression(penalty='l2',C=0.001,random_state=1)
clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0)
clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski')
pipe1 = ... | enols',
'Proanthocyanins',
'Color intensity', 'Hue',
'OD280/OD315 of diluted wines',
'Proline']
# drop 1 class
df_wine = df_wine[df_wine['Class label'] != 1]
y = df_wine['Class label'].values
X = df_wine[['Alcoho... | vanoid ph | identifier_name |
app.py | random_state=1)
clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0)
clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski')
pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]])
pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]])
mv_clf = MajoritVoteClass... | range,linestyle='--',label='base error',lw='2')
plt.plot(error_range,ens_errors,label='ensemble error',lw='2')
plt.xlabel("base error")
plt.ylabel("base/ensemble error")
plt.legend(loc='upper left')
plt.grid(alpha=0.5)
plt.show()
#################集成分类器---简单投票分类器#################################... | identifier_body | |
nargs.go | .(type) {
case *ast.FuncDecl:
funcDecl = topLevelType
if funcDecl.Body == nil {
// This means funcDecl is an external (non-Go) function, these
// should not be included in the analysis
return v
}
stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList)
file = v.fileSet.File(funcDecl.Pos())
case *... | handleFieldList | identifier_name | |
nargs.go | v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList)
case *ast.SelectStmt:
stmtList = append(stmtList, s.Body)
case *ast.CommClause:
stmtList = append(stmtList, s.Body...)
stmtList = append(stmtList, s.Comm)
case *ast.BranchStmt:
handleIdent(paramMap, s.Label)
case *ast.SwitchStmt:
stmtList... | {
for _, paramList := range funcDecl.Type.Params.List {
for _, name := range paramList.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
} | conditional_block | |
nargs.go | byLineNumber) Len() int { return len(a) }
func (a byLineNumber) Less(i, j int) bool {
iLine := strings.Split(a[i], ":")
num := strings.Split(iLine[1], " ")
iNum, _ := strconv.Atoi(num[0])
jLine := strings.Split(a[j], ":")
num = strings.Split(jLine[1], " ")
jNum, _ := strconv.Atoi(num[0])
return iNum < jNum
}
f... |
// Visit implements the ast.Visitor Visit method.
func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor {
var stmtList []ast.Stmt
var file *token.File
paramMap := make(map[string]bool)
var funcDecl *ast.FuncDecl
switch topLevelType := node.(type) {
case *ast.FuncDecl:
funcDecl = topLevelType
if funcDec... | { a[i], a[j] = a[j], a[i] } | identifier_body |
nargs.go | Exprs(paramMap, []ast.Expr{s.Cond}, stmtList)
case *ast.AssignStmt:
assigned := false
for index, right := range s.Rhs {
funcLit, ok := right.(*ast.FuncLit)
if !ok {
continue
}
funcName, ok := s.Lhs[index].(*ast.Ident)
if !ok {
//TODO - understand this case a little more
// lo... | // no-op, ImportSpecs do not contain functions
| random_line_split | |
raft.go | retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here (2C).
// Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w)
// e.Encode(rf.xxx)
// e.Encode(rf.yyy)
// data := w.Bytes()
// rf.persister.Sav... | (command interface{}) (int, int, bool) {
index := -1
term := -1
isLeader := true
// Your code here (2B).
rf.mu.Lock()
defer rf.mu.Unlock()
index = rf.commitIndex + 1
term = rf.currentTerm
isLeader = rf.currentState == StateLeader
return index, term, isLeader
}
//
// the tester doesn't halt goroutines creat... | Start | identifier_name |
raft.go | retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here (2C).
// Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w)
// e.Encode(rf.xxx)
// e.Encode(rf.yyy)
// data := w.Bytes()
// rf.persister.Sav... |
rf.tryEnterFollowState(args.Term)
rf.currentTerm = args.Term
rf.votedFor = args.CandidateId
reply.VoteGranted = true
}
//
// example code to send a RequestVote RPC to a server.
// server is the index of the target server in rf.peers[].
// expects RPC arguments in args.
// fills in *reply with RPC reply, so call... | {
// If this node is more up-to-date than candidate, then reject vote
//DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me,
// lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm)
reply.VoteGranted = false
return
} | conditional_block |
raft.go |
//
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here (2C).
// Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w)
// ... | {
//var term int
//var isleader bool
// Your code here (2A).
rf.mu.Lock()
defer rf.mu.Unlock()
return rf.currentTerm, rf.currentState == StateLeader
} | identifier_body | |
raft.go | // (Initialized to leader last log index + 1)
nextIndex []int
// For each server, index of the highest log entry known to be
// replicated on server
// (Initialized to 0, increases monotonically)
matchIndex []int
// Handle AppendEntriesRPC reply int this channel
appendEntriesReplyHandler chan AppendEntriesRepl... | // Volatile fields on leader, reinitialized after election
//
// For each server, index of the highest log entry to send to that server | random_line_split | |
svc.go | method implements the yaml.Unmarshaler (v3) interface.
func (r *Range) UnmarshalYAML(value *yaml.Node) error {
if err := value.Decode(&r.RangeConfig); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !r.RangeConfig.IsEmpty() {
// Unmarshaled successfully to r.... | () bool {
return r.ScalingConfig.IsEmpty() && r.Value == nil
}
// IsEmpty returns whether AdvancedScalingConfig is empty
func (a *AdvancedScalingConfig[_]) IsEmpty() bool {
return a.Cooldown.IsEmpty() && a.Value == nil
}
// IsEmpty returns whether Cooldown is empty
func (c *Cooldown) IsEmpty() bool {
return c.Scal... | IsEmpty | identifier_name |
svc.go | method implements the yaml.Unmarshaler (v3) interface.
func (r *Range) UnmarshalYAML(value *yaml.Node) error {
if err := value.Decode(&r.RangeConfig); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !r.RangeConfig.IsEmpty() {
// Unmarshaled successfully to r.... |
// RangeConfig containers a Min/Max and an optional SpotFrom field which
// specifies the number of services you want to start placing on spot. For
// example, if your range is 1-10 and `spot_from` is 5, up to 4 services will
// be placed on dedicated Fargate capacity, and then after that, any scaling
// event will p... | {
minMax := strings.Split(string(r), "-")
if len(minMax) != 2 {
return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r))
}
min, err = strconv.Atoi(minMax[0])
if err != nil {
return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0])
}
max, err =... | identifier_body |
svc.go | This method implements the yaml.Unmarshaler (v3) interface.
func (r *Range) UnmarshalYAML(value *yaml.Node) error {
if err := value.Decode(&r.RangeConfig); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !r.RangeConfig.IsEmpty() {
// Unmarshaled successfully ... | if err := value.Decode(&r.Value); err != nil {
return errors.New(`unable to unmarshal into int or composite-style map`)
}
return nil
}
// IsEmpty returns whether Count is empty.
func (c *Count) IsEmpty() bool {
return c.Value == nil && c.AdvancedCount.IsEmpty()
}
// Desired returns the desiredCount to be set on... | return nil
}
| random_line_split |
svc.go | method implements the yaml.Unmarshaler (v3) interface.
func (r *Range) UnmarshalYAML(value *yaml.Node) error {
if err := value.Decode(&r.RangeConfig); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !r.RangeConfig.IsEmpty() {
// Unmarshaled successfully to r.... |
if !r.ScalingConfig.IsEmpty() {
// Successfully unmarshalled ScalingConfig fields, return
return nil
}
if err := value.Decode(&r.Value); err != nil {
return errors.New(`unable to unmarshal into int or composite-style map`)
}
return nil
}
// IsEmpty returns whether Count is empty.
func (c *Count) IsEmpty(... | {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
} | conditional_block |
lib.rs | Regex;
#[derive(Clone, Debug)]
enum Line {
Blank,
Comment(String),
Entry(Entry),
}
#[derive(Clone, Debug)]
struct Entry {
key: String,
value: String,
}
impl Entry {
pub fn new(key: String, value: String) -> Self {
Self { key, value }
}
pub fn | (&self) -> &str {
&self.value
}
pub fn get_key(&self) -> &str {
&self.key
}
pub fn set_value(&mut self, value: String) {
self.value = value;
}
}
/// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data.
/... | get_value | identifier_name |
lib.rs | Regex;
#[derive(Clone, Debug)]
enum Line {
Blank,
Comment(String),
Entry(Entry),
}
#[derive(Clone, Debug)]
struct Entry {
key: String,
value: String,
}
impl Entry {
pub fn new(key: String, value: String) -> Self {
Self { key, value }
}
pub fn get_value(&self) -> &str {
... | if let Line::Entry(entry) = e {
if entry.get_key() == key {
entry.set_value(value.clone());
n += 1;
}
}
}
if n == 0 {
self.lines
.push(Line::Entry(Entry::new(key.to_string(), valu... | }
let mut n = 0;
for e in self.lines.iter_mut() { | random_line_split |
lib.rs | ;
#[derive(Clone, Debug)]
enum Line {
Blank,
Comment(String),
Entry(Entry),
}
#[derive(Clone, Debug)]
struct Entry {
key: String,
value: String,
}
impl Entry {
pub fn new(key: String, value: String) -> Self {
Self { key, value }
}
pub fn get_value(&self) -> &str {
&se... |
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::fs::read_to_string;
use std::iter;
use super::*;
fn random_alphanumeric() -> String {
let mut rng ... | {
let mut output = HashMap::new();
conf.keys_values_iter().for_each(|(key, value)| {
output.insert(key.to_owned(), value.to_owned());
});
output
} | identifier_body |
ctrl_map.rs | Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum MappingType {
None,
Absolute,
Relative
}
#[derive(Clone, Copy, Debug)]
pub struct CtrlMapEntry {
id: ParamId,
map_type: MappingType,
val_range: &'static ValueRange,
}
/// ValueRange contains a reference, so it can't be stored easily. Inste... | (&mut self, ctrl_no: u64, ctrl_type: MappingType) {
let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter);
self.map.add_mapping(1,
ctrl_no,
ctrl_type,
self.param_id,
... | add_controller | identifier_name |
ctrl_map.rs | Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum MappingType {
None,
Absolute,
Relative
}
#[derive(Clone, Copy, Debug)]
pub struct CtrlMapEntry {
id: ParamId,
map_type: MappingType,
val_range: &'static ValueRange,
}
/// ValueRange contains a reference, so it can't be stored easily. Inste... |
MappingType::None => panic!(),
};
Ok(result)
}
// Load controller mappings from file
pub fn load(&mut self, filename: &str) -> std::io::Result<()> {
info!("Reading controller mapping from {}", filename);
let file = File::open(filename)?;
let mut reader =... | {
// For relative: Increase/ decrease value
let sound_value = sound.get_value(&mapping.id);
let delta = if value >= 64 { -1 } else { 1 };
result.value = mapping.val_range.add_value(sound_value, delta);
} | conditional_block |
ctrl_map.rs | , Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum MappingType {
None,
Absolute,
Relative
}
#[derive(Clone, Copy, Debug)]
pub struct CtrlMapEntry {
id: ParamId,
map_type: MappingType,
val_range: &'static ValueRange,
}
/// ValueRange contains a reference, so it can't be stored easily. Inst... | controller: u64,
value: u64,
sound: &SoundData) -> Result<SynthParam, ()> {
// Get mapping
if !self.map[set].contains_key(&controller) {
return Err(());
}
let mapping = &self.map[set][&controller];
let mut re... | set: usize, | random_line_split |
ctrl_map.rs | Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum MappingType {
None,
Absolute,
Relative
}
#[derive(Clone, Copy, Debug)]
pub struct CtrlMapEntry {
id: ParamId,
map_type: MappingType,
val_range: &'static ValueRange,
}
/// ValueRange contains a reference, so it can't be stored easily. Inste... |
#[test]
fn value_can_be_changed_absolute() {
let mut context = TestContext::new();
assert_eq!(context.has_value(50.0), true);
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 0), true);
assert_eq!(context.has_value(0.0), true);
}
#[test]
fn relative_contro... | {
let mut context = TestContext::new();
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 50), true);
} | identifier_body |
random.rs | state.nonce = 0;
state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]);
state
.plaintext
.copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]);
}
async fn generate_bytes(&self, mut output: &mut [u8]) {
let state = {
let mut guard = self.state.... | {
Self {
w: 32,
n: 624,
m: 397,
r: 31,
a: 0x9908B0DF,
u: 11,
d: 0xffffffff,
s: 7,
b: 0x9D2C5680,
t: 15,
c: 0xEFC60000,
l: 18,
f: 1812433253,
x... | identifier_body | |
random.rs | <T: RngNumber>(&mut self, min: T, max: T) -> T {
let mut buf = T::Buffer::default();
self.generate_bytes(buf.as_mut());
T::between_buffer(buf, min, max)
}
fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T {
assert!(!elements.is_empty(), "Choosing from empty list");
... | assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); | random_line_split | |
random.rs | ::new(GlobalRngState {
bytes_since_reseed: Mutex::new(std::usize::MAX),
rng: ChaCha20RNG::new(),
}),
}
}
}
#[async_trait]
impl SharedRng for GlobalRng {
fn seed_size(&self) -> usize {
0
}
async fn seed(&self, _new_seed: &[u8]) {
// Gl... | () -> Self {
Self {
state: Mutex::new(ChaCha20RNGState {
key: [0u8; CHACHA20_KEY_SIZE],
nonce: 0,
plaintext: [0u8; CHACHA20_BLOCK_SIZE],
}),
}
}
}
#[async_trait]
impl SharedRng for ChaCha20RNG {
fn seed_size(&self) -> usize... | new | identifier_name |
random.rs |
let mut buf = vec![];
buf.resize(upper.byte_width(), 0);
let mut num_bytes = ceil_div(upper.value_bits(), 8);
let msb_mask: u8 = {
let r = upper.value_bits() % 8;
if r == 0 {
0xff
} else {
!((1 << (8 - r)) - 1)
}
};
// TODO: Refactor o... | {
return Err(err_msg("Invalid upper/lower range"));
} | conditional_block | |
main.rs | io::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Block, Borders, Paragraph, Text, Widget};
use tui::Terminal;
const DRAW_EVERY: std::time::Duration = std::time::Duration::from_mill... | {
window: BTreeMap<usize, String>,
}
fn main() -> Result<(), io::Error> {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backe... | Thread | identifier_name |
main.rs | io::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Block, Borders, Paragraph, Text, Widget};
use tui::Terminal;
const DRAW_EVERY: std::time::Duration = std::time::Duration::from_mill... | lines.push(Text::styled(
format!(" {}{}\n", frame, offset),
Style::default().modifier(Modifier::DIM),
));
}
}
lines.push(Text::raw("\n"));
}
| } else { | random_line_split |
main.rs | io::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Block, Borders, Paragraph, Text, Widget};
use tui::Terminal;
const DRAW_EVERY: std::time::Duration = std::time::Duration::from_mill... |
}
Either::Right(key) => {
let key = key?;
if let termion::event::Key::Char('q') = key {
break;
}
}
}
}
terminal.clear()?;
Ok(())
})
}
fn draw<B: ... | {
assert!(inframe.is_some());
stack.push_str(line.trim());
stack.push(';');
} | conditional_block |
main.rs | io::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Modifier, Style};
use tui::widgets::{Block, Borders, Paragraph, Text, Widget};
use tui::Terminal;
const DRAW_EVERY: std::time::Duration = std::time::Duration::from_mill... | .direction(Direction::Vertical)
.margin(2)
.constraints([Constraint::Percentage(100)].as_ref())
.split(f.size());
Block::default()
.borders(Borders::ALL)
.title("Common thread fan-out points")
.title_style(Style::default().fg(Co... | {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend... | identifier_body |
sbot.py | = image_file_to_string(image_file + '.tif', graceful_errors=True)
except IOError:
print("Error converting tif to text")
except errors.Tesser_General_Exception:
print("Error converting tif to text in Tesseract")
return text
def convTIF2PNG(fileName):
image_file = Image.open(fi... | if rarity == "Rare" and not hasSpeedSub:
keep = False
else:
keep = True | conditional_block | |
sbot.py |
def adbdevices():
return adb.adbdevices()
def touchscreen_devices():
return adb.touchscreen_devices()
def tap(x, y):
command = "input tap " + str(x) + " " + str(y)
command = str.encode(command)
adbshell(command.decode('utf-8'))
def screenCapture():
# perform a search in th... | return adb.adbpull(command) | identifier_body | |
sbot.py | Epoch)):
sys.stdout.write('\r' + str(int(timeEpoch)-i)+' ')
sys.stdout.flush()
time.sleep(1)
last_sec = i
if timeEpoch-float(last_sec+1) > 0:
time.sleep(timeEpoch-float(last_sec+1))
# print("")
sys.stdout.write('\r')
sys.stdout.flush()
# print(""... | ():
i = 2
keep = True
hasSpeedSub = False
foundRare = False
global soldRunes
global keptRunes
while i > 0:
i-=1
performOCR()
fileN = crop(1200,350,50,100,"capcha") # Rarity
convPNG2TIF(fileN)
try:
img = ... | keepOrSellRune | identifier_name |
sbot.py | return adb.touchscreen_devices()
def tap(x, y):
command = "input tap " + str(x) + " " + str(y)
command = str.encode(command)
adbshell(command.decode('utf-8'))
def screenCapture():
# perform a search in the sdcard of the device for the SummonerBot
# folder. if we found it, we delet... | def adbdevices():
return adb.adbdevices()
def touchscreen_devices():
| random_line_split | |
triggers.go | github.com/fnproject/fn_go/clientv2"
apiTriggers "github.com/fnproject/fn_go/clientv2/triggers"
models "github.com/fnproject/fn_go/modelsv2"
"github.com/fnproject/fn_go/provider"
"github.com/urfave/cli"
)
type triggersCmd struct {
provider provider.Provider
client *fnclient.Fn
}
// TriggerFlags used to create... | (c *cli.Context) error {
resTriggers, err := getTriggers(c, t.client)
if err != nil {
return err
}
fnName := c.Args().Get(1)
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
if len(fnName) != 0 {
fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n")
for _, trigger := ... | list | identifier_name |
triggers.go | github.com/fnproject/fn_go/clientv2"
apiTriggers "github.com/fnproject/fn_go/clientv2/triggers"
models "github.com/fnproject/fn_go/modelsv2"
"github.com/fnproject/fn_go/provider"
"github.com/urfave/cli"
)
type triggersCmd struct {
provider provider.Provider
client *fnclient.Fn
}
// TriggerFlags used to create... |
// CreateTrigger request
func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error {
resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{
Context: context.Background(),
Body: trigger,
})
if err != nil {
switch e := err.(type) {
case *apiTriggers.CreateTriggerBadRequ... | {
if !strings.HasPrefix(ts, "/") {
ts = "/" + ts
}
return ts
} | identifier_body |
triggers.go | fn annotation (can be specified multiple times)",
},
}
func (t *triggersCmd) create(c *cli.Context) error {
appName := c.Args().Get(0)
fnName := c.Args().Get(1)
triggerName := c.Args().Get(2)
app, err := app.GetAppByName(t.client, appName)
if err != nil {
return err
}
fn, err := fn.GetFnByName(t.client, ap... | {
return nil, err
} | conditional_block | |
triggers.go | "github.com/fnproject/fn_go/clientv2"
apiTriggers "github.com/fnproject/fn_go/clientv2/triggers"
models "github.com/fnproject/fn_go/modelsv2"
"github.com/fnproject/fn_go/provider"
"github.com/urfave/cli"
)
type triggersCmd struct {
provider provider.Provider
client *fnclient.Fn
}
// TriggerFlags used to crea... | endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"]
fmt.Println("Trigger Endpoint:", endpoint)
return nil
}
func (t *triggersCmd) list(c *cli.Context) error {
resTriggers, err := getTriggers(c, t.client)
if err != nil {
return err
}
fnName := c.Args().Get(1)
w := tabwriter.NewWriter(os... | }
fmt.Println("Successfully created trigger:", resp.Payload.Name) | random_line_split |
sql_utils.rs | : &Path,
pgcb: S,
) -> Result<(Cow<Path>, SqliteConnection), crate::Error> {
// early return in case the file does not actually exist
if !archive_path.exists() {
return Ok((archive_path.into(), sqlite_connect(archive_path)?));
}
let migrate_to_path = {
let mut tmp = archive_path.to_path_buf();
tmp.set_exten... |
#[test]
fn test_input_unknown_archive() {
let string0 = "
youtube ____________
youtube ------------
youtube aaaaaaaaaaaa
soundcloud 0000000000
";
let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl");
let pgcounter = RwLock::new(Vec::<ImportProgress>::new());
let re... | {
return |imp| c.write().expect("write failed").push(imp);
} | identifier_body |
sql_utils.rs | : &Path,
pgcb: S,
) -> Result<(Cow<Path>, SqliteConnection), crate::Error> {
// early return in case the file does not actually exist
if !archive_path.exists() {
return Ok((archive_path.into(), sqlite_connect(archive_path)?));
}
let migrate_to_path = {
let mut tmp = archive_path.to_path_buf();
tmp.set_exten... |
assert!(res.is_err());
let res = match res {
Ok(_) => panic!("Expected a Error value"),
Err(err) => err,
};
assert!(res
.to_string()
.contains("Unknown Archive type to migrate, maybe try importing"));
assert_eq!(0, pgcounter.read().expect("read failed").len());
}
#[test]
fn test_... | random_line_split | |
sql_utils.rs | : &Path,
pgcb: S,
) -> Result<(Cow<Path>, SqliteConnection), crate::Error> {
// early return in case the file does not actually exist
if !archive_path.exists() {
return Ok((archive_path.into(), sqlite_connect(archive_path)?));
}
let migrate_to_path = {
let mut tmp = archive_path.to_path_buf();
tmp.set_exten... | ,
ArchiveType::JSON => {
debug!("Applying Migration from JSON to SQLite");
// handle case where the input path matches the changed path
if migrate_to_path == archive_path {
return Err(crate::Error::other(
"Migration cannot be done: Input path matches output path (setting extension to \".db\")",
... | {
return Err(crate::Error::other(
"Unknown Archive type to migrate, maybe try importing",
))
} | conditional_block |
sql_utils.rs | : &Path,
pgcb: S,
) -> Result<(Cow<Path>, SqliteConnection), crate::Error> {
// early return in case the file does not actually exist
if !archive_path.exists() {
return Ok((archive_path.into(), sqlite_connect(archive_path)?));
}
let migrate_to_path = {
let mut tmp = archive_path.to_path_buf();
tmp.set_exten... | (c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_ {
return |imp| c.write().expect("write failed").push(imp);
}
#[test]
fn test_input_unknown_archive() {
let string0 = "
youtube ____________
youtube ------------
youtube aaaaaaaaaaaa
soundcloud 0000000000
";
let (path, _... | callback_counter | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.