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 |
|---|---|---|---|---|
marketplace.js |
return formatted;
};
var searchReports = function(search, callback) {
$.ajax({
url: './handlers/MarketplaceReportSearchHandler.ashx',
data: { language: languageId, instance: instanceId, search: JSON.stringify(search) },
success: function (d) {
if (callback) callback(d);
... | {
var regexp = new RegExp('\\{' + i + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
} | conditional_block | |
marketplace.js | rid));
}
else {
std_row = result.after(report_template.format(id, name, logo, rid));
}
getStandardResults(rid, id, 0, function (d) {
showStandardResults(d.Data, '#data-' + rid + '-' + id);
});
... | return text.replace(/^"/, '')
.replace(/",$/, '')
.split('","');
};
| identifier_body | |
marketplace.js | type: 'POST'
});
}
var getCompanyDetails = function (companyId, profileId, languageId, callback) {
$.ajax({
url: './handlers/MarketplaceCompanyDetailsHandler.ashx',
data: { company: companyId, profile: profileId, language: languageId },
success: function (d) {
if (ca... | data: { report: reportId, standard: standardId, profile: profileId },
success: function (d) {
if (callback) callback(d);
},
dataType: 'json', | random_line_split | |
copy.go | - If the root node is a manifest list, it will be mapped to the first
// matching manifest if exists, otherwise ErrNotFound will be returned.
// - Otherwise ErrUnsupported will be returned.
func (opts *CopyOptions) WithTargetPlatform(p *ocispec.Platform) {
if p == nil {
return
}
mapRoot := opts.MapRoot
o... | {
if opts.PreCopy != nil {
if err := opts.PreCopy(ctx, desc); err != nil {
if err == errSkipDesc {
return nil
}
return err
}
}
if err := doCopyNode(ctx, src, dst, desc); err != nil {
return err
}
if opts.PostCopy != nil {
return opts.PostCopy(ctx, desc)
}
return nil
} | identifier_body | |
copy.go | , error)
}
// WithTargetPlatform configures opts.MapRoot to select the manifest whose
// platform matches the given platform. When MapRoot is provided, the platform
// selection will be applied on the mapped root node.
// - If the given platform is nil, no platform selection will be applied.
// - If the root node ... | (ctx context.Context, src content.ReadOnlyStorage, dst content.Storage, desc ocispec.Descriptor) error {
rc, err := src.Fetch(ctx, desc)
if err != nil {
return err
}
defer rc.Close()
err = dst.Push(ctx, desc, rc)
if err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
return err
}
return nil
}
// copyN... | doCopyNode | identifier_name |
copy.go | error)
}
// WithTargetPlatform configures opts.MapRoot to select the manifest whose
// platform matches the given platform. When MapRoot is provided, the platform
// selection will be applied on the mapped root node.
// - If the given platform is nil, no platform selection will be applied.
// - If the root node i... |
}
return nil
}
// find successors while non-leaf nodes will be fetched and cached
successors, err := opts.FindSuccessors(ctx, proxy, desc)
if err != nil {
return err
}
successors = removeForeignLayers(successors)
if len(successors) != 0 {
// for non-leaf nodes, process successors and wait f... | {
return err
} | conditional_block |
copy.go | // reference will be passed to MapRoot, and the mapped descriptor will be
// used as the root node for copy.
MapRoot func(ctx context.Context, src content.ReadOnlyStorage, root ocispec.Descriptor) (ocispec.Descriptor, error)
}
// WithTargetPlatform configures opts.MapRoot to select the manifest whose
// platform ma... | random_line_split | ||
alumniMap-controller.js | results"]
if (results.length > 0){
result = results[0];
lat = parseFloat(result["geometry"]["lat"]);
lon = parseFloat(result["geometry"]["lng"]);
return [lat, lon];
} else {
throw new Error('No Results');
}
})
.catch( error => console.error('Error fetching lat & lon:', error) ... |
function create_popup(location, alumns) {
alumns_html = 'Residents:'
alumns_html += '<br><ul class="popup">\n'
for (var i=0; i<alumns.length; i++){
alumn = alumns[i];
alumns_html += "<li>"+alumn+"</li>\n";
}
alumns_html += "</ul>"
return "<b>"+location+"</b>"+"<br>"+alumns_html;
}
... | {
let id = "12lGrmIhj2dlLHt2GNucD69IktFoOA5k9Zi9rnLR0OoI";
let bubble_list = await convert_sheet_to_bubble_list(id);
return bubble_list;
} | identifier_body |
alumniMap-controller.js | results"]
if (results.length > 0){
result = results[0];
lat = parseFloat(result["geometry"]["lat"]);
lon = parseFloat(result["geometry"]["lng"]);
return [lat, lon];
} else {
throw new Error('No Results');
}
})
.catch( error => console.error('Error fetching lat & lon:', error) ... |
bubble_list = []
for ( let [loc, alumn_list] of Object.entries(organized_by_location)) {
// let geo = await get_lat_and_lon(loc+", US");
let lat = location_dict[loc][0];
let lon = location_dict[loc][1];
bubble_list.push({location: loc, latitude: lat,
longitude: lon, radi... | }
} | random_line_split |
alumniMap-controller.js | results"]
if (results.length > 0){
result = results[0];
lat = parseFloat(result["geometry"]["lat"]);
lon = parseFloat(result["geometry"]["lng"]);
return [lat, lon];
} else {
throw new Error('No Results');
}
})
.catch( error => console.error('Error fetching lat & lon:', error) ... | (id) {
const options = {
sheetId: id,
sheetNumber: 1,
returnAllResults: true
};
return await gsheetProcessor(options, process_results);
}
async function create_bubble_list() {
let id = "12lGrmIhj2dlLHt2GNucD69IktFoOA5k9Zi9rnLR0OoI";
let bubble_list = await convert_sheet_to_bubble_list(id);
return bu... | convert_sheet_to_bubble_list | identifier_name |
alumniMap-controller.js | results"]
if (results.length > 0){
result = results[0];
lat = parseFloat(result["geometry"]["lat"]);
lon = parseFloat(result["geometry"]["lng"]);
return [lat, lon];
} else {
throw new Error('No Results');
}
})
.catch( error => console.error('Error fetching lat & lon:', error) ... |
}else{
name_list[alumn] = {
"location": place,
"timestamp": timestamp,
"year": year,
"lat": lat,
"lon":lon
};
}
}
});
organized_by_location = {};
for (let [alumn, val] of Object.entries(organized_by_alumn))... | {
name_list[alumn] = {
"location": place,
"timestamp": timestamp,
"year": year,
"lat": lat,
"lon":lon
};
} | conditional_block |
db.go | merge attempts, giving up")
}
func mkCommit(r *git.Repository, refname string, msg string, tree *git.Tree, parent *git.Commit, extraParents ...*git.Commit) (*git.Commit, error) {
var parents []*git.Commit
if parent != nil {
parents = append(parents, parent)
}
if len(extraParents) > 0 {
parents = append(parent... | {
builder, err := repo.TreeBuilder()
if err != nil {
return nil, err
}
return builder.Write()
} | identifier_body | |
db.go | of the Git blob at path `key`.
// If there is no blob at the specified key, an error
// is returned.
func (db *DB) Get(key string) (string, error) {
if db.parent != nil {
return db.parent.Get(path.Join(db.scope, key))
}
return TreeGet(db.repo, db.tree, path.Join(db.scope, key))
}
// Set writes the specified valu... | if dir == "" {
dir, err = ioutil.TempDir("", "libpack-checkout-")
if err != nil {
return "", err
} | random_line_split | |
db.go |
return db, nil
}
func newRepo(repo *git.Repository, ref string) (*DB, error) {
db := &DB{
repo: repo,
ref: ref,
}
if err := db.Update(); err != nil {
db.Free()
return nil, err
}
return db, nil
}
// Free must be called to release resources when a database is no longer
// in use.
// This is required in ... | {
return nil, err
} | conditional_block | |
db.go | ()
if isGitIterOver(err) {
break
} else if err != nil {
return nil, err
}
if c.Our != nil {
idx.RemoveConflict(c.Our.Path)
if err := idx.Add(c.Our); err != nil {
return nil, fmt.Errorf("error resolving merge conflict for '%s': %v", c.Our.Path, err)
}
}
}
mergedId... | lookupTip | identifier_name | |
file_hook.rs | 0x00, 0x00, 0x00, 0x00, 0x02, 0x10];
static DUMMY_SKINS: &[u8] = br#"{"skins":[]}"#;
fn check_dummied_out_hd(path: &[u8]) -> Option<&'static [u8]> {
if path.ends_with(b".anim") {
// Avoid touching tileset/foliage.anim
if path.starts_with(b"anim/") {
return Some(DUMMY_ANIM);
}
... |
unsafe extern fn read_file(file: *mut scr::FileRead, out: *mut u8, size: u32) -> u32 {
let file = (*file).inner as *mut FileAllocation;
let buf = std::slice::from_raw_parts_mut(out, size as usize);
(*file).file.read(buf)
}
unsafe extern fn skip(file: *mut scr::FileRead, size: u32) {
let file = (*file... | {
let read = (*file).read;
let vtable = (*read).vtable;
(*vtable).skip.call2(read, size)
} | identifier_body |
file_hook.rs | 0x00, 0x00, 0x00, 0x00, 0x02, 0x10];
static DUMMY_SKINS: &[u8] = br#"{"skins":[]}"#;
fn check_dummied_out_hd(path: &[u8]) -> Option<&'static [u8]> {
if path.ends_with(b".anim") {
// Avoid touching tileset/foliage.anim
if path.starts_with(b"anim/") {
return Some(DUMMY_ANIM);
}
... | true => match c_path.iter().rev().position(|&x| x == b'.') {
Some(period) => &c_path[..c_path.len() - period - 1],
None => c_path,
},
false => c_path,
};
if let Err(_) = buffer.try_extend_from_slice(c_path_for_switched_extension) {
return None;
}
i... | let c_path_for_switched_extension = match alt_extension.is_some() { | random_line_split |
file_hook.rs | 0x00, 0x00, 0x00, 0x00, 0x02, 0x10];
static DUMMY_SKINS: &[u8] = br#"{"skins":[]}"#;
fn check_dummied_out_hd(path: &[u8]) -> Option<&'static [u8]> {
if path.ends_with(b".anim") {
// Avoid touching tileset/foliage.anim
if path.starts_with(b"anim/") {
return Some(DUMMY_ANIM);
}
... | (buffer: &'static [u8], handle: *mut scr::FileHandle) {
let inner = Box::new(FileAllocation {
file: FileState {
buffer,
pos: 0,
},
read: scr::FileRead {
vtable: &*FILE_READ_VTABLE,
inner: null_mut(),
},
peek: scr::FilePeek {
... | memory_buffer_to_bw_file_handle | identifier_name |
evaluate.ts | max = 6;
private localIds = [];
private serverIds = [];
private isweb = false;
private allowDelete: boolean = true;
private len = 0;
private imgUrl = [];
private WimgUrl = [];
constructor(public navCtrl: NavController,
public navParams: NavParams,
private httpService: HttpService,
private n... | sole.info("不成功" + result)
});
}
getImg() {
if (!this.nativeService.isMobile()) {
this.addWxPicture();
}
}
onChange1(event: any) {
if(this.fileObjList.length<6){
}else{
this.nativeService.showToast("最多只能上传6张图片");
return
}
let files = event.target.files;
var fil... | }
//con | identifier_name |
evaluate.ts | max = 6;
private localIds = [];
private serverIds = [];
private isweb = false;
private allowDelete: boolean = true;
private len = 0;
private imgUrl = [];
private WimgUrl = [];
constructor(public navCtrl: NavController,
public navParams: NavParams,
private httpService: HttpService,
private n... |
givestaar(i) {
this.list = [{ "statue": false }, { "statue": false }, { "statue": false }, { "statue": false }, { "statue": false },];
for (var n = 0; n < (i + 1); n++) {
this.list[n].statue = true;
};
this.num = (i + 1)
if (i == 0) {
this.status = "非常差";
} else if (i == 1) {
... | {
} | identifier_body |
evaluate.ts | private max = 6;
private localIds = [];
private serverIds = [];
private isweb = false;
private allowDelete: boolean = true;
private len = 0;
private imgUrl = [];
private WimgUrl = [];
constructor(public navCtrl: NavController,
public navParams: NavParams,
private httpService: HttpService,
p... | // for (var i = 0; i < localIds.length; i++) {
that.WxUpLoad(localIds);
// }
// wx.getLocalImgData({
// localId: localIds, // 图片的localID
// success: function (res) {
// var localData = res.localData;
// that.localIds = localData; // localData是图... | sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds;
that.len = localIds.length; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 | random_line_split |
evaluate.ts | max = 6;
private localIds = [];
private serverIds = [];
private isweb = false;
private allowDelete: boolean = true;
private len = 0;
private imgUrl = [];
private WimgUrl = [];
constructor(public navCtrl: NavController,
public navParams: NavParams,
private httpService: HttpService,
private n... | }
}
}
}
login(filearray: any[]) {
//console.info(this.fileObjList[0])
var userInfo = {
Userid: this.userID,
goodsID: this.goodsDetail.ProductID,
Detail: this.textarea,
anonymity: 0,
Degree: this.num,
orderID: this.goodslist.ID,
file: this.fileObjLis... |
this.login(this.imgUrl);
| conditional_block |
activity.py | ("activityobj", idx+1, c)
with open(dataset_json_path) as dataset_json_file:
self.json_data = json.load(dataset_json_file)
print("Elements in the json file:", str(len(self.json_data)))
for image_path, masks in self.json_data.items():
image = skimage.io.imread(image_pat... |
if return_coco:
return coco
def auto_download(self, dataDir, dataType, dataYear):
"""Download the COCO dataset/annotations if requested.
dataDir: The root directory of the COCO dataset.
dataType: What to load (train, val, minival, valminusminival)
dataYear: What... | self.add_image(
"coco", image_id=i,
path=os.path.join(image_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(imgIds=[i], catIds=class_ids, iscrowd=None))) | conditional_block |
activity.py | # Import Mask RCNN
#sys.path.append(ROOT_DIR) # To find local version of the library
sys.path.append("third_party/Mask_RCNN/") # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils
import common
#from train import ActivityConfig, ActivityDataset
# Path to t... | random_line_split | ||
activity.py | ["width"], len(self.json_data[info["id"]])], dtype=np.uint8)
lbls = np.zeros(len(self.json_data[info["id"]]), dtype=np.int32)
for idx, (mask_path, mask_info) in enumerate(self.json_data[info["id"]].items()):
mask_class = mask_info["class"]
mask[:,:,idx] = np.array(PIL.Image.open... | """Load instance masks for the given image.
Different datasets use different ways to store masks. This
function converts the different mask format to one format
in the form of a bitmap [height, width, instances].
Returns:
masks: A bool array of shape [height, width, instance co... | identifier_body | |
activity.py | ("activityobj", idx+1, c)
with open(dataset_json_path) as dataset_json_file:
self.json_data = json.load(dataset_json_file)
print("Elements in the json file:", str(len(self.json_data)))
for image_path, masks in self.json_data.items():
image = skimage.io.imread(image_pat... | (self, dataDir, dataType, dataYear):
"""Download the COCO dataset/annotations if requested.
dataDir: The root directory of the COCO dataset.
dataType: What to load (train, val, minival, valminusminival)
dataYear: What dataset year to load (2014, 2017) as a string, not an integer
... | auto_download | identifier_name |
net.rs | /// session: Session::load_or_create("hello-world.session")?,
/// api_id: API_ID,
/// api_hash: API_HASH.to_string(),
/// params: Default::default(),
/// }).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect(mut config: Config) -> Result<Self, AuthorizationErro... | {
// `Client` is already dropped, no need to disconnect again.
} | conditional_block | |
net.rs | longer knows about it)
// TODO all up-to-date server addresses should be stored in the session for future initial connections
let _remote_config = sender
.invoke(&tl::functions::InvokeWithLayer {
layer: tl::LAYER,
query: tl::functions::InitConnection {
api_id: co... | invoke | identifier_name | |
net.rs | {
/// session: Session::load_or_create("hello-world.session")?,
/// api_id: API_ID,
/// api_hash: API_HASH.to_string(),
/// params: Default::default(),
/// }).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect(mut config: Config) -> Result<Self, AuthorizationE... | } | random_line_split | |
net.rs | 3),
(Ipv4Addr::new(149, 154, 167, 51), 443),
(Ipv4Addr::new(149, 154, 175, 100), 443),
(Ipv4Addr::new(149, 154, 167, 92), 443),
(Ipv4Addr::new(91, 108, 56, 190), 443),
];
pub(crate) async fn connect_sender(
dc_id: i32,
config: &mut Config,
) -> Result<Sender<transport::Full, mtp::Encrypted>, Au... | sender
};
// TODO handle -404 (we had a previously-valid authkey, but server no longer knows about it)
// TODO all up-to-date server addresses should be stored in the session for future initial connections
let _remote_config = sender
.invoke(&tl::functions::InvokeWithLayer {
... | {
let transport = transport::Full::new();
let addr = DC_ADDRESSES[dc_id as usize];
let mut sender = if let Some(auth_key) = config.session.auth_key.as_ref() {
info!(
"creating a new sender with existing auth key to dc {} {:?}",
dc_id, addr
);
sender::connect... | identifier_body |
Props.ts | cn ms, 两次提交间隔时长(防止重复提交)
* @default 1000
*/
throttle?: number
/**
* @en bind form ref, Can call some form methods
* @cn 绑定 form 的引用, 可以调用某些 form 的方法
* @override
*/
formRef?: ((form: FormRef<Value>) => void) | { current?: FormRef<Value> }
/**
* @inner 内部属性
*/
error?: ObjectType<string | ... | identifier_name | ||
Props.ts | import { CardConsumerType } from '../Card/Props'
import { GetDatumFormProps } from '../Datum/Props'
export interface RuleObject {
[name: string]: FormItemRule<any> | RuleObject
}
/** ----------------fieldSet-----------------------* */
export interface FieldSetChildrenFunc<Value = any> {
(
params: {
list... | import { FormError } from '../utils/errors'
import FormDatum from '../Datum/Form'
import { ForceAdd, ObjectType, StandardProps, RegularAttributes, PartialKeys } from '../@types/common'
import { FormItemRule } from '../Rule/Props'
import { ButtonProps } from '../Button/Props' | random_line_split | |
views.py | products = Product.objects.values('title', 'balance', 'price')
result['Список товаров с остатками и ценами'] = list(products)
# Суммарная стоимость всех товаров на складе
total_cost = Product.objects.aggregate(summary_cost=Sum(F('balance')*F('price')))
result['Суммарная стоимость всех товаров на ск... | esponse(request.GET['dt'])
| conditional_block | |
views.py | список товаров
products = Product.objects.values('title', 'balance', 'price')
result['Список товаров с остатками и ценами'] = list(products)
# Суммарная стоимость всех товаров на складе
total_cost = Product.objects.aggregate(summary_cost=Sum(F('balance')*F('price')))
result['Суммарная стоимость вс... | identifier_name | ||
views.py | их заказов'],
['GET /spec_stat/vip_clients_and_orders_video/', 'vip-клиенты и список их заказов, включающих видеокарты'],
['GET /spec_stat/products_cost/', 'Список товаров с их полной стоимостью (цена*количество)'],
['GET /get_clients/', 'Список клиентов (формируется с помощью DRF)'... | clients = Client.objects.all()
products = Product.objects.all()
# Добавляем новые заказы
today = date.today()
for i in range(0, orders_count):
client = random.choice(clients)
product = random.choice(products)
t_delta = timedelta(days=random.randint(0, 10))
dt_create... |
# Получаем списки клиентов и товаров | random_line_split |
views.py | ым клиентом
clients_with_order_counts = Client.objects.annotate(Count('order')).order_by('-order__count')
result['Количество заказов, сделанных клиентами'] = {
client.title: client.order__count for client in clients_with_order_counts
}
# По примеру формирования списка клиентов формируем и списо... | sion])
def test_permission(request):
return Response('Тест разрешений выполнен успешно')
@api_view(['GET'])
def clear_ord | identifier_body | |
main.rs | (?P<ref>\w+))?:(?P<script>.+)$").unwrap();
static ref GIT_SOURCE_REGEX: Regex =
Regex::new(r"^(?P<repo>((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\./\-~]+)(\.git)?(/)?)(@(?P<ref>\w+))?:(?P<script>.+)$")
.unwrap();
}
#[derive(Clap, Debug)]
#[clap(author, about, version)]
#[clap(global_settin... | {
Git,
Saved,
}
impl ScriptSource {
fn parse(script: &str, action: ScriptAction) -> Result<ScriptSource> {
if let Some(matches) = API_SOURCE_REGEX.captures(script) {
let repo = matches
.name("alias")
.expect("No alias matched")
.as_str()
... | SourceType | identifier_name |
main.rs | (?P<ref>\w+))?:(?P<script>.+)$").unwrap();
static ref GIT_SOURCE_REGEX: Regex =
Regex::new(r"^(?P<repo>((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\./\-~]+)(\.git)?(/)?)(@(?P<ref>\w+))?:(?P<script>.+)$")
.unwrap();
}
#[derive(Clap, Debug)]
#[clap(author, about, version)]
#[clap(global_settin... | SourceType::Git => git::GitRepo::from_src(&self),
};
let rref = self.rref.clone().unwrap_or("HEAD".to_owned());
Ok(repo.fetch_script(&self.script_name, &rref, fresh).await?)
| .get(&self.repo)
.ok_or(anyhow!("Repo `{}` was not found", &self.repo))?
.box_clone(), | random_line_split |
main.rs | (?P<ref>\w+))?:(?P<script>.+)$").unwrap();
static ref GIT_SOURCE_REGEX: Regex =
Regex::new(r"^(?P<repo>((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\./\-~]+)(\.git)?(/)?)(@(?P<ref>\w+))?:(?P<script>.+)$")
.unwrap();
}
#[derive(Clap, Debug)]
#[clap(author, about, version)]
#[clap(global_settin... | .context("Failed to save updated config")?;
println!("Repo `{}` was successfully added", &name);
}
RepoCommand::Remove { name } => {
if !config.repo.contains_key(&name) {
bail!("Repo `{}` was not found", &name);
... | {
if config.repo.contains_key(&name) {
bail!("A repository with the name `{}` already exists", &name);
}
let password_for_parse = match (password, password_env, password_stdin) {
(Some(pass), _, _) => Password::Saved(pass),
... | conditional_block |
ledger_manager.rs | 256>,
pub tx_confirmed: HashSet<H256>,
pub tx_count: usize,
}
//ledger-manager will periodically loop and confirm the transactions
pub struct LedgerManager {
pub ledger_manager_state: LedgerManagerState,
pub blockchain: Arc<Mutex<Blockchain>>,
pub utxo_state: Arc<Mutex<UtxoState>>,
pub voter_d... | }
num_confirmed_votes.insert(*block, total_k_deep_votes);
}
}
for (proposer, votes) in num_confirmed_votes.iter() {
println!("proposer {:?} votes {}", proposer, *votes);
if *votes > (num_voter_chains / 2) {
new_leade... | {
//TODO: We might also need number of voter blocks at a particular level of a voter chain
//This is not urgent as we can **assume**, there is one block at each level
let voters_info = &locked_blockchain.proposer2voterinfo[block];
if voter... | conditional_block |
ledger_manager.rs | {
pub last_level_processed: u32,
pub leader_sequence: Vec<H256>,
pub proposer_blocks_processed: HashSet<H256>,
pub tx_confirmed: HashSet<H256>,
pub tx_count: usize,
}
//ledger-manager will periodically loop and confirm the transactions
pub struct LedgerManager {
pub ledger_manager_state: Ledg... | LedgerManagerState | identifier_name | |
ledger_manager.rs | 256>,
pub tx_confirmed: HashSet<H256>,
pub tx_count: usize,
}
//ledger-manager will periodically loop and confirm the transactions
pub struct LedgerManager {
pub ledger_manager_state: LedgerManagerState,
pub blockchain: Arc<Mutex<Blockchain>>,
pub utxo_state: Arc<Mutex<UtxoState>>,
pub voter_d... |
fn get_leader_sequence(&mut self) -> Vec<H256> {
let locked_blockchain = self.blockchain.lock().unwrap();
let mut leader_sequence: Vec<H256> = vec![];
//TODO: This is a workaround for now till we have some DS which asserts that
//all voter chains at a particular level has... | {
loop{
//Step 1
//let leader_sequence = self.get_leader_sequence();
//This one uses the algorithm described in Prism Paper
let leader_sequence = self.get_confirmed_leader_sequence();
//Step 2
let tx_sequence = sel... | identifier_body |
ledger_manager.rs | State>>, k: u32) -> Self {
let ledger_manager_state = LedgerManagerState{
last_level_processed: 1,
proposer_blocks_processed: HashSet::new(),
leader_sequence: Vec::new(),
tx_confirmed: HashSet::new(),
tx_count: 0,
};
LedgerManager {
... | self.ledger_manager_state.proposer_blocks_processed.insert(*leader);
}
tx_sequence | random_line_split | |
PredictionRuntimeInspector.py | brk; brk(port=9011)
exp.pause = True
self.pause = True
self.pauseAtPhaseSetup = False
else:
self.pauseAtPhaseSetup = True
def onPhaseTeardown(self, exp):
title()
index = exp.position.phase
# Last phase
if index == len(exp.workflow) - 1:
self.done = True
def on... | try:
self._setProgress()
except:
# may fail when switching from training to inference
from dbgp.client import brk; brk(port=9011)
pass | conditional_block | |
PredictionRuntimeInspector.py | ("Repeat")
# The "Next Error" button becomes "Next Target" when user sets a custom one
nextTargetButton = Event # Button with dynamic label
targetButtonLabels = ('Next error', 'Next target') | pauseTarget = Str
backwardButton = Button('Back',
image=ImageResource(getNTAImage('backward_36_26')))
runButton = Button('Run',
image=ImageResource(getNTAImage('play_36_26')))
pauseButton = Button('Pause',
image=ImageResource(... | targetButtonLabel = Str(targetButtonLabels[0])
customTargetButton = Button('Custom...') | random_line_split |
PredictionRuntimeInspector.py | i):
""" """
title(additional='(), self.pause = ' + str(self.pause))
self.iteration += 1
# check if the pause button was clicked
if self.pause:
exp.pause = True
elif self.runCount is not None:
self.runCount -= 1
if self.runCount == 0:
exp.pause = True
runtimeliste... | wx.CallLater(self.runInterval, self._step) | identifier_body | |
PredictionRuntimeInspector.py | ("Repeat")
# The "Next Error" button becomes "Next Target" when user sets a custom one
nextTargetButton = Event # Button with dynamic label
targetButtonLabels = ('Next error', 'Next target')
targetButtonLabel = Str(targetButtonLabels[0])
customTargetButton = Button('Custom...')
pauseTarget = Str
backward... | (self):
d = self.experiment.description
for name in 'spTrain', 'tpTrain', 'classifierTrain', 'infer':
if not name in d:
continue
phase = d[name]
if len(phase) > 0:
assert self.onPhaseSetup not in phase[0]['setup']
phase[0]['setup'].append(self.onPhaseSetup)
phas... | _registerCallbacks | identifier_name |
04-aruco_calibration.py | uco_type = list(df[(df["place"]=="floor") & (df["aruco_type"]==aruco_type)]["id"])
if len(corners) > 0: # verify *at least* one ArUco marker was detected
for i, markerID in enumerate(list(ids.flatten())): # loop over the detected ArUCo corners
if markerID in ids_on_floor_... | """ Loads camera matrix and distortion coefficients. """
# FILE_STORAGE_READ
cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_READ)
# note we also have to specify the type to retrieve other wise we only get a
# FileNode object back instead of a matrix
camera_matrix = cv_file.getNode("K").mat()
... | identifier_body | |
04-aruco_calibration.py | # verify *at least* one ArUco marker was detected on floor
if len(corners_all) > 0:
rvecs = []
tvecs = []
# loop over the detected ArUCo corners and draw ids and bounding boxes around the detected markers
for (markerCorner, markerID, markerSize) in zip(corners_all, ids_all, size... | print("Escape hit, closing...")
img = cv2.imread(img_name)
break | conditional_block | |
04-aruco_calibration.py | boxes around the detected markers
for (markerCorner, markerID, markerSize) in zip(corners_all, ids_all, sizes_all):
# extract the marker corners (which are always returned in
# top-left, top-right, bottom-right, and bottom-left order)
corners = markerCorner.reshape((4, 2))
... | save_coefficients | identifier_name | |
04-aruco_calibration.py | uco.DICT_APRILTAG_36h10,
"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}
def calibrate_aruco(intrinsic_calib_path, intrinsic_calib_path_undistorted, image_dir, image_name, image_format, aruco_tags_info_path):
[mtx, dist, R_co, R_oc, T_co, T_oc] = load_coefficients(intrinsic_calib_path)
[mtx_new, d... |
frame = capture_img(image_dir, image_name, image_format)
# try undistorted image
# h, w = frame.shape[:2]
# newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
# undistort
# # frame = cv2.undistort(frame, mtx, dist, None, newcameramtx)
frame = cv2.undistort(f... | random_line_split | |
huff_algorithm.py | (self):
if (self.lvl ==None):
return "\t%.3d=%c id:%0.3d : %.3f\r\n" % (self.symbol, self.symbol,\
self.id,self.prob)
else :
return "\t%.3d=%c id:%0.3d : %.3f (%d)\r\n" % (self.symbol,self.symbol,\
self.id,self.prob, self.lvl)
# @brief Binary tree leaf constructor specific class prototype contains symbol_v... | __repr__ | identifier_name | |
huff_algorithm.py | Dict = newDict
def SortedLeafGen(self):
for leaf_no in range(0, len(self.pSymbolsList_sorted)):
self.pBTLeafList.append(TBinTree_Leaf(self.pSymbolsList_sorted[leaf_no][0],self.pSymbolsList_sorted[leaf_no][1]))
self.LeafPopulation = len(self.pBTLeafList)
def DictPrint(self):
print ("\r\nIn total = %d... | print "Generating Soure tree implementing bottom-up algorithm."
print LeavesList.__class__.__name__
print LeavesList
while (len(LeavesList)>1):
for leafIndex in range(0,len(LeavesList)-1) :
if (LeavesList[leafIndex].prob>LeavesList[leafIndex+1].prob):
temp = LeavesList.pop(leafIndex)
LeavesList.insert(l... | identifier_body | |
huff_algorithm.py | )\r\n" % (self.symbol,self.symbol,\
self.id,self.prob, self.lvl)
# @brief Binary tree leaf constructor specific class prototype contains symbol_val field and does
# not need any fields for descending nodes (dead end, None on default)
# @param Symbol value -> character which is represented by this node
# @par... |
def Pop2Prob(self): # takes total population into consideration and tranlates it into probability
for x in range(0,len(self.pSymbolsList_sorted)):
tempItem = list(self.pSymbolsList_sorted.pop(x))
tempItem[1]=float(tempItem[1])/self.pPopulation
print tempItem
self.pSymbolsList_sorted.insert(x,tempItem)
... | for key, value in sorted(self.pSymbolsDict.iteritems(), key=lambda (k,v): (v,k),reverse=False):
self.pSymbolsList_sorted.append((key,value)) | random_line_split |
huff_algorithm.py | r\n" % (self.symbol,self.symbol,\
self.id,self.prob, self.lvl)
# @brief Binary tree leaf constructor specific class prototype contains symbol_val field and does
# not need any fields for descending nodes (dead end, None on default)
# @param Symbol value -> character which is represented by this node
# @param... |
elif (CodedMsg[0]=='1') :
return fDecodeBit(CurrentNode.b_one, CodedMsg[1:])
else :
print "DecodeError 2 Message!"
else:
print "DecodeError 1 Message!"
# @brief Indepednent function with implementation of suboptimal top-down method of source tree generation
# algorithm
# @param List of BTLeaves re... | return fDecodeBit(CurrentNode.b_zero, CodedMsg[1:]) | conditional_block |
rtc_api.rs | const COUNTA_HAPPENED = 0b0100_0000;
const WATCHA_HAPPENED = 0b1000_0000;
}
}
pub const ABRTCMC_CONTROL3: u8 = 0x02;
bitflags! {
pub struct Control3: u8 {
const BATTLOW_INT = 0b0000_0001;
const BATTSWITCH_INT = 0b0000_0010;
const BATTLOW_STAT = 0b0000_0100;
... | rtc_to_seconds | identifier_name | |
rtc_api.rs | 000_0001;
const TIMER_A_WATCHDOG = 0b0000_0100;
const TIMER_A_COUNTDWN = 0b0000_0010;
const TIMER_A_DISABLE = 0b0000_0000;
const TIMER_A_DISABLE2 = 0b0000_0110;
const CLKOUT_32768_HZ = 0b0000_0000;
const CLKOUT_16384_HZ = 0b0000_1000;
const CLKOUT_8192_HZ = ... | } | random_line_split | |
mod.rs | //! methods!
//!
//! Aside from the cognitive complexity of having so many methods on a single
//! trait, this approach had numerous other drawbacks as well:
//!
//! - Implementations that did not implement all available protocol extensions
//! still had to "pay" for the unused packet parsing/handler code, resultin... | //! to the extreme, would have resulted in literally _hundreds_ of associated | random_line_split | |
main.rs | gl_Position = scale * vec4(0.5 * a_Pos, 0.0, 1.0);
}
";
const FS_SHADER: &'static str = "
#version 150 core
in vec4 v_Color;
out vec4 Target0;
void main() {
Target0 = v_Color;
}
";
const VERTICES: &'static [[f32;2];3] = &[
[-1.0, -0.57],
[ 1.0, -0.57],
... | v_Color = vec4(a_Color, 1.0); | random_line_split | |
main.rs | () -> GlHandles {
GlHandles {
vao: Cell::new(0 as gl::GLuint),
vbos: Cell::new([0,0]),
program: Cell::new(0 as gl::GLuint),
scale: Cell::new(0.0),
}
}
}
const CLEAR_COLOR: (f32, f32, f32, f32) = (0.0, 0.2, 0.3, 1.0);
const WIN_WIDTH: i32 = 256;
const ... | new | identifier_name | |
main.rs | = &[
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]
];
fn add_shader(program: gl::GLuint, src: &str, ty: gl::GLenum) {
let id = unsafe { gl::CreateShader(ty) };
if id == (0 as gl::GLuint) {
panic!("Failed to create shader type: {:?}", ty);
}
let mut source = Vec:... |
}
fn compile_shaders(handles: &GlHandles) {
handles.program.set(gl::create_program());
if handles.program.get() == (0 as gl::GLuint) {
panic!("Failed to create shader program");
}
add_shader(handles.program.get(), VS_SHADER, gl::VERTEX_SHADER);
add_shader(handles.program.get(), FS_SHADER,... | {
if !log.is_empty() {
println!("Warnings detected on shader:\n{}", log);
}
gl::attach_shader(program, id);
} | conditional_block |
main.go | : in6dest,
In6Plen: uint(64), Rt6Dest: rt6dest, Rt6Plen: uint(64)}
event(logdebug, li, "Session [%v] deactivation parameters: [Interface "+
"name: %v, Tunnel source: %v, Tunnel destination: %v, Server "+
"inet6 address: %v/64, Client inet6 address: %v/64, Routed "+
"prefix: %v/64]", e.Id, ifname, app.SvInfo.T... | {
var str = fmt.Sprintf("%v-%v\nusage: %v [-d] [-h] [-c config file]\n",
APPNAME, APPVER, APPNAME)
fmt.Fprintf(os.Stderr, str)
os.Exit(1)
} | identifier_body | |
main.go | 64
ReqError int64
ReqErrUrl int64
ReqErrHeader int64
ReqErrPayload int64
ReqErrSignature int64
ReqErrServerId int64
ReqErrUserId int64
ReqErrMsgId int64
ReqErrCommand int64
ReqErrData int64
ReqErrActivate int64
ReqErrDeactivate int64
ReqErrCheck int64
ReqE... | () (err error) {
var data = &RebanaRequestMsg{UserId: 102, Command: "server-info",
Data: app.HostName}
var buf, _ = json.Marshal(data)
var url = app.RebanaUrl + "/v/info"
var rd = bytes.NewReader(buf)
var req *http.Request
if req, err = http.NewRequest("POST", url, rd); err != nil {
return
}
var loc = &... | serverInfo | identifier_name |
main.go | Opt string
}
type IdList struct {
Id int64
Entry []Id
}
type ServerInfo struct {
Id int64
TunSrc string
PpPrefix string
RtPrefix string
Session []Session
}
type Session struct {
Id int64
Dst string
Idx int64
}
type BindInfo struct {
Host string
Port string
}
type AppConfig struct {
Hos... | Id int64
ErrNo int | random_line_split | |
main.go | v:%v::", rt[0], e.Id)
var s = &CSession{Ifname: ifname, TunAddr: app.SvInfo.TunSrc,
TunDest: e.Opt, In6Addr: in6addr, In6Dest: in6dest,
In6Plen: uint(64), Rt6Dest: rt6dest, Rt6Plen: uint(64)}
event(logdebug, li, "Session [%v] deactivation parameters: [Interface "+
"name: %v, Tunnel source: %v, Tunnel destinat... | {
event(lognotice, li, "Terminating..")
os.Remove(PIDFILE)
os.Exit(0)
} | conditional_block | |
digits_DG_Gphi_projection.py | d(c_in, c_out, 3, stride=1, padding=1)
self.relu = nn.ReLU(True)
def forward(self, x):
return self.relu(self.conv(x))
class ConvNet(Backbone):
def __init__(self, c_hidden=64):
super().__init__()
self.conv1 = Convolution(3, c_hidden)
self.conv2 = Convolution(c_hidden, ... | #print(h.shape)
h = h.view(-1, 1, 16,16)
#print(h.shape)
h=h.detach()
recon_batch, mu, logvar = vae(h)
loss = loss_function(recon_batch, h, mu, logvar)
loss.backward()
train_loss += loss.item()
VAEoptim.step()
print('====> Epoch: {} Average l... | VAEoptim.zero_grad()
h = digits_fnet(image_batch).to(dev) | random_line_split |
digits_DG_Gphi_projection.py | d(c_in, c_out, 3, stride=1, padding=1)
self.relu = nn.ReLU(True)
def forward(self, x):
return self.relu(self.conv(x))
class ConvNet(Backbone):
def __init__(self, c_hidden=64):
super().__init__()
self.conv1 = Convolution(3, c_hidden)
self.conv2 = Convolution(c_hidden, ... | (nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class UnFlatten(nn.Module):
def forward(self, input, size=64):
return input.view(input.size(0), size, 1, 1)
class VAE_Digits(nn.Module):
def __init__(self, image_channels=1, h_dim=64, z_dim=32):
su... | Flatten | identifier_name |
digits_DG_Gphi_projection.py | d(c_in, c_out, 3, stride=1, padding=1)
self.relu = nn.ReLU(True)
def forward(self, x):
return self.relu(self.conv(x))
class ConvNet(Backbone):
def __init__(self, c_hidden=64):
super().__init__()
self.conv1 = Convolution(3, c_hidden)
self.conv2 = Convolution(c_hidden, ... |
else:
self.transform = transform
# make a list of all the files in the root_dir
# and read the labels
self.img_files = []
self.labels = []
self.domain_labels = []
for domain in self.domains:
for category in self.categories:
for image in os.listdir(self.root_dir+domain+'/... | self.transform = transforms.ToTensor() | conditional_block |
digits_DG_Gphi_projection.py |
class ConvNet(Backbone):
def __init__(self, c_hidden=64):
super().__init__()
self.conv1 = Convolution(3, c_hidden)
self.conv2 = Convolution(c_hidden, c_hidden)
self.conv3 = Convolution(c_hidden, c_hidden)
self.conv4 = Convolution(c_hidden, c_hidden)
self._out_fea... | def __init__(self, c_in, c_out):
super().__init__()
self.conv = nn.Conv2d(c_in, c_out, 3, stride=1, padding=1)
self.relu = nn.ReLU(True)
def forward(self, x):
return self.relu(self.conv(x)) | identifier_body | |
script.js | -nav-parent-active')
panel.css('max-height',panel.prop('scrollHeight') + "px")
} else {
panel.attr('style','');
$(this).toggleClass('links-nav-parent-active')
}
}
})
//menu-script
$('.m-nav-icon').on('click',function(event){
$('.header-overley').addClass('show-overlay');
$('body... | if($('div').is('.post-nav-container')){
if($(window).width() > 768){
$(".sp-text-col h2,.sp-text-col h3,.sp-text-col h4").each(function(i) {
var current = $(this);
current.attr("id", "title" + i);
$(".sp-links .post-nav-container").append("<a calass='post-nav-link' id='link" + i + "' href='#title" + i + "... | //post-nav | random_line_split |
script.js | -parent-active')
panel.css('max-height',panel.prop('scrollHeight') + "px")
} else {
panel.attr('style','');
$(this).toggleClass('links-nav-parent-active')
}
}
})
//menu-script
$('.m-nav-icon').on('click',function(event){
$('.header-overley').addClass('show-overlay');
$('body').a... | () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
//tabs
$(".tab-t").on("click",function(e){
$('.tab-t').removeClass('tab-t... | getScrollBarWidth | identifier_name |
script.js | -parent-active')
panel.css('max-height',panel.prop('scrollHeight') + "px")
} else {
panel.attr('style','');
$(this).toggleClass('links-nav-parent-active')
}
}
})
//menu-script
$('.m-nav-icon').on('click',function(event){
$('.header-overley').addClass('show-overlay');
$('body').a... |
$(".close-modal, .modal-overley").on("click",function(e){
hideModal()
})
$(document).keydown(function(eventObject){
if (eventObject.which == 27)
hideModal()
});
$('[data-modal-open]').on("click",function(e){
event.preventDefault()
$('[data-modal='+ $(this).attr('data-modal-open') +']').addClass('visible-modal'... | {
$('[data-modal]').removeClass('visible-modal');
$('.modal-overley').removeClass('modal-overley-show');
setTimeout(function(){
$('body').removeClass('stop-scroll');
$('body').css('padding-right',0+'px');
$('.site-header').css('padding-right',0+'px')
}, 300);
} | identifier_body |
script.js | -parent-active')
panel.css('max-height',panel.prop('scrollHeight') + "px")
} else {
panel.attr('style','');
$(this).toggleClass('links-nav-parent-active')
}
}
})
//menu-script
$('.m-nav-icon').on('click',function(event){
$('.header-overley').addClass('show-overlay');
$('body').a... |
if(curentStage==2){
$('.c-q-c-c-item-selected').each(function(i) {
var values = $('[data-field-id=field--2]').val();
values += $(this).find('.c-q-c-c-item-descr').text();
$('[data-field-id=field--2]').val(values.replace(/\s/g, '')+',');
});
}
if(curentStage==3){
$('[data-stage='+curentStage+'] .c-check input:ch... | {
$('[data-stage='+curentStage+'] .c-check input:checked').each(function(i) {
var values = $('[data-field-id=field--1]').val();
values += $(this).parent('.c-check').text();
$('[data-field-id=field--1]').val(values.replace(/\s/g, '')+',');
});
} | conditional_block |
CORAL_train.py | ", "", "")
flags.DEFINE_integer('n_test', 10000, 'Number of test images')
flags.DEFINE_string('test_txt', '', 'Test text(label) path')
flags.DEFINE_string('test_img', '', 'Test images path')
flags.DEFINE_string("output_loss_txt", "/yuwhan/Edisk/yuwhan/Edisk/4th_paper/age_banchmark/UTK/loss_CORAL.txt", "")
FLAGS = ... |
@tf.function
def train_step(model, images, levels, imp):
with tf.GradientTape() as tape:
logits, probs = run_model(model, images)
#total_loss = (-tf.reduce_sum((tf.nn.log_softmax(logits, axis=2)[:,:,1]*levels + tf.nn.log_softmax(logits, axis=2)[:,:,0]*(1-levels))*imp, 1))
... | logits, probs = model(images, training=True)
return logits, probs | identifier_body |
CORAL_train.py | .000005)
initializer = tf.keras.initializers.glorot_normal()
for layer in train_model.layers:
for attr in ['kernel_regularizer']:
if hasattr(layer, attr):
setattr(layer, attr, regularizer)
# for attr_ in ["kernel_initializer"]:
# if hasattr(layer, attr_):... | data_name = np.loadtxt(FLAGS.test_txt, dtype='<U100', skiprows=0, usecols=0)
data_name = [FLAGS.test_img + data_name_ for data_name_ in data_name]
data_label = np.loadtxt(FLAGS.txt_path, dtype=np.float32, skiprows=0, usecols=1)
data_generator = tf.data.Dataset.from_tensor_slices((data_name, dat... | conditional_block | |
CORAL_train.py | ", "", "")
flags.DEFINE_integer('n_test', 10000, 'Number of test images')
flags.DEFINE_string('test_txt', '', 'Test text(label) path')
flags.DEFINE_string('test_img', '', 'Test images path')
flags.DEFINE_string("output_loss_txt", "/yuwhan/Edisk/yuwhan/Edisk/4th_paper/age_banchmark/UTK/loss_CORAL.txt", "")
FLAGS = ... | (model, images):
logits, probs = model(images, training=True)
return logits, probs
@tf.function
def train_step(model, images, levels, imp):
with tf.GradientTape() as tape:
logits, probs = run_model(model, images)
#total_loss = (-tf.reduce_sum((tf.nn.log_softmax(logits, axis=2)[:,:,1]*... | run_model | identifier_name |
CORAL_train.py | ))*imp, 1))
#total_loss = -tf.reduce_sum((tf.math.log(tf.nn.softmax(logits, 2)[:, :, 1] + 1e-7) * levels \
# + tf.math.log(tf.nn.softmax(logits, 2)[:, :, 0] + 1e-7) * (1 - levels)) * imp, 1)
total_loss = tf.reduce_mean(total_loss)
gradients = tape.gradient(total_loss, model.trainable_va... | val_data_generator = val_data_generator.prefetch(tf.data.experimental.AUTOTUNE) | random_line_split | |
sales-component.component.ts | SalePaymentMethod } from 'app/InventoryApp/Models/DTOs/SalePaymentMethod';
import { SaleUserBranchProductsDTO } from 'app/InventoryApp/Models/DTOs/SaleUserBranchProductsDTO';
import { DxStoreOptions } from 'app/InventoryApp/Models/DxStoreOptions';
import { LoginResponse } from 'app/InventoryApp/Models/LoginResponse';
... | {
// 0 means Erkek, 1 means Kadin
return gender ? "Kadın" : "Erkek"
}
openSatisDialog() {
const dialogRef = this.dialog.open(PaymentScreenComponent, {
height: '600px',
width: '800px',
data: { Total: this.ProductsToSellTotalPrice = this.ProductsToSellDataSource.map(t => t.SellingPrice)... | : number) | identifier_name |
sales-component.component.ts | SalePaymentMethod } from 'app/InventoryApp/Models/DTOs/SalePaymentMethod';
import { SaleUserBranchProductsDTO } from 'app/InventoryApp/Models/DTOs/SaleUserBranchProductsDTO';
import { DxStoreOptions } from 'app/InventoryApp/Models/DxStoreOptions';
import { LoginResponse } from 'app/InventoryApp/Models/LoginResponse';
... | : void {
this.unsubscribe.forEach(sb => sb.unsubscribe());
}
InitilizeProductAndPriceForm() {
this.ProductAndPriceFormGroup = this.fb.group({
ProductBarcode: ['', Validators.compose([
Validators.required
])
],
SellingPrice: ['', Validators.compose([
Validators.requi... | roy() | identifier_body |
sales-component.component.ts | DTO } from 'app/InventoryApp/Models/DTOs/SaleUserBranchProductsDTO';
import { DxStoreOptions } from 'app/InventoryApp/Models/DxStoreOptions';
import { LoginResponse } from 'app/InventoryApp/Models/LoginResponse';
import { UIResponse } from 'app/InventoryApp/Models/UIResponse';
import { PaymentScreenComponent } from 'ap... | asCampaign = false;
}
} else {
| conditional_block | |
sales-component.component.ts | SalePaymentMethod } from 'app/InventoryApp/Models/DTOs/SalePaymentMethod';
import { SaleUserBranchProductsDTO } from 'app/InventoryApp/Models/DTOs/SaleUserBranchProductsDTO';
import { DxStoreOptions } from 'app/InventoryApp/Models/DxStoreOptions';
import { LoginResponse } from 'app/InventoryApp/Models/LoginResponse';
... | hasCampaign = false;
isProductCountEnough = false;
async productCodeFocusOut() {
this.PriceInput.nativeElement.focus();
const productCode = this.ProductAndPriceFormGroup.controls.ProductBarcode.value;
if (productCode && productCode.length == 12) {
let res: UIResponse<ProductView> = await this.no... |
isProductExist = false;
lowProductCount = false; | random_line_split |
doc_zh_CN.go | ErrMessageTooLong is returned when attempting to encrypt a message which is too
// large for the size of the public key.
var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
// ErrVerification represents a failure to verify a signature. It is deliberately
// vague to avoid adapti... | func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error)
// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding
// scheme from PKCS#1 v1.5. If rand != nil, it uses RSA blinding to avoid timing
// side-channel attacks. It returns an error if the ciphertext... | // attacks.
// DecryptPKCS1v15使用PKCS#1
// v1.5规定的填充方案和RSA算法解密密文。如果random不是nil,函数会注意规避时间侧信道攻击。 | random_line_split |
doc_zh_CN.go | TooLong is returned when attempting to encrypt a message which is too
// large for the size of the public key.
var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
// ErrVerification represents a failure to verify a signature. It is deliberately
// vague to avoid adaptive attacks.... | length
// or if the ciphertext is greater than the public modulus. Otherwise, no error is
// returned. If the padding is valid, the resulting plaintext message is copied
// into key. Otherwise, key is unchanged. These alternatives occur in constant
// time. It is intended that the user of this function generate a rando... | t is the wrong | identifier_name |
types.rs | <T: Encodable + Decodable + Send + Clone> {
current_term: u64,
voted_for: Option<u64>, // request_vote cares if this is `None`
log: File,
last_index: u64, // The last index of the file.
last_term: u64, // The last index of the file.
marker: marker::PhantomData<T>, /... | PersistentState | identifier_name | |
types.rs | pub fn append_entries(&mut self, prev_log_index: u64, prev_log_term: u64,
entries: Vec<(u64, T)>) -> io::Result<()> {
// TODO: No checking of `prev_log_index` & `prev_log_term` yet... Do we need to?
let position = try!(self.move_to(prev_log_index + 1));
let number = entrie... | (3, "Three".to_string()),
(4, "Four".to_string())]),
Ok(()));
assert_eq!(state.get_last_index(), 4); | random_line_split | |
types.rs | #the-corner-case-unused-parameters-and-parameters-that-are-only-used-unsafely
}
impl<T: Encodable + Decodable + Send + Clone> PersistentState<T> {
pub fn new(current_term: u64, log_path: Path) -> PersistentState<T> {
let mut open_opts = OpenOptions::new();
open_opts.read(true);
open_opts.wr... | ;
self.last_term = last_term;
Ok(())
}
fn encode(entry: T) -> String {
let json_encoded = json::encode(&entry)
.unwrap(); // TODO: Don't unwrap.
json_encoded.as_bytes().to_base64(Config {
char_set: CharacterSet::UrlSafe,
newline: Newline::LF,
... | { prev_log_index + number as u64 } | conditional_block |
sync.go |
}
type timestampedError struct {
t time.Time
err error
}
func createSyncHandler(fromName, toName string,
from blobserver.Storage, to blobserver.BlobReceiver,
queue sorted.KeyValue, isToIndex bool) (*SyncHandler, error) {
h := &SyncHandler{
copierPoolSize: 3,
from: from,
to: to,
... | {
return errorf("source fetch size mismatch: get=%d, enumerate=%d", fromSize, sb.Size)
} | conditional_block | |
sync.go | ) String() string {
return fmt.Sprintf("[SyncHandler %v -> %v]", sh.fromName, sh.toName)
}
func (sh *SyncHandler) logf(format string, args ...interface{}) {
log.Printf(sh.String()+" "+format, args...)
}
var (
_ blobserver.Storage = (*SyncHandler)(nil)
_ blobserver.HandlerIniter = (*SyncHandler)(nil)
)
func... | if sh.idle {
return
}
fmt.Fprintf(rw, "<h2>Stats:</h2><ul>")
fmt.Fprintf(rw, "<li>Blobs copied: %d</li>", sh.totalCopies)
fmt.Fprintf(rw, "<li>Bytes copied: %d</li>", sh.totalCopyBytes)
if !sh.recentCopyTime.IsZero() {
fmt.Fprintf(rw, "<li>Most recent copy: %s</li>", sh.recentCopyTime.Format(time.RFC3339))
... | fmt.Fprintf(rw, "<h1>%s to %s Sync Status</h1><p><b>Current status: </b>%s</p>",
sh.fromName, sh.toName, html.EscapeString(sh.status)) | random_line_split |
sync.go | ) String() string {
return fmt.Sprintf("[SyncHandler %v -> %v]", sh.fromName, sh.toName)
}
func (sh *SyncHandler) logf(format string, args ...interface{}) {
log.Printf(sh.String()+" "+format, args...)
}
var (
_ blobserver.Storage = (*SyncHandler)(nil)
_ blobserver.HandlerIniter = (*SyncHandler)(nil)
)
func... | (ctx *context.Context, src blobserver.BlobEnumerator) func(chan<- blob.SizedRef, <-chan struct{}) error {
return func(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
return blobserver.EnumerateAll(ctx, src, func(sb blob.SizedRef) error {
select {
case dst <- sb:
case <-intr:
return errors.New("i... | blobserverEnumerator | identifier_name |
sync.go | ) String() string {
return fmt.Sprintf("[SyncHandler %v -> %v]", sh.fromName, sh.toName)
}
func (sh *SyncHandler) logf(format string, args ...interface{}) {
log.Printf(sh.String()+" "+format, args...)
}
var (
_ blobserver.Storage = (*SyncHandler)(nil)
_ blobserver.HandlerIniter = (*SyncHandler)(nil)
)
func... |
func (sh *SyncHandler) enumerateQueuedBlobs(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
defer close(dst)
it := sh.queue.Find("", "")
for it.Next() {
br, ok := blob.Parse(it.Key())
size, err := strconv.ParseInt(it.Value(), 10, 64)
if !ok || err != nil {
sh.logf("ERROR: bogus sync queue entry: %... | {
return func(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
return blobserver.EnumerateAll(ctx, src, func(sb blob.SizedRef) error {
select {
case dst <- sb:
case <-intr:
return errors.New("interrupted")
}
return nil
})
}
} | identifier_body |
feature_table.rs | QualifierValue::nom)), |(_, v)| v);
map(
tuple((parse_name, opt(parse_value))),
|(name, value)| Qualifier{ name, value }
)(input)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum QualifierValue {
QuotedText(String),
VocabularyTerm(FtString),
ReferenceNumber(u32),
}
impl <'a, E : ParseError<&'a str>> N... | random_line_split | ||
feature_table.rs | , FtString, E> {
let uc = Interval('A', 'Z');
let lc = Interval('a', 'z');
let di = Interval('0', '9');
let misc = "_-'*";
let ft_char = {
move |c: char|
uc.contains(&c) ||
lc.contains(&c) ||
di.contains(&c) ||
misc.contains(c)
};
let alpha = {
move |c: char|
uc.con... | ))(input)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Loc {
Remote { within: String, at: Local },
Local(Local)
}
impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for Loc {
fn nom(input: &'a str) -> IResult<&'a str, Loc, E> {
let parse_accession = take_while1(|c| {
let b = c as u8;
is_alpha... | {
let parse_within = map(
tuple((Point::nom, tag("."), Point::nom)),
|(from, _, to)| Local::Within { from, to });
let parse_span = map(
tuple((
opt(tag("<")), Position::nom, tag(".."), opt(tag(">")), Position::nom)),
|(before_from, from, _, after_to, to)| Local::Span {
f... | identifier_body |
feature_table.rs | {
key: String,
location: LocOp,
qualifiers: Vec<Qualifier>
}
// impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for FeatureRecord {
// fn nom(input: &'a str) -> IResult<&'a str, FeatureRecord, E> {
// }
// }
/// An ID that's valid within the feature table.
///
/// This is:
/// * At least one let... | FeatureRecord | identifier_name | |
room_list_item.go | this.SetLastMsg(fmt.Sprintf("%s: %s",
gopp.StrSuf4ui(msgo.PeerNameUi, 9, 1), msgo.LastMsgUi), msgo.Time, msgo.EventId)
this.totalCount += 1
if uictx.msgwin.item == this {
uictx.uiw.LabelMsgCount2.SetText(fmt.Sprintf("%3d", this.totalCount))
uictx.uiw.LabelMsgCount.SetText(fmt.Sprintf("%3d", this.totalCount))
... | ).Seconds())
cqzone := time.FixedZone("Chongqing", secondsEastOfUTC)
time.Local = cqzone
}
}
// 两类时间,server time, client time
func (this *RoomListItem) SetLastMsg(ms | identifier_body | |
room_list_item.go | qtwidgets.DeleteQMenu(item.menu)
}
item.menu = nil
if item.cticon != nil {
qtgui.DeleteQIcon(item.cticon)
}
item.cticon = nil
if item.sticon != nil {
qtgui.DeleteQIcon(item.sticon)
}
item.sticon = nil
item.OnConextMenu = nil
item.subws = nil
item.msgitmdl = nil
item.msgos = nil
}
}
////... |
onMousePress := func(event *qtgui.QMouseEvent) {
uictx.gtreco.onMousePress(this, event)
// log.Println(event)
if event.Button() == qtcore.Qt__LeftButton {
for _, room := range uictx.ctitmdl {
if room != this {
room.SetPressState(false)
}
}
this.SetPressState(true)
}
}
onMouseRelease :=... | this.ToolButton_2.SetMouseTracking(true)
w := this.ContactItemView
w.SetMouseTracking(true) | random_line_split |
room_list_item.go | ui
switch ct := info.(type) {
case *thspbs.FriendInfo:
this.frndInfo = ct
name := gopp.IfElseStr(ct.GetName() == "", ct.GetPubkey()[:7], ct.GetName())
nametip := gopp.IfElseStr(ct.GetName() == "", ct.GetPubkey()[:17], ct.GetName())
this.Label_2.SetText(trtxt(name, 26))
this.Label_2.SetToolTip(nametip)
th... | ticon = Get | identifier_name | |
room_list_item.go | TimeLine(&this.timeline, this.GetId(), this.GetName())
}
}
}
}
func (this *RoomListItem) AddMessageImpl(msgo *Message, msgiw *MessageItem, prev bool) {
showMeIcon := msgo.Me // 是否显示自己的icon。根据是否是自己的消息
showName := true
showPeerIcon := !showMeIcon
msgiw.Label_5.SetText(msgo.MsgUi)
msgiw.LabelUserName4Message... | this.Label_2.SetText(gopp.StrSuf4ui(name, 26))
// this.Label_2.SetToolTip(name)
// this.ToolButton_2.SetToolTip(name + "." + this.GetId()[:7])
}
} else {
if this.frndInfo.Name != name {
this.frndInfo.Name = name
| conditional_block | |
bibtexParser.ts | (this);
}
}
type Node =
| RootNode
| TextNode
| BlockNode
| EntryNode
| CommentNode
| PreambleNode
| StringNode
| FieldNode
| ConcatNode
| LiteralNode
| BracedNode
| QuotedNode;
export function generateAST(input: string): RootNode {
const rootNode = new RootNode();
let node: Node = rootNode;
let line ... | isWhitespace | identifier_name | |
bibtexParser.ts | string,
public braces: number,
public parens: number
) {
parent.block = this;
}
}
export class EntryNode {
type = 'entry' as const;
key?: string;
keyEnded?: boolean;
fields: FieldNode[];
constructor(public parent: BlockNode, public wrapType: '{' | '(') {
parent.block = this;
this.fields = [];
}
}
exp... | node.parent.children.push(node);
}
node.command = '';
} else if (char === '{' || char === '(') {
const commandTrimmed = node.command.trim();
if (commandTrimmed === '' || /\s/.test(commandTrimmed)) {
// A block without a command is invalid. It's sometimes used in comments though, e.g.... | new TextNode(node.parent, '@' + node.command); | random_line_split |
bibtexParser.ts | RootNode();
let node: Node = rootNode;
let line = 1;
let column = 0;
for (let i = 0; i < input.length; i++) {
const char = input[i]!;
const prev = input[i - 1]!;
if (char === '\n') {
line++;
column = 0;
}
column++;
switch (node.type) {
case 'root': {
node = char === '@' ? new BlockNode(... | {
return !/[#%{}~$,]/.test(char);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.