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 |
|---|---|---|---|---|
http.rs | VmType, WithVM, IO};
use vm::gc::{Gc, Traverseable};
use gluon::import::add_extern_module;
use vm::internal::Value;
use gluon::{new_vm, Compiler};
// `Handler` is a type defined in http.glu but since we need to refer to it in the signature of
// listen we define a phantom type which we can use with `OpaqueValue` to... | stream.poll().map(|async| async.map(IO::Value))
})))
}
// A http body that is being written
pub struct ResponseBody(Arc<Mutex<Option<Sender<Result<Chunk, hyper::Error>>>>>);
impl fmt::Debug for ResponseBody {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hyper::Response")
... | // polled until completion. After `poll` returns `Ready` the value is then returned to the
// gluon function which called `read_chunk`
FutureResult(Box::new(poll_fn(move || {
let mut stream = body.lock().unwrap(); | random_line_split |
http.rs | mType, WithVM, IO};
use vm::gc::{Gc, Traverseable};
use gluon::import::add_extern_module;
use vm::internal::Value;
use gluon::{new_vm, Compiler};
// `Handler` is a type defined in http.glu but since we need to refer to it in the signature of
// listen we define a phantom type which we can use with `OpaqueValue` to s... |
}
define_vmtype! { StatusCode }
impl<'vm> Getable<'vm> for Wrap<StatusCode> {
fn from_value(_: &'vm Thread, value: Variants) -> Self {
use hyper::StatusCode::*;
match value.as_ref() {
ValueRef::Data(data) => Wrap(match data.tag() {
0 => Ok,
1 => NotFoun... | {
use hyper::Method::*;
context.stack.push(Value::tag(match self.0 {
Get => 0,
Post => 1,
Delete => 2,
_ => {
return Err(VmError::Message(format!(
"Method `{:?}` does not exist in gluon",
self.0
... | identifier_body |
http.rs | make_type(vm)])
}
}
// Rust does not let us define traits on types defined in a different crate such as `hyper`. We can
// however work around this by defining a wrapper type which we are then able to define the traits
// on.
struct Wrap<T>(T);
macro_rules! define_vmtype {
($name: ident) => {
impl VmT... |
let _ = stderr().write(err.as_bytes());
Ok(
HyperResponse::new()
.with_status(StatusCode::InternalServerError),
)
... | conditional_block | |
http.rs | mType, WithVM, IO};
use vm::gc::{Gc, Traverseable};
use gluon::import::add_extern_module;
use vm::internal::Value;
use gluon::{new_vm, Compiler};
// `Handler` is a type defined in http.glu but since we need to refer to it in the signature of
// listen we define a phantom type which we can use with `OpaqueValue` to s... | (
response: &ResponseBody,
bytes: &[u8],
) -> FutureResult<Box<Future<Item = IO<()>, Error = VmError> + Send + 'static>> {
use futures::future::poll_fn;
use futures::AsyncSink;
// Turn `bytes´ into a `Chunk` which can be sent to the http body
let mut unsent_chunk = Some(Ok(bytes.to_owned().into... | write_response | identifier_name |
functional_dependencies.rs | ?;
Ok(idx)
})
.collect::<Result<Vec<_>>>()?;
Ok(if *is_primary {
Constraint::PrimaryKey(indices)
} else {
Constraint::Unique(indices)
})... | /// this flag is `false`.
/// Note that as the schema changes between different stages in a plan,
/// such as after LEFT JOIN or RIGHT JOIN operations, this property may
/// change.
pub nullable: bool,
// The functional dependency mode:
pub mode: Dependency,
}
/// Describes functional depen... | pub target_indices: Vec<usize>,
/// Flag indicating whether one of the `source_indices` can receive NULL values.
/// For a data source, if the constraint in question is `Constraint::Unique`,
/// this flag is `true`. If the constraint in question is `Constraint::PrimaryKey`, | random_line_split |
functional_dependencies.rs | DataFusionError::Execution(
"Primary key doesn't exist".to_string(),
)
})?;
Ok(idx)
})
.collect::<Re... | {
let constraints = constraints
.iter()
.map(|c: &TableConstraint| match c {
TableConstraint::Unique {
columns,
is_primary,
..
} => {
// Get primary key and/or unique indices i... | identifier_body | |
functional_dependencies.rs | ?;
Ok(idx)
})
.collect::<Result<Vec<_>>>()?;
Ok(if *is_primary {
Constraint::PrimaryKey(indices)
} else {
Constraint::Unique(indices)
})... | (dependencies: Vec<FunctionalDependence>) -> Self {
Self { deps: dependencies }
}
/// Creates a new `FunctionalDependencies` object from the given constraints.
pub fn new_from_constraints(
constraints: Option<&Constraints>,
n_field: usize,
) -> Self {
if let Some(Constra... | new | identifier_name |
functional_dependencies.rs | ?;
Ok(idx)
})
.collect::<Result<Vec<_>>>()?;
Ok(if *is_primary | else {
Constraint::Unique(indices)
})
}
TableConstraint::ForeignKey { .. } => Err(DataFusionError::Plan(
"Foreign key constraints are not currently supported".to_string(),
)),
TableConstraint... | {
Constraint::PrimaryKey(indices)
} | conditional_block |
views.py | current_page + 3 >= pages:
# return range(pages - 4, pages + 1)
# else:
# return range(current_page - 2, current_page + 2)
def loginValid(fun):
@functools.wraps(fun)
def inner(*args, **kwargs):
id = request.cookies.get('id', 0)
username = request.cookies.get('use... | task.validate_on_submit() # 判断是否是一个有效的post请求
task.validate() # 判断是否是一个有效的post请求
task.data # 提交的数据
:return:
'''
errors = {}
task = TaskForm()
if request.method == 'POST':
if task.validate_on_submit():
formData = task.data
else:
errors_... | def add_task():
'''
task.errors # 表单校验错误
| random_line_split |
views.py | _page + 3 >= pages:
# return range(pages - 4, pages + 1)
# else:
# return range(current_page - 2, current_page + 2)
def loginValid(fun):
@functools.wraps(fun)
def inner(*args, **kwargs):
id = request.cookies.get('id', 0)
username = request.cookies.get('username')
... | ister(): # 视图
err_msg = ''
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
if username:
if email:
if password:
user = User()
... | ods=['GET', 'POST']) # 路由
def reg | identifier_body |
views.py | 加密
hl = md5(pwd.encode(encoding='utf-8'))
new_pwd = hl.hexdigest()
return new_pwd
# def back_page(pages, current_page): # 返回页数
# if pages <= 5:
# return range(1, pages + 1)
# if current_page <= 3:
# return range(1, 6)
# elif current_page + 3 >= pages:
# ret... | : # 密码 | identifier_name | |
views.py | _page + 3 >= pages:
# return range(pages - 4, pages + 1)
# else:
# return range(current_page - 2, current_page + 2)
def loginValid(fun):
@functools.wraps(fun)
def inner(*args, **kwargs):
id = request.cookies.get('id', 0)
username = request.cookies.get('username')
... | ethod == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user:
if set_pwd(password) == user.password:
response = redirect('/index/')
response.set_cooki... | err_msg = ''
if request.m | conditional_block |
apigroup.rs | , ResourceExt};
/// #[tokio::main]
/// async fn main() -> Result<(), kube::Error> {
/// let client = Client::try_default().await?;
/// let apigroup = discovery::group(&client, "apiregistration.k8s.io").await?;
/// for (apiresource, caps) in apigroup.versioned_resources("v1") {
/// println!("Found ... |
}
Err(DiscoveryError::MissingKind(format!("{:?}", gvk)).into())
}
// shortcut method to give cheapest return for a pinned group
pub(crate) async fn query_gv(client: &Client, gv: &GroupVersion) -> Result<Self> {
let apiver = gv.api_version();
let list = if gv.group.is_empty(... | {
let ar = parse::parse_apiresource(res, &list.group_version)?;
let caps = parse::parse_apicapabilities(&list, &res.name)?;
return Ok((ar, caps));
} | conditional_block |
apigroup.rs | discovery, ResourceExt};
/// #[tokio::main]
/// async fn main() -> Result<(), kube::Error> {
/// let client = Client::try_default().await?;
/// let apigroup = discovery::group(&client, "apiregistration.k8s.io").await?;
/// for (apiresource, caps) in apigroup.versioned_resources("v1") {
/// printl... | (&mut self) {
self.data
.sort_by_cached_key(|gvd| Version::parse(gvd.version.as_str()))
}
// shortcut method to give cheapest return for a single GVK
pub(crate) async fn query_gvk(
client: &Client,
gvk: &GroupVersionKind,
) -> Result<(ApiResource, ApiCapabilities)> {... | sort_versions | identifier_name |
apigroup.rs | s.io").await?;
/// for (apiresource, caps) in apigroup.versioned_resources("v1") {
/// println!("Found ApiResource {}", apiresource.kind);
/// }
/// Ok(())
/// }
/// ```
///
/// But if you do not know this information, you can use [`ApiGroup::preferred_version_or_latest`].
///
/// Whichever way y... | /// for (ar, caps) in apigroup.recommended_resources() {
/// if !caps.supports_operation(verbs::LIST) {
/// continue;
/// }
/// let api: Api<DynamicObject> = Api::all_with(client.clone(), &ar); | random_line_split | |
apigroup.rs | , ResourceExt};
/// #[tokio::main]
/// async fn main() -> Result<(), kube::Error> {
/// let client = Client::try_default().await?;
/// let apigroup = discovery::group(&client, "apiregistration.k8s.io").await?;
/// for (apiresource, caps) in apigroup.versioned_resources("v1") {
/// println!("Found ... |
// shortcut method to give cheapest return for a pinned group
pub(crate) async fn query_gv(client: &Client, gv: &GroupVersion) -> Result<Self> {
let apiver = gv.api_version();
let list = if gv.group.is_empty() {
client.list_core_api_resources(&apiver).await?
} else {
... | {
let apiver = gvk.api_version();
let list = if gvk.group.is_empty() {
client.list_core_api_resources(&apiver).await?
} else {
client.list_api_group_resources(&apiver).await?
};
for res in &list.resources {
if res.kind == gvk.kind && !res.name.... | identifier_body |
tlcell.rs | same memory.
#[inline]
pub fn rw3<'a, T: ?Sized, U: ?Sized, V: ?Sized>(
&'a mut self,
tc1: &'a TLCell<Q, T>,
tc2: &'a TLCell<Q, U>,
tc3: &'a TLCell<Q, V>,
) -> (&'a mut T, &'a mut U, &'a mut V) {
assert!(
(tc1 as *const _ as *const () as usize != tc2 as *... | {
Box::new(ACell::new(Squares(init)))
} | conditional_block | |
tlcell.rs | /// support `Send` or `Sync`.
pub fn new() -> Self {
SINGLETON_CHECK.with(|set| {
assert!(set.borrow_mut().insert(TypeId::of::<Q>()),
"Illegal to create two TLCellOwner instances within the same thread with the same marker type parameter");
});
Self {
... | /// thread, `Sync` is not supported for this type. However it *is*
/// possible to send the cell to another thread, which then allows its
/// contents to be borrowed using the owner in that thread.
///
/// See also [crate documentation](index.html).
///
/// [`TLCellOwner`]: struct.TLCellOwner.html
#[repr(transparent)]... | /// [`TLCellOwner`].
///
/// To borrow from this cell, use the borrowing calls on the
/// [`TLCellOwner`] instance that shares the same marker type. Since
/// there may be another indistinguishable [`TLCellOwner`] in another | random_line_split |
tlcell.rs | (*const ());
/// Borrowing-owner of zero or more [`TLCell`](struct.TLCell.html)
/// instances.
///
/// See [crate documentation](index.html).
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub struct TLCellOwner<Q: 'static> {
// Use NotSendOrSync to disable Send and Sync,
not_send_or_sync: PhantomData<NotSendO... | NotSendOrSync | identifier_name | |
transaction.go | // null marks beginning of list - not used as a record type
NullTag = TagType(iota)
// valid record types
// OBSOLETE items must still be supported to process older blocks
BaseDataTag = TagType(iota) // OBSOLETE: block owner
AssetDataTag = TagType(iota) // create asset
Bit... | turn TagType(recordType)
}
// RecordName - returns the name of a transaction record as a string
func RecordName(record interface{}) (string, bool) {
switch record.(type) {
case *OldBaseData, OldBaseData:
return "BaseData", true
case *AssetData, AssetData:
return "AssetData", true
case *BitmarkIssue, BitmarkI... | return NullTag
}
re | conditional_block |
transaction.go | // grant some value to another account
ShareSwapTag = TagType(iota) // atomically swap shares between accounts
// this item must be last
InvalidTag = TagType(iota)
)
// Packed - packed records are just a byte slice
type Packed []byte
// Transaction - generic transaction interface
type Transact... | eturn NewAssetIdentifier([]byte(assetData.Fingerprint))
}
// | identifier_body | |
transaction.go | FingerprintLength = 1
maxFingerprintLength = 1024
maxSignatureLength = 1024
)
// OldBaseData - the unpacked Proofer Data structure (OBSOLETE)
// this is first tx in every block and can only be used there
type OldBaseData struct {
Currency currency.Currency `json:"currency"` // utf-8 → Enum
PaymentAdd... | rshalText(s [ | identifier_name | |
transaction.go |
// TagType - type code for transactions
type TagType uint64
// enumerate the possible transaction record types
// this is encoded a Varint64 at start of "Packed"
const (
// null marks beginning of list - not used as a record type
NullTag = TagType(iota)
// valid record types
// OBSOLETE items must still be suppo... | random_line_split | ||
history.component.ts | welcomeMessageHistory";
logout: string = "Logout";
DASHBOAR: string = "DASHBOARD,";
ENVELOPES: string = "ENVELOPES";
GOALS: string = "GOALS";
BILLS: string = "BILLS";
HISTORY: string = "HISTORY";
UTILITIES: string = "UTILITIES";
user: string = "User";
settings: string = "Settings";
appearance: strin... | roups, category) {
for (let group of groups) {
if (group.name == category) return group;
}
return null;
}
makeDataArray1(array): Array<any> {
const returnTable = [array.length];
for (let i = 0; i < array.length; i++) {
returnTable[i] = array[i].sum;
}
return returnTable;
... | ndGroupByCategory(g | identifier_name |
history.component.ts | "welcomeMessageHistory";
logout: string = "Logout";
DASHBOAR: string = "DASHBOARD,";
ENVELOPES: string = "ENVELOPES";
GOALS: string = "GOALS";
BILLS: string = "BILLS";
HISTORY: string = "HISTORY";
UTILITIES: string = "UTILITIES";
user: string = "User";
settings: string = "Settings";
appearance: str... | lse if (a.month == b.month) {
if (a.day < b.day) {
return 1;
} else {
return -1;
}
} else {
return -1;
}
} else {
return -1;
}
return 0;
}
groupByCategories(parsedTable) {
const groups = [];
... | return 1;
} e | conditional_block |
history.component.ts | "welcomeMessageHistory";
logout: string = "Logout";
DASHBOAR: string = "DASHBOARD,";
ENVELOPES: string = "ENVELOPES";
GOALS: string = "GOALS";
BILLS: string = "BILLS";
HISTORY: string = "HISTORY";
UTILITIES: string = "UTILITIES";
user: string = "User";
settings: string = "Settings";
appearance: str... | }
translateMonth(month) {
switch (month) {
case '01':
return "JAN";
case '02':
return "FEB";
case '03':
return "MAR";
case '04':
return "APR";
case '05':
return "MAY";
case '06':
return "JUN"... | var expensesArray = []
for (var exp of expense) {
var date = exp.date.split('T')[0].split('-');
expensesArray.push({
id: exp._id,
year: date[0],
month: date[1],
monthName: this.translateMonth(date[1]),
day: date[2],
categor... | identifier_body |
history.component.ts | "welcomeMessageHistory";
logout: string = "Logout";
DASHBOAR: string = "DASHBOARD,";
ENVELOPES: string = "ENVELOPES";
GOALS: string = "GOALS";
BILLS: string = "BILLS";
HISTORY: string = "HISTORY";
UTILITIES: string = "UTILITIES";
user: string = "User";
settings: string = "Settings";
appearance: str... | const pieChart = this.groupByCategories(parsedTable);
const lineChartData = this.makeDataForGraph(this.filterByCategory(this.expenses))
this.chartData1 = this.makeDataArray1(pieChart);
this.chartColors1 = this.makeColorArray1(pieChart);
this.chartLabels1 = this.makeLabelArray1(pieChart);
... | const parsedTable = this.parseTable(this.expenses);
document.querySelector(".totaltext").innerHTML = "<h5>" + this.historyTotal + ": " + parsedTable.sum.toFixed(2); + "€</h5>"; | random_line_split |
blueberry_segmentation.py | 'image',
}
)
test_transform = A.Compose(
[
A.Resize(IMAGE_HEIGHT, IMAGE_WIDTH)
]
)
to_grayscale = A.Compose(
[
ToTensorV2()
]
)
class BlueberryDataset(Dataset):
def __init__(self, base_path, image_path, mask_path, transform=None):
self.images = []
self.masks = []
... | (self, index):
image = imread(self.images[index])
image = cvtColor(image, COLOR_BGR2RGB)
mask = imread(self.masks[index])
mask = cvtColor(mask, COLOR_BGR2RGB)
transformed = self.transform(image=image, mask=mask)
image = transformed['image']
... | __getitem__ | identifier_name |
blueberry_segmentation.py | """# Imports"""
import os
import matplotlib.pyplot as plt
from cv2 import imread, cvtColor, COLOR_BGR2RGB, COLOR_BGR2GRAY
from PIL import Image
import albumentations as A
from albumentations.pytorch.transforms import ToTensorV2
import torch
import torch.nn as nn
from torchvision import models
from torchvision import ... |
!pip install albumentations==0.4.6
!pip install torch
!pip install torchvision
| random_line_split | |
blueberry_segmentation.py | self.transform = transform
self.to_tensor = transforms.Compose([transforms.ToTensor()])
for image_file in os.listdir(image_path):
self.images.append(os.path.join(image_path, image_file))
def __len__(self):
return len(self.images)
def __getitem__(sel... | inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outpu... | conditional_block | |
blueberry_segmentation.py | 'image',
}
)
test_transform = A.Compose(
[
A.Resize(IMAGE_HEIGHT, IMAGE_WIDTH)
]
)
to_grayscale = A.Compose(
[
ToTensorV2()
]
)
class BlueberryDataset(Dataset):
def __init__(self, base_path, image_path, mask_path, transform=None):
|
def __len__(self):
return len(self.images)
def __getitem__(self, index):
image = imread(self.images[index])
image = cvtColor(image, COLOR_BGR2RGB)
mask = imread(self.masks[index])
mask = cvtColor(mask, COLOR_BGR2RGB)
transformed = self.tr... | self.images = []
self.masks = []
self.transform = transform
self.to_tensor = transforms.Compose([transforms.ToTensor()])
self.process_mask = transforms.Compose(
[
transforms.Grayscale(num_output_channels=1),
transforms.ToTensor(),
]
... | identifier_body |
post.page.ts | profile picture',
profile_picture_female: 'updated her profile picture',
profile_cover_male: 'updated his cover photo',
profile_cover_female: 'updated her cover photo',
page_picture: 'updated page picture',
page_cover: 'updated cover photo',
group_picture: 'updated group picture',
group_cover: 'updated group co... | {
this.post.sharePost({'do':type,id:id,my_id:localStorage.getItem('user_id')}).subscribe(async (resp) => {
const toast = await this.toastCtrl.create({
message: "Post has been shared successfully",
duration: 3000,
position: 'top'
});
toast.present();
}, async (err) => {
const toast = await this.toa... | identifier_body | |
post.page.ts | badgeCount = 6;
postFeeds: any = [];
post_type: any = {
shared: 'shared',
link: 'shared a link',
poll: 'created a poll',
product: 'added new product for sell',
article: 'added new article',
video : 'added a video',
audio: 'added an audio',
file: 'added a file',
photos: 'added a photo',
profile_picture_ma... | else {
return 'url(assets/followthebirdImgs/story_background.png)'
}
}
getMedia(media) {
let obj = JSON.parse(media)
return this.mediapath+obj[0].src;
}
sharePost(type,id){
this.post.sharePost({'do':type,id:id,my_id:localStorage.getItem('user_id')}).subscribe(async (resp) => {
const toast = | {
console.log(media);
let obj = JSON.parse(media)
return 'url(' + this.mediapath+obj[0].src + ')'
} | conditional_block |
post.page.ts | badgeCount = 6;
postFeeds: any = [];
post_type: any = {
shared: 'shared',
link: 'shared a link',
poll: 'created a poll',
product: 'added new product for sell',
article: 'added new article',
video : 'added a video',
audio: 'added an audio',
file: 'added a file',
photos: 'added a photo',
profile_picture_ma... | let item = data[0];
localStorage.setItem('last_post_live',item[0].post_id);
for (var key in item) {
if(item[key].post_type == 'photos'){
this.post_type.photos = "added "+item[key].photos_num+"photos";
}
this.postFeeds.push(item[key]);
}
});
}
doInfinite(event) {
setTimeout(() => ... | this.postElement['id'] = '';
this.post.getfeeds('newsfeed',localStorage.getItem('user_id'),localStorage.getItem('user_id'),{})
.then(data => {
this.postFeeds = []; | random_line_split |
post.page.ts | badgeCount = 6;
postFeeds: any = [];
post_type: any = {
shared: 'shared',
link: 'shared a link',
poll: 'created a poll',
product: 'added new product for sell',
article: 'added new article',
video : 'added a video',
audio: 'added an audio',
file: 'added a file',
photos: 'added a photo',
profile_picture_ma... | (filePath){
let arr = filePath.split('/');
var filename = arr.pop();
let url = encodeURI(filePath);
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(this.mediapath+filePath, this.file.dataDirectory + filename).then((entry) => {
let toast = this.toastCtrl.create({
m... | downloadAttachment | identifier_name |
clarans.py | param[in] data (list): Input data that is presented as list of points (objects), each point should be
represented by list or tuple.
@param[in] number_clusters (uint): Amount of clusters that should be allocated.
@param[in] numlocal (uint): The number of local minima obtained (amount of iteration... |
# case 4:
else:
candidate_cost += (
distance_candidate - distance_nearest
)
if candidate_cost < 0:
counter += 1
# set candidate that has ... | pass | conditional_block |
clarans.py | .__numlocal < 0:
raise ValueError(
"Local minima (current value: '%d') should be greater or equal to 0."
% self.__numlocal
)
if self.__maxneighbor < 0:
raise ValueError(
"Maximum number of neighbors (current value: '%d') should... | compute_cost_clarans | identifier_name | |
clarans.py | @brief Cluster analysis algorithm: CLARANS.
@details Implementation based on paper @cite article::clarans::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2019
@copyright GNU Public License
@cond GNU_PUBLIC_LICENSE
PyClustering is free software: you can redistribute it and/or modify
it under th... | """!
| random_line_split | |
clarans.py | [in] data (list): Input data that is presented as list of points (objects), each point should be
represented by list or tuple.
@param[in] number_clusters (uint): Amount of clusters that should be allocated.
@param[in] numlocal (uint): The number of local minima obtained (amount of iterations for... |
# update clusters in line with random allocated medoids
self.__update_clusters(self.__current)
# optimize configuration
self.__optimize_configuration()
# obtain cost of current cluster configuration and compare it with the best obtained
estimati... | """!
@brief Performs cluster analysis in line with rules of CLARANS algorithm.
@return (clarans) Returns itself (CLARANS instance).
@see get_clusters()
@see get_medoids()
"""
random.seed()
# loop for a numlocal number of times
for _ in range(0, self._... | identifier_body |
mod.rs | zero or more children.
pub trait Block: std::fmt::Debug {
/// The output of executing this block.
type Output;
/// The signatures on this block.
type Signature;
/// Whether consensus has decided to commit this block. This kind of blocks are expected to be
/// sent to storage very soon, unless... | id,
);
}
hash_map::Entry::Vacant(_) => bail_err!(AddBlockError::ParentNotFound { block }),
}
Ok(())
}
//
/ Returns a reference to a specific block, if it exists in the tree.
pub fn get_block(&self, id: HashValue) -> Option<&B> {
... | assert!(!self.id_to_block.contains_key(&self.last_committed_id));
let id = block.id();
if self.id_to_block.contains_key(&id) {
bail_err!(AddBlockError::BlockAlreadyExists { block });
}
let parent_id = block.parent_id();
if parent_id == self.last_committed_id {
... | identifier_body |
mod.rs | zero or more children.
pub trait Block: std::fmt::Debug {
/// The output of executing this block.
type Output;
/// The signatures on this block.
type Signature;
/// Whether consensus has decided to commit this block. This kind of blocks are expected to be
/// sent to storage very soon, unless... | lf, last_committed_id: HashValue) {
let mut | ut se | identifier_name |
mod.rs | zero or more children.
pub trait Block: std::fmt::Debug {
/// The output of executing this block.
type Output;
/// The signatures on this block.
type Signature;
/// Whether consensus has decided to commit this block. This kind of blocks are expected to be
/// sent to storage very soon, unless... | let mut current_heads = self.heads.clone();
while let Some(committed_head) = self.get_committed_head(¤t_heads) {
assert!(
current_heads.remove(&committed_head),
"committed_head should exist.",
);
for id in current_heads {
... |
// First find if there is a committed block in current heads. Since these blocks are at the
// same height, at most one of them can be committed. If all of them are pending we have
// nothing to do here. Otherwise, one of the branches is committed. Throw away the rest of
// them and ad... | random_line_split |
mod.rs | ) -> Result<libc::tm, Error> {
let mut result = new_libc_tm();
unsafe {
if libc::gmtime_r(&epoch, &mut result).is_null() {
bail!("libc::gmtime failed for '{}'", epoch);
}
}
Ok(result)
}
/// Returns Unix Epoch (now)
///
/// Note: This panics if the SystemTime::now() returns... |
Ok(digit - 48)
};
let check_max = |i: i32, max: i32| {
if i > max {
bail!("value too large ({} > {})", i, max);
}
Ok(i)
};
crate::try_block!({
if input.len() < 20 || input.len() > 25 {
bail!("timestamp of unexpected length");
}
... | {
bail!("unexpected char at pos {}", pos);
} | conditional_block |
mod.rs | ) -> Result<libc::tm, Error> {
let mut result = new_libc_tm();
unsafe {
if libc::gmtime_r(&epoch, &mut result).is_null() {
bail!("libc::gmtime failed for '{}'", epoch);
}
}
Ok(result)
}
/// Returns Unix Epoch (now)
///
/// Note: This panics if the SystemTime::now() returns... | (format: &str, epoch: i64) -> Result<String, Error> {
let localtime = localtime(epoch)?;
strftime(format, &localtime)
}
/// Format epoch as utc time
pub fn strftime_utc(format: &str, epoch: i64) -> Result<String, Error> {
let gmtime = gmtime(epoch)?;
strftime(format, &gmtime)
}
/// Convert Unix epoch ... | strftime_local | identifier_name |
mod.rs | ) -> Result<libc::tm, Error> {
let mut result = new_libc_tm();
unsafe {
if libc::gmtime_r(&epoch, &mut result).is_null() {
bail!("libc::gmtime failed for '{}'", epoch);
}
}
Ok(result)
}
/// Returns Unix Epoch (now)
///
/// Note: This panics if the SystemTime::now() returns... |
/// Convert Unix epoch into RFC3339 UTC string
pub fn epoch_to_rfc3339_utc(epoch: i64) -> Result<String, Error> {
let gmtime = gmtime(epoch)?;
let year = gmtime.tm_year + 1900;
if year < 0 || year > 9999 {
bail!("epoch_to_rfc3339_utc: wrong year '{}'", year);
}
strftime("%010FT%TZ", &gmt... | {
let gmtime = gmtime(epoch)?;
strftime(format, &gmtime)
} | identifier_body |
mod.rs | POCH.duration_since(now).unwrap().as_secs())
.expect("epoch_i64: now is too small")
}
}
/// Returns Unix Epoch (now) as f64 with subseconds resolution
///
/// Note: This can be inacurrate for values greater the 2^53. But this
/// should never happen.
pub fn epoch_f64() -> f64 {
use std::time::{Syst... | let converted =
epoch_to_rfc3339_utc(upper).expect("converting upper bound of RFC3339 range should work");
assert_eq!(converted, upper_str);
| random_line_split | |
GP.py | :
self._Xmean = X.mean(0)[None,:]
self._Xstd = X.std(0)[None,:]
self.X = (X.copy() - self._Xmean) / self._Xstd
if hasattr(self,'Z'):
self.Z = (self.Z - self._Xmean) / self._Xstd
else:
self._Xmean = np.zeros((1,self.X.shape[1]))
... | (self):
return np.hstack((self.kern._get_params_transformed(), self.likelihood._get_params()))
def _get_param_names(self):
return self.kern._get_param_names_transformed() + self.likelihood._get_param_names()
def update_likelihood_approximation(self):
"""
Approximates a non-gaus... | _get_params | identifier_name |
GP.py |
# parse arguments
self.Xslices = Xslices
self.X = X
assert len(self.X.shape)==2
self.N, self.Q = self.X.shape
assert isinstance(kernel, kern.kern)
self.kern = kernel
#here's some simple normalization for the inputs
if normalize_X:
sel... | """
Gaussian Process model for regression and EP
:param X: input observations
:param kernel: a GPy kernel, defaults to rbf+white
:parm likelihood: a GPy likelihood
:param normalize_X: whether to normalize the input data before computing (predictions will be in original scales)
:type normalize_... | identifier_body | |
GP.py | :
self._Xmean = X.mean(0)[None,:]
self._Xstd = X.std(0)[None,:]
self.X = (X.copy() - self._Xmean) / self._Xstd
if hasattr(self,'Z'):
self.Z = (self.Z - self._Xmean) / self._Xstd
else:
self._Xmean = np.zeros((1,self.X.shape[1]))
... |
:param samples: the number of a posteriori samples to plot
:param which_data: which if the training data to plot (default all)
:type which_data: 'all' or a slice object to slice self.X, self.Y
:param plot_limits: The limits of the plot. If 1D [xmin,xmax], if 2D [[xmin,ymin],[xmax,ymax]]... | Plot the GP's view of the world, where the data is normalized and the likelihood is Gaussian | random_line_split |
GP.py | :
self._Xmean = X.mean(0)[None,:]
self._Xstd = X.std(0)[None,:]
self.X = (X.copy() - self._Xmean) / self._Xstd
if hasattr(self,'Z'):
self.Z = (self.Z - self._Xmean) / self._Xstd
else:
self._Xmean = np.zeros((1,self.X.shape[1]))
... |
else:
m,v = self._raw_predict(Xnew, slices=which_functions,full_cov=True)
Ysim = np.random.multivariate_normal(m.flatten(),v,samples)
gpplot(Xnew,m,m-2*np.sqrt(np.diag(v)[:,None]),m+2*np.sqrt(np.diag(v))[:,None])
| m,v = self._raw_predict(Xnew, slices=which_functions)
gpplot(Xnew,m,m-2*np.sqrt(v),m+2*np.sqrt(v))
pb.plot(self.X[which_data],self.likelihood.Y[which_data],'kx',mew=1.5) | conditional_block |
vision.py | 2([
[-5, -1. * -105], #22
[90, -1. * -100], #27
[90, -1. * 110], #26
[0, -1. * 107] #25
])#*self.IMG_SCALE + self.IMG_OFFSET'''
# Swap x-y coordinates (WTF!)
'''self.worldpts = np.float32([
[-105,-5], #22
[-100, 90], #27
[110, 90], #26
[107, 0] ... | rCentroid, self.rTagImg = self.findMarker(self.warpImg, rd, 10, smin, rvmin)
#vu.printCentroids(gCentroid, rCentroid)
if(bgroundFlag):
self.rgbImg = vu.comboImage(self.bTagImg, self.gTagImg, self.rTagImg, self.warpImg)
else:
self.rgbImg = vu.comboImage(self.bTagImg, self.gTagImg, self.rTagImg)... | rvmin = cv2.getTrackbarPos('R Cutoff', self.CTL_NAME)
smin = cv2.getTrackbarPos('Sat Cutoff', self.CTL_NAME)
bgroundFlag = cv2.getTrackbarPos('Show Background', self.CTL_NAME)
bCentroid, self.bTagImg = self.findMarker(self.warpImg, bl, 10, smin, bvmin)
gCentroid, self.gTagImg = self.findMarker(self.warpI... | random_line_split |
vision.py | cv2.imshow(self.CAM_FEED_NAME, self.drawCalMarkers())
if(self.calstate == CalState.CALIBRATED):
self.remapImage() # Apply perspective warp
bl = cv2.getTrackbarPos('Blue', self.CTL_NAME)
gr = cv2.getTrackbarPos('Green', self.CTL_NAME)
rd = cv2.getTrackbarPos('Red', self.CTL_NAME)
bvmin = cv2.get... | trackbarChangeHandler | identifier_name | |
vision.py | [90, -1. * 110], #26
[0, -1. * 107] #25
])#*self.IMG_SCALE + self.IMG_OFFSET'''
# Swap x-y coordinates (WTF!)
'''self.worldpts = np.float32([
[-105,-5], #22
[-100, 90], #27
[110, 90], #26
[107, 0] #25
])#*self.IMG_SCALE + self.IMG_OFFSET'''
self.worldp... | vu.drawSquareMarker(markedImg, pt[0], pt[1], 5, (255,0,255)) | conditional_block | |
vision.py | # [self.XSIZE,self.YSIZE/2]
# ])
# ===== ***** Calibration points from world *****===== #
'''self.worldpts = np.float32([
[-5, -1. * -105], #22
[90, -1. * -100], #27
[90, -1. * 110], #26
[0, -1. * 107] #25
])#*self.IMG_SCALE + self.IMG_OFFSET'''
# Swap x-y c... | self.camera = camera
self.calstate = CalState.UNCAL
self.calpts = []
self.XSIZE = 1000
self.YSIZE = 1000
self.x_est = -1
self.y_est = -1
self.theta_est = -1
# Drawing storage
self.waypointEst = [(300,300)] # Waypoint estimates for UI
self.tagLoc = (10,10) # Tag location estimate
self.fVectorSta... | identifier_body | |
theoretical_tools.py | fi*(Ti*Ui)**2/2./(Ti+Tm))
fe, fi = fe+1e-9, fi+1e-9 # just to insure a non zero division,
Tv = ( fe*(Ue*Te)**2 + fi*(Ti*Ui)**2 ) /( fe*(Ue*Te)**2/(Te+Tm) + fi*(Ti*Ui)**2/(Ti+Tm) )
TvN = Tv*Gl/Cm
return muV, sV+1e-12, muGn, TvN
def mean_and_var_conductance(Fe, Fi, Qe, Te, Ee, Qi, T... |
else:
if(sV<1e-4):
sV=1e-4
Fout_th = erfc_func(muV, sV, TvN, Vthre, Gl, Cm)
if(hasattr(Fout_th, "__len__")):
#print("ttt",isinstance(muV, list), hasattr(muV, "__len__"))
Fout_th[Fout_th<1e-8]=1e-8
else:
... | sV[sV<1e-4]=1e-4 | conditional_block |
theoretical_tools.py | fi*(Ti*Ui)**2/2./(Ti+Tm))
fe, fi = fe+1e-9, fi+1e-9 # just to insure a non zero division,
Tv = ( fe*(Ue*Te)**2 + fi*(Ti*Ui)**2 ) /( fe*(Ue*Te)**2/(Te+Tm) + fi*(Ti*Ui)**2/(Ti+Tm) )
TvN = Tv*Gl/Cm
return muV, sV+1e-12, muGn, TvN
def mean_and_var_conductance(Fe, Fi, Qe, Te, Ee, Qi, T... |
outhet, err = quad(Phet, 0.1, 5)
return outhet
# @numba.jit()
def make_loop(t, nu, vm, nu_aff_exc, nu_aff_inh, BIN,\
Qe, Te, Ee, Qi, Ti, Ei, Gl, Cm, El, Ntot, pconnec, gei, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10):
dt = t[1]-t[0]
... | locale=gaussian(k,1.,0.2)*TF_my_templateup(fe, fi,XX, Qe, Te, Ee, Qi, Ti, Ei, Gl, Cm, El*k, Ntot, pconnec, gei, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10)
return locale | identifier_body |
theoretical_tools.py | fi*(Ti*Ui)**2/2./(Ti+Tm))
fe, fi = fe+1e-9, fi+1e-9 # just to insure a non zero division,
Tv = ( fe*(Ue*Te)**2 + fi*(Ti*Ui)**2 ) /( fe*(Ue*Te)**2/(Te+Tm) + fi*(Ti*Ui)**2/(Ti+Tm) )
TvN = Tv*Gl/Cm
| return muV, sV+1e-12, muGn, TvN
def mean_and_var_conductance(Fe, Fi, Qe, Te, Ee, Qi, Ti, Ei, Gl, Cm, El, Ntot, pconnec, gei, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10):
# here TOTAL (sum over synapses) excitatory and inhibitory input
fe = Fe*(1.-gei)*pconnec*Ntot # default is 1 !!
fi = Fi*... | random_line_split | |
theoretical_tools.py | fi*(Ti*Ui)**2/2./(Ti+Tm))
fe, fi = fe+1e-9, fi+1e-9 # just to insure a non zero division,
Tv = ( fe*(Ue*Te)**2 + fi*(Ti*Ui)**2 ) /( fe*(Ue*Te)**2/(Te+Tm) + fi*(Ti*Ui)**2/(Ti+Tm) )
TvN = Tv*Gl/Cm
return muV, sV+1e-12, muGn, TvN
def mean_and_var_conductance(Fe, Fi, Qe, Te, Ee, Qi, T... | (muV, sV, TvN, muGn, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10):
"""
setting by default to True the square
because when use by external modules, coeff[5:]=np.zeros(3)
in the case of a linear threshold
"""
muV0, DmuV0 = -60e-3,10e-3
sV0, DsV0 =4e-3, 6e-3
TvN0, DTvN0 = 0.5,... | threshold_func | identifier_name |
Home.js | text == 'object') {
objs.push(text)
return objs
}
let openBrace = -1
for(let i=0; i<text.length; i++) {
if(text[i] == '{' && openBrace == -1) {
openBrace = i
}
else if(text[i] == '}' && openBrace != -1) {
const subText = text.substring(openBrace, i+1)
// console.log(openBra... | const level = trace.get('level')
const text = trace.get('text')
// console.log(trace) | random_line_split | |
Home.js | f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633'
}
function parseObjects(text) {
const objs = []
if(!text)
return objs
if(typeof text == 'object') {
objs.push(text)
return objs
}
let openBrace = -1
for(let i=0; i<text.length; i+... |
onScroll(e) {
}
onClick(e) {
this.checkScroll()
//these delays trigger after the tree expands, can probably be improved upon by adding an expand listener to the tree object
setTimeout(this.checkScroll, 200)
setTimeout(this.checkScroll, 500)
}
onWheel(e) {
const ele = e.currentTarget
... | {
if(this.props.shouldScrollBottom) {
const ele = ReactDOM.findDOMNode(this.refs.trailingDiv)
if(ele)
ele.scrollIntoView({behavior: "smooth"})
}
} | identifier_body |
Home.js | f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633'
}
function parseObjects(text) {
const objs = []
if(!text)
return objs
if(typeof text == 'object') {
objs.push(text)
return objs
}
let openBrace = -1
for(let i=0; i<text.length; i+... | (prevProps, prevState) {
this.checkScroll()
}
checkScroll() {
if(this.props.shouldScrollBottom) {
const ele = ReactDOM.findDOMNode(this.refs.trailingDiv)
if(ele)
ele.scrollIntoView({behavior: "smooth"})
}
}
onScroll(e) {
}
onClick(e) {
this.checkScroll()
//these ... | componentDidUpdate | identifier_name |
mc6845.rs | :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICU... | self.update_start_address();
}
CrtcRegister::StartAddressL => {
// (R13) 8 bit write only
self.reg[13] = byte;
trace_regs!(self);
trace!(
self,
"CRTC Register Write (0Dh): Star... | "CRTC Register Write (0Ch): StartAddressH updated: {:02X}",
byte
); | random_line_split |
mc6845.rs | :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICU... | reg: [u8; 18], // Externally-accessable CRTC register file
reg_select: CrtcRegister, // Selected CRTC register
start_address: u16, // Calculated value from R12 & R13
cursor_address: u16, // Calculated value from R14 & R15
lightpen_position: u16, // ... | {
| identifier_name |
mc6845.rs | The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR... |
trace_regs!(self);
trace!(
self,
"CRTC Register Write (04h): VerticalTotal updated: {}",
self.reg[4]
)
},
CrtcRegister::VerticalTotalAdjust => {
// (R5) 5 bit write only
... | match self.reg_select {
CrtcRegister::HorizontalTotal => {
// (R0) 8 bit write only
self.reg[0] = byte;
},
CrtcRegister::HorizontalDisplayed => {
// (R1) 8 bit write only
self.reg[1] = byte;
}
... | identifier_body |
UnFlowLoss.py | (x)
x_floor = x1.clamp(0, W - 1)
y1 = torch.floor(y)
y_floor = y1.clamp(0, H - 1)
x0 = x1 + 1
x_ceil = x0.clamp(0, W - 1)
y0 = y1 + 1
y_ceil = y0.clamp(0, H - 1)
x_ceil_out = x0 != x_ceil
y_ceil_out = y0 != y_ceil
x_floor_out = x1 != x_floor
y_floor_out = y1 != y_floor
i... |
def smooth_grad_1st(flow, image, alpha):
img_dx, img_dy = gradient(image)
weights_x = torch.exp(-torch.mean(torch.abs(img_dx), 1, keepdim=True) * alpha)
weights_y = torch.exp(-torch.mean(torch.abs(img_dy), 1, keepdim=True) * alpha)
dx, dy = gradient(flow)
loss_x = weights_x * dx.abs() / 2.
l... | D_dy = data[:, :, 1:] - data[:, :, :-1]
D_dx = data[:, :, :, 1:] - data[:, :, :, :-1]
return D_dx, D_dy | identifier_body |
UnFlowLoss.py | (x)
x_floor = x1.clamp(0, W - 1)
y1 = torch.floor(y)
y_floor = y1.clamp(0, H - 1)
x0 = x1 + 1
x_ceil = x0.clamp(0, W - 1)
y0 = y1 + 1
y_ceil = y0.clamp(0, H - 1)
x_ceil_out = x0 != x_ceil
y_ceil_out = y0 != y_ceil
x_floor_out = x1 != x_floor
y_floor_out = y1 != y_floor
i... |
self.smooth_w = 75.0 if 'smooth_w' not in kwargs else kwargs['smooth_w']
if 'w_sm_scales' in kwargs:
self.w_sm_scales = kwargs['w_sm_scales']
else:
self.w_sm_scales = [1.0, 0.0, 0.0, 0.0, 0.0]
if 'w_wrp_scales' in kwargs:
self.w_wrp_scales = kwargs... | self.smooth_args = {"degree": 2, "alpha" : 0.2, "weighting": 75.0} | conditional_block |
UnFlowLoss.py | (x)
x_floor = x1.clamp(0, W - 1)
y1 = torch.floor(y)
y_floor = y1.clamp(0, H - 1)
x0 = x1 + 1
x_ceil = x0.clamp(0, W - 1)
y0 = y1 + 1
y_ceil = y0.clamp(0, H - 1)
x_ceil_out = x0 != x_ceil
y_ceil_out = y0 != y_ceil
x_floor_out = x1 != x_floor
y_floor_out = y1 != y_floor
i... | (image, flow12, pad='border', mode='bilinear'):
'''
Warps an image given a flow prediction using grid_sample
'''
batch_sz, _, height, width = image.size()
base_grid = mesh_grid(batch_sz, height, width).type_as(image) # B2HW
v_grid = norm_grid(base_grid + flow12) # BHW2
im1_recons = nn.fu... | flow_warp | identifier_name |
UnFlowLoss.py | (x)
x_floor = x1.clamp(0, W - 1)
y1 = torch.floor(y)
y_floor = y1.clamp(0, H - 1)
x0 = x1 + 1
x_ceil = x0.clamp(0, W - 1)
y0 = y1 + 1
y_ceil = y0.clamp(0, H - 1)
x_ceil_out = x0 != x_ceil
y_ceil_out = y0 != y_ceil
x_floor_out = x1 != x_floor
y_floor_out = y1 != y_floor
i... |
corresponding_map.scatter_add_(1, indices, values)
# decode coordinates
corresponding_map = corresponding_map.view(B, H, W)
return corresponding_map.unsqueeze(1)
def flow_warp(image, flow12, pad='border', mode='bilinear'):
'''
Warps an image given a flow prediction using grid_sample
'''
... |
values[invalid] = 0 | random_line_split |
model.py | self.clear_groups()
# 再全部重新分类
for sample in self.samples:
to_group = self.groups.get(sample.target_value)
if to_group:
to_group.add_sample(sample)
def classify(self, iteration_callback, completion_callback):
self.iteration_callback = iteration... |
self.classify_to_group() # 分类到所属群里
self.completion_callback(self.iteration_times, self.weights, self.bias, self.groups.values())
def _iteration(self):
if self.iteration_callback:
self.iteration_callback(self.iteration_times, self.weights, self.bias)
def _random_pi... | ion(self):
if self.completion_callback: | conditional_block |
model.py | ):
self.clear_groups()
# 再全部重新分类
for sample in self.samples:
to_group = self.groups.get(sample.target_value)
if to_group:
to_group.add_sample(sample)
def classify(self, iteration_callback, completion_callback):
self.iteration_callback = iterat... | random_index = np.random.random_integers(0, max-1)
if random_index == avoid_index:
random_index = self._random_pick_index(avoid_index)
return random_index
def _update_parameters(self, update_alphas=[]):
alphas_count = len(update_alphas)
# 如果 update_alphas... | cking
| identifier_name |
model.py | ):
self.clear_groups()
# 再全部重新分类
for sample in self.samples:
to_group = self.groups.get(sample.target_value)
if to_group:
to_group.add_sample(sample)
def classify(self, iteration_callback, completion_callback):
self.iteration_callback = iterat... |
# Quickly updating the weights and bias by used 2 new alpha values
# 1). calculates the delta weights, Formula:
# delta main = (new alpha 1 - old alpha 1) * target1 * x1
# delta match = (new alpha 2 - old alpha 2) * target2 * x2
# delta weights = delta main + delta match
... | main = self.samples[main_index]
match = self.samples[match_index]
new_match_alpha = self._calculate_new_match_alpha(main, match)
new_main_alpha =self._calculate_new_main_alpha(main, match, new_match_alpha) | random_line_split |
model.py | del self.samples[:]
def clear_groups(self):
# 清空 group 里记录的 samples
for target, group in self.groups.items():
group.clear()
# 从每一个 Sample 的target value 来逐一判断该点是属于哪一群
def classify_to_group(self):
self.clear_groups()
# 再全部重新分类
for sample in self.samp... | self.weights[:]
for i in xrange(0, count):
self.weights.append(0.0)
def clear_samples(self):
| identifier_body | |
coeditor.rs | Constraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};
use std::time::Duration;
use crate::editor_binding::EditorBinding;
use crate::code_editor::code_editor::CodeEditor;
use c... |
let data = message.unwrap().to_string();
println!("Received: {}", &data);
client2.write().handle_message(serde_json::from_slice(data.as_bytes()).expect("parse data failed"));
});
client.write().send_info();
client.write().send_cursor_data();
if let Some(outstan... | {
return;
} | conditional_block |
coeditor.rs | BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};
use std::time::Duration;
use crate::editor_binding::EditorBinding;
use crate::code_editor::code_editor::CodeEditor;
u... | use futures::StreamExt;
use log::{info, warn};
pub const COEDITOR_INIT_CLIENT: Selector<Arc<RwLock<RustpadClient>>> = Selector::new("coeditor-init-client");
pub const USER_EDIT_SELECTOR: Selector<Edit> = Selector::new("user-edit");
pub const USER_CURSOR_UPDATE_SELECTOR: Selector<()> = Selector::new("user-cursor-data")... | use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::connect_async; | random_line_split |
coeditor.rs | Constraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};
use std::time::Duration;
use crate::editor_binding::EditorBinding;
use crate::code_editor::code_editor::CodeEditor;
use c... |
}
impl CoEditorWidget {
pub fn new(server_url: String) -> Self {
println!("CoEditorWidget created");
CoEditorWidget {
inner: WidgetPod::new(CodeEditor::<EditorBinding>::multiline()),
server_url,
id: WidgetId::next(),
client: None,
connect... | {
self.close_tx.send(()).unwrap();
futures::executor::block_on(
tokio::time::timeout(Duration::from_secs(5),
self.connection_handle.take().unwrap(),
)
);
println!("CoEditorWidget destructed");
} | identifier_body |
coeditor.rs | BoxConstraints, Target, LifeCycle, LifeCycleCtx, Size};
use std::sync::Arc;
use tokio::sync::broadcast::{Sender};
use tokio::task::JoinHandle;
use parking_lot::RwLock;
use crate::{RustpadClient, Edit};
use std::time::Duration;
use crate::editor_binding::EditorBinding;
use crate::code_editor::code_editor::CodeEditor;
u... | (&mut self, ctx: &mut EventCtx, event: &Event, data: &mut EditorBinding, env: &Env) {
if let Event::Command(cmd) = event {
println!("received {:?}", cmd);
}
match event {
Event::Command(command) if command.get(COEDITOR_INIT_CLIENT).is_some()
&& command.tar... | event | identifier_name |
build-xml.js | str, prefix, ignores) {
// 替换字符串中 {{}} 包含的表达式
// 获取类似 a.b.c 表达式中第一个 | ction getFirstWord(word) {
return word.match(/[_a-z][\w\d]*/i)[0];
}
// 检查类似 a.b.c 格式表达式是否忽略绑定
function shouldIgnore(word, matchs, n) {
if (word[0] === '"' || word[0] === "'" || /^\d+$/.test(word)) return true;
let w = getFirstWord(word);
if (ignores.hasOwnProperty(w) || (matchs && inText(matchs,... | 有效变量名 a
fun | identifier_name |
build-xml.js | str, prefix, ignores) {
// 替换字符串中 {{}} 包含的表达式
// 获取类似 a.b.c 表达式中第一个有效变量名 a
function getFirstWord(word) {
return word.match(/[_a-z][\w\d]*/i)[0];
}
// 检查类似 a.b.c 格式表达式是否忽略绑定
function shouldIgnore(word, matchs, n) {
if (word[0] === '"' || word[0] === "'" || /^\d+$/.test(word)) return true;
let ... | ]*\s*$/.test(words)) {
let word = words.match(/\s*\.\.\.([\w_][\w\d\-_.\[\]]*)/)[1].trim();
if (shouldIgnore(word)) {
return matchs;
}
return `{{...${prefix}${word}}}`;
}
let isArray = /{{\s*\[/.test(matchs);
if (!isArray) {
//支持对象简写
let arrays = words.split(',')... | com/maichong/labrador');
}
return false;
}
if (prefix) {
prefix += '.';
} else {
prefix = '';
}
return str.replace(/\{\{([^}]+)\}\}/ig, function (matchs, words) {
// matchs 是{{xxxxx}}格式的字符串
// words 是{{}}中间的表达式
// ...foo
if (/^\s*\.\.\.[\w_][\w\d\-_.\[\] | conditional_block |
build-xml.js | str, prefix, ignores) {
// 替换字符串中 {{}} 包含的表达式
// 获取类似 a.b.c 表达式中第一个有效变量名 a
function getFirstWord(word) {
return word.match(/[_a-z][\w\d]*/i)[0];
}
// 检查类似 a.b.c 格式表达式是否忽略绑定
function shouldIgnore(word, matchs, n) {
if (word[0] === '"' || word[0] === "'" || /^\d+$/.test(word)) return true;
let ... | // 不转换template 定义
if (n.nodeName === 'template' && n.getAttribute('name')) {
bindTemplateEvents(n);
continue;
}
bind(from, n, comPrefix, valPrefix, clsPrefix, ignores);
}
}
/**
* 递归绑定template标签子节点中的事件
* @param node
*/
function bindTemplateEvents(node) {
//处理节点属性
let attributes = no... |
//递归处理子节点
for (let i in node.childNodes) {
if (!/^\d+$/.test(i)) continue;
let n = node.childNodes[i]; | random_line_split |
build-xml.js | str, prefix, ignores) {
// 替换字符串中 {{}} 包含的表达式
// 获取类似 a.b.c 表达式中第一个有效变量名 a
function getFirstWord(word) {
return word.match(/[_a-z][\w\d]*/i)[0];
}
// 检查类似 a.b.c 格式表达式是否忽略绑定
function shouldIgnore(word, matchs, n) {
if (word[0] === '"' || word[0] === "'" || /^\d+$/.test(word)) return true;
let ... | attr.value = attr.value.replace(/\{\{([^}]+)\}\}/ig, function (match) {
matchArr.push(match);
matchArr.push(match);
return '$';
});
// => "xxx prefix-xxx $ prefix-$"
attr.value = attr.value.split(' ').map(cls => `${cls} ${clsPrefix}-${cls}`).join(' ');
// => "xxx ... | r.name)) {
node.setAttribute('data-' + attr.name, attr.value);
attr.value = '_dispatch';
if (!hasPath && comPrefix) {
node.setAttribute('data-path', comPrefix);
}
}
//如果是循环标签,则在子标签中忽略循环索引和值变量
if (attr.name === 'wx:for') {
let index = node.getAttribute('wx:for-index') |... | identifier_body |
lib.rs | .bin_name("self_update_example")
.show_download_progress(true)
.current_version(cargo_crate_version!())
.build()?
.update()?;
println!("Update status: `{}`!", status.version());
Ok(())
}
# fn main() { }
```
Run the above example to see `self_update` in action: `cargo run --exam... | (&self, into_dir: &path::Path) -> Result<()> {
let source = fs::File::open(self.source)?;
let archive: Box<io::Read> = match self.encoding {
EncodingKind::Plain => Box::new(source),
EncodingKind::Gz => {
let reader = flate2::read::GzDecoder::new(source);
... | extract_into | identifier_name |
lib.rs | .bin_name("self_update_example")
.show_download_progress(true)
.current_version(cargo_crate_version!())
.build()?
.update()?;
println!("Update status: `{}`!", status.version());
Ok(())
}
# fn main() { }
```
Run the above example to see `self_update` in action: `cargo run --exam... | pub fn updated(&self) -> bool {
match *self {
Status::Updated(_) => true,
_ => false,
}
}
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Status::*;
match *self {
UpToDate(ref s) =... | _ => false,
}
}
/// Returns `true` if `Status::Updated` | random_line_split |
lib.rs | println!("{:#?}\n", releases);
// get the first available release
let asset = releases[0]
.asset_for(&target).unwrap();
let tmp_dir = self_update::TempDir::new_in(::std::env::current_dir()?, "self_update")?;
let tmp_tarball_path = tmp_dir.path().join(&asset.name);
let tmp_tarball = ::std:... | {
match self.temp {
None => {
fs::rename(self.source, dest)?;
}
Some(temp) => {
if dest.exists() {
fs::rename(dest, temp)?;
match fs::rename(self.source, dest) {
Err(e) => {
... | identifier_body | |
sample.app.js | UCMS.alert("서버와 통신 중 오류["+textStatus+","+jqXHR.status+"]가 발생하였습니다.<br>잠시 후 다시 시도해주세요.<br>이용에 불편을 드려 죄송합니다!")
.then(
function()
{
reloadApp();
});
}
return true;
}
,
onInitializeBefore: function(options)
{
UCMS.log("onInitializeBefore()");
this._appInfo = o... | },
| random_line_split | |
mod.rs | -> Range<usize> {
start + offset..end + offset
}
impl SubMatch {
pub fn match_indices(&self, offset: usize) -> Range<usize> {
range(self.start, self.end, offset)
}
// FIXME find the word in non-utf8?
pub fn match_indices_for_dumb_jump(&self, offset: usize, search_word: &Word) -> Range<usi... | {
ShellCommand::new(RG_EXEC_CMD.into(), PathBuf::from(dir.as_ref()))
} | identifier_body | |
mod.rs | ()
.map(|exit_status| exit_status.success())
.unwrap_or(false)
});
/// Map of file extension to ripgrep language.
///
/// https://github.com/BurntSushi/ripgrep/blob/20534fad04/crates/ignore/src/default_types.rs
static RG_LANGUAGE_EXT_TABLE: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
default_types::... | pub re: regex::Regex,
}
impl Word {
pub fn new(re_word: String, re: regex::Regex) -> Word {
Self {
len: re_word.len(),
raw: re_word,
re,
}
}
pub fn find(&self, line: &str) -> Option<usize> {
self.re.find(line).map(|mat| mat.start())
}
}
... | random_line_split | |
mod.rs | ()
.map(|exit_status| exit_status.success())
.unwrap_or(false)
});
/// Map of file extension to ripgrep language.
///
/// https://github.com/BurntSushi/ripgrep/blob/20534fad04/crates/ignore/src/default_types.rs
static RG_LANGUAGE_EXT_TABLE: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
default_types::... |
}
}
impl Match {
/// Returns a pair of the formatted `String` and the offset of origin match indices.
///
/// The formatted String is same with the output line using rg's -vimgrep option.
fn grep_line_format(&self, enable_icon: bool) -> (String, usize) {
let path = self.path();
let... | {
Err("Not Message::Match type".into())
} | conditional_block |
mod.rs | ()
.map(|exit_status| exit_status.success())
.unwrap_or(false)
});
/// Map of file extension to ripgrep language.
///
/// https://github.com/BurntSushi/ripgrep/blob/20534fad04/crates/ignore/src/default_types.rs
static RG_LANGUAGE_EXT_TABLE: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
default_types::... | (&self) -> dumb_analyzer::Priority {
self.path()
.rsplit_once('.')
.and_then(|(_, file_ext)| {
dumb_analyzer::calculate_pattern_priority(self.pattern(), file_ext)
})
.unwrap_or_default()
}
/// Returns a pair of the formatted `String` and t... | pattern_priority | identifier_name |
tls_accept.rs | fn plaintext() {
let (client_result, server_result) = run_test(
Conditional::None(tls::ReasonForNoIdentity::Disabled),
|conn| write_then_read(conn, PING),
Conditional::None(tls::ReasonForNoIdentity::Disabled),
|(_, conn)| read_then_write(conn, PING.len(), PONG),
);
assert_eq!... | AcceptTls<A, CrtKey>: Accept<<Listen as CoreListen>::Connection>,
{
Init {
listen: Listen,
accept: AcceptTls<A, CrtKey>, | random_line_split | |
tls_accept.rs | plaintext() {
let (client_result, server_result) = run_test(
Conditional::None(tls::ReasonForNoIdentity::Disabled),
|conn| write_then_read(conn, PING),
Conditional::None(tls::ReasonForNoIdentity::Disabled),
|(_, conn)| read_then_write(conn, PING.len(), PONG),
);
assert_eq!(c... |
}
/// Runs a test for a single TCP connection. `client` processes the connection
/// on the client side and `server` processes the connection on the server
/// side.
fn run_test<C, CF, CR, S, SF, SR>(
client_tls: tls::Conditional<(CrtKey, Name)>,
client: C,
server_tls: tls::Conditional<CrtKey>,
server... | {
self.peer_identity
.as_ref()
.map(|i| i.is_some())
.unwrap_or(false)
} | identifier_body |
tls_accept.rs | assert_eq!(client_result.is_tls(), false);
assert_eq!(&client_result.result.expect("pong")[..], PONG);
assert_eq!(server_result.is_tls(), false);
assert_eq!(&server_result.result.expect("ping")[..], PING);
}
#[test]
fn proxy_to_proxy_tls_works() {
let server_tls = test_util::FOO_NS1.validate().unwrap(... | ClientTls | identifier_name | |
AutomobilesOnSale.py | df_auto[df_auto.monthOfRegistration != 12]
# Univariate Analysis of : Sellers
sns.barplot(df_auto.seller.value_counts().index, df_auto.seller.value_counts().values, alpha=0.9)
plt.xlabel('Sellers')
plt.ylabel('Count')
plt.title('Distribution Of Car Sellers');
# As almost all of the Sellers are from private we can... | plt.xlabel('Years of Registration')
plt.ylabel('Price')
plt.title('Variation Of Price with Year');
# No of days it took to sold while purchasing from E-bay
days = []
for time1, time2 in zip(df_auto['dateCrawled'], df_auto['lastSeen']):
time = datetime.strptime(time2, '%Y-%m-%d %H:%M:%S') - datetime.strptime(tim... | sns.lineplot(df_auto.groupby('yearOfRegistration')['price'].count().index,
df_auto.groupby('yearOfRegistration')['price'].count().values,
data=df_auto) | random_line_split |
AutomobilesOnSale.py | values, alpha=0.9)
plt.xlabel('Type of Vehicle')
plt.ylabel('Count')
plt.title('Distribution Of Vehicle Types');
# Univariate Analysis of : Gear Type
sns.barplot(df_auto.gearbox.value_counts().index, df_auto.gearbox.value_counts().values, alpha=0.9)
plt.xlabel('Type of Gears')
plt.ylabel('Count')
plt.title('Distri... | data = df_auto[(df_auto.yearOfRegistration == year) & (df_auto.monthOfRegistration == month) &
(df_auto.Sold_In_Days == days) & (df_auto.gearbox == gearbox) &
(df_auto.notRepairedDamage == damage)]
area = 2 * df_auto.powerPS
data.plot.scatter('powerPS', 'price',... | identifier_body | |
AutomobilesOnSale.py | .price)
plt.xlabel("Price")
plt.ylabel('Frequency')
plt.title("Distribution of Car's Price");
# Logarithm of Price Distribution
sns.distplot(np.log(df_auto.price))
plt.xlabel("Logarithm of Car's Price")
plt.ylabel('Frequency')
plt.title("Distribution Log of Car's Price");
# Univariate Analysis of : AB Testing
sns... | plot_year | identifier_name | |
AutomobilesOnSale.py | 00) & (df_auto.price < 200000)]
# Distribution of Price
sns.distplot(df_auto.price)
plt.xlabel("Price")
plt.ylabel('Frequency')
plt.title("Distribution of Car's Price");
# Logarithm of Price Distribution
sns.distplot(np.log(df_auto.price))
plt.xlabel("Logarithm of Car's Price")
plt.ylabel('Frequency')
plt.title(... | print(col, len(df_auto[col].unique())) | conditional_block | |
metapipeline.go | the generation of the effective jenkins-x pipeline config
createEffectivePipelineStepName = "create-effective-pipeline"
// createTektonCRDsStepName is the meta pipeline step name for the Tekton CRD creation
createTektonCRDsStepName = "create-tekton-crds"
tektonBaseDir = "/workspace"
)
// CRDCreationParameters ar... | (params CRDCreationParameters) ([]syntax.Step, error) {
var steps []syntax.Step
// 1)
step := stepMergePullRefs(params.PullRef)
steps = append(steps, step)
// 2)
step = stepEffectivePipeline(params)
steps = append(steps, step)
log.Logger().Debugf("creating pipeline steps for extending apps")
// 3)
for _, a... | buildSteps | identifier_name |
metapipeline.go | generation of the effective jenkins-x pipeline config
createEffectivePipelineStepName = "create-effective-pipeline"
// createTektonCRDsStepName is the meta pipeline step name for the Tekton CRD creation
createTektonCRDsStepName = "create-tekton-crds"
tektonBaseDir = "/workspace"
)
// CRDCreationParameters are th... |
return parsedPipeline, nil
}
// buildSteps builds the meta pipeline steps.
// The tasks of the meta pipeline are:
// 1) make sure the right commits are merged
// 2) create the effective pipeline and write it to disk
// 3) one step for each extending app
// 4) create Tekton CRDs for the meta pipeline
func buildSteps... | {
steps, err := buildSteps(params)
if err != nil {
return nil, errors.Wrap(err, "unable to create app extending pipeline steps")
}
stage := syntax.Stage{
Name: appExtensionStageName,
Steps: steps,
Agent: &syntax.Agent{
Image: determineDefaultStepImage(params.DefaultImage),
},
}
parsedPipeline := &... | identifier_body |
metapipeline.go | the generation of the effective jenkins-x pipeline config
createEffectivePipelineStepName = "create-effective-pipeline"
// createTektonCRDsStepName is the meta pipeline step name for the Tekton CRD creation
createTektonCRDsStepName = "create-tekton-crds"
tektonBaseDir = "/workspace"
)
// CRDCreationParameters ar... | BranchIdentifier string
PullRef prow.PullRefs
SourceDir string
PodTemplates map[string]*corev1.Pod
ServiceAccount string
Labels []string
EnvVars []string
DefaultImage string
Apps []jenkinsv1.App
VersionsDir string
}
// CreateMetaPipelineCRDs creat... | ResourceName string
PipelineKind string
BuildNumber string
GitInfo gits.GitRepository | random_line_split |
metapipeline.go | generation of the effective jenkins-x pipeline config
createEffectivePipelineStepName = "create-effective-pipeline"
// createTektonCRDsStepName is the meta pipeline step name for the Tekton CRD creation
createTektonCRDsStepName = "create-tekton-crds"
tektonBaseDir = "/workspace"
)
// CRDCreationParameters are th... |
// 4)
step = stepCreateTektonCRDs(params)
steps = append(steps, step)
return steps, nil
}
func stepMergePullRefs(pullRefs prow.PullRefs) syntax.Step {
// we only need to run the merge step in case there is anything to merge
// Tekton has at this stage the base branch already checked out
if len(pullRefs.ToMer... | {
if app.Spec.PipelineExtension == nil {
log.Logger().Warnf("Skipping app %s in meta pipeline. It contains label %s with value %s, but does not contain PipelineExtension fields.", app.Name, apps.AppTypeLabel, apps.PipelineExtension)
continue
}
extension := app.Spec.PipelineExtension
step := syntax.Step{
... | conditional_block |
distributed_dqn_v2.py | dqn_model import _DQNModel
from memory import ReplayBuffer
from memory_remote import ReplayBuffer_remote
import matplotlib.pyplot as plt
from custom_cartpole import CartPoleEnv
FloatTensor = torch.FloatTensor
# =================== Helper Function ===================
def plot_result(total_rewards ,learning_num, leg... | learning: The trigger of agent learning. It is on while training agent. It is off while testing agent.
action_space: The action space of the current environment, e.g 2.
"""
self.episode = 0
self.steps = 0
self.best_reward = 0
self.learning = True
s... | def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)):
self.env = env
self.max_episode_steps = env._max_episode_steps
"""
beta: The discounted factor of Q-value function
(epsilon): The explore or exploit policy epsilon.
initial_epsil... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.