file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
role_conversion.py | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
# process the next batch of entities
start_key = entities[-1].key()
deferred.defer(self._process, start_key, batch_size)
except DeadlineExceededError:
# here we should probably be more careful
deferred.defer(self._process, start_key, batch_size)
class RoleUpdater(object):
"""Clas... | sponsor = entity.scope
host_for = entity.user.host_for
if not host_for:
host_for = []
user = entity.user
if sponsor.key() not in host_for:
host_for.append(sponsor.key())
user.host_for = host_for
db.put(user) | conditional_block |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | 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 | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... |
}
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 | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | }
}
Err(err) => {
let _ = stderr().write(format!("{}", err).as_bytes());
Ok(HyperResponse::new().with_status(StatusCode::InternalServerError))
}
... |
let _ = stderr().write(err.as_bytes());
Ok(
HyperResponse::new()
.with_status(StatusCode::InternalServerError),
)
... | conditional_block |
http.rs | //! This example uses [hyper][] to create a http server which handles requests asynchronously in
//! gluon. To do this we define a few types and functions in Rust with which we register in gluon
//! so that we can communicate with `hyper`. The rest of the implementation is done in gluon,
//! routing the requests and co... | (
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 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | /// 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 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Check whether constraints is empty
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}
impl Display for Constraints {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let pk: Vec<String> = self.inner.iter().map(|c| format!("{:?}", c)).collect();
let pk = p... | {
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 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (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 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | 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 | import os
import math
import random
import datetime
import functools
from app.models import *
# from app import csrf
from hashlib import md5
from .forms import TaskForm
from app import api
from . import main
from flask_restful import Resource
from flask import jsonify # flask 封装后的json方法
from flask_sqlalch... | 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 | import os
import math
import random
import datetime
import functools
from app.models import *
# from app import csrf
from hashlib import md5
from .forms import TaskForm
from app import api
from . import main
from flask_restful import Resource
from flask import jsonify # flask 封装后的json方法
from flask_sqlalch... | 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 | import os
import math
import random
import datetime
import functools
from app.models import *
# from app import csrf
from hashlib import md5
from .forms import TaskForm
from app import api
from . import main
from flask_restful import Resource
from flask import jsonify # flask 封装后的json方法
from flask_sqlalch... | 加密
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 | import os
import math
import random
import datetime
import functools
from app.models import *
# from app import csrf
from hashlib import md5
from .forms import TaskForm
from app import api
from . import main
from flask_restful import Resource
from flask import jsonify # flask 封装后的json方法
from flask_sqlalch... | 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 | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... |
}
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 | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... | (&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 | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... | /// for inst in api.list(&Default::default()).await? {
/// println!("Found {}: {}", ar.kind, inst.name());
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// This is equivalent to taking the [`ApiGroup::versioned_resources`] at the [`ApiGroup::preferred_... | /// 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 | use super::{
parse::{self, GroupVersionData},
version::Version,
};
use crate::{error::DiscoveryError, Client, Result};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{APIGroup, APIVersions};
pub use kube_core::discovery::{verbs, ApiCapabilities, ApiResource, Scope};
use kube_core::gvk::{GroupVersion, Group... |
// 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 | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct NotSendOrSync(*const ());
/// Borrowing-owner o... | else {
Box::new(ACell::new(Integers(init as u64)))
}
}
let own = &mut owner;
let cell1 = series(4, false);
let cell2 = series(7, true);
let cell3 = series(3, true);
assert_eq!(cell1.ro(own).value(), 4);
cell1.rw(own).step();
a... | {
Box::new(ACell::new(Squares(init)))
} | conditional_block |
tlcell.rs | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct NotSendOrSync(*const ());
/// Borrowing-owner o... | /// 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 | use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashSet;
use std::marker::PhantomData;
use super::Invariant;
std::thread_local! {
static SINGLETON_CHECK: std::cell::RefCell<HashSet<TypeId>> = std::cell::RefCell::new(HashSet::new());
}
struct | (*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 | // SPDX-License-Identifier: ISC
// Copyright (c) 2014-2021 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord
import (
"encoding/hex"
"github.com/bitmark-inc/bitmarkd/account"
"github.com/bitmark-inc/bitmarkd/currency"
"github... | 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 | // SPDX-License-Identifier: ISC
// Copyright (c) 2014-2021 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord
import (
"encoding/hex"
"github.com/bitmark-inc/bitmarkd/account"
"github.com/bitmark-inc/bitmarkd/currency"
"github... | MakeLink - Create an link for a packed record
func (record Packed) MakeLink() merkle.Digest {
return merkle.NewDigest(record)
}
// MarshalText - convert a packed to its hex JSON form
func (record Packed) MarshalText() ([]byte, error) {
size := hex.EncodedLen(len(record))
b := make([]byte, size)
hex.Encode(b, reco... | eturn NewAssetIdentifier([]byte(assetData.Fingerprint))
}
// | identifier_body |
transaction.go | // SPDX-License-Identifier: ISC
// Copyright (c) 2014-2021 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord
import (
"encoding/hex"
"github.com/bitmark-inc/bitmarkd/account"
"github.com/bitmark-inc/bitmarkd/currency"
"github... | ]byte) error {
size := hex.DecodedLen(len(s))
*record = make([]byte, size)
_, err := hex.Decode(*record, s)
return err
}
| rshalText(s [ | identifier_name |
transaction.go | // SPDX-License-Identifier: ISC
// Copyright (c) 2014-2021 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord
import (
"encoding/hex"
"github.com/bitmark-inc/bitmarkd/account"
"github.com/bitmark-inc/bitmarkd/currency"
"github... |
// 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 | import { Component, OnInit, ElementRef, ViewChild, Inject } from '@angular/core';
import { ApiService } from '../../services/api.service';
import { DOCUMENT } from '@angular/common'
import { element } from 'protractor';
import { ChartDataSets } from 'chart.js';
import { Color } from 'ng2-charts';
import * as pdfMake fr... | 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 | import { Component, OnInit, ElementRef, ViewChild, Inject } from '@angular/core';
import { ApiService } from '../../services/api.service';
import { DOCUMENT } from '@angular/common'
import { element } from 'protractor';
import { ChartDataSets } from 'chart.js';
import { Color } from 'ng2-charts';
import * as pdfMake fr... | 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 | import { Component, OnInit, ElementRef, ViewChild, Inject } from '@angular/core';
import { ApiService } from '../../services/api.service';
import { DOCUMENT } from '@angular/common'
import { element } from 'protractor';
import { ChartDataSets } from 'chart.js';
import { Color } from 'ng2-charts';
import * as pdfMake fr... | 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 | import { Component, OnInit, ElementRef, ViewChild, Inject } from '@angular/core';
import { ApiService } from '../../services/api.service';
import { DOCUMENT } from '@angular/common'
import { element } from 'protractor';
import { ChartDataSets } from 'chart.js';
import { Color } from 'ng2-charts';
import * as pdfMake fr... | 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 | # -*- coding: utf-8 -*-
"""blueberry_segmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fez-oHMJuNSvBrawtIQ9S5Wf9d8UeanD
# Mount Google Drive
"""
from google.colab import drive
drive.mount('/content/gdrive/', force_remount=True)
"""#... | (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 | # -*- coding: utf-8 -*-
"""blueberry_segmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fez-oHMJuNSvBrawtIQ9S5Wf9d8UeanD
# Mount Google Drive
"""
from google.colab import drive
drive.mount('/content/gdrive/', force_remount=True)
"""#... | """# 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 | # -*- coding: utf-8 -*-
"""blueberry_segmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fez-oHMJuNSvBrawtIQ9S5Wf9d8UeanD
# Mount Google Drive
"""
from google.colab import drive
drive.mount('/content/gdrive/', force_remount=True)
"""#... |
print_metrics(metrics, epoch_samples, phase)
epoch_loss = metrics['loss'] / epoch_samples
# deep copy the model
if phase == 'val' and epoch_loss < best_loss:
print("saving best model")
best_loss = epoch_loss
best_model_wt... | 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 | # -*- coding: utf-8 -*-
"""blueberry_segmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fez-oHMJuNSvBrawtIQ9S5Wf9d8UeanD
# Mount Google Drive
"""
from google.colab import drive
drive.mount('/content/gdrive/', force_remount=True)
"""#... |
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 | import { Component, ViewChild,Input } from '@angular/core';
import { NavController, IonInfiniteScroll, Platform, ActionSheetController, ToastController, MenuController, ModalController, AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Camera, CameraOptions } from '@ionic-nativ... |
reactAction(type,post_id){
let params :any = {
'do': type,
'id': post_id,
'my_id' : localStorage.getItem('user_id')
};
this.post.reaction(params).subscribe((resp) => {
}, (err) => {
});
}
reportAction(handle,id){
let params :any = {
'handle': handle,
'id': id,
'my_id' : lo... | {
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 | import { Component, ViewChild,Input } from '@angular/core';
import { NavController, IonInfiniteScroll, Platform, ActionSheetController, ToastController, MenuController, ModalController, AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Camera, CameraOptions } from '@ionic-nativ... | 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 = awai... | {
console.log(media);
let obj = JSON.parse(media)
return 'url(' + this.mediapath+obj[0].src + ')'
} | conditional_block |
post.page.ts | import { Component, ViewChild,Input } from '@angular/core';
import { NavController, IonInfiniteScroll, Platform, ActionSheetController, ToastController, MenuController, ModalController, AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Camera, CameraOptions } from '@ionic-nativ... | 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 | import { Component, ViewChild,Input } from '@angular/core';
import { NavController, IonInfiniteScroll, Platform, ActionSheetController, ToastController, MenuController, ModalController, AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Camera, CameraOptions } from '@ionic-nativ... | (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 | """!
@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 un... |
# case 4:
else:
candidate_cost += (
distance_candidate - distance_nearest
)
if candidate_cost < 0:
counter += 1
# set candidate that has ... | pass | conditional_block |
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 un... | (data, _cur_choice):
# modified from that of CLARA
"""A function to compute the configuration cost.
:param data: The input dataframe.
:param _cur_choice: The current set of medoid choices.
:return: The total configuration cost, the medoids.
"""
total_cost = 0.0
medoids = ... | 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 | """!
@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 un... |
def get_clusters(self):
"""!
@brief Returns allocated clusters by the algorithm.
@remark Allocated clusters can be returned only after data processing (use method process()), otherwise empty
list is returned.
@return (list) List of allocated clusters, each cluster contain... | """!
@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 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | / Returns a reference to a specific block, if it exists in the tree.
pub fn get_block(&self, id: HashValue) -> Option<&B> {
self.id_to_block.get(&id)
}
/// Returns a mutable reference to a specific block, if it exists in the tree.
pub fn get_block_mut(&mut self, id: HashValue) -> Option<&mut 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 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | lf, last_committed_id: HashValue) {
let mut new_block_tree = BlockTree::new(last_committed_id);
std::mem::swap(self, &mut new_block_tree);
}
}
/// An error returned by `add_block`. The error contains the block being added so the caller does
/// not lose it.
#[derive(Debug, Eq, PartialEq)]
pub enum ... | ut se | identifier_name |
mod.rs | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! In a leader based consensus algorithm, each participant maintains a block tree that looks like
//! the following:
//! ```text
//! Height 5 6 7 ...
//!
//! Committed -> B5 -> B6 -> B7
//! |
//! ... | 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 | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... |
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 | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... | (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 | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... |
/// 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 | use anyhow::{bail, format_err, Error};
use std::ffi::{CStr, CString};
mod tm_editor;
pub use tm_editor::*;
/// Safe bindings to libc timelocal
///
/// We set tm_isdst to -1.
/// This also normalizes the parameter
pub fn timelocal(t: &mut libc::tm) -> Result<i64, Error> {
t.tm_isdst = -1;
let epoch = unsafe {... | let parsed =
parse_rfc3339(lower_str).expect("parsing lower bound of RFC3339 range should work");
assert_eq!(parsed, lower);
let parsed =
parse_rfc3339(upper_str).expect("parsing upper bound of RFC3339 range should work");
assert_eq!(parsed, upper);
epoch_to_rfc3339_utc(lower - 1)
... | 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 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import pylab as pb
from .. import kern
from ..core import model
from ..util.linalg import pdinv,mdot
from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango
from ..likelihoods import E... | (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 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import pylab as pb
from .. import kern
from ..core import model
from ..util.linalg import pdinv,mdot
from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango
from ..likelihoods import E... | """
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 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import pylab as pb
from .. import kern
from ..core import model
from ..util.linalg import pdinv,mdot
from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango
from ..likelihoods import E... |
: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 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import pylab as pb
from .. import kern
from ..core import model
from ..util.linalg import pdinv,mdot
from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango
from ..likelihoods import E... |
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])
for i in range(samples):
... | 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 | # Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... | 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 | # Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... | (self, x):
pass
# Gain slider handler
def gainChanged(self, gain):
uvc.set(self.camera, uvc.GAIN, gain)
# Saturation slider handler
def saturationChanged(self, sat):
uvc.set(self.camera, uvc.SATURATION, sat)
# Exposure slider handler
def exposureChanged(self, exp):
uvc.set(self.camera, uvc.EXPOSURE_AB... | trackbarChangeHandler | identifier_name |
vision.py | # Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... |
return markedImg
# Finds a marker's central moment
def findMarker(self, image, hueCenter, hueWidth, satMin, valMin):
hsvImg = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
markerImg = cv2.inRange(hsvImg, np.array([hueCenter-hueWidth/2, satMin, valMin]), np.array([hueCenter+hueWidth/2, 255, 255]))
cleanElement = cv... | vu.drawSquareMarker(markedImg, pt[0], pt[1], 5, (255,0,255)) | conditional_block |
vision.py | # Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... |
# Run vision on a frame
def processFrame(self):
### Main processing loop ###
#while(True):
frameRet, self.camImg = self.vidcap.read()
#Img = self.drawCalMarkers()
cv2.imshow(self.CAM_FEED_NAME, self.drawCalMarkers())
if(self.calstate == CalState.CALIBRATED):
self.remapImage() # Apply perspe... | 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 | import numpy as np
import numba
import scipy.special as sp_spec
import scipy.integrate as sp_int
from scipy.optimize import minimize, curve_fit
import sys
import matplotlib.pyplot as plt
from scipy import signal
from scipy.integrate import quad
def pseq_params(params):
Qe, Te, Ee = params['Qe'], params['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 | import numpy as np
import numba
import scipy.special as sp_spec
import scipy.integrate as sp_int
from scipy.optimize import minimize, curve_fit
import sys
import matplotlib.pyplot as plt
from scipy import signal
from scipy.integrate import quad
def pseq_params(params):
Qe, Te, Ee = params['Qe'], params['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 | import numpy as np
import numba
import scipy.special as sp_spec
import scipy.integrate as sp_int
from scipy.optimize import minimize, curve_fit
import sys
import matplotlib.pyplot as plt
from scipy import signal
from scipy.integrate import quad
def pseq_params(params):
Qe, Te, Ee = params['Qe'], params['T... | 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 | import numpy as np
import numba
import scipy.special as sp_spec
import scipy.integrate as sp_int
from scipy.optimize import minimize, curve_fit
import sys
import matplotlib.pyplot as plt
from scipy import signal
from scipy.integrate import quad
def pseq_params(params):
Qe, Te, Ee = params['Qe'], params['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 | import React from 'react'
import axios from 'axios'
import ReactDOM from 'react-dom'
import moment from 'moment'
// import ColorPicker from 'rc-color-picker'
import JSONTree from 'react-json-tree'
const treeTheme = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: 'none', //'#272822... | const parsedObjects = parseObjects(text)
return (
<div className={'trace ' + level} key={i}
style={{background:style.background}}>
<span className='trace-timestamp'>{timestamp}</span>
<span className='trace-bundle'>{bundle}</span>
... | const level = trace.get('level')
const text = trace.get('text')
// console.log(trace) | random_line_split |
Home.js | import React from 'react'
import axios from 'axios'
import ReactDOM from 'react-dom'
import moment from 'moment'
// import ColorPicker from 'rc-color-picker'
import JSONTree from 'react-json-tree'
const treeTheme = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: 'none', //'#272822... |
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 | import React from 'react'
import axios from 'axios'
import ReactDOM from 'react-dom'
import moment from 'moment'
// import ColorPicker from 'rc-color-picker'
import JSONTree from 'react-json-tree'
const treeTheme = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: 'none', //'#272822... | (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 | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limi... | 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 | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limi... | 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 | /*
MartyPC
https://github.com/dbalsom/martypc
Copyright 2022-2023 Daniel Balsom
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limi... | b fn read_register(&self) -> u8 {
match self.reg_select {
CursorAddressH | CursorAddressL | LightPenPositionH | LightPenPositionL => {
self.reg[self.reg_select as usize]
}
_ => REGISTER_UNREADABLE_VALUE
}
}
pub fn read_address(&self) -> u16 {... | 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 | from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .loss_functions import SSIM
__all__ = ['unFlowLoss', 'flow_warp']
def mesh_grid(batch_sz, height, width):
'''
Creates meshgrid of two dimensions which is the pixel location
'''
# mesh grid
x_base = to... |
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 | from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .loss_functions import SSIM
__all__ = ['unFlowLoss', 'flow_warp']
def mesh_grid(batch_sz, height, width):
'''
Creates meshgrid of two dimensions which is the pixel location
'''
# mesh grid
x_base = to... |
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 | from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .loss_functions import SSIM
__all__ = ['unFlowLoss', 'flow_warp']
def mesh_grid(batch_sz, height, width):
'''
Creates meshgrid of two dimensions which is the pixel location
'''
# mesh grid
x_base = to... | (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 | from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .loss_functions import SSIM
__all__ = ['unFlowLoss', 'flow_warp']
def mesh_grid(batch_sz, height, width):
'''
Creates meshgrid of two dimensions which is the pixel location
'''
# mesh grid
x_base = to... |
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 | # -*- coding: utf-8 -*-
import numpy as np
from sample import Sample
from kernel import Method, Kernel
from enum import Enum
from group import Group
import copy
class TrainingTypes(Enum):
OneIterationFinished = 0, # 一个迭代的结束
AllConformedKKT = 1, # 全部点皆符合KKT条件
Failed = 2
class Mode... |
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 | # -*- coding: utf-8 -*-
import numpy as np
from sample import Sample
from kernel import Method, Kernel
from enum import Enum
from group import Group
import copy
class TrainingTypes(Enum):
OneIterationFinished = 0, # 一个迭代的结束
AllConformedKKT = 1, # 全部点皆符合KKT条件
Failed = 2
class Mode... | 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 | # -*- coding: utf-8 -*-
import numpy as np
from sample import Sample
from kernel import Method, Kernel
from enum import Enum
from group import Group
import copy
class TrainingTypes(Enum):
OneIterationFinished = 0, # 一个迭代的结束
AllConformedKKT = 1, # 全部点皆符合KKT条件
Failed = 2
class Mode... |
# 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 | # -*- coding: utf-8 -*-
import numpy as np
from sample import Sample
from kernel import Method, Kernel
from enum import Enum
from group import Group
import copy
class TrainingTypes(Enum):
OneIterationFinished = 0, # 一个迭代的结束
AllConformedKKT = 1, # 全部点皆符合KKT条件
Failed = 2
class Mode... | 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 | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, 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};... |
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 | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, 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 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 | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, 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};... |
}
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 | use druid::{Selector, WidgetPod, WidgetId, ExtEventSink, EventCtx, Event, Env, Widget, UpdateCtx, LayoutCtx, PaintCtx, 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};... | (&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 | /**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-09-26
* @author Liang <liang@maichong.it>
*/
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const xmldom = require('xmldom');
const utils = require('./utils');
const config = requi... | 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 | /**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-09-26
* @author Liang <liang@maichong.it>
*/
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const xmldom = require('xmldom');
const utils = require('./utils');
const config = requi... | ]*\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 | /**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-09-26
* @author Liang <liang@maichong.it>
*/
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const xmldom = require('xmldom');
const utils = require('./utils');
const config = requi... | // 不转换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 | /**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-09-26
* @author Liang <liang@maichong.it>
*/
'use strict';
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const xmldom = require('xmldom');
const utils = require('./utils');
const config = requi... | comPrefix
* @param {string} valPrefix
* @param {string} clsPrefix
* @param {Object} depends
* @returns {Document}
*/
function build(from, comPrefix, valPrefix, clsPrefix, depends) {
if (typeof from === 'string') {
from = utils.getInfo(from);
}
const components = config.srcDir + 'components/';
let data... | 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 | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[ -> 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 | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[ -> 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 | /*!
[](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[](https://travis-ci.org/jaemk/self_update)
[]
pub struct Download {
show_progress: bool,
url: String,
}
impl Download {
/// Specify download url
pub fn from_url(url: &str) -> Self {
Self {
show_progress: false,
url: url.to_owned()... | {
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 | /**
* Project : UCMS( Unified Contents Messaging Solution )
*
* Copyright (c) 2013, 2014 FREECORE, Inc. All rights reserved.
*
* @author dbongman
*/
define(
[
"BaroAppBase", "BaroProps", "Logger", "osapi"
]
, function(BaroAppBase, BaroProps, Logger, osapi)
{
var baroappTrackingId = "UA-46722680-5";
var bar... | _moduleLoading : function(moduleName, action, id, title, item_id){
var self = this;
require([ moduleName ], function(klass)
{
var selfPanel = new klass({parentView : self, mode: action, container_id : id, title : title, item_id : item_id});
self._showFrame( selfPanel );
});
}
,
... | },
| random_line_split |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | {
ShellCommand::new(RG_EXEC_CMD.into(), PathBuf::from(dir.as_ref()))
} | identifier_body | |
mod.rs | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | 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 | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... |
}
}
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 | mod default_types;
mod jsont;
mod stats;
use crate::cache::Digest;
use crate::process::ShellCommand;
use anyhow::Result;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::... | (&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 | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... | },
Accepting(<AcceptTls<A, CrtKey> as Accept<<Listen as CoreListen>::Connection>>::Future),
Serving(<AcceptTls<A, CrtKey> as Accept<<Listen as CoreListen>::Connection>>::ConnectionFuture),
}
#[derive(Clone)]
struct Target(SocketAddr, Conditional<Name>);
#[derive(Clone)]
struct ClientTls(CrtKey);
impl<A: ... | AcceptTls<A, CrtKey>: Accept<<Listen as CoreListen>::Connection>,
{
Init {
listen: Listen,
accept: AcceptTls<A, CrtKey>, | random_line_split |
tls_accept.rs | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... |
}
/// 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 | #![cfg(test)]
// These are basically integration tests for the `connection` submodule, but
// they cannot be "real" integration tests because `connection` isn't a public
// interface and because `connection` exposes a `#[cfg(test)]`-only API for use
// by these tests.
use linkerd2_error::Never;
use linkerd2_identity:... | (CrtKey);
impl<A: Accept<ServerConnection> + Clone> Future for Server<A> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
*self = match self {
Server::Init {
ref mut listen,
ref mut a... | ClientTls | identifier_name |
AutomobilesOnSale.py | # Importing Necessary Library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import chi2_contingency
from datetime import datetime
from ipywidgets import interact, widgets
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('darkgrid')
# ... | 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 | # Importing Necessary Library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import chi2_contingency
from datetime import datetime
from ipywidgets import interact, widgets
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('darkgrid')
# ... |
interact(plot_year, year=widgets.IntSlider(min=1989, max=2019, step=1, value=2003, description='Year '),
month=widgets.IntSlider(min=1, max=12, step=1, value=2, description='Month '),
days=widgets.IntSlider(min=0, max=10, step=1, value=0, description='Day '),
gearbox = widgets.RadioButtons(... | 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 | # Importing Necessary Library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import chi2_contingency
from datetime import datetime
from ipywidgets import interact, widgets
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('darkgrid')
# ... | (year, month, days, gearbox, damage):
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... | plot_year | identifier_name |
AutomobilesOnSale.py | # Importing Necessary Library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import chi2_contingency
from datetime import datetime
from ipywidgets import interact, widgets
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set_style('darkgrid')
# ... |
# Interactive Distribution of Horsepower with Price
# Visualization possible among year/month/days/gearbox/damage
def plot_year(year, month, days, gearbox, damage):
data = df_auto[(df_auto.yearOfRegistration == year) & (df_auto.monthOfRegistration == month) &
(df_auto.Sold_In_Days == day... | print(col, len(df_auto[col].unique())) | conditional_block |
metapipeline.go | package metapipeline
import (
"fmt"
"path/filepath"
jenkinsv1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/apps"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/prow"
"... | (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 | package metapipeline
import (
"fmt"
"path/filepath"
jenkinsv1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/apps"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/prow"
"... |
// 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(params CRDCreationParameters) ... | {
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 | package metapipeline
import (
"fmt"
"path/filepath"
jenkinsv1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/apps"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/prow"
"... | 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 | package metapipeline
import (
"fmt"
"path/filepath"
jenkinsv1 "github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/apps"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/prow"
"... |
// 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.