conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
=======
var bulk = model.collection.initializeUnorderedBulkOp();
>>>>>>>
<<<<<<<
let newModel = mongooseHelper.getNewModelFromObject(model, result);
var objectId = new Mongoose.Types.ObjectId(result._id);
=======
var objectId = Utils.getCastObjectId(model, result._id);
>>>>>>>
let newModel = mongooseHelper.getNewModelFromObject(model, result);
var objectId = Utils.getCastObjectId(newModel, result._id);
<<<<<<<
if (updateParentRequired.length > 0) {
Object.keys(allBulkExecute).forEach(x => {
let bulk = allBulkExecute[x];
asyncCalls.push(Q.nbind(bulk.execute, bulk)());
});
=======
if (updateParentRequired.length > 0) {
promBulkUpdate = Q.nbind(bulk.execute, bulk)();
>>>>>>>
if (updateParentRequired.length > 0) {
Object.keys(allBulkExecute).forEach(x => {
let bulk = allBulkExecute[x];
asyncCalls.push(Q.nbind(bulk.execute, bulk)());
});
<<<<<<<
if (updateParentRequired.length > 0) {
let updateObject = [];
updateParentRequired.forEach(x => {
updateObject.push(objArr.find(obj => obj._id == x));
});
updateParentProm = mongooseHelper.updateParent(model, updateObject);
=======
if (updateParentRequired.length > 0) {
let updateObject = [];
updateParentRequired.forEach(x => {
updateObject.push(objects.find(obj => obj._id.toString() == x));
});
updateParentProm = mongooseHelper.updateParent(model, updateObject);
>>>>>>>
if (updateParentRequired.length > 0) {
let updateObject = [];
updateParentRequired.forEach(x => {
updateObject.push(objects.find(obj => obj._id.toString() == x));
});
updateParentProm = mongooseHelper.updateParent(model, updateObject);
<<<<<<<
var objectId = new Mongoose.Types.ObjectId(result._id);
let newModel = mongooseHelper.getNewModelFromObject(model, result);
if (!allBulkExecute[newModel.modelName]) {
allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
}
let bulk = allBulkExecute[newModel.modelName];
=======
var objectId = Utils.getCastObjectId(model, result._id);
>>>>>>>
var objectId = Utils.getCastObjectId(model, result._id);
let newModel = mongooseHelper.getNewModelFromObject(model, result);
if (!allBulkExecute[newModel.modelName]) {
allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
}
let bulk = allBulkExecute[newModel.modelName];
<<<<<<<
let newModels = {};
newModels[model.modelName] = model;
let obj: ShardInfo = InstanceService.getInstanceFromType(getEntity(model.modelName), true);
if (obj.getShardKey) {
let key = obj.getShardKey();
if (query[key]) {
if (CoreUtils.isJSON(query[key])) {
if (query[key]['$in']) {
query[key]['$in'].forEach(x => {
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, query[key]);
newModels[newModel.modelName] = newModel;
});
}
=======
let queryObj = model.find(query, sel).lean();
if (sort) {
queryObj = queryObj.sort(sort);
}
if (skip) {
queryObj = queryObj.skip(skip);
}
if (limit) {
queryObj = queryObj.limit(limit);
}
//winstonLog.logInfo(`findWhere query is ${query}`);
return Q.nbind(queryObj.exec, queryObj)()
.then((result: Array<any>) => {
// update embedded property, if any
if (toLoadChilds != undefined && toLoadChilds == false) {
mongooseHelper.transformAllEmbeddedChildern1(model, result);
console.log("findWhere end" + model.modelName);
return result;
>>>>>>>
let newModels = {};
newModels[model.modelName] = model;
let obj: ShardInfo = InstanceService.getInstanceFromType(getEntity(model.modelName), true);
if (obj.getShardKey) {
let key = obj.getShardKey();
if (query[key]) {
if (CoreUtils.isJSON(query[key])) {
if (query[key]['$in']) {
query[key]['$in'].forEach(x => {
let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, query[key]);
newModels[newModel.modelName] = newModel;
});
} |
<<<<<<<
//this.getHalModel1(association, this.repository.modelName(), this.repository.getEntityType());
//this.sendresult(req, res, association);
var parent = (<any>result).toObject();
var association = parent[req.params.prop];
var metaData = Utils.getAllRelationalMetaDataForField(this.repository.getEntityType(), req.params.prop);
if (metaData != null && metaData.length > 0 &&
association !== undefined && association !== null) {
var meta = metaData[0]; // by deafult take first relation
var repo = GetRepositoryForName(meta.propertyType.rel);
if (repo == null) return;
var resourceName = this.getFullBaseUrlUsingRepo(req, repo.modelName());
if (meta.propertyType.embedded) {
if (meta.propertyType.isArray) {
Enumerable.from(association).forEach(x=> {
this.getHalModel1(x, resourceName + '/' + x['_id'], repo.getEntityType());
});
association = this.getHalModels(association, resourceName);
}
else {
this.getHalModel1(association, resourceName + '/' + association['_id'], repo.getEntityType());
}
this.sendresult(req, res, association);
}
else {
var ids = association;
if (!meta.propertyType.isArray) {
ids = [association];
}
return repo.findMany(ids)
.then((result) => {
if (result.length > 0) {
if (meta.propertyType.isArray) {
Enumerable.from(result).forEach(x=> {
this.getHalModel1(x, resourceName + '/' + x['_id'], repo.getEntityType());
});
result = this.getHalModels(result, resourceName);
}
else {
result = result[0];
this.getHalModel1(result, resourceName + '/' + result['_id'], repo.getEntityType());
}
this.sendresult(req, res, result);
}
});
}
}
else {
this.sendresult(req, res, association);
}
=======
var resourceName=this.getFullDataUrl(req) + "/" + req.params.prop;
if(association instanceof Array)
result = this.getHalModels(association,resourceName);
else
{
if(association._id)
resourceName="/"+association._id;
this.getHalModel1(association, resourceName, this.repository.getEntityType());
}
this.sendresult(req, res, association);
>>>>>>>
//this.getHalModel1(association, this.repository.modelName(), this.repository.getEntityType());
//this.sendresult(req, res, association);
var parent = (<any>result).toObject();
var association = parent[req.params.prop];
var metaData = Utils.getAllRelationalMetaDataForField(this.repository.getEntityType(), req.params.prop);
if (metaData != null && metaData.length > 0 &&
association !== undefined && association !== null) {
var meta = metaData[0]; // by deafult take first relation
var repo = GetRepositoryForName(meta.propertyType.rel);
if (repo == null) return;
var resourceName = this.getFullBaseUrlUsingRepo(req, repo.modelName());
if (meta.propertyType.embedded) {
if (meta.propertyType.isArray) {
Enumerable.from(association).forEach(x=> {
this.getHalModel1(x, resourceName + '/' + x['_id'], repo.getEntityType());
});
association = this.getHalModels(association, resourceName);
}
else {
this.getHalModel1(association, resourceName + '/' + association['_id'], repo.getEntityType());
}
this.sendresult(req, res, association);
}
else {
var ids = association;
if (!meta.propertyType.isArray) {
ids = [association];
}
return repo.findMany(ids)
.then((result) => {
if (result.length > 0) {
if (meta.propertyType.isArray) {
Enumerable.from(result).forEach(x=> {
this.getHalModel1(x, resourceName + '/' + x['_id'], repo.getEntityType());
});
result = this.getHalModels(result, resourceName);
}
else {
result = result[0];
this.getHalModel1(result, resourceName + '/' + result['_id'], repo.getEntityType());
}
this.sendresult(req, res, result);
}
});
}
}
else {
this.sendresult(req, res, association);
}
<<<<<<<
private getFullBaseUrl(req): string {
var fullbaseUr: string = "";
fullbaseUr = req.protocol + '://' + req.get('host') + req.originalUrl;
return fullbaseUr;
}
private getFullBaseUrlUsingRepo(req, repoName): string {
var fullbaseUr: string = "";
fullbaseUr = req.protocol + '://' + req.get('host') + '/' + Config.Config.basePath + '/' + repoName;
=======
private getFullDataUrl(req): string{
var fullbaseUr:string="";
fullbaseUr=req.protocol + '://' + req.get('host') + "/" + Config.Config.basePath;
return fullbaseUr;
}
private getFullBaseUrl(req): string{
var fullbaseUr:string="";
fullbaseUr=req.protocol + '://' + req.get('host') + req.originalUrl;
>>>>>>>
private getFullDataUrl(req): string{
var fullbaseUr:string="";
fullbaseUr=req.protocol + '://' + req.get('host') + "/" + Config.Config.basePath;
return fullbaseUr;
}
private getFullBaseUrl(req): string {
var fullbaseUr: string = "";
fullbaseUr = req.protocol + '://' + req.get('host') + req.originalUrl;
return fullbaseUr;
}
private getFullBaseUrlUsingRepo(req, repoName): string {
var fullbaseUr: string = "";
fullbaseUr = req.protocol + '://' + req.get('host') + '/' + Config.Config.basePath + '/' + repoName; |
<<<<<<<
function isJsonMapEnabled(params: IAssociationParams) {
if (params && (params.storageType == StorageType.JSONMAP)) {
return true;
}
return false;
}
function embedChild(objects: Array<any>, prop, relMetadata: MetaData, parentModelName: string): Q.Promise<any> {
=======
function embedChild(objects: Array<any>, prop, relMetadata: MetaData): Q.Promise<any> {
>>>>>>>
export function isJsonMapEnabled(params: IAssociationParams) {
if (params && (params.storageType == StorageType.JSONMAP)) {
return true;
}
return false;
}
function embedChild(objects: Array<any>, prop, relMetadata: MetaData, parentModelName: string): Q.Promise<any> {
<<<<<<<
val[i][ConstantKeys.parent] = Utils.getParentKey(parentModelName, prop, (obj._id ? obj._id : obj[ConstantKeys.TempId]));
=======
>>>>>>>
val[i][ConstantKeys.parent] = Utils.getParentKey(parentModelName, prop, (obj._id ? obj._id : obj[ConstantKeys.TempId]));
<<<<<<<
val[ConstantKeys.parent] = Utils.getParentKey(parentModelName, prop, (obj._id ? obj._id : obj[ConstantKeys.TempId]));
=======
>>>>>>>
val[ConstantKeys.parent] = Utils.getParentKey(parentModelName, prop, (obj._id ? obj._id : obj[ConstantKeys.TempId])); |
<<<<<<<
MetaUtils.addMetaData(target, Decorators.ONETOMANY, DecoratorType.PROPERTY, params, key);
//console.log('onetomany - propertyKey: ', key, ', target:', target);
=======
Utils.addMetaData(target, Decorators.ONETOMANY, DecoratorType.PROPERTY, params, key);
>>>>>>>
MetaUtils.addMetaData(target, Decorators.ONETOMANY, DecoratorType.PROPERTY, params, key); |
<<<<<<<
private dependencyOrder: Map<ClassType, number>;
addService(fn: Function, params: any) {
serviceMap.set(fn, params);
//services.push({ fn: fn, params: params });
}
resolve<T>(cls: ClassType): T {
this.dependencyOrder = new Map<ClassType, number>();
if (serviceMap.has(cls)) {
return this.resolveServiceDependency<T>(cls, serviceMap.get(cls));
}
return this.resolveRepositoryDependency<T>(cls);
=======
private dependencyOrder: Map<ClassType<any>, number>;
/**
* Registers all the services, i.e. classes having @service decorator, in the DI container.
* DI container will inject only those services that are registered with this method.
* @param {class} cls Typescript class having @service decorator
* @param {Object} params Decorator params
*/
addService<T>(cls: ClassType<T>, params: any) {
serviceMap.set(cls, params);
}
/**
*
* @param {class} cls Typescript class to inject
*/
resolve<T>(cls: ClassType<T>): T {
this.dependencyOrder = new Map<ClassType<any>, number>();
return this.resolveDependencies<T>(cls);
>>>>>>>
private dependencyOrder: Map<ClassType<any>, number>;
/**
* Registers all the services, i.e. classes having @service decorator, in the DI container.
* DI container will inject only those services that are registered with this method.
* @param {class} cls Typescript class having @service decorator
* @param {Object} params Decorator params
*/
addService<T>(cls: ClassType<T>, params: any) {
serviceMap.set(cls, params);
}
/**
*
* @param {class} cls Typescript class to inject
*/
resolve<T>(cls: ClassType<T>): T {
this.dependencyOrder = new Map<ClassType<any>, number>();
<<<<<<<
private resolveServiceDependency<T>(cls: ClassType, service): T {
=======
private resolveDependencies<T>(cls: ClassType<T>): T {
if (serviceMap.has(cls)) {
return this.resolveServiceDependency<T>(cls, serviceMap.get(cls));
}
return this.resolveRepositoryDependency<T>(cls);
}
private resolveServiceDependency<T>(cls: ClassType<T>, service): T {
>>>>>>>
private resolveDependencies<T>(cls: ClassType<T>): T {
if (serviceMap.has(cls)) {
return this.resolveServiceDependency<T>(cls, serviceMap.get(cls));
}
return this.resolveRepositoryDependency<T>(cls);
}
private resolveServiceDependency<T>(cls: ClassType<T>, service): T { |
<<<<<<<
import {getEntity, getModel} from './model-entity';
import {MetaUtils} from "../metadata/utils";
import {Decorators} from '../constants';
=======
import {pathRepoMap, getEntity, getModel} from './model-entity';
import {MetaUtils} from "../metadata/utils";
>>>>>>>
import {pathRepoMap, getEntity, getModel} from './model-entity';
import {MetaUtils} from "../metadata/utils";
import {Decorators} from '../constants';
<<<<<<<
private schemaName: string;
private entityService: IEntityService;
=======
>>>>>>>
private entityService: IEntityService;
<<<<<<<
constructor(repositoryPath: string, target: Function|Object,model?:any) {
=======
constructor(repositoryPath: string, target: Function | Object) {
>>>>>>>
constructor(repositoryPath: string, target: Function|Object,model?:any) { |
<<<<<<<
router.get(this.path + "/search", securityImpl.ensureLoggedIn(), (req, res) => {
=======
router.get(this.path + "/search", securityUtils.ensureLoggedIn(), (req, res) => {
let links = { "self": { "href": this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/search" } };
for (var prop in search) {
search[prop]["href"] = this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/search/" + search[prop]["href"];
links[prop] = search[prop];
}
this.sendresult(req, res, links);
});
}
addActionPaths() {
let modelRepo = this.repository.getEntityType();
let decoratorFields = MetaUtils.getMetaData(modelRepo.model.prototype, Decorators.FIELD);
let fieldsWithSearchIndex =
Enumerable.from(decoratorFields)
.where(ele => {
return ele.key
&& decoratorFields[ele.key]
&& decoratorFields[ele.key].params
&& (<any>decoratorFields[ele.key].params).searchIndex;
}).toArray();
let searchPropMap = GetAllActionFromPrototype(modelRepo) as Array<IActionPropertyMap>;
var actions = {};
searchPropMap.forEach(map => {
router.post(this.path + "/action/" + map.key, (req, res) => {
try {
let modelRepo = this.repository.getEntityType();
var param = [];
for (var prop in req.body) {
param.push(req.body[prop]);
}
modelRepo[map.key].apply(modelRepo, param);
this.sendresult(req, res, 'success');
}
catch (err) {
this.sendError(res, err);
}
});
actions[map.key] = { "href": map.key, "params": map.args };
});
router.get(this.path + "/action", securityUtils.ensureLoggedIn(), (req, res) => {
let links = { "self": { "href": this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/action" } };
for (var prop in actions) {
actions[prop]["href"] = this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/action/" + actions[prop]["href"];
links[prop] = actions[prop];
}
>>>>>>>
router.get(this.path + "/search", securityImpl.ensureLoggedIn(), (req, res) => {
let links = { "self": { "href": this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/search" } };
for (var prop in search) {
search[prop]["href"] = this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/search/" + search[prop]["href"];
links[prop] = search[prop];
}
this.sendresult(req, res, links);
});
}
addActionPaths() {
let modelRepo = this.repository.getEntityType();
let decoratorFields = MetaUtils.getMetaData(modelRepo.model.prototype, Decorators.FIELD);
let fieldsWithSearchIndex =
Enumerable.from(decoratorFields)
.where(ele => {
return ele.key
&& decoratorFields[ele.key]
&& decoratorFields[ele.key].params
&& (<any>decoratorFields[ele.key].params).searchIndex;
}).toArray();
let searchPropMap = GetAllActionFromPrototype(modelRepo) as Array<IActionPropertyMap>;
var actions = {};
searchPropMap.forEach(map => {
router.post(this.path + "/action/" + map.key, (req, res) => {
try {
let modelRepo = this.repository.getEntityType();
var param = [];
for (var prop in req.body) {
param.push(req.body[prop]);
}
modelRepo[map.key].apply(modelRepo, param);
this.sendresult(req, res, 'success');
}
catch (err) {
this.sendError(res, err);
}
});
actions[map.key] = { "href": map.key, "params": map.args };
});
router.get(this.path + "/action", securityUtils.ensureLoggedIn(), (req, res) => {
let links = { "self": { "href": this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/action" } };
for (var prop in actions) {
actions[prop]["href"] = this.getFullBaseUrlUsingRepo(req, this.repository.modelName()) + "/action/" + actions[prop]["href"];
links[prop] = actions[prop];
} |
<<<<<<<
/*
* final state sent to issuer is built as follows:
* state = nonce + nonceStateSeparator + additional state
* Default separator is ';' (encoded %3B).
* In rare cases, this character might be forbidden or inconvenient to use by the issuer so it can be customized.
*/
public nonceStateSeparator? = ';';
=======
constructor(json?: Partial<AuthConfig>) {
if (json) {
Object.assign(this, json);
}
}
>>>>>>>
/*
* final state sent to issuer is built as follows:
* state = nonce + nonceStateSeparator + additional state
* Default separator is ';' (encoded %3B).
* In rare cases, this character might be forbidden or inconvenient to use by the issuer so it can be customized.
*/
public nonceStateSeparator? = ';';
constructor(json?: Partial<AuthConfig>) {
if (json) {
Object.assign(this, json);
}
} |
<<<<<<<
*
* { provide: OAuthStorage, useValue: localStorage }
*
=======
*
*
* { provide: OAuthStorage, useFactory: oAuthStorageFactory }
* export function oAuthStorageFactory(): OAuthStorage { return localStorage; }
*
>>>>>>>
*
*
* { provide: OAuthStorage, useFactory: oAuthStorageFactory }
* export function oAuthStorageFactory(): OAuthStorage { return localStorage; } |
<<<<<<<
import Log from "../utils/log";
import { mergeVideo, mergeVideoNew, download, decrypt } from "../utils/media";
=======
import Logger from '../utils/log';
let Log = Logger.getInstance();
import { mergeVideo, mergeVideoNew } from "../utils/media";
>>>>>>>
import Logger from '../utils/log';
let Log = Logger.getInstance();
import { mergeVideo, mergeVideoNew, download, decrypt } from "../utils/media";
<<<<<<<
console.error(e);
console.log(task);
=======
//console.error(e);
//console.log(task, this.m3u8);
Log.info(JSON.stringify(task) + " " + JSON.stringify(this.m3u8));
Log.error("Something happenned.", e);
>>>>>>>
Log.info(JSON.stringify(task) + " " + JSON.stringify(this.m3u8));
Log.error("Something happenned.", e); |
<<<<<<<
techniqueIDSelectionLock: boolean = true;
changeTechniqueIDSelectionLock(){
this.techniqueIDSelectionLock = !this.techniqueIDSelectionLock;
}
=======
showTacticRowBackground: boolean = false;
tacticRowBackground: string = "#dddddd";
>>>>>>>
techniqueIDSelectionLock: boolean = true;
changeTechniqueIDSelectionLock(){
this.techniqueIDSelectionLock = !this.techniqueIDSelectionLock;
}
showTacticRowBackground: boolean = false;
tacticRowBackground: string = "#dddddd"; |
<<<<<<<
layerLayerOperation(scoreExpression: string, scoreVariables: Map<string, ViewModel>, comments: ViewModel, coloring: ViewModel, enabledness: ViewModel, layerName: string, filters: ViewModel, legendItems: ViewModel): ViewModel {
let result = new ViewModel("layer by operation", this.domain);
=======
layerLayerOperation(scoreExpression: string, scoreVariables: Map<string, ViewModel>, comments: ViewModel, coloring: ViewModel, enabledness: ViewModel, layerName: string, filters: ViewModel): ViewModel {
let result = new ViewModel("layer by operation", this.domain, "vm" + this.getNonce());
>>>>>>>
layerLayerOperation(scoreExpression: string, scoreVariables: Map<string, ViewModel>, comments: ViewModel, coloring: ViewModel, enabledness: ViewModel, layerName: string, filters: ViewModel, legendItems: ViewModel): ViewModel {
let result = new ViewModel("layer by operation", this.domain, "vm" + this.getNonce()); |
<<<<<<<
/**
* return an acronym version of the given string
* @param words the string of words to get the acrnoym of
* @return the acronym string
*/
acronym(words: string): string {
let skipWords = ["on","and", "the", "with", "a", "an", "of", "in", "for", "from"]
let result = "";
let wordSplit = words.split(" ");
if (wordSplit.length > 1) {
let wordIndex = 0;
// console.log(wordSplit);
while (result.length < 4 && wordIndex < wordSplit.length) {
if (skipWords.includes(wordSplit[wordIndex].toLowerCase())) {
wordIndex++;
continue;
}
//find first legal char of word
for (let charIndex = 0; charIndex < wordSplit[wordIndex].length; charIndex++) {
let code = wordSplit[wordIndex].charCodeAt(charIndex);
if (code < 48 || (code > 57 && code < 65) || (code > 90 && code < 97) || code > 122) { //illegal character
continue;
} else {
result += wordSplit[wordIndex].charAt(charIndex).toUpperCase()
break;
}
}
wordIndex++;
}
return result;
} else {
return wordSplit[0].charAt(0).toUpperCase();
}
}
=======
updateLegendColorPresets(): void {
this.legendColorPresets = this.backgroundPresets;
for(var i = 0; i < this.gradient.colors.length; i++){
this.legendColorPresets.push(this.gradient.labelToColor[this.gradient.colors[i].color]);
}
}
>>>>>>>
updateLegendColorPresets(): void {
this.legendColorPresets = this.backgroundPresets;
for(var i = 0; i < this.gradient.colors.length; i++){
this.legendColorPresets.push(this.gradient.labelToColor[this.gradient.colors[i].color]);
}
}
/**
* return an acronym version of the given string
* @param words the string of words to get the acrnoym of
* @return the acronym string
*/
acronym(words: string): string {
let skipWords = ["on","and", "the", "with", "a", "an", "of", "in", "for", "from"]
let result = "";
let wordSplit = words.split(" ");
if (wordSplit.length > 1) {
let wordIndex = 0;
// console.log(wordSplit);
while (result.length < 4 && wordIndex < wordSplit.length) {
if (skipWords.includes(wordSplit[wordIndex].toLowerCase())) {
wordIndex++;
continue;
}
//find first legal char of word
for (let charIndex = 0; charIndex < wordSplit[wordIndex].length; charIndex++) {
let code = wordSplit[wordIndex].charCodeAt(charIndex);
if (code < 48 || (code > 57 && code < 65) || (code > 90 && code < 97) || code > 122) { //illegal character
continue;
} else {
result += wordSplit[wordIndex].charAt(charIndex).toUpperCase()
break;
}
}
wordIndex++;
}
return result;
} else {
return wordSplit[0].charAt(0).toUpperCase();
}
} |
<<<<<<<
import {RouterModule, Routes} from '@angular/router';
=======
import {MatFormFieldModule} from '@angular/material/form-field';
>>>>>>>
import {MatFormFieldModule} from '@angular/material/form-field';
import {RouterModule, Routes} from '@angular/router';
<<<<<<<
MdButtonModule,
MdCheckboxModule,
MdInputModule,
MdSelectModule,
MdSlideToggleModule,
MdSliderModule,
RouterModule.forRoot(appRoutes, {useHash: true})
=======
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatSlideToggleModule,
MatSliderModule,
>>>>>>>
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatSlideToggleModule,
MatSliderModule,
RouterModule.forRoot(appRoutes, {useHash: true}) |
<<<<<<<
function configureFixtureForExternalFeedbackStyleConfiguration(
fixture: ComponentFixture<test_components.ConvaiCheckerCustomDemoSettings>) {
let demoSettings = getCopyOfDefaultDemoSettings();
demoSettings.communityId = 'testCommunityId';
fixture.componentInstance.setDemoSettings(demoSettings);
}
=======
>>>>>>>
<<<<<<<
TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
configureFixtureForExternalFeedbackStyleConfiguration(fixture);
=======
TestBed.createComponent(ConvaiCheckerCustomDemoSettingsTestComponent);
let demoSettings = getCopyOfDefaultDemoSettings();
demoSettings.communityId = 'testCommunityId';
fixture.componentInstance.setDemoSettings(demoSettings);
>>>>>>>
TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
let demoSettings = getCopyOfDefaultDemoSettings();
demoSettings.communityId = 'testCommunityId';
fixture.componentInstance.setDemoSettings(demoSettings);
<<<<<<<
tick(REQUEST_LIMIT_MS);
// Expect a request to have been sent.
const mockReq = httpMock.expectOne('test-url/check');
// Once a request is in flight, loading is set to true.
tick();
expect(checker.analyzeCommentResponse).toBe(null);
expect(checker.statusWidget.isLoading).toBe(true);
// Now we have checked the expectations before the response is sent, we
// send back the response.
mockReq.flush(mockResponse);
tick();
// Checks that the response is received and stored.
expect(checker.analyzeCommentResponse).not.toBe(null);
expect(checker.analyzeCommentResponse).toEqual(mockResponse);
// Checks that the response was emitted.
expect(lastEmittedResponse).toEqual(mockResponse);
expect(emittedResponseCount).toEqual(1);
// Checks that the score was emitted.
expect(lastEmittedScore).toEqual(mockScore);
expect(emittedScoreCount).toEqual(1);
// Checks that loading has stopped.
expect(checker.statusWidget.isLoading).toBe(false);
}));
it('Should handle analyze comment error, demo config', fakeAsync(() => {
let fixture = TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
=======
it('Should handle analyze comment error, demo config', async(() => {
let fixture = TestBed.createComponent(ConvaiCheckerCustomDemoSettingsTestComponent);
>>>>>>>
tick(REQUEST_LIMIT_MS);
// Expect a request to have been sent.
const mockReq = httpMock.expectOne('test-url/check');
// Once a request is in flight, loading is set to true.
tick();
expect(checker.analyzeCommentResponse).toBe(null);
expect(checker.statusWidget.isLoading).toBe(true);
// Now we have checked the expectations before the response is sent, we
// send back the response.
mockReq.flush(mockResponse);
tick();
// Checks that the response is received and stored.
expect(checker.analyzeCommentResponse).not.toBe(null);
expect(checker.analyzeCommentResponse).toEqual(mockResponse);
// Checks that the response was emitted.
expect(lastEmittedResponse).toEqual(mockResponse);
expect(emittedResponseCount).toEqual(1);
// Checks that the score was emitted.
expect(lastEmittedScore).toEqual(mockScore);
expect(emittedScoreCount).toEqual(1);
// Checks that loading has stopped.
expect(checker.statusWidget.isLoading).toBe(false);
}));
it('Should handle analyze comment error, demo config', fakeAsync(() => {
let fixture = TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
<<<<<<<
it('Should update UI for sending score feedback, demo config ', fakeAsync(() => {
let fixture =
TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
fixture.detectChanges();
let checker = fixture.componentInstance.checker;
let queryText = 'Your mother was a hamster';
let textArea = fixture.debugElement.query(
By.css('#' + checker.inputId)).nativeElement;
// Send an input event to trigger the service call.
setTextAndFireInputEvent(queryText, textArea);
tick(REQUEST_LIMIT_MS);
=======
it('Should update UI for sending score feedback, demo config ', (done: Function) => {
let fixture = TestBed.createComponent(ConvaiCheckerCustomDemoSettingsTestComponent);
fixture.detectChanges();
let checker = fixture.componentInstance.checker;
>>>>>>>
it('Should update UI for sending score feedback, demo config ', fakeAsync(() => {
let fixture =
TestBed.createComponent(test_components.ConvaiCheckerCustomDemoSettings);
fixture.detectChanges();
let checker = fixture.componentInstance.checker;
let queryText = 'Your mother was a hamster';
let textArea = fixture.debugElement.query(
By.css('#' + checker.inputId)).nativeElement;
// Send an input event to trigger the service call.
setTextAndFireInputEvent(queryText, textArea);
tick(REQUEST_LIMIT_MS);
<<<<<<<
// Wait for the UI to update, then click the 'Yes' button
tick();
fixture.detectChanges();
sendClickEvent(document.getElementById('yesButtonDemoConfig'));
const mockSuggestReq = httpMock.expectOne('test-url/suggest_score');
tick();
fixture.detectChanges();
// The yes and no buttons should have disappeared while the request is
// in progress.
expect(fixture.nativeElement.textContent).not.toContain('Yes');
expect(fixture.nativeElement.textContent).not.toContain('No');
mockSuggestReq.flush({clientToken: "token"});
tick();
fixture.detectChanges();
// Confirm the UI state after feedback is submitted.
expect(fixture.nativeElement.textContent).toContain('Thanks');
httpMock.verify();
}));
=======
>>>>>>>
// Wait for the UI to update, then click the 'Yes' button
tick();
fixture.detectChanges();
sendClickEvent(document.getElementById('yesButtonDemoConfig'));
const mockSuggestReq = httpMock.expectOne('test-url/suggest_score');
tick();
fixture.detectChanges();
// The yes and no buttons should have disappeared while the request is
// in progress.
expect(fixture.nativeElement.textContent).not.toContain('Yes');
expect(fixture.nativeElement.textContent).not.toContain('No');
mockSuggestReq.flush({clientToken: "token"});
tick();
fixture.detectChanges();
// Confirm the UI state after feedback is submitted.
expect(fixture.nativeElement.textContent).toContain('Thanks');
httpMock.verify();
})); |
<<<<<<<
//% color=300 weight=100
declare namespace neopixel {
/**
* Gets the default pin for built in neopixels
*/
//% parts="neopixel" shim=neopixel::defaultPin
function defaultPin(): DigitalPin;
/**
* Sends a neopixel buffer to the specified digital pin
* @param pin The pin that the neopixels are connected to
* @param buf The buffer to send to the pin
*/
//% parts="neopixel" shim=neopixel::sendBuffer
function sendBuffer(pin: DigitalPin, buf: Buffer): void;
}
=======
//% color="#FB48C7" weight=99 icon="\uf192"
declare namespace input {
/**
* Reads the light level applied to the LED screen in a range from ``0`` (dark) to ``1024`` bright.
*/
//% help=input/light-level weight=57
//% blockId=device_get_light_level block="light level" blockGap=8
//% parts="lightsensor" shim=input::lightLevel
function lightLevel(): number;
/**
* Registers an event that runs when particular lighting conditions (dark, bright) are encountered.
* @param condition the condition that event triggers on
*/
//% help=input/on-light-condition-changed
//% blockId=input_on_light_condition_changed block="on %condition"
//% parts="lightsensor" shim=input::onLightConditionChanged
function onLightConditionChanged(condition: LightCondition, handler: () => void): void;
/**
* Gets the temperature in Celsius degrees (°C).
*/
//% weight=55
//% help=input/temperature
//% blockId=device_temperature block="temperature (°C)" blockGap=8
//% parts="thermometer" shim=input::temperature
function temperature(): number;
/**
* Registers an event raised when the temperature condition (hold, cold) changes.
* @param condition the condition, hot or cold, the event triggers on
* @param temperature the temperature, in degree Celcius, at which this event happens, eg: 15
*/
//% blockId=input_on_temperature_condition_changed block="on %condition|at (°C)%temperature"
//% parts="thermometer"
//% help=input/on-temperature-condition-changed shim=input::onTemperateConditionChanged
function onTemperateConditionChanged(condition: TemperatureCondition, temperature: number, handler: () => void): void;
/**
* Gets the number of milliseconds elapsed since power on.
*/
//% help=input/running-time weight=50
//% blockId=device_get_running_time block="running time (ms)"
//% advanced=true shim=input::runningTime
function runningTime(): number;
}
declare namespace buttons {
/**
* Left push button.
*/
//% indexedInstanceNS=buttons indexedInstanceShim=pxt::getButton
//% fixedInstance shim=pxt::getButton(0)
const left: Button;
/**
* Right push button.
*/
//% fixedInstance shim=pxt::getButton(1)
const right: Button;
/**
* Slide switch.
*/
//% fixedInstance shim=pxt::getButton(2)
const slide: Button;
}
>>>>>>>
//% color=300 weight=100
declare namespace neopixel {
/**
* Gets the default pin for built in neopixels
*/
//% parts="neopixel" shim=neopixel::defaultPin
function defaultPin(): DigitalPin;
/**
* Sends a neopixel buffer to the specified digital pin
* @param pin The pin that the neopixels are connected to
* @param buf The buffer to send to the pin
*/
//% parts="neopixel" shim=neopixel::sendBuffer
function sendBuffer(pin: DigitalPin, buf: Buffer): void;
}
//% color="#FB48C7" weight=99 icon="\uf192"
declare namespace input {
/**
* Reads the light level applied to the LED screen in a range from ``0`` (dark) to ``1024`` bright.
*/
//% help=input/light-level weight=57
//% blockId=device_get_light_level block="light level" blockGap=8
//% parts="lightsensor" shim=input::lightLevel
function lightLevel(): number;
/**
* Registers an event that runs when particular lighting conditions (dark, bright) are encountered.
* @param condition the condition that event triggers on
*/
//% help=input/on-light-condition-changed
//% blockId=input_on_light_condition_changed block="on %condition"
//% parts="lightsensor" shim=input::onLightConditionChanged
function onLightConditionChanged(condition: LightCondition, handler: () => void): void;
/**
* Gets the temperature in Celsius degrees (°C).
*/
//% weight=55
//% help=input/temperature
//% blockId=device_temperature block="temperature (°C)" blockGap=8
//% parts="thermometer" shim=input::temperature
function temperature(): number;
/**
* Registers an event raised when the temperature condition (hold, cold) changes.
* @param condition the condition, hot or cold, the event triggers on
* @param temperature the temperature, in degree Celcius, at which this event happens, eg: 15
*/
//% blockId=input_on_temperature_condition_changed block="on %condition|at (°C)%temperature"
//% parts="thermometer"
//% help=input/on-temperature-condition-changed shim=input::onTemperateConditionChanged
function onTemperateConditionChanged(condition: TemperatureCondition, temperature: number, handler: () => void): void;
/**
* Gets the number of milliseconds elapsed since power on.
*/
//% help=input/running-time weight=50
//% blockId=device_get_running_time block="running time (ms)"
//% advanced=true shim=input::runningTime
function runningTime(): number;
}
declare namespace buttons {
/**
* Left push button.
*/
//% indexedInstanceNS=buttons indexedInstanceShim=pxt::getButton
//% fixedInstance shim=pxt::getButton(0)
const left: Button;
/**
* Right push button.
*/
//% fixedInstance shim=pxt::getButton(1)
const right: Button;
/**
* Slide switch.
*/
//% fixedInstance shim=pxt::getButton(2)
const slide: Button;
} |
<<<<<<<
* Capacitive pin A4
*/
//% indexedInstanceNS=input indexedInstanceShim=pxt::getTouchButton
//% block="pin A4" fixedInstance shim=pxt::getTouchButton(0)
const pinA4: Button;
/**
* Capacitive pin A5
*/
//% block="pin A5" fixedInstance shim=pxt::getTouchButton(1)
const pinA5: Button;
/**
* Capacitive pin A6
*/
//% block="pin A6" fixedInstance shim=pxt::getTouchButton(2)
const pinA6: Button;
/**
* Capacitive pin A7
*/
//% block="pin A7" fixedInstance shim=pxt::getTouchButton(3)
const pinA7: Button;
/**
* Capacitive pin A8
*/
//% block="pin A8" fixedInstance shim=pxt::getTouchButton(4)
const pinA8: Button;
/**
* Capacitive pin A9
*/
//% block="pin A9" fixedInstance shim=pxt::getTouchButton(5)
const pinA9: Button;
/**
* Capacitive pin A10
*/
//% block="pin A10" fixedInstance shim=pxt::getTouchButton(6)
const pinA10: Button;
/**
* Capacitive pin A11
*/
//% block="pin A11" fixedInstance shim=pxt::getTouchButton(7)
const pinA11: Button;
/**
* Left push button.
=======
* Left button.
>>>>>>>
* Capacitive pin A4
*/
//% indexedInstanceNS=input indexedInstanceShim=pxt::getTouchButton
//% block="pin A4" fixedInstance shim=pxt::getTouchButton(0)
const pinA4: Button;
/**
* Capacitive pin A5
*/
//% block="pin A5" fixedInstance shim=pxt::getTouchButton(1)
const pinA5: Button;
/**
* Capacitive pin A6
*/
//% block="pin A6" fixedInstance shim=pxt::getTouchButton(2)
const pinA6: Button;
/**
* Capacitive pin A7
*/
//% block="pin A7" fixedInstance shim=pxt::getTouchButton(3)
const pinA7: Button;
/**
* Capacitive pin A8
*/
//% block="pin A8" fixedInstance shim=pxt::getTouchButton(4)
const pinA8: Button;
/**
* Capacitive pin A9
*/
//% block="pin A9" fixedInstance shim=pxt::getTouchButton(5)
const pinA9: Button;
/**
* Capacitive pin A10
*/
//% block="pin A10" fixedInstance shim=pxt::getTouchButton(6)
const pinA10: Button;
/**
* Capacitive pin A11
*/
//% block="pin A11" fixedInstance shim=pxt::getTouchButton(7)
const pinA11: Button;
/**
* Left button. |
<<<<<<<
const copiesById = getCopiesById(state)
return copiesById[id]
}
=======
const { servicePath, keepCopiesInStore, serverAlias } = state
if (keepCopiesInStore) {
return state.copiesById[id]
} else {
const Model = _get(models, [serverAlias, 'byServicePath', servicePath])
return Model.copiesById[id]
}
},
isCreatePendingById: ({ isIdCreatePending }: ServiceState) => (id: Id) =>
isIdCreatePending.includes(id),
isUpdatePendingById: ({ isIdUpdatePending }: ServiceState) => (id: Id) =>
isIdUpdatePending.includes(id),
isPatchPendingById: ({ isIdPatchPending }: ServiceState) => (id: Id) =>
isIdPatchPending.includes(id),
isRemovePendingById: ({ isIdRemovePending }: ServiceState) => (id: Id) =>
isIdRemovePending.includes(id),
isSavePendingById: (state: ServiceState, getters) => (id: Id) =>
getters.isCreatePendingById(id) ||
getters.isUpdatePendingById(id) ||
getters.isPatchPendingById(id),
isPendingById: (state: ServiceState, getters) => (id: Id) =>
getters.isSavePendingById(id) ||
getters.isRemovePendingById(id)
>>>>>>>
const copiesById = getCopiesById(state)
return copiesById[id]
},
isCreatePendingById: ({ isIdCreatePending }: ServiceState) => (id: Id) =>
isIdCreatePending.includes(id),
isUpdatePendingById: ({ isIdUpdatePending }: ServiceState) => (id: Id) =>
isIdUpdatePending.includes(id),
isPatchPendingById: ({ isIdPatchPending }: ServiceState) => (id: Id) =>
isIdPatchPending.includes(id),
isRemovePendingById: ({ isIdRemovePending }: ServiceState) => (id: Id) =>
isIdRemovePending.includes(id),
isSavePendingById: (state: ServiceState, getters) => (id: Id) =>
getters.isCreatePendingById(id) ||
getters.isUpdatePendingById(id) ||
getters.isPatchPendingById(id),
isPendingById: (state: ServiceState, getters) => (id: Id) =>
getters.isSavePendingById(id) || getters.isRemovePendingById(id) |
<<<<<<<
import * as fs from "fs";
=======
import fileType = require("file-type");
import * as fs from "fs-extra";
import * as Zip from "jszip";
>>>>>>>
import fileType = require("file-type");
import * as fs from "fs";
<<<<<<<
import { ZipFile } from "yauzl";
import { bufferEntry, Entry, open, walkEntries } from "yauzlw";
=======
import * as yauzl from "yauzlw";
import { deflate, inflate, inflateSync, unzip, unzipSync } from "zlib";
>>>>>>>
import { ZipFile } from "yauzl";
import { bufferEntry, Entry, open, walkEntries } from "yauzlw";
import { deflate, inflate, inflateSync, unzip, unzipSync } from "zlib";
<<<<<<<
const entry = findEntryFolder(map);
if (entry) { return entry; } else { throw new Error("Illegal Map"); }
}
const zip = typeof map === "string" ? await open(map) : map;
const zipEntry = await findEntryZip(zip);
zip.close();
if (zipEntry) {
return zipEntry;
=======
if (!(await fs.stat(map)).isDirectory()) {
const zip = await new Zip().loadAsync(await fs.readFile(map));
const entry = await findEntryZip(zip);
if (entry) { return entry; }
} else if (fs.existsSync(path.join(map, "level.dat"))) {
return "level.dat";
}
>>>>>>>
const entry = findEntryFolder(map);
if (entry) { return entry; } else { throw new Error("Illegal Map"); }
}
const zip = typeof map === "string" ? await open(map) : map;
const zipEntry = await findEntryZip(zip);
zip.close();
if (zipEntry) {
return zipEntry; |
<<<<<<<
volumePower: 5,
=======
>>>>>>>
volumePower: 5,
<<<<<<<
if (this.state.stackhelper && _event.detail.needsRender) {
window.console.log('INTERACTION_FINISHED');
this.state.renderTask = Math.pow(2, this.state.volumePower);
=======
if (this.state.stackhelper) {
this.state.renderTask = this.getVolumePower();
}
},
getVolumePower(): number {
// 256 steps for desktop (8), 32 steps for mobile (5)
let power;
if (AFRAME.utils.device.isMobile()) {
power = 5;
} else {
power = 8;
>>>>>>>
if (this.state.stackhelper && _event.detail.needsRender) {
window.console.log('INTERACTION_FINISHED');
this.state.renderTask = Math.pow(2, this.state.volumePower);
}
},
getVolumePower(): number {
// 256 steps for desktop (8), 32 steps for mobile (5)
let power;
if (AFRAME.utils.device.isMobile()) {
power = 5;
} else {
power = 8;
<<<<<<<
this.state.renderTask = Math.pow(2, this.state.volumePower);
}, 250);
=======
this.state.renderTask = this.getVolumePower();
}, 250); // allow some time for the stackhelper to reorient itself
>>>>>>>
this.state.renderTask = Math.pow(2, this.state.volumePower);
}, 250); |
<<<<<<<
populateBuiltins(): { blocks: Blocks, inlines: Inlines } {
return populateBuiltins();
}
abstract hasHelper(helperName: Option<string>[], blockMeta: TemplateMeta): boolean;
abstract lookupHelper(helperName: Option<string>[], blockMeta: TemplateMeta): Helper;
=======
abstract hasHelper(helperName: string, blockMeta: TemplateMeta): boolean;
abstract lookupHelper(helperName: string, blockMeta: TemplateMeta): Helper;
>>>>>>>
populateBuiltins(): { blocks: Blocks, inlines: Inlines } {
return populateBuiltins();
}
abstract hasHelper(helperName: string, blockMeta: TemplateMeta): boolean;
abstract lookupHelper(helperName: string, blockMeta: TemplateMeta): Helper; |
<<<<<<<
return new RenderInverseIdentitySyntax({ args, templates });
case 'each':
return new EachSyntax({ args, templates });
=======
return new RenderInverseIdentitySyntax({ args: block.args, templates: block.templates });
>>>>>>>
return new RenderInverseIdentitySyntax({ args, templates });
<<<<<<<
type EachOptions = { args: ArgsSyntax };
class EachSyntax extends StatementSyntax {
type = "each-statement";
public args: ArgsSyntax;
public templates: Templates;
public isStatic = false;
constructor({ args, templates }: { args: ArgsSyntax, templates: Templates }) {
super();
this.args = args;
this.templates = templates;
}
prettyPrint() {
return `#each ${this.args.prettyPrint()}`;
}
compile(compiler: CompileInto & SymbolLookup, env: Environment) {
// PutArgs
// EnterList(BEGIN, END)
// ITER: Noop
// NextIter(BREAK)
// EnterWithKey(BEGIN, END)
// BEGIN: Noop
// PushChildScope
// Evaluate(default)
// PopScope
// END: Noop
// Exit
// Jump(ITER)
// BREAK: Noop
// ExitList
let BEGIN = new LabelOpcode({ label: "BEGIN" });
let ITER = new LabelOpcode({ label: "ITER" });
let BREAK = new LabelOpcode({ label: "BREAK" });
let END = new LabelOpcode({ label: "END" });
compiler.append(new PutArgsOpcode({ args: this.args.compile(compiler, env) }));
compiler.append(new EnterListOpcode(BEGIN, END));
compiler.append(ITER);
compiler.append(new NextIterOpcode(BREAK));
compiler.append(new EnterWithKeyOpcode(BEGIN, END));
compiler.append(BEGIN);
compiler.append(new PushChildScopeOpcode());
compiler.append(new EvaluateOpcode({ debug: "default", block: this.templates.default }));
compiler.append(new PopScopeOpcode());
compiler.append(END);
compiler.append(new ExitOpcode());
compiler.append(new JumpOpcode({ target: ITER }));
compiler.append(BREAK);
compiler.append(new ExitListOpcode());
}
}
=======
>>>>>>> |
<<<<<<<
=======
public component = <Component>null,
public manager: Option<ComponentManager<Component>> = null,
public shadow: Option<InlineBlock> = null
>>>>>>>
<<<<<<<
push(start: number, end: number) {
=======
push(start: number, end: number, component = <Component>null, manager: Option<ComponentManager<Component>> = null, shadow: Option<InlineBlock> = null) {
>>>>>>>
push(start: number, end: number) {
<<<<<<<
let frame = this.currentFrame;
let ip = frame.ip;
let end = frame.end;
if (ip <= end) {
let program = env.program;
frame.ip += 4;
return program.opcode(ip);
} else {
this.pop();
return null;
=======
while (this.frame !== -1) {
let frame = this.frames[this.frame];
let ip = frame.ip;
let end = frame.end;
if (ip < end) {
let program = env.program;
frame.ip += 4;
return program.opcode(ip);
} else {
this.pop();
}
>>>>>>>
while (this.frame !== -1) {
let frame = this.frames[this.frame];
let ip = frame.ip;
let end = frame.end;
if (ip <= end) {
let program = env.program;
frame.ip += 4;
return program.opcode(ip);
} else {
this.pop();
} |
<<<<<<<
import { VM } from './vm';
import RenderResult from './vm/render-result';
import Scanner, { Program, Block } from './scanner';
=======
import { VM, RenderResult, IteratorResult } from './vm';
import Scanner, {
EntryPoint,
PartialBlock,
Layout
} from './scanner';
>>>>>>>
import { VM, RenderResult, IteratorResult } from './vm';
import Scanner, { Program, Block } from './scanner';
<<<<<<<
render(self: PathReference<Opaque>, appendTo: Simple.Element, dynamicScope: DynamicScope): RenderResult;
=======
render(self: PathReference<any>, appendTo: Simple.Element, dynamicScope: DynamicScope): TemplateIterator;
>>>>>>>
render(self: PathReference<Opaque>, appendTo: Simple.Element, dynamicScope: DynamicScope): TemplateIterator;
<<<<<<<
let compiled = this.asEntryPoint().compileDynamic(env);
let vm = VM.initial(env, self, dynamicScope, elementStack, rawBlock.symbols.length);
return vm.execute(compiled.start, compiled.end);
}
asEntryPoint(): Program {
if (!this.entryPoint) this.entryPoint = this.scanner.scanEntryPoint(this.compilationMeta());
return this.entryPoint;
}
asLayout(attrs?: Statements.Attribute[]): Program {
if (!this.layout) this.layout = this.scanner.scanLayout(this.compilationMeta(), attrs || EMPTY_ARRAY);
return this.layout;
}
asPartial(): Program {
if (!this.partial) this.partial = this.scanner.scanEntryPoint(this.compilationMeta(true));
return this.partial;
}
asBlock(): Block {
if (!this.block) this.block = this.scanner.scanBlock(this.compilationMeta());
return this.block;
}
private compilationMeta(asPartial = false) {
return { templateMeta: this.meta, symbols: this.symbols, asPartial };
}
=======
let compiled = asEntryPoint().compile(env);
let vm = VM.initial(env, self, dynamicScope, elementStack, compiled);
return new TemplateIterator(vm);
};
return { id, meta, _block: block, asEntryPoint, asLayout, asPartial, render };
>>>>>>>
let compiled = this.asEntryPoint().compileDynamic(env);
let vm = VM.initial(env, self, dynamicScope, elementStack, compiled);
return new TemplateIterator(vm);
}
asEntryPoint(): Program {
if (!this.entryPoint) this.entryPoint = this.scanner.scanEntryPoint(this.compilationMeta());
return this.entryPoint;
}
asLayout(attrs?: Statements.Attribute[]): Program {
if (!this.layout) this.layout = this.scanner.scanLayout(this.compilationMeta(), attrs || EMPTY_ARRAY);
return this.layout;
}
asPartial(): Program {
if (!this.partial) this.partial = this.scanner.scanEntryPoint(this.compilationMeta(true));
return this.partial;
}
asBlock(): Block {
if (!this.block) this.block = this.scanner.scanBlock(this.compilationMeta());
return this.block;
}
private compilationMeta(asPartial = false) {
return { templateMeta: this.meta, symbols: this.symbols, asPartial };
} |
<<<<<<<
// case 'each':
// return new EachSyntax({ args, templates });
=======
case 'each':
return new EachSyntax({ args: block.args, templates: block.templates });
>>>>>>>
case 'each':
return new EachSyntax({ args, templates }); |
<<<<<<<
onChooseValue: (item: TemplateValue) => void
=======
onUpdateDefaultTemplateValue: (v: string) => void
notify?: (message: Notification) => void
>>>>>>>
onUpdateDefaultTemplateValue: (item: TemplateValue) => void
notify?: (message: Notification) => void |
<<<<<<<
private _zIndex: number = 0;
set zIndex(zIndex: number) {
this._renderer.setElementStyle(this._ngEl.nativeElement, "z-index", zIndex.toString());
this._zIndex = zIndex;
}
get zIndex(): number {
return this._zIndex;
}
=======
private _resizeDirections: string[] = [];
>>>>>>>
private _resizeDirections: string[] = [];
private _zIndex: number = 0;
set zIndex(zIndex: number) {
this._renderer.setElementStyle(this._ngEl.nativeElement, "z-index", zIndex.toString());
this._zIndex = zIndex;
}
get zIndex(): number {
return this._zIndex;
} |
<<<<<<<
var addOne = (resp, suff) => {
logs.push(RT.App.createInfoMessage(''));
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- server log -- " + suff));
logs = logs.concat(resp.applog);
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- touchdevelop log -- " + suff));
logs = logs.concat(resp.tdlog);
}
if (resp.workers)
resp.workers.forEach(r => {
if (r.body && r.body.applog)
addOne(r.body, r.worker)
else
logs.push(RT.App.createInfoMessage(wa.website + " -- server log -- " + r.worker + " missing; " + r.code));
})
else addOne(resp, "")
TDev.RT.App.showLog(logs);
=======
logs.push(RT.App.createInfoMessage(''));
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- server log"));
logs = logs.concat(resp.applog);
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- touchdevelop log"));
logs = logs.concat(resp.tdlog);
this.host.showAppView(logs);
>>>>>>>
var addOne = (resp, suff) => {
logs.push(RT.App.createInfoMessage(''));
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- server log -- " + suff));
logs = logs.concat(resp.applog);
logs.push(RT.App.createInfoMessage('---------------------'));
logs.push(RT.App.createInfoMessage(wa.website + " -- touchdevelop log -- " + suff));
logs = logs.concat(resp.tdlog);
}
if (resp.workers)
resp.workers.forEach(r => {
if (r.body && r.body.applog)
addOne(r.body, r.worker)
else
logs.push(RT.App.createInfoMessage(wa.website + " -- server log -- " + r.worker + " missing; " + r.code));
})
else addOne(resp, "")
this.host.showAppView(logs); |
<<<<<<<
findReferences: true,
gotoNavigation: true,
selectStatements: true,
stringEditFullScreen: true,
recordsSection: true,
persistanceRadio: true,
databaseSection: true,
actionSettings:true,
//MORE
=======
>>>>>>>
findReferences: true,
gotoNavigation: true,
selectStatements: true,
stringEditFullScreen: true,
recordsSection: true,
persistanceRadio: true,
databaseSection: true,
//MORE |
<<<<<<<
const activeRect = new Rect2(ctx.bounds.position, new Vec2(ctx.bounds.width * relative, ctx.bounds.height));
const activeItem = ctx.renderer.createRoundedRectangle(activeRect, 0, 0);
=======
const activeBounds = new Rect2(ctx.bounds.x, ctx.bounds.y, ctx.bounds.width * relative, ctx.bounds.height);
const activeShape = ctx.renderer.createRectangle(0, 0, activeBounds);
>>>>>>>
const activeBounds = new Rect2(ctx.bounds.x, ctx.bounds.y, ctx.bounds.width * relative, ctx.bounds.height);
const activeItem = ctx.renderer.createRectangle(0, 0, activeBounds);
<<<<<<<
const inactiveRect = new Rect2(new Vec2(ctx.bounds.width * relative, ctx.bounds.top), new Vec2(ctx.bounds.width * (1 - relative), ctx.bounds.height));
const inactiveItem = ctx.renderer.createRoundedRectangle(inactiveRect, 0, 0);
=======
const inactiveBounds = new Rect2(ctx.bounds.width * relative, ctx.bounds.top, ctx.bounds.width * (1 - relative), ctx.bounds.height);
const inactiveShape = ctx.renderer.createRectangle(0, 0, inactiveBounds);
>>>>>>>
const inactiveBounds = new Rect2(ctx.bounds.width * relative, ctx.bounds.top, ctx.bounds.width * (1 - relative), ctx.bounds.height);
const inactiveItem = ctx.renderer.createRectangle(0, 0, inactiveBounds);
<<<<<<<
ctx.add(ctx.renderer.createClipGroup(clipMask, activeItem, inactiveItem));
=======
ctx.add(ctx.renderer.createGroup([activeShape, inactiveShape], clipMask));
>>>>>>>
ctx.add(ctx.renderer.createGroup([activeItem, inactiveItem], clipMask)); |
<<<<<<<
if (!showDebugMarkers) {
const boxItem = ctx.renderer.createRectangle(1);
=======
if (!showDebugMarkers) {
const boxItem = ctx.renderer.createRoundedRectangle(ctx.bounds.inflate(1, 1), 1, 0);
>>>>>>>
if (showDebugMarkers) {
const boxItem = ctx.renderer.createRectangle(1); |
<<<<<<<
import { Client, ClientConstructor, AccountInfo } from './types/Global'
=======
import GoogleAdsError from './Error'
import { Client, ClientConstructor } from './types/Global'
>>>>>>>
import GoogleAdsError from './Error'
import { Client, ClientConstructor, AccountInfo } from './types/Global'
<<<<<<<
log(body.error.details);
reject(error)
=======
console.log(error)
reject(new GoogleAdsError(
error.message,
error.status,
error.details,
error.code
))
log(body.error.details[0].errors);
// reject(error)
>>>>>>>
// console.log(error)
reject(new GoogleAdsError(
error.message,
error.status,
error.details,
error.code
)) |
<<<<<<<
import { IPatchInfoRequestData, IPatchValidateInfoResult, IRpoInfoData as RpoInfoResult } from "./rpoInfo/rpoPath";
import { PatchResult } from "./patch/patchGenerate";
export interface IPermissionsResult {
message: string;
serverPermissions: {
operation: string[];
}
}
=======
import { IRpoInfoData as RpoInfoResult } from "./rpoInfo/rpoPath";
>>>>>>>
import { IPatchInfoRequestData, IPatchValidateInfoResult, IRpoInfoData as RpoInfoResult } from "./rpoInfo/rpoPath";
import { PatchResult } from "./patch/patchGenerate";
export interface IPermissionsResult {
message: string;
serverPermissions: {
operation: string[];
}
}
<<<<<<<
}
export function sendRpoInfo(server: ServerItem): Thenable<RpoInfoResult> {
return languageClient
.sendRequest("$totvsserver/rpoInfo", {
rpoInfo: {
connectionToken: server.token,
environment: server.environment,
},
})
.then(
(response: any) => {
return response.message;
},
(error: Error) => {
return error.message;
}
);
}
export function sendServerPermissions(token: string): Thenable<string[]> {
return languageClient
.sendRequest("$totvsserver/server_permissions", {
serverPermissionsInfo: {
connectionToken: token
},
})
.then(
(response: IPermissionsResult) => {
return response.serverPermissions.operation;
},
(error: Error) => {
return [error.message];
}
);
}
export function sendApplyPatchRequest(server: ServerItem, patchUris: Array<string>, permissions, validate: boolean, applyOld: boolean = false): Thenable<IPatchInfoRequestData> {
return languageClient.sendRequest('$totvsserver/patchApply', {
"patchApplyInfo": {
"connectionToken": server.token,
"authenticateToken": permissions.authorizationToken,
"environment": server.environment,
"patchUris": patchUris,
"isLocal": true,
"validatePatch": validate,
"applyOldProgram": applyOld
}
}).then((response: PatchResult) => {
if (response.returnCode == 99999) {
return Promise.reject({
error: true,
message: "Insufficient privileges",
errorCode: response.returnCode
});
}
const result = {
error: false,
message: "",
data: null
}
return Promise.resolve(result);
}, (err: ResponseError<object>) => {
const error: IPatchInfoRequestData = {
error: true,
message: err.message,
data: err.data,
errorCode: err.code
};
return Promise.reject(error);
});
}
export function sendValidPatchRequest(server: ServerItem, patchUri: string, permissions, applyOld: boolean = false): Thenable<IPatchInfoRequestData> {
return languageClient.sendRequest('$totvsserver/patchValidate', {
"patchValidateInfo": {
"connectionToken": server.token,
"authenticateToken": permissions.authorizationToken,
"environment": server.environment,
"patchUri": patchUri,
"isLocal": true,
"applyOldProgram": applyOld
}
}).then((response: IPatchValidateInfoResult) => {
if (response.returnCode == 99999) {
return Promise.reject({
error: true,
message: "Insufficient privileges",
errorCode: response.returnCode,
data: { error_number: 0, data: response.patchValidates }
});
}
const result = {
error: response.returnCode !== 0,
message: response.message,
data: { error_number: 1, data: response.patchValidates }
}
return result.error ? Promise.reject(result):Promise.resolve(result);
}, (err: ResponseError<object>) => {
const error: IPatchInfoRequestData = {
error: true,
message: err.message,
data: err.data,
errorCode: err.code
};
return Promise.reject(error);
});
=======
}
export function sendRpoInfo(server: ServerItem): Thenable<RpoInfoResult> {
return languageClient
.sendRequest("$totvsserver/rpoInfo", {
rpoInfo: {
connectionToken: server.token,
environment: server.environment,
},
})
.then(
(response: RpoInfoResult) => {
return response;
}
);
>>>>>>>
}
export function sendRpoInfo(server: ServerItem): Thenable<RpoInfoResult> {
return languageClient
.sendRequest("$totvsserver/rpoInfo", {
rpoInfo: {
connectionToken: server.token,
environment: server.environment,
},
})
.then(
(response: RpoInfoResult) => {
return response;
}
);
}
export function sendServerPermissions(token: string): Thenable<string[]> {
return languageClient
.sendRequest("$totvsserver/server_permissions", {
serverPermissionsInfo: {
connectionToken: token
},
})
.then(
(response: IPermissionsResult) => {
return response.serverPermissions.operation;
},
(error: Error) => {
return [error.message];
}
);
}
export function sendApplyPatchRequest(server: ServerItem, patchUris: Array<string>, permissions, validate: boolean, applyOld: boolean = false): Thenable<IPatchInfoRequestData> {
return languageClient.sendRequest('$totvsserver/patchApply', {
"patchApplyInfo": {
"connectionToken": server.token,
"authenticateToken": permissions.authorizationToken,
"environment": server.environment,
"patchUris": patchUris,
"isLocal": true,
"validatePatch": validate,
"applyOldProgram": applyOld
}
}).then((response: PatchResult) => {
if (response.returnCode == 99999) {
return Promise.reject({
error: true,
message: "Insufficient privileges",
errorCode: response.returnCode
});
}
const result = {
error: false,
message: "",
data: null
}
return Promise.resolve(result);
}, (err: ResponseError<object>) => {
const error: IPatchInfoRequestData = {
error: true,
message: err.message,
data: err.data,
errorCode: err.code
};
return Promise.reject(error);
});
}
export function sendValidPatchRequest(server: ServerItem, patchUri: string, permissions, applyOld: boolean = false): Thenable<IPatchInfoRequestData> {
return languageClient.sendRequest('$totvsserver/patchValidate', {
"patchValidateInfo": {
"connectionToken": server.token,
"authenticateToken": permissions.authorizationToken,
"environment": server.environment,
"patchUri": patchUri,
"isLocal": true,
"applyOldProgram": applyOld
}
}).then((response: IPatchValidateInfoResult) => {
if (response.returnCode == 99999) {
return Promise.reject({
error: true,
message: "Insufficient privileges",
errorCode: response.returnCode,
data: { error_number: 0, data: response.patchValidates }
});
}
const result = {
error: response.returnCode !== 0,
message: response.message,
data: { error_number: 1, data: response.patchValidates }
}
return result.error ? Promise.reject(result):Promise.resolve(result);
}, (err: ResponseError<object>) => {
const error: IPatchInfoRequestData = {
error: true,
message: err.message,
data: err.data,
errorCode: err.code
};
return Promise.reject(error);
}); |
<<<<<<<
=======
export const LANGUAGES = [
{ label: 'Mongolian', value: 'mn' },
{ label: 'English', value: 'en' },
{ label: 'French', value: 'fr' },
{ label: 'Deustch', value: 'de' },
{ label: 'Korean', value: 'kr' },
{ label: 'Spanish', value: 'es' },
{ label: 'Portuguese', value: 'pt_br' },
{ label: 'Chinese', value: 'zh' }
];
>>>>>>> |
<<<<<<<
bgColor
=======
isWatched
>>>>>>>
bgColor
isWatched |
<<<<<<<
};
export interface IFormProps {
errors: any;
values: any[];
registerChild: (child: any) => void;
runValidations?: (callback: any) => void;
}
=======
};
export type IOption = {
label: string;
value: string;
avatar?: string;
};
>>>>>>>
};
export interface IFormProps {
errors: any;
values: any[];
registerChild: (child: any) => void;
runValidations?: (callback: any) => void;
}
export type IOption = {
label: string;
value: string;
avatar?: string;
}; |
<<<<<<<
image: '/images/icons/erxes-22.svg',
to: '/insights/summary-report',
=======
image: '',
to: '/inbox/insights/summary-report',
>>>>>>>
image: '/images/icons/erxes-22.svg',
to: '/inbox/insights/summary-report',
<<<<<<<
image: '/images/icons/erxes-23.svg',
to: '/insights/export-report',
=======
image: '',
to: '/inbox/insights/export-report',
>>>>>>>
image: '/images/icons/erxes-23.svg',
to: '/inbox/insights/export-report', |
<<<<<<<
import { coins, Erc20Coin } from '@bitgo/statics';
import { BuildTransactionError } from '../baseCoin/errors';
import { InvalidParameterValueError } from '../baseCoin/errors';
import { sendMultiSigData, sendMultiSigTokenData } from './utils';
import {
sendMultisigMethodId,
sendMultiSigTypes,
sendMultiSigTokenTypes,
sendMultisigTokenMethodId,
} from './walletUtil';
import { isValidEthAddress } from './utils';
=======
import { BuildTransactionError, InvalidParameterValueError } from '../baseCoin/errors';
import { isValidEthAddress, sendMultiSigData, isValidAmount } from './utils';
import { sendMultisigMethodId } from './walletUtil';
>>>>>>>
import { coins, Erc20Coin } from '@bitgo/statics';
import { BuildTransactionError } from '../baseCoin/errors';
import { InvalidParameterValueError } from '../baseCoin/errors';
import { sendMultiSigData, sendMultiSigTokenData } from './utils';
import {
sendMultisigMethodId,
sendMultiSigTypes,
sendMultiSigTokenTypes,
sendMultisigTokenMethodId,
} from './walletUtil';
import { isValidEthAddress, isValidAmount } from './utils';
<<<<<<<
/**
* A method to set the ERC20 token to be transferred.
* This ERC20 token may not be compatible with the network.
*
* @param {string} coin the ERC20 coin to be set
* @returns {TransferBuilder} the transfer builder instance modified
*/
coin(coin: string): TransferBuilder {
const coinType = coins.get(coin);
if (!(coinType instanceof Erc20Coin)) {
throw new BuildTransactionError('There was an error using that coin as a transfer currency');
}
this._tokenContractAddress = coinType.contractAddress.toString();
return this;
}
data(additionalData: string): TransferBuilder {
this._signature = undefined;
this._data = additionalData;
return this;
}
amount(amount: string): TransferBuilder {
=======
amount(amount: string): this {
if (!isValidAmount(amount)) {
throw new InvalidParameterValueError('Invalid amount');
}
>>>>>>>
/**
* A method to set the ERC20 token to be transferred.
* This ERC20 token may not be compatible with the network.
*
* @param {string} coin the ERC20 coin to be set
* @returns {TransferBuilder} the transfer builder instance modified
*/
coin(coin: string): TransferBuilder {
const coinType = coins.get(coin);
if (!(coinType instanceof Erc20Coin)) {
throw new BuildTransactionError('There was an error using that coin as a transfer currency');
}
this._tokenContractAddress = coinType.contractAddress.toString();
return this;
}
data(additionalData: string): TransferBuilder {
this._signature = undefined;
this._data = additionalData;
return this;
}
amount(amount: string): this {
if (!isValidAmount(amount)) {
throw new InvalidParameterValueError('Invalid amount');
}
<<<<<<<
if (this._tokenContractAddress !== undefined) {
return sendMultiSigTokenData(
this._toAddress,
new BigNumber(this._amount).toNumber(),
this._tokenContractAddress,
this._expirationTime,
this._sequenceId,
this.getSignature(),
);
} else {
return sendMultiSigData(
this._toAddress,
new BigNumber(this._amount).toNumber(),
this._data,
this._expirationTime,
this._sequenceId,
this.getSignature(),
);
}
=======
return sendMultiSigData(
this._toAddress,
this._amount,
this._data,
this._expirationTime,
this._sequenceId,
this.getSignature(),
);
>>>>>>>
if (this._tokenContractAddress !== undefined) {
return sendMultiSigTokenData(
this._toAddress,
this._amount,
this._tokenContractAddress,
this._expirationTime,
this._sequenceId,
this.getSignature(),
);
} else {
return sendMultiSigData(
this._toAddress,
this._amount,
this._data,
this._expirationTime,
this._sequenceId,
this.getSignature(),
);
} |
<<<<<<<
const isAddressMarker = (marker: Marker): marker is AddressMarker => {
return (<AddressMarker>marker).address !== undefined;
}
const isLatLongMarker = (marker: Marker): marker is LatLongMarker => {
return (<LatLongMarker>marker).latitude !== undefined && (<LatLongMarker>marker).longitude !== undefined;
}
export type Marker = AddressMarker | LatLongMarker;
=======
>>>>>>>
const isAddressMarker = (marker: Marker): marker is AddressMarker => {
return (<AddressMarker>marker).address !== undefined;
}
const isLatLongMarker = (marker: Marker): marker is LatLongMarker => {
return (<LatLongMarker>marker).latitude !== undefined && (<LatLongMarker>marker).longitude !== undefined;
}
export type Marker = AddressMarker | LatLongMarker;
<<<<<<<
private googleMapsApi: GoogleMapsAPI;
private validMarkers: LatLongMarker[];
=======
private googleMapsApi: GoogleMapsAPI;
>>>>>>>
private googleMapsApi: GoogleMapsAPI;
private validMarkers: LatLongMarker[];
<<<<<<<
* Geocodes an address, once the Google Map script
* has been properly loaded and promise instantiated.
*
* @param address string
* @param geocoder any
*
*/
geocodeAddress(address: string) {
this.geocode(address).then(firstResult => {
this.setCenter(firstResult.geometry.location);
this.createMarker({
map: this.map,
position: firstResult.geometry.location
}).then((createdMarker: any) => {
this._locationByAddressMarkers.push(createdMarker);
this.eventAggregator.publish(LOCATIONADDED, Object.assign(createdMarker, { placeId: firstResult.place_id }));
});
}).catch(console.info);
}
/**
* Geocodes Address and returns the coordinates once the google map has been properly initialized
*
* @param marker string
*
*/
addressMarkerToMarker(marker: AddressMarker): Promise<void | BaseMarker> {
return this.geocode(marker.address).then(firstResults => {
return {
... marker,
latitude: firstResults.geometry.location.lat(),
longitude: firstResults.geometry.location.lng(),
};
}).catch(console.info);
}
/**
* Geocodes Address and returns the firstresults object after google maps has initialized
*
* @param address string
*
*/
private geocode(address: string): Promise<any> {
return this._mapPromise.then(() => {
return new Promise((resolve, reject) => {
this.geocoder.geocode({ 'address': address }, (results: any, status: string) => {
if (status !== (<any>window).google.maps.GeocoderStatus.OK) {
reject(new Error(`Failed to geocode address '${address}' with status: ${status}`));
}
resolve(results[0]);
});
});
});
}
private get geocoder() {
if (!this._geocoder) {
this._geocoder = new (<any>window).google.maps.Geocoder;
}
return this._geocoder;
}
/**
=======
>>>>>>>
* Geocodes an address, once the Google Map script
* has been properly loaded and promise instantiated.
*
* @param address string
* @param geocoder any
*
*/
geocodeAddress(address: string) {
this.geocode(address).then(firstResult => {
this.setCenter(firstResult.geometry.location);
this.createMarker({
map: this.map,
position: firstResult.geometry.location
}).then((createdMarker: any) => {
this._locationByAddressMarkers.push(createdMarker);
this.eventAggregator.publish(LOCATIONADDED, Object.assign(createdMarker, { placeId: firstResult.place_id }));
});
}).catch(console.info);
}
/**
* Geocodes Address and returns the coordinates once the google map has been properly initialized
*
* @param marker string
*
*/
addressMarkerToMarker(marker: AddressMarker): Promise<void | BaseMarker> {
return this.geocode(marker.address).then(firstResults => {
return {
... marker,
latitude: firstResults.geometry.location.lat(),
longitude: firstResults.geometry.location.lng(),
};
}).catch(console.info);
}
/**
* Geocodes Address and returns the firstresults object after google maps has initialized
*
* @param address string
*
*/
private geocode(address: string): Promise<any> {
return this._mapPromise.then(() => {
return new Promise((resolve, reject) => {
this.geocoder.geocode({ 'address': address }, (results: any, status: string) => {
if (status !== (<any>window).google.maps.GeocoderStatus.OK) {
reject(new Error(`Failed to geocode address '${address}' with status: ${status}`));
}
resolve(results[0]);
});
});
});
}
private get geocoder() {
if (!this._geocoder) {
this._geocoder = new (<any>window).google.maps.Geocoder;
}
return this._geocoder;
}
/**
<<<<<<<
Promise.all<LatLongMarker>(
newValue.map(marker => {
if (isAddressMarker(marker) && !isLatLongMarker(marker)) {
return this.addressMarkerToMarker(marker);
} else {
return marker;
}
})
).then(validMarkers => {
// Addresses that fail to parse return undefined (because the error is caught earlier in the promise chain)
this.validMarkers = validMarkers.filter(marker => typeof marker !== 'undefined');
return Promise.all(this.validMarkers.map(this.renderMarker.bind(this)));
}).then(() => {
/**
* We queue up a task to update the bounds, because in the case of multiple bound properties changing all at once,
* we need to let Aurelia handle updating the other properties before we actually trigger a re-render of the map
*/
this.taskQueue.queueTask(() => {
this.zoomToMarkerBounds();
});
=======
let markerPromises = newValue.map(marker => {
return this.renderMarker(marker);
});
// Wait until all of the renderMarker calls have been resolved
return Promise.all(markerPromises);
}).then(() => {
/**
* We queue up a task to update the bounds, because in the case of multiple bound properties changing all at once,
* we need to let Aurelia handle updating the other properties before we actually trigger a re-render of the map
*/
this.taskQueue.queueTask(() => {
this.zoomToMarkerBounds();
>>>>>>>
Promise.all<LatLongMarker>(
newValue.map(marker => {
if (isAddressMarker(marker) && !isLatLongMarker(marker)) {
return this.addressMarkerToMarker(marker);
} else {
}
return marker;
})
).then(validMarkers => {
// Addresses that fail to parse return undefined (because the error is caught earlier in the promise chain)
this.validMarkers = validMarkers.filter(marker => typeof marker !== 'undefined');
return Promise.all(this.validMarkers.map(this.renderMarker.bind(this)));
}).then(() => {
/**
* We queue up a task to update the bounds, because in the case of multiple bound properties changing all at once,
* we need to let Aurelia handle updating the other properties before we actually trigger a re-render of the map
*/
this.taskQueue.queueTask(() => {
this.zoomToMarkerBounds();
});
});
// Wait until all of the renderMarker calls have been resolved
return Promise.all(markerPromises);
}).then(() => {
/**
* We queue up a task to update the bounds, because in the case of multiple bound properties changing all at once,
* we need to let Aurelia handle updating the other properties before we actually trigger a re-render of the map
*/
this.taskQueue.queueTask(() => {
this.zoomToMarkerBounds(); |
<<<<<<<
header?: HeaderFooterPictureWidgetConfig | HeaderFooterButtonWidgetConfig;
footer?: HeaderFooterPictureWidgetConfig | HeaderFooterButtonWidgetConfig;
}
export interface HeaderFooterPictureWidgetConfig extends LovelaceCardConfig {
type: "picture"
image: string
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
}
export interface HeaderFooterButtonWidgetConfig extends LovelaceCardConfig {
type: "buttons"
entities: EntityConfig | string;
=======
state_color?: boolean;
>>>>>>>
state_color?: boolean;
header?: HeaderFooterPictureWidgetConfig | HeaderFooterButtonWidgetConfig;
footer?: HeaderFooterPictureWidgetConfig | HeaderFooterButtonWidgetConfig;
}
export interface HeaderFooterPictureWidgetConfig extends LovelaceCardConfig {
type: "picture"
image: string
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
}
export interface HeaderFooterButtonWidgetConfig extends LovelaceCardConfig {
type: "buttons"
entities: EntityConfig | string; |
<<<<<<<
put(PhotoViewingActions.refreshThreadsRequest()),
call(refreshTokens),
=======
put(ThreadsActions.refreshThreadsRequest()),
>>>>>>>
put(PhotoViewingActions.refreshThreadsRequest()), |
<<<<<<<
// import sourceSagas from './containers/Source/sagas'
// import bizlogicSagas from './containers/Bizlogic/sagas'
import widgetSagas from './containers/Widget/sagas'
=======
import sourceSagas from './containers/Source/sagas'
import bizlogicSagas from './containers/Bizlogic/sagas'
// import widgetSagas from './containers/Widget/sagas'
>>>>>>>
import sourceSagas from './containers/Source/sagas'
import bizlogicSagas from './containers/Bizlogic/sagas'
import widgetSagas from './containers/Widget/sagas'
<<<<<<<
...userSagas,
// ...sourceSagas,
// ...bizlogicSagas,
...widgetSagas,
=======
...userSagas,
...sourceSagas,
...bizlogicSagas
// ...widgetSagas,
>>>>>>>
...userSagas,
...sourceSagas,
...bizlogicSagas,
...widgetSagas |
<<<<<<<
=======
>>>>>>>
<<<<<<<
=======
declare var zone: Zone;
>>>>>>>
declare var zone: Zone; |
<<<<<<<
import { Home } from './home';
import { RouterActive } from './router-active';
import { MyItemComponent } from './appointment/appointment.component';
import { AppointmentForm } from './appointment/new-appointment.component';
=======
>>>>>>>
<<<<<<<
pipes: [ ],
providers: [ ],
directives: [RouterActive],
=======
>>>>>>>
<<<<<<<
styles: [
=======
styleUrls: [
'./app.style.css'
>>>>>>>
styleUrls: [
'./app.style.css'
<<<<<<<
<md-sidenav-layout fullscreen>
<md-sidenav #sidenav>
<md-nav-list>
<a md-list-item *ngFor="let view of views">
<md-icon md-list-icon>{{view.icon}}</md-icon>
<span md-line>{{view.name}}</span>
<span md-line class="secondary">{{view.description}}</span>
</a>
</md-nav-list>
</md-sidenav>
<md-toolbar color="primary">
<button md-icon-button (click)="sidenav.open()">
<md-icon>menu</md-icon>
</button>
Medical Appointment Scheduling
</md-toolbar>
<span router-active>
<button md-raised-button [routerLink]=" ['Index'] ">
Index
</button>
</span>
<span router-active>
<button md-raised-button [routerLink]=" ['Home'] ">
Home
</button>
</span>
<span router-active>
<button md-raised-button [routerLink]=" ['Appointments'] ">
Appointments
</button>
</span>
<span router-active>
<button md-raised-button [routerLink]=" ['About'] ">
About
</button>
</span>
=======
<nav>
<span>
<a [routerLink]=" ['./'] ">
Index
</a>
</span>
|
<span>
<a [routerLink]=" ['./home'] ">
Home
</a>
</span>
|
<span>
<a [routerLink]=" ['./about'] ">
About
</a>
</span>
</nav>
>>>>>>>
<md-sidenav-layout fullscreen>
<md-sidenav #sidenav>
<md-nav-list>
<a md-list-item *ngFor="let view of views">
<md-icon md-list-icon>{{view.icon}}</md-icon>
<span md-line>{{view.name}}</span>
<span md-line class="secondary">{{view.description}}</span>
</a>
</md-nav-list>
</md-sidenav>
<md-toolbar color="primary">
<button md-icon-button (click)="sidenav.open()">
<md-icon>menu</md-icon>
</button>
Medical Appointment Scheduling
</md-toolbar>
<nav>
<span>
<a [routerLink]=" ['./'] ">
Index
</a>
</span>
|
<span>
<a [routerLink]=" ['./home'] ">
Home
</a>
</span>
|
<span>
<a [routerLink]=" ['./appointments'] ">
Appointments
</a>
</span>
|
<span>
<a [routerLink]=" ['./about'] ">
About
</a>
</span>
</nav>
<<<<<<<
</md-sidenav-layout>
`
=======
<footer>
<span>WebPack Angular 2 Starter by <a [href]="url">@AngularClass</a></span>
<div>
<a [href]="url">
<img [src]="angularclassLogo" width="25%">
</a>
</div>
</footer>
`
>>>>>>>
</md-sidenav-layout>
`
<<<<<<<
@RouteConfig([
{ path: '/', name: 'Index', component: Home, useAsDefault: true },
{ path: '/home', name: 'Home', component: Home },
// Async load a component using Webpack's require with es6-promise-loader and webpack `require`
{ path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
{ path: '/appointments', name: 'Appointments', component: MyItemComponent },
{ path: '/new-appointment', name: 'New Appointment', component: AppointmentForm }
])
=======
>>>>>>> |
<<<<<<<
import {BeaconChain, ChainEventEmitter, IBeaconChain} from "../../../../src/chain";
=======
import {BeaconChain, IBeaconChain} from "../../../../src/chain";
import {silentLogger} from "../../../utils/logger";
>>>>>>>
import {BeaconChain, ChainEventEmitter, IBeaconChain} from "../../../../src/chain";
import {silentLogger} from "../../../utils/logger";
<<<<<<<
validateBlock(config, sinon.createStubInstance(WinstonLogger), forkChoiceStub, eventBusStub),
=======
validateBlock(config, logger, forkChoiceStub, chainStub),
>>>>>>>
validateBlock(config, logger, forkChoiceStub, eventBusStub),
<<<<<<<
validateBlock(config, sinon.createStubInstance(WinstonLogger), forkChoiceStub, eventBusStub),
=======
validateBlock(config, logger, forkChoiceStub, chainStub),
>>>>>>>
validateBlock(config, logger, forkChoiceStub, eventBusStub),
<<<<<<<
validateBlock(config, sinon.createStubInstance(WinstonLogger), forkChoiceStub, eventBusStub),
=======
validateBlock(config, logger, forkChoiceStub, chainStub),
>>>>>>>
validateBlock(config, logger, forkChoiceStub, eventBusStub), |
<<<<<<<
attestation.signature = this.privateKey.signMessage(
hashTreeRoot(attestation.data, this.config.types.AttestationData),
=======
attestation.signature = this.keypair.privateKey.signMessage(
hashTreeRoot(this.config.types.AttestationData, attestation.data),
>>>>>>>
attestation.signature = this.privateKey.signMessage(
hashTreeRoot(this.config.types.AttestationData, attestation.data), |
<<<<<<<
import {LodestarEventIterator} from "../../../util/events";
=======
import {IBeaconBlocksApi} from "./blocks";
>>>>>>>
import {LodestarEventIterator} from "../../../util/events";
import {IBeaconBlocksApi} from "./blocks"; |
<<<<<<<
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger});
=======
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger: logger, metrics});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger: logger, metrics});
>>>>>>>
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger, metrics});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger, metrics}); |
<<<<<<<
import {BeaconDB, LevelDbPersistance} from "../db";
import {EthersEth1Notifier} from "../eth1";
import {P2PNetwork} from "../p2p";
=======
import {LevelDB} from "../db";
import {EthersEth1Notifier, EthersEth1Options} from "../eth1";
import {P2PNetwork, P2pOptions} from "../p2p";
>>>>>>>
import {BeaconDB, LevelDbPersistance} from "../db";
import {EthersEth1Notifier} from "../eth1";
import {P2PNetwork} from "../p2p";
import {LevelDB} from "../db";
import {EthersEth1Notifier, EthersEth1Options} from "../eth1";
import {P2PNetwork, P2pOptions} from "../p2p";
<<<<<<<
this.db = new BeaconDB({
persistance: new LevelDbPersistance(
this.conf.db
)
});
this.network = new P2PNetwork(this.conf.network);
=======
this.db = new LevelDB(this.conf.db);
this.network = new P2PNetwork(this.conf.p2p);
>>>>>>>
this.db = new BeaconDB({
persistance: new LevelDbPersistance(
this.conf.db
)
});
this.network = new P2PNetwork(this.conf.p2p); |
<<<<<<<
// @ts-ignore
import promisify from "promisify-es6";
import {Status, ResponseBody} from "@chainsafe/eth2.0-types";
=======
import {promisify} from "es6-promisify";
import {Hello, ResponseBody} from "@chainsafe/eth2.0-types";
>>>>>>>
import {promisify} from "es6-promisify";
import {Status, ResponseBody} from "@chainsafe/eth2.0-types";
<<<<<<<
import {INetworkOptions} from "../../../src/network/options";
=======
import PeerInfo from "peer-info";
>>>>>>>
import {INetworkOptions} from "../../../src/network/options";
import PeerInfo from "peer-info";
<<<<<<<
// @ts-ignore
await promisify(nodeA.dial.bind(nodeA))(nodeB.peerInfo);
=======
await promisify<void, PeerInfo>(nodeA.dial.bind(nodeA))(nodeB.peerInfo);
>>>>>>>
await promisify<void, PeerInfo>(nodeA.dial.bind(nodeA))(nodeB.peerInfo); |
<<<<<<<
import {processProposerSlashing} from "../../../../src/chain/stateTransition/block/proposerSlashings";
import {proposerSlashingFromYaml} from "../../../utils/proposerSlashing";
import {equals} from "@chainsafe/ssz";
import {BeaconState} from "../../../../src/types";
=======
import {processProposerSlashing} from "../../../../src/chain/stateTransition/block/operations";
import {BeaconState, ProposerSlashing} from "../../../../src/types";
import {expandYamlValue} from "../../../utils/expandYamlValue";
>>>>>>>
import {equals} from "@chainsafe/ssz";
import {processProposerSlashing} from "../../../../src/chain/stateTransition/block/operations";
import {BeaconState, ProposerSlashing} from "../../../../src/types";
import {expandYamlValue} from "../../../utils/expandYamlValue"; |
<<<<<<<
const state = await this.db.state.getLatest();
=======
this.logger.verbose("Starting chain");
const state = this.latestState || await this.db.state.getLatest();
this.eth1.initBlockCache(this.config, state);
>>>>>>>
this.logger.verbose("Starting chain");
const state = await this.db.state.getLatest();
this.eth1.initBlockCache(this.config, state);
<<<<<<<
=======
public async isValidBlock(state: BeaconState, signedBlock: SignedBeaconBlock): Promise<boolean> {
// The parent block with root block.previous_block_root has been processed and accepted.
// const hasParent = await this.db.block.has(block.parentRoot);
// if (!hasParent) {
// return false;
// }
// An Ethereum 1.0 block pointed to by the state.
// latest_eth1_data.block_hash has been processed and accepted.
// TODO: implement
return getCurrentSlot(this.config, state.genesisTime) >= signedBlock.message.slot;
}
private processBlock = async (job: IBlockProcessJob, blockHash: Root): Promise<void> => {
const parentBlock = await this.db.block.get(job.signedBlock.message.parentRoot.valueOf() as Uint8Array);
if (!parentBlock) {
this.logger.warn(`Block(${toHexString(blockHash)}) at slot ${job.signedBlock.message.slot} `
+ ` is missing parent block (${toHexString(job.signedBlock.message.parentRoot)}).`
);
this.emit("unknownBlockRoot", job.signedBlock.message.parentRoot.valueOf() as Uint8Array);
setTimeout((queue) => queue.add(job), 1000, this.blockProcessingQueue);
return;
}
const pre = await this.db.state.get(parentBlock.message.stateRoot.valueOf() as Uint8Array);
const isValidBlock = await this.isValidBlock(pre, job.signedBlock);
assert(isValidBlock);
const hexBlockHash = toHexString(blockHash);
this.logger.info(`${hexBlockHash} is valid, running state transition...`);
// process current slot
const post = await this.runStateTransition(job.signedBlock, pre);
this.logger.info(
`Slot ${job.signedBlock.message.slot} Block ${hexBlockHash} ` +
`State ${toHexString(this.config.types.BeaconState.hashTreeRoot(post))} passed state transition`
);
await this.opPool.processBlockOperations(job.signedBlock);
job.signedBlock.message.body.attestations.forEach((attestation: Attestation) => {
this.receiveAttestation(attestation);
});
await this.attestationProcessor.receiveBlock(job.signedBlock);
this.metrics.currentSlot.inc(1);
// forward processed block for additional processing
this.emit("processedBlock", job.signedBlock);
};
/**
*
* @param signedBlock
* @param state
* @param trusted if state transition should trust that block is valid
*/
private async runStateTransition(
signedBlock: SignedBeaconBlock,
state: BeaconState,
trusted = false
): Promise<BeaconState | null> {
const preSlot = state.slot;
const preFinalizedEpoch = state.finalizedCheckpoint.epoch;
const preJustifiedEpoch = state.currentJustifiedCheckpoint.epoch;
// Run the state transition
let newState: BeaconState;
const blockRoot = this.config.types.BeaconBlock.hashTreeRoot(signedBlock.message);
try {
// if block is trusted don't verify state roots, proposer or signature
newState = stateTransition(this.config, state, signedBlock, !trusted, !trusted, !trusted);
} catch (e) {
// store block root in db and terminate
await this.db.block.storeBadBlock(blockRoot);
this.logger.warn(`Found bad block, block root: ${toHexString(blockRoot)} ` + e.message);
return;
}
this.latestState = newState;
// On successful transition, update system state
await Promise.all([
this.db.state.set(signedBlock.message.stateRoot.valueOf() as Uint8Array, newState),
this.db.block.set(blockRoot, signedBlock),
]);
this.forkChoice.addBlock({
slot: signedBlock.message.slot,
blockRootBuf: blockRoot,
stateRootBuf: signedBlock.message.stateRoot.valueOf() as Uint8Array,
parentRootBuf: signedBlock.message.parentRoot.valueOf() as Uint8Array,
justifiedCheckpoint: newState.currentJustifiedCheckpoint,
finalizedCheckpoint: newState.finalizedCheckpoint
});
await this.applyForkChoiceRule();
await this.updateDepositMerkleTree(newState);
// update metrics
this.metrics.currentSlot.set(signedBlock.message.slot);
// Post-epoch processing
const currentEpoch = computeEpochAtSlot(this.config, newState.slot);
if (computeEpochAtSlot(this.config, preSlot) < currentEpoch) {
this.emit("processedCheckpoint", {epoch: currentEpoch, root: blockRoot});
// Update FFG Checkpoints
// Newly justified epoch
if (preJustifiedEpoch < newState.currentJustifiedCheckpoint.epoch) {
const justifiedBlockRoot = newState.currentJustifiedCheckpoint.root;
const justifiedBlock = await this.db.block.get(justifiedBlockRoot.valueOf() as Uint8Array);
this.logger.important(`Epoch ${computeEpochAtSlot(this.config, justifiedBlock.message.slot)} is justified!`);
await Promise.all([
this.db.chain.setJustifiedStateRoot(justifiedBlock.message.stateRoot.valueOf() as Uint8Array),
this.db.chain.setJustifiedBlockRoot(justifiedBlockRoot.valueOf() as Uint8Array),
]);
this.emit("justifiedCheckpoint", newState.currentJustifiedCheckpoint);
}
// Newly finalized epoch
if (preFinalizedEpoch < newState.finalizedCheckpoint.epoch) {
const finalizedBlockRoot = newState.finalizedCheckpoint.root;
const finalizedBlock = await this.db.block.get(finalizedBlockRoot.valueOf() as Uint8Array);
this.logger.important(`Epoch ${computeEpochAtSlot(this.config, finalizedBlock.message.slot)} is finalized!`);
await Promise.all([
this.db.chain.setFinalizedStateRoot(finalizedBlock.message.stateRoot.valueOf() as Uint8Array),
this.db.chain.setFinalizedBlockRoot(finalizedBlockRoot.valueOf() as Uint8Array),
]);
this.eth1.pruneBlockCache(this.config, {...newState, slot: finalizedBlock.message.slot});
this.emit("finalizedCheckpoint", newState.finalizedCheckpoint);
}
this.metrics.previousJustifiedEpoch.set(newState.previousJustifiedCheckpoint.epoch);
this.metrics.currentJustifiedEpoch.set(newState.currentJustifiedCheckpoint.epoch);
this.metrics.currentFinalizedEpoch.set(newState.finalizedCheckpoint.epoch);
this.metrics.currentEpochLiveValidators.set(
Array.from(newState.validators).filter((v: Validator) => isActiveValidator(v, currentEpoch)).length
);
}
return newState;
}
private async updateDepositMerkleTree(newState: BeaconState): Promise<void> {
const upperIndex = newState.eth1DepositIndex + Math.min(
this.config.params.MAX_DEPOSITS,
newState.eth1Data.depositCount - newState.eth1DepositIndex
);
const [depositDatas, depositDataRootList] = await Promise.all([
this.db.depositData.getAllBetween(newState.eth1DepositIndex, upperIndex),
this.db.depositDataRootList.get(newState.eth1DepositIndex),
]);
depositDataRootList.push(...depositDatas.map(this.config.types.DepositData.hashTreeRoot));
//TODO: remove deposits with index <= newState.depositIndex
await this.db.depositDataRootList.set(newState.eth1DepositIndex, depositDataRootList);
}
>>>>>>> |
<<<<<<<
import {processSlots} from "@chainsafe/lodestar-beacon-state-transition/lib/fast/slot";
import {BlockErrorCode} from "../../chain/errors/blockError";
import {IBlockProcessJob} from "../../chain";
import {AttestationErrorCode} from "../../chain/errors/attestationError";
=======
>>>>>>>
import {BlockErrorCode} from "../../chain/errors/blockError";
import {IBlockProcessJob} from "../../chain";
import {AttestationErrorCode} from "../../chain/errors/attestationError"; |
<<<<<<<
import {
clamp, getActiveValidatorIndices, getEpochStartSlot, intSqrt, isActiveValidator, readUIntBE, slotToEpoch, split,
} from "../../helpers/stateTransitionHelpers";
import {EpochNumber, SlotNumber, Validator} from "../../types";
import {generateMnemonic} from "bip39";
import {generateValidator} from "../utils/validator";
=======
import { clamp, getActiveValidatorIndices, intSqrt, isPowerOfTwo, readUIntBE, split } from "../../helpers/stateTransitionHelpers";
import { Validator } from "../../types";
>>>>>>>
import {
clamp, getActiveValidatorIndices, getEpochStartSlot, intSqrt, isActiveValidator, isPowerOfTwo, readUIntBE, slotToEpoch, split,
} from "../../helpers/stateTransitionHelpers";
import {EpochNumber, SlotNumber, Validator} from "../../types";
import {generateValidator} from "../utils/validator"; |
<<<<<<<
import {BeaconDB, LevelDbController} from "../db";
import {EthersEth1Notifier, IEth1Notifier} from "../eth1";
import {INetwork, Libp2pNetwork, NodejsNode} from "../network";
=======
import {BeaconDB, LevelDbController, ValidatorDB} from "../db";
import {EthersEth1Notifier, EthersEth1Options, IEth1Notifier} from "../eth1";
import {Libp2pNetwork, INetworkOptions, NodejsNode, INetwork} from "../network";
>>>>>>>
import {BeaconDB, LevelDbController} from "../db";
import {EthersEth1Notifier, IEth1Notifier} from "../eth1";
import {INetwork, Libp2pNetwork, NodejsNode} from "../network";
<<<<<<<
import HttpServer from "../rpc/transport/http";
import Validator from "../validator";
=======
import Validator from "../validator";
>>>>>>>
import HttpServer from "../rpc/transport/http";
import Validator from "../validator";
<<<<<<<
=======
// Temporarily have properties be optional until others portions of lodestar are ready
export interface BeaconNodeCtx {
chain?: object;
db?: DBOptions;
eth1?: EthersEth1Options;
network?: INetworkOptions;
rpc?: RpcCtx;
sync?: object;
opPool?: object;
validator?: {
key: string;
password?: string;
db?: string;
};
}
interface RpcCtx {
apis?: IApiConstructor[];
}
>>>>>>>
<<<<<<<
public constructor(opts: Partial<IBeaconNodeOptions>, {logger}: { logger: ILogger }) {
=======
public constructor(opts: BeaconNodeCtx, {logger}: { logger: ILogger }) {
>>>>>>>
public constructor(opts: Partial<IBeaconNodeOptions>, {logger}: { logger: ILogger }) {
<<<<<<<
if (this.conf.validator) {
await this.validator.start();
}
=======
if(this.conf.validator){
await this.validator.start();
}
>>>>>>>
<<<<<<<
if (this.conf.validator){
await this.validator.stop();
}
}
private initRpc(): JSONRPC {
let transports = [];
this.conf.api.transports.forEach((transportOpt) => {
switch (transportOpt.type) {
case TransportType.HTTP: {
transports.push(new HttpServer(transportOpt, {logger: this.logger}));
}
break;
case TransportType.WS: {
new WSServer(transportOpt);
}
break;
}
});
return new JSONRPC(this.conf.api, {
transports,
apis: this.conf.api.apis.map((Api) => {
return new Api(this.conf.api, {chain: this.chain, db: this.db, eth1: this.eth1});
})
});
=======
if(this.conf.validator){
await this.validator.stop();
}
>>>>>>> |
<<<<<<<
import {
Slot, bytes32, bytes, uint16, uint64,
bytes8, Epoch, number64, Version, Hash,
} from "./primitive";
import {BeaconBlock} from "./block";
=======
import {Slot, Hash, bytes, uint16, uint64, bytes8, Epoch, number64} from "./primitive";
import {BeaconBlockBody} from "./block";
import {BeaconBlockHeader} from "./misc";
import {BeaconState} from "./state";
>>>>>>>
import {
Slot, Epoch, Hash, number64, Version, uint64,
} from "./primitive";
import {BeaconBlock} from "./block";
<<<<<<<
=======
export type Method = number;
export interface BlockRootSlot {
blockRoot: Hash;
slot: Slot;
}
export interface WireRequest {
id: bytes8;
method: uint16;
body: bytes;
}
export interface WireResponse {
id: bytes8;
responseCode: uint16;
result: bytes;
}
export interface RpcRequest {
id: uint64;
method: uint16;
body: RequestBody;
}
export interface RpcResponse {
id: uint64;
responseCode: uint16;
result?: ResponseBody;
}
>>>>>>>
<<<<<<<
forkVersion: Version;
finalizedRoot: Hash;
finalizedEpoch: Epoch;
headRoot: Hash;
headSlot: Slot;
=======
networkId: uint64;
chainId: uint16;
latestFinalizedRoot: Hash;
latestFinalizedEpoch: Epoch;
bestRoot: Hash;
bestSlot: Slot;
>>>>>>>
forkVersion: Version;
finalizedRoot: Hash;
finalizedEpoch: Epoch;
headRoot: Hash;
headSlot: Slot;
<<<<<<<
export interface BeaconBlocksRequest {
headBlockRoot: Hash;
=======
// Method ID: 2
export interface Status {
sha: Hash;
userAgent: bytes;
timestamp: number64;
}
// Method ID: 10
export interface BeaconBlockRootsRequest {
>>>>>>>
export interface BeaconBlocksRequest {
headBlockRoot: Hash;
<<<<<<<
export interface RecentBeaconBlocksRequest {
blockRoots: Hash[];
=======
// Method ID: 11
export interface BeaconBlockHeadersRequest {
startRoot: Hash;
startSlot: Slot;
maxHeaders: number64;
skipSlots: number64;
}
export interface BeaconBlockHeadersResponse {
headers: BeaconBlockHeader[];
}
// Method ID: 12
export interface BeaconBlockBodiesRequest {
blockRoots: Hash[];
}
export interface BeaconBlockBodiesResponse {
blockBodies: BeaconBlockBody[];
}
// Method ID: 13
export interface BeaconStatesRequest {
hashes: Hash[];
>>>>>>>
export interface RecentBeaconBlocksRequest {
blockRoots: Hash[]; |
<<<<<<<
return await this.getAllData(Bucket.deposit, Deposit);
=======
return await this.getAllData(Bucket.genesisDeposit, this.config.types.Deposit);
>>>>>>>
return await this.getAllData(Bucket.deposit, this.config.types.Deposit);
<<<<<<<
await this.db.put(encodeKey(Bucket.deposit, index), serialize(deposit, Deposit));
=======
await this.db.put(encodeKey(Bucket.genesisDeposit, index), serialize(deposit, this.config.types.Deposit));
>>>>>>>
await this.db.put(encodeKey(Bucket.deposit, index), serialize(deposit, this.config.types.Deposit)); |
<<<<<<<
fastify.get(produceBlockController.url, produceBlockController.opts, produceBlockController.handler);
=======
fastify.get(proposerDutiesController.url, proposerDutiesController.opts, proposerDutiesController.handler);
>>>>>>>
fastify.get(produceBlockController.url, produceBlockController.opts, produceBlockController.handler);
fastify.get(proposerDutiesController.url, proposerDutiesController.opts, proposerDutiesController.handler); |
<<<<<<<
try {
const [headBlock, validatorIndex] = await Promise.all([
db.block.get(chain.forkChoice.head()),
db.getValidatorIndex(validatorPubKey)
]);
const headState = await db.state.get(headBlock.stateRoot);
await processSlots(config, headState, slot);
return await assembleAttestation({config, db}, headState, headBlock, validatorIndex, index, slot);
} catch (e) {
throw e;
}
=======
const [headState, headBlock, validatorIndex] = await Promise.all([
clone(config.types.BeaconState, chain.latestState) as BeaconState,
db.block.get(chain.forkChoice.head()),
db.getValidatorIndex(validatorPubKey)
]);
return await assembleAttestation({config, db}, headState, headBlock, validatorIndex, shard, slot);
>>>>>>>
const [headBlock, validatorIndex] = await Promise.all([
db.block.get(chain.forkChoice.head()),
db.getValidatorIndex(validatorPubKey)
]);
const headState = await db.state.get(headBlock.stateRoot);
await processSlots(config, headState, slot);
return await assembleAttestation({config, db}, headState, headBlock, validatorIndex, index, slot); |
<<<<<<<
import {hash, signingRoot} from "@chainsafe/ssz";
=======
>>>>>>>
import {hash, signingRoot} from "@chainsafe/ssz";
<<<<<<<
=======
import {signingRoot} from "@chainsafe/ssz";
import {hash} from "../util/crypto";
>>>>>>> |
<<<<<<<
// import sourceReducer from './containers/Source/reducer'
// import bizlogicReducer from './containers/Bizlogic/reducer'
import widgetReducer from './containers/Widget/reducer'
=======
import sourceReducer from './containers/Source/reducer'
import bizlogicReducer from './containers/Bizlogic/reducer'
// import widgetReducer from './containers/Widget/reducer'
>>>>>>>
import sourceReducer from './containers/Source/reducer'
import bizlogicReducer from './containers/Bizlogic/reducer'
import widgetReducer from './containers/Widget/reducer'
<<<<<<<
// source: sourceReducer,
// bizlogic: bizlogicReducer,
widget: widgetReducer,
=======
source: sourceReducer,
bizlogic: bizlogicReducer,
// widget: widgetReducer,
>>>>>>>
source: sourceReducer,
bizlogic: bizlogicReducer,
widget: widgetReducer, |
<<<<<<<
import {IDatabaseController, SearchOptions} from "../interface";
import {Attestation} from "../../../types";
=======
import {SearchOptions} from "../interface";
import {Attestation} from "@chainsafe/eth2.0-types";
import {IDatabaseController} from "../interface";
>>>>>>>
import {IDatabaseController, SearchOptions} from "../interface";
import {Attestation} from "@chainsafe/eth2.0-types"; |
<<<<<<<
export * from "./math";
export * from "./bytes";
export * from "./converters";
=======
export * from "./math";
export * from "./yaml";
>>>>>>>
export * from "./math";
export * from "./bytes";
export * from "./converters";
export * from "./yaml"; |
<<<<<<<
import {getCurrentSlot} from "../../chain/stateTransition/util/genesis";
=======
import {INewEpochCallback, INewSlotCallback, IRpcClient} from "./interface";
>>>>>>>
import {getCurrentSlot} from "../../chain/stateTransition/util/genesis";
import {INewEpochCallback, INewSlotCallback, IRpcClient} from "./interface";
<<<<<<<
public abstract url: string;
private currentSlot: Slot;
=======
private currentSlot: Slot = 0;
>>>>>>>
public abstract url: string;
private currentSlot: Slot = 0; |
<<<<<<<
it("should reject - bad block", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("bad block", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should reject - bad block", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
<<<<<<<
it("should ignore - already proposed", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("already proposed", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should ignore - already proposed", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
<<<<<<<
it("should ignore - missing parent", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("missing parent", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should ignore - missing parent", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
<<<<<<<
it("should reject - invalid signature", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("invalid signature", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should reject - invalid signature", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
<<<<<<<
it("should reject - wrong proposer", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("wrong proposer", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should reject - wrong proposer", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
<<<<<<<
it("should reject - finalized checkpoint not an ancestor of block", async function () {
chainStub.getGenesisTime.returns(Date.now() / 1000 - config.params.SECONDS_PER_SLOT);
=======
it("valid block", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1);
>>>>>>>
it("should reject - finalized checkpoint not an ancestor of block", async function () {
sinon.stub(chainStub.clock, "currentSlot").get(() => 1); |
<<<<<<<
import {BeaconBlock, bytes48, Slot, ValidatorIndex} from "../types";
import {getRandaoMix, slotToEpoch} from "../chain/stateTransition/util";
import {RpcClient} from "./rpc";
=======
/**
* @module validator
*/
import ssz from "@chainsafe/ssz";
import {ValidatorIndex, BeaconBlock, BeaconState, bytes48} from "../types";
import {Domain} from "../constants";
import {blsSign} from "../stubs/bls";
import {getDomain, slotToEpoch} from "../chain/stateTransition/util";
import {getEmptyBlock} from "../chain/genesis";
import RPCProvider from "./stubs/rpc";
>>>>>>>
/**
* @module validator
*/
import ssz from "@chainsafe/ssz";
import {ValidatorIndex, BeaconBlock, BeaconState, bytes48} from "../types";
import {Domain} from "../constants";
import {blsSign} from "../stubs/bls";
import {getDomain, slotToEpoch} from "../chain/stateTransition/util";
import {getEmptyBlock} from "../chain/genesis";
import RPCProvider from "./stubs/rpc";
import {BeaconBlock, bytes48, Slot, ValidatorIndex} from "../types";
import {getRandaoMix, slotToEpoch} from "../chain/stateTransition/util";
import {RpcClient} from "./rpc"; |
<<<<<<<
import {ILMDGHOST, StatefulDagLMDGHOST} from "./forkChoice";
import {computeEpochOfSlot, getAttestingIndices} from "./stateTransition/util";
=======
import {LMDGHOST, StatefulDagLMDGHOST} from "./forkChoice";
import {getAttestingIndices, computeEpochOfSlot, isActiveValidator} from "./stateTransition/util";
>>>>>>>
import {LMDGHOST, StatefulDagLMDGHOST} from "./forkChoice";
import {getAttestingIndices, computeEpochOfSlot, isActiveValidator} from "./stateTransition/util";
<<<<<<<
public constructor(opts: IChainOptions, {config, db, eth1, opPool, logger}: IBeaconChainModules) {
=======
private metrics: IBeaconMetrics;
private opts: IChainOptions;
public constructor(opts: IChainOptions, {config, db, eth1, opPool, logger, metrics}: IBeaconChainModules) {
>>>>>>>
private metrics: IBeaconMetrics;
private opts: IChainOptions;
public constructor(opts: IChainOptions, {config, db, eth1, opPool, logger, metrics}: IBeaconChainModules) {
<<<<<<<
this.chain = opts.name;
=======
this.opts = opts;
this.chain = opts.name;
>>>>>>>
this.opts = opts;
this.chain = opts.name;
<<<<<<<
this.eth1.on("block", this.checkGenesis);
=======
this.logger.info("Chain not started, listening for genesis block");
this.eth1.on('block', this.checkGenesis);
>>>>>>>
this.logger.info("Chain not started, listening for genesis block");
this.eth1.on("block", this.checkGenesis); |
<<<<<<<
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger});
=======
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger: logger, metrics});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger: logger, metrics});
>>>>>>>
netA = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger, metrics});
netB = new Libp2pNetwork(opts, {config, libp2p: createNode(multiaddr), logger, metrics}); |
<<<<<<<
private encodeResponse(method: Method, body: ResponseBody): Buffer {
let output: Uint8Array;
switch (method) {
case Method.Status:
output = this.config.types.Status.serialize(body as Status);
break;
case Method.Goodbye:
output = this.config.types.Goodbye.serialize(body as Goodbye);
break;
case Method.BeaconBlocksByRange:
output = this.config.types.BeaconBlocksByRangeResponse.serialize(body as BeaconBlocksByRangeResponse);
break;
case Method.BeaconBlocksByRoot:
output = this.config.types.BeaconBlocksByRootResponse.serialize(body as BeaconBlocksByRootResponse);
break;
}
return Buffer.concat([
Buffer.alloc(1),
Buffer.from(varint.encode(output.length)),
output,
]);
}
private encodeResponseError(err: Error): Buffer {
const b = Buffer.from("c" + err.message);
b[0] = err.message === ERR_INVALID_REQ ? 1 : 2;
return b;
}
=======
>>>>>>> |
<<<<<<<
import {Module} from "../logger/abstract";
import defaultChainOption, {IChainOptions} from "./options";
import deepmerge from "deepmerge";
=======
import {OpPool} from "../opPool";
import {Block} from "ethers/providers";
export interface IBeaconChainModules {
config: IBeaconConfig;
opPool: OpPool;
db: IBeaconDb;
eth1: IEth1Notifier;
logger: ILogger;
}
>>>>>>>
import {Module} from "../logger/abstract";
import defaultChainOption, {IChainOptions} from "./options";
import deepmerge from "deepmerge";
import {OpPool} from "../opPool";
import {Block} from "ethers/providers";
export interface IBeaconChainModules {
config: IBeaconConfig;
opPool: OpPool;
db: IBeaconDb;
eth1: IEth1Notifier;
logger: ILogger;
}
<<<<<<<
this.logger = logger || new WinstonLogger(this.opts.loggingLevel, Module.CHAIN);
=======
this.opPool = opPool;
this.logger = logger;
>>>>>>>
this.opPool = opPool;
this.logger = logger || new WinstonLogger(this.opts.loggingLevel, Module.CHAIN); |
<<<<<<<
await (new Eth1Wallet(wallet.privateKey, defaults.depositContract.abi, config, logger, provider))
.submitValidatorDeposit(options.contract, ethers.utils.parseEther(options.value));
=======
await (new Eth1Wallet(wallet.privateKey, abi, config, logger, provider))
.createValidatorDeposit(options.contract, ethers.utils.parseEther(options.value));
>>>>>>>
await (new Eth1Wallet(wallet.privateKey, abi, config, logger, provider))
.submitValidatorDeposit(options.contract, ethers.utils.parseEther(options.value)); |
<<<<<<<
import {IPeerMetadataStore} from "../../../src/network/peers/interface";
import {Libp2pPeerMetadataStore} from "../../../src/network/peers/metastore";
=======
import {silentLogger} from "../../utils/logger";
>>>>>>>
import {IPeerMetadataStore} from "../../../src/network/peers/interface";
import {Libp2pPeerMetadataStore} from "../../../src/network/peers/metastore";
import {silentLogger} from "../../utils/logger";
<<<<<<<
logger = new WinstonLogger();
logger.silent = true;
=======
repsStub = sandbox.createStubInstance(ReputationStore);
>>>>>>>
<<<<<<<
logger,
=======
reputationStore: repsStub,
logger: silentLogger,
>>>>>>>
logger,
<<<<<<<
=======
repsStub.get.returns({
latestMetadata: null,
latestStatus: null,
score: 0,
encoding: ReqRespEncoding.SSZ_SNAPPY,
});
>>>>>>>
<<<<<<<
=======
const reputation: IReputation = {
latestMetadata: null,
latestStatus: null,
score: 0,
encoding: ReqRespEncoding.SSZ_SNAPPY,
};
repsStub.get.returns(reputation);
repsStub.getFromPeerId.returns(reputation);
>>>>>>>
<<<<<<<
=======
repsStub.get.returns({
latestMetadata: null,
latestStatus: null,
score: 0,
encoding: ReqRespEncoding.SSZ_SNAPPY,
});
>>>>>>> |
<<<<<<<
* Obtains validator index attached to his public key
* @param validatorPublicKey
=======
* Requests the BeaconNode to provide a set of “duties”, which are actions that should be performed by ValidatorClients. This API call should be polled at every slot, to ensure that any chain reorganisations are catered for, and to ensure that the currently connected BeaconNode is properly synchronised.
* @returns A list of unique validator public keys, where each item is a 0x encoded hex string.
>>>>>>>
* Obtains validator index attached to his public key
<<<<<<<
* @param index
* @param {Slot} slot
* @returns {Promise<{slot: Slot, proposer: boolean}}
=======
>>>>>>>
<<<<<<<
* Requests a validators committeeAssignment,
* can be used for past, current and one epoch in the future
* @param {ValidatorIndex} index
* @param {Epoch} epoch
=======
* Requests a validators committeeAssignment, can be used for past, current and one epoch in the future
>>>>>>>
* Requests a validators committeeAssignment,
* can be used for past, current and one epoch in the future
<<<<<<<
* Requests a BeaconNode to produce a valid block,
* which can then be signed by a ValidatorClient.
* @param {Slot} slot
* @param {bytes} randaoReveal
* @returns {Promise<BeaconBlock>} A proposed BeaconBlock object,
* but with the signature field left blank.
=======
* Requests a BeaconNode to produce a valid block, which can then be signed by a ValidatorClient.
* @returns A proposed BeaconBlock object, but with the signature field left blank.
>>>>>>>
* Requests a BeaconNode to produce a valid block,
* which can then be signed by a ValidatorClient.
* @returns {Promise<BeaconBlock>} A proposed BeaconBlock object,
* but with the signature field left blank.
<<<<<<<
* Requests that the BeaconNode produce an IndexedAttestation,
* with a blank signature field, which the ValidatorClient will then sign.
* @param {Slot} slot
* @param {Shard} shard
* @returns {Promise<Attestation>}
=======
* Requests that the BeaconNode produce an IndexedAttestation, with a blank signature field, which the ValidatorClient will then sign.
>>>>>>>
* Requests that the BeaconNode produce an IndexedAttestation,
* with a blank signature field, which the ValidatorClient will then sign.
<<<<<<<
* Instructs the BeaconNode to publish a newly signed beacon block
* to the beacon network, to be included in the beacon chain.
* @param {BeaconBlock} beaconBlock
* @returns {Promise<void>}
=======
* Instructs the BeaconNode to publish a newly signed beacon block to the beacon network, to be included in the beacon chain.
>>>>>>>
* Instructs the BeaconNode to publish a newly signed beacon block
* to the beacon network, to be included in the beacon chain.
<<<<<<<
* Instructs the BeaconNode to publish a newly signed IndexedAttestation object,
* to be incorporated into the beacon chain.
* @param {Attestation} attestation
* @returns {Promise<void>}
=======
* Instructs the BeaconNode to publish a newly signed IndexedAttestation object, to be incorporated into the beacon chain.
>>>>>>>
* Instructs the BeaconNode to publish a newly signed IndexedAttestation object,
* to be incorporated into the beacon chain. |
<<<<<<<
import {deserialize, serialize} from "@chainsafe/ssz";
=======
>>>>>>> |
<<<<<<<
import {ArrayDagLMDGHOST, BeaconChain, ChainEventEmitter, IBeaconChain, ILMDGHOST} from "../../../../src/chain";
import {WinstonLogger} from "@chainsafe/lodestar-utils/lib/logger";
=======
import {BeaconChain, IBeaconChain, ILMDGHOST, ArrayDagLMDGHOST, ChainEventEmitter} from "../../../../src/chain";
>>>>>>>
import {ArrayDagLMDGHOST, BeaconChain, ChainEventEmitter, IBeaconChain, ILMDGHOST} from "../../../../src/chain";
<<<<<<<
chain: chainStub,
logger: sinon.createStubInstance(WinstonLogger),
=======
//@ts-ignore
chain: chainEventEmitter,
logger,
>>>>>>>
//@ts-ignore
chain: chainStub,
logger,
<<<<<<<
chain: chainStub,
logger: sinon.createStubInstance(WinstonLogger),
=======
//@ts-ignore
chain: chainEventEmitter,
logger,
>>>>>>>
//@ts-ignore
chain: chainStub,
logger, |
<<<<<<<
slot,
index,
beaconBlockRoot: signingRoot(headBlock, config.types.BeaconBlock),
=======
crosslink: getCrosslinkVote(config, headState, shard, currentEpoch),
beaconBlockRoot: signingRoot(config.types.BeaconBlock, headBlock),
>>>>>>>
slot,
index,
beaconBlockRoot: signingRoot(config.types.BeaconBlock, headBlock),
<<<<<<<
=======
}
export function getCrosslinkVote(
config: IBeaconConfig,
state: BeaconState,
shard: Shard,
targetEpoch: Epoch
): Crosslink {
const parentCrosslink = state.currentCrosslinks[shard];
return {
startEpoch: parentCrosslink.endEpoch,
endEpoch: Math.min(targetEpoch, parentCrosslink.endEpoch + config.params.MAX_EPOCHS_PER_CROSSLINK),
dataRoot: ZERO_HASH,
shard: shard,
parentRoot: hashTreeRoot(config.types.Crosslink, state.currentCrosslinks[shard])
};
>>>>>>> |
<<<<<<<
export type Settings = {
welcomeShown: boolean;
analytics: boolean;
bannerDismissed: string[];
logSizeLimit: number;
truncateRouteName: boolean;
routeMenuSize: number;
logsMenuSize: number;
};
export interface PreMigrationSettings extends Settings {
lastMigration: number;
}
export type SettingsProperties = { [T in keyof Settings]?: Settings[T] };
=======
>>>>>>>
<<<<<<<
truncateRouteName: true,
routeMenuSize: undefined,
logsMenuSize: undefined
=======
truncateRouteName: true,
fakerLocale: 'en',
fakerSeed: null
>>>>>>>
truncateRouteName: true,
routeMenuSize: undefined,
logsMenuSize: undefined,
fakerLocale: 'en',
fakerSeed: null |
<<<<<<<
import {bytes48, Slot, Shard, ValidatorIndex, BLSPubkey} from "../types";
import {RpcClient} from "./rpc";
=======
import {Shard, Slot, ValidatorIndex} from "../types";
import {Keypair} from "@chainsafe/bls-js/lib/keypair";
>>>>>>>
import {Shard, Slot, ValidatorIndex} from "../types";
import {RpcClient} from "./rpc";
import {Keypair} from "@chainsafe/bls-js/lib/keypair";
<<<<<<<
publicKey: BLSPubkey;
privateKey: bytes48[];
rpcUrl?: string;
rpc?: RpcClient;
=======
keypair: Keypair;
rpcUrl: string;
>>>>>>>
rpcUrl?: string;
rpc?: RpcClient;
keypair: Keypair |
<<<<<<<
choices: ["beacon", "validator"],
description: "Pick namespaces to expose for HTTP API",
=======
choices: ["beacon", "node", "validator"],
>>>>>>>
choices: ["beacon", "node", "validator"],
description: "Pick namespaces to expose for HTTP API", |
<<<<<<<
import defaultConf, {IBeaconNodeOptions} from "./options";
=======
>>>>>>>
<<<<<<<
this.logger = logger.child(this.conf.logger.node);
=======
this.logger = logger;
this.metrics = new BeaconMetrics(this.conf.metrics);
this.metricsServer = new HttpMetricsServer(this.conf.metrics, {metrics: this.metrics});
>>>>>>>
this.logger = logger.child(this.conf.logger.node);
this.metrics = new BeaconMetrics(this.conf.metrics);
this.metricsServer = new HttpMetricsServer(this.conf.metrics, {metrics: this.metrics});
<<<<<<<
const rpc = new SyncRpc(this.conf.sync, {
config,
db: this.db,
chain: this.chain,
network: this.network,
reps: this.reps,
logger: logger.child(this.conf.logger.network),
});
=======
>>>>>>>
<<<<<<<
logger: logger.child(this.conf.logger.network),
=======
logger: this.logger,
metrics: this.metrics,
>>>>>>>
logger: logger.child(this.conf.logger.network),
metrics: this.metrics,
<<<<<<<
rpc,
logger: logger.child(this.conf.logger.sync),
=======
rpc: syncRpc,
logger: this.logger,
>>>>>>>
rpc,
logger: logger.child(this.conf.logger.sync), |
<<<<<<<
import { EnvironmentLogs } from 'src/app/types/server.type';
import { dragulaNamespaces as DraggableContainerNames } from 'src/app/types/ui.type';
=======
import { EnvironmentLogs } from 'src/app/types/server.type.js';
import { dragulaNamespaces as DraggableContainerNames, Scroll } from 'src/app/types/ui.type.js';
import '../assets/custom_theme.js';
const platform = require('os').platform();
>>>>>>>
import { EnvironmentLogs } from 'src/app/types/server.type';
import { dragulaNamespaces as DraggableContainerNames } from 'src/app/types/ui.type';
import { Scroll } from 'src/app/types/ui.type.js';
import '../assets/custom_theme.js';
const platform = require('os').platform(); |
<<<<<<<
this.node = new BeaconNode(optionsMap);
await this.node.start();
=======
const node = new BeaconNode(optionsMap, {logger});
await node.start();
>>>>>>>
this.node = new BeaconNode(optionsMap, {logger});
await this.node.start(); |
<<<<<<<
import {RequestId,} from "../constants";
=======
import {CommitteeIndex} from "@chainsafe/eth2.0-types";
import {RequestId, SHARD_SUBNET_COUNT, SHARD_ATTESTATION_TOPIC, BLOCK_TOPIC, ATTESTATION_TOPIC} from "../constants";
>>>>>>>
import {RequestId,} from "../constants";
import {CommitteeIndex} from "@chainsafe/eth2.0-types";
<<<<<<<
=======
// gossip
export function blockTopic(encoding: string = "ssz"): string {
return `${BLOCK_TOPIC}/${encoding}`;
}
export function attestationTopic(encoding: string = "ssz"): string {
return `${ATTESTATION_TOPIC}/${encoding}`;
}
export function shardSubnetAttestationTopic(index: CommitteeIndex, encoding: string = "ssz"): string {
return `${SHARD_ATTESTATION_TOPIC.replace("{shard}", String(index % SHARD_SUBNET_COUNT))}/${encoding}`;
}
export function shardAttestationTopic(index: CommitteeIndex): string {
return SHARD_ATTESTATION_TOPIC.replace("{shard}", String(index));
}
>>>>>>> |
<<<<<<<
logger: logger || new WinstonLogger({level: LogLevel.error}),
=======
logger: logger || silentLogger,
eth1: new InteropEth1Notifier(),
>>>>>>>
logger: logger || silentLogger, |
<<<<<<<
import BN from "bn.js";
import {assert, expect} from "chai";
=======
import {assert} from "chai";
>>>>>>>
import {assert, expect} from "chai"; |
<<<<<<<
import defaultLoggerOptions, {IBeaconLoggerOptions, BeaconLoggerOptions} from "./loggerOptions";
=======
import defaultMetricsOptions, {IMetricsOptions} from "../metrics/options";
>>>>>>>
import defaultLoggerOptions, {IBeaconLoggerOptions, BeaconLoggerOptions} from "./loggerOptions";
import defaultMetricsOptions, {IMetricsOptions} from "../metrics/options";
<<<<<<<
logger: IBeaconLoggerOptions;
=======
metrics: IMetricsOptions;
>>>>>>>
logger: IBeaconLoggerOptions;
metrics: IMetricsOptions;
<<<<<<<
logger: defaultLoggerOptions,
=======
metrics: defaultMetricsOptions,
>>>>>>>
logger: defaultLoggerOptions,
metrics: defaultMetricsOptions, |
<<<<<<<
import { addEnvironmentAction, addRouteAction, addRouteResponseAction, moveEnvironmentsAction, moveRouteResponsesAction, moveRoutesAction, navigateEnvironmentsAction, navigateRoutesAction, removeEnvironmentAction, removeRouteAction, removeRouteResponseAction, setActiveEnvironmentAction, setActiveEnvironmentLogTabAction, setActiveRouteAction, setActiveRouteResponseAction, setActiveTabAction, setActiveViewAction, setInitialEnvironmentsAction, updateEnvironmentAction, updateRouteAction, updateRouteResponseAction } from 'src/app/stores/actions';
=======
import { SettingsService } from 'src/app/services/settings.service';
import { ToastsService } from 'src/app/services/toasts.service';
import { addEnvironmentAction, addRouteAction, addRouteResponseAction, moveEnvironmentsAction, moveRouteResponsesAction, moveRoutesAction, navigateEnvironmentsAction, navigateRoutesAction, removeEnvironmentAction, removeRouteAction, removeRouteResponseAction, setActiveEnvironmentAction, setActiveEnvironmentLogTabAction, setActiveRouteAction, setActiveRouteResponseAction, setActiveTabAction, setActiveViewAction, setInitialEnvironmentsAction, updateEnvironmentAction, updateRouteAction, updateRouteResponseAction, updateSettingsAction } from 'src/app/stores/actions';
>>>>>>>
import { addEnvironmentAction, addRouteAction, addRouteResponseAction, moveEnvironmentsAction, moveRouteResponsesAction, moveRoutesAction, navigateEnvironmentsAction, navigateRoutesAction, removeEnvironmentAction, removeRouteAction, removeRouteResponseAction, setActiveEnvironmentAction, setActiveEnvironmentLogTabAction, setActiveRouteAction, setActiveRouteResponseAction, setActiveTabAction, setActiveViewAction, setInitialEnvironmentsAction, updateEnvironmentAction, updateRouteAction, updateRouteResponseAction, updateSettingsAction } from 'src/app/stores/actions'; |
<<<<<<<
import {promisify} from "es6-promisify";
=======
import {serialize} from "@chainsafe/ssz";
>>>>>>>
<<<<<<<
await promisify<void, string, Uint8Array>(this.pubsub.publish.bind(this.pubsub))(
getGossipTopic(GossipEvent.VOLUNTARY_EXIT), Buffer.from(this.config.types.SignedVoluntaryExit.serialize(voluntaryExit)));
=======
await this.pubsub.publish(
getGossipTopic(GossipEvent.VOLUNTARY_EXIT), serialize(this.config.types.SignedVoluntaryExit, voluntaryExit));
>>>>>>>
await this.pubsub.publish(
getGossipTopic(GossipEvent.VOLUNTARY_EXIT), Buffer.from(this.config.types.SignedVoluntaryExit.serialize(voluntaryExit))); |
<<<<<<<
import {GossipEncoding} from "../../../../src/network/gossip/encoding";
=======
import {BeaconState} from "@chainsafe/lodestar-types";
>>>>>>>
import {GossipEncoding} from "../../../../src/network/gossip/encoding";
import {BeaconState} from "@chainsafe/lodestar-types"; |
<<<<<<<
import {IDiscv5DiscoveryInputOptions} from "@chainsafe/discv5";
import {BeaconNode} from "@chainsafe/lodestar/lib/node";
=======
import {BeaconNode} from "@chainsafe/lodestar";
>>>>>>>
import {BeaconNode} from "@chainsafe/lodestar/lib/node";
<<<<<<<
=======
import {Validator} from "@chainsafe/lodestar-validator/lib";
import {initDevChain, storeSSZState} from "@chainsafe/lodestar/lib/node/utils/state";
import {createEnr, createPeerId} from "../../config";
import {IGlobalArgs} from "../../options";
import {mkdir, YargsError} from "../../util";
import rimraf from "rimraf";
import {IDevArgs} from "./options";
>>>>>>>
<<<<<<<
import {Validator} from "@chainsafe/lodestar-validator/lib";
import {initDevState, storeSSZState} from "@chainsafe/lodestar/lib/node/utils/state";
import {BeaconDb} from "@chainsafe/lodestar/lib/db";
import {LevelDbController} from "@chainsafe/lodestar-db";
import {initStateFromAnchorState} from "@chainsafe/lodestar/lib/chain";
=======
>>>>>>>
import {Validator} from "@chainsafe/lodestar-validator/lib";
import {initDevState, storeSSZState} from "@chainsafe/lodestar/lib/node/utils/state";
import {BeaconDb} from "@chainsafe/lodestar/lib/db";
import {LevelDbController} from "@chainsafe/lodestar-db";
import {initStateFromAnchorState} from "@chainsafe/lodestar/lib/chain";
<<<<<<<
import {mergeConfigOptions} from "../../config/beacon";
import {getBeaconConfig} from "../../util";
import {getBeaconPaths} from "../beacon/paths";
=======
>>>>>>>
<<<<<<<
import {createEnr, createPeerId} from "../../network";
import {IGlobalArgs} from "../../options";
import {IDevArgs} from "./options";
=======
import {initializeOptionsAndConfig} from "../init/handler";
import {defaultRootDir} from "../../paths/global";
/* eslint-disable no-console */
>>>>>>>
import {createEnr, createPeerId} from "../../config";
import {IGlobalArgs} from "../../options";
import {IDevArgs} from "./options";
import {initializeOptionsAndConfig} from "../init/handler";
import {mkdir} from "../../util";
import {defaultRootDir} from "../../paths/global";
<<<<<<<
} else {
throw new Error("Unable to start node: no available genesis state");
=======
} else {
throw new YargsError("Must use genesisValidators or genesisStateFile arg");
>>>>>>>
} else {
throw new Error("Unable to start node: no available genesis state");
<<<<<<<
await Promise.all([
Promise.all(validators.map((v) => v.stop())),
node.close(),
async () => {
if (options.reset) {
logger.info("Cleaning db directories");
await promisify(rimraf)(chainDir);
await promisify(rimraf)(validatorsDir);
}
},
]);
=======
await Promise.all([Promise.all(validators.map((v) => v.stop())), node.stop()]);
if (args.reset) {
logger.info("Cleaning db directories");
await promisify(rimraf)(chainDir);
await promisify(rimraf)(validatorsDir);
}
>>>>>>>
await Promise.all([Promise.all(validators.map((v) => v.stop())), node.close()]);
if (args.reset) {
logger.info("Cleaning db directories");
await promisify(rimraf)(chainDir);
await promisify(rimraf)(validatorsDir);
}
<<<<<<<
if (options.startValidators) {
const range = options.startValidators.split(":").map((s) => parseInt(s));
const api = getValidatorApiClient(options.server, logger, node);
validators = Array.from({length: range[1] + range[0]}, (v, i) => i + range[0]).map((index) => {
return getInteropValidator(
node.config,
validatorsDir,
{
api,
logger,
},
index
);
});
validators.forEach((v) => v.start());
=======
await node.start();
if (args.startValidators) {
const [fromIndex, toIndex] = args.startValidators.split(":").map((s) => parseInt(s));
const api = getValidatorApiClient(args.server, logger, node);
for (let i = fromIndex; i < toIndex; i++) {
validators.push(getInteropValidator(node.config, validatorsDir, {api, logger}, i));
}
await Promise.all(validators.map((validator) => validator.start()));
>>>>>>>
if (args.startValidators) {
const [fromIndex, toIndex] = args.startValidators!.split(":").map((s) => parseInt(s));
const api = getValidatorApiClient(args.server, logger, node);
for (let i = fromIndex; i < toIndex; i++) {
validators.push(getInteropValidator(node.config, validatorsDir, {api, logger}, i));
}
await Promise.all(validators.map((validator) => validator.start())); |
<<<<<<<
// TODO: enable after we add peerbook persisting
// //refresh peer statuses
// const myStatus = await this.createStatus();
// await Promise.all(
// this.network.getPeers().map(async (peerInfo) => {
// this.reps.get(peerInfo.id.toB58String()).latestStatus =
// await this.network.reqResp.status(peerInfo, myStatus);
// }
// )
// );
this.network.on("peer:connect", this.handshake);
=======
>>>>>>>
<<<<<<<
=======
this.network.on("peer:connect", this.handshake);
const myStatus = await this.createStatus();
await Promise.all(
this.network.getPeers().map((peerInfo) =>
this.network.reqResp.status(peerInfo, myStatus)));
>>>>>>>
this.network.on("peer:connect", this.handshake);
const myStatus = await this.createStatus();
await Promise.all(
this.network.getPeers().map((peerInfo) =>
this.network.reqResp.status(peerInfo, myStatus)));
<<<<<<<
const state = await this.chain.getHeadState();
// peer is on a different fork version
return !this.config.types.Version.equals(state.fork.currentVersion, request.headForkVersion);
=======
const currentForkDigest = this.chain.currentForkDigest;
return !this.config.types.ForkDigest.equals(currentForkDigest, request.forkDigest);
>>>>>>>
const currentForkDigest = this.chain.currentForkDigest;
return !this.config.types.ForkDigest.equals(currentForkDigest, request.forkDigest);
<<<<<<<
headSlot = await this.db.chain.getChainHeadSlot();
const headBlock = await this.chain.getHeadBlock();
const state = await this.chain.getHeadState();
headRoot = this.config.types.BeaconBlockHeader.hashTreeRoot(blockToHeader(this.config, headBlock.message));
=======
const state = await this.chain.getHeadState();
headSlot = state.slot;
headRoot = this.config.types.BeaconBlockHeader.hashTreeRoot(state.latestBlockHeader);
>>>>>>>
const state = await this.chain.getHeadState();
headSlot = state.slot;
headRoot = this.config.types.BeaconBlockHeader.hashTreeRoot(state.latestBlockHeader);
<<<<<<<
headForkVersion,
=======
forkDigest: this.chain.currentForkDigest,
>>>>>>>
forkDigest: this.chain.currentForkDigest,
<<<<<<<
private handshake = async (peerInfo: PeerInfo): Promise<void> => {
const randomDelay = Math.floor(Math.random() * 5000);
await sleep(randomDelay);
if (
this.network.hasPeer(peerInfo) &&
!this.reps.get(peerInfo.id.toB58String()).latestStatus
) {
=======
private handshake = async (peerInfo: PeerInfo, direction: "inbound"|"outbound"): Promise<void> => {
if(direction === "outbound") {
>>>>>>>
private handshake = async (peerInfo: PeerInfo, direction: "inbound"|"outbound"): Promise<void> => {
if(direction === "outbound") { |
<<<<<<<
encodeKeyStub.withArgs(Bucket.deposit, Buffer.alloc(0)).returns('lower');
encodeKeyStub.withArgs(Bucket.deposit + 1, Buffer.alloc(0)).returns('higher');
dbStub.search.resolves([serialize(generateDeposit(), Deposit)]);
=======
encodeKeyStub.withArgs(Bucket.genesisDeposit, Buffer.alloc(0)).returns('lower');
encodeKeyStub.withArgs(Bucket.genesisDeposit + 1, Buffer.alloc(0)).returns('higher');
dbStub.search.resolves([serialize(generateDeposit(), config.types.Deposit)]);
>>>>>>>
encodeKeyStub.withArgs(Bucket.deposit, Buffer.alloc(0)).returns('lower');
encodeKeyStub.withArgs(Bucket.deposit + 1, Buffer.alloc(0)).returns('higher');
dbStub.search.resolves([serialize(generateDeposit(), config.types.Deposit)]); |
<<<<<<<
import {AttestationOperations, OpPool} from "../../../../../src/opPool";
import {generateEmptyBlock} from "../../../../utils/block";
import {expect} from "chai";
import {generateState} from "../../../../utils/state";
=======
import {OpPool} from "../../../../../src/opPool";
>>>>>>>
import {OpPool} from "../../../../../src/opPool";
import {AttestationOperations, OpPool} from "../../../../../src/opPool";
import {generateEmptyBlock} from "../../../../utils/block";
import {expect} from "chai";
import {generateState} from "../../../../utils/state";
<<<<<<<
opStub.attestations = sandbox.createStubInstance(AttestationOperations);
validatorApi = new ValidatorApi({}, {chain: chainStub, db: dbStub, opPool: opStub, eth1: eth1Stub});
=======
validatorApi = new ValidatorApi({}, {config, chain: chainStub, db: dbStub, opPool: opStub, eth1: eth1Stub});
>>>>>>>
opStub.attestations = sandbox.createStubInstance(AttestationOperations);
validatorApi = new ValidatorApi({}, {config, chain: chainStub, db: dbStub, opPool: opStub, eth1: eth1Stub}); |
<<<<<<<
=======
let loggingOptions;
if (options.loggingLevel) {
loggingOptions = {
loggingLevel: LogLevel[options.loggingLevel],
};
}else {
loggingOptions = {
loggingLevel: LogLevel.DEFAULT,
};
}
logger.setLogLevel(loggingOptions.loggingLevel);
>>>>>>>
<<<<<<<
this.node = new BeaconNode(conf, {config,logger});
=======
this.node = new BeaconNode(conf, {config, logger, loggingOptions});
>>>>>>>
this.node = new BeaconNode(conf, {config,logger});
<<<<<<<
conf.validator, {
config: config,
logger,
}
=======
conf.validator, {
config: config,
logger: new WinstonLogger({
loggingLevel: loggingOptions.loggingLevel,
loggingModule: Module.VALIDATOR,
}),
loggingOptions: loggingOptions,
}
>>>>>>>
conf.validator, {
config: config,
logger,
} |
<<<<<<<
import {SyncRpc} from "../network/libp2p/syncRpc";
=======
import {ILoggingOptions} from "../logger/interface";
import {Module} from "../logger/abstract";
>>>>>>>
import {SyncRpc} from "../network/libp2p/syncRpc";
import {Module} from "../logger/abstract";
<<<<<<<
public constructor(opts: Partial<IBeaconNodeOptions>, {config, logger}:
{config: IBeaconConfig; logger?: ILogger}) {
=======
public constructor(opts: Partial<IBeaconNodeOptions>, {config, logger, loggingOptions}:
{config: IBeaconConfig; logger: ILogger; loggingOptions: ILoggingOptions}) {
>>>>>>>
public constructor(opts: Partial<IBeaconNodeOptions>, {config, logger}:
{config: IBeaconConfig; logger?: ILogger}) {
<<<<<<<
this.logger = logger || new WinstonLogger();
=======
this.logger = logger;
this.loggingOptions = loggingOptions;
>>>>>>>
this.logger = logger || new WinstonLogger();
<<<<<<<
const rpc = new SyncRpc(this.conf.sync, {
config,
db: this.db,
chain: this.chain,
network: this.network,
reps: this.reps,
logger,
});
=======
>>>>>>>
const rpc = new SyncRpc({
...this.conf.sync,
loggingLevel: this.conf.loggingOptions[Module.NETWORK],
}, {
config,
db: this.db,
chain: this.chain,
network: this.network,
reps: this.reps,
logger,
});
<<<<<<<
logger,
=======
logger: new WinstonLogger({
loggingLevel: this.loggingOptions.loggingLevel,
loggingModule: Module.NETWORK,
}),
>>>>>>>
logger,
<<<<<<<
rpc,
logger,
=======
logger: new WinstonLogger({
loggingLevel: this.loggingOptions.loggingLevel,
loggingModule: Module.SYNC,
}),
>>>>>>>
rpc,
logger, |
<<<<<<<
import BN from "bn.js";
import {
BeaconState,
BLSSignature,
CommitteeIndex,
Epoch,
Slot,
uint64,
Validator,
ValidatorIndex,
} from "@chainsafe/eth2.0-types";
=======
import {BeaconState, Epoch, uint64, Validator, ValidatorIndex,} from "@chainsafe/eth2.0-types";
>>>>>>>
import {
BeaconState,
BLSSignature,
CommitteeIndex,
Epoch,
Slot,
uint64,
Validator,
ValidatorIndex,
} from "@chainsafe/eth2.0-types"; |
<<<<<<<
=======
"SignedBeaconBlockHeader",
"FFGData",
>>>>>>>
"SignedBeaconBlockHeader", |
<<<<<<<
for (const type in operations) {
types[type] = operations[type](types, params);
}
for (const type in block) {
types[type] = block[type](types, params);
}
for (const type in state) {
types[type] = state[type](types, params);
}
for (const type in validator) {
types[type] = validator[type](types, params);
}
for (const type in wire) {
types[type] = wire[type](types, params);
}
*/
types.phase1 = createPhase1SSTTypes(params, types);
types.lightclient = createLightClientTypes(params, types);
=======
>>>>>>>
types.phase1 = createPhase1SSTTypes(params, types);
types.lightclient = createLightClientTypes(params, types); |
<<<<<<<
'use strict';
=======
import {TCP} from "libp2p-tcp";
import {Mplex} from "libp2p-mplex";
import {Bootstrap} from "libp2p-bootstrap";
import {WStar} from "libp2p-webrtc-star";
import {KadDHT} from "libp2p-kad-dht";
import {PeerInfo} from "peer-info";
import {defaultsDeep} from "@nodeutils/defaults-deep";
import {promisify} from "promisify-es6";
import LibP2p from "libp2p";
import * as FloodSub from "libp2p-floodsub";
import {LodestarNodeOpts} from "./node";
>>>>>>>
<<<<<<<
import Libp2p from "libp2p";
import TCP from "libp2p-tcp";
import Mplex from "libp2p-mplex";
import Bootstrap from "libp2p-bootstrap";
import WStar from "libp2p-webrtc-star";
import KadDHT from "libp2p-kad-dht";
import defaultsDeep from "@nodeutils/defaults-deep";
class LodestarNode extends Libp2p {
public constructor(_options: Libp2p.OptionsConfig) {
=======
export class LodestarNode2 extends LibP2p {
constructor(_options: LodestarNodeOpts) {
>>>>>>>
<<<<<<<
=======
static async createNode (callback) {
var node: LibP2p;
const peerInfo = await promisify(PeerInfo.create(callback));
// Opens a tcp socket at port 9000. Will change
peerInfo.multiaddrs.add('ip4/0.0.0.0/tcp/9000');
peerInfo.multiaddrs.add('ip4/0.0.0.0/ws');
node = new LodestarNode2({
peerInfo
});
node.start(callback);
node.pubsub = new FloodSub(node);
node.pubsub.start((err) => {
if (err) {
throw new Error('PubSub failed to start.');
}
});
}
>>>>>>> |
<<<<<<<
import {BlockRepository, StateRepository} from "../../../src/db/api/beacon/repositories";
import {WinstonLogger} from "@chainsafe/lodestar-utils/lib/logger";
import {generateEmptySignedBlock} from "../../utils/block";
import {generateEmptyAttestation} from "../../utils/attestation";
import {generateState} from "../../utils/state";
import {generateValidators} from "../../utils/validator";
import {fail} from "assert";
import {Checkpoint} from "@chainsafe/lodestar-types";
=======
import { BlockRepository } from "../../../src/db/api/beacon/repositories";
import { WinstonLogger } from "@chainsafe/lodestar-utils/lib/logger";
import { generateEmptySignedBlock } from "../../utils/block";
import { generateEmptyAttestation } from "../../utils/attestation";
import { generateState } from "../../utils/state";
import { generateValidators } from "../../utils/validator";
import { fail } from "assert";
import { StubbedBeaconDb } from "../../utils/stub";
>>>>>>>
import { BlockRepository } from "../../../src/db/api/beacon/repositories";
import { WinstonLogger } from "@chainsafe/lodestar-utils/lib/logger";
import { generateEmptySignedBlock } from "../../utils/block";
import { generateEmptyAttestation } from "../../utils/attestation";
import { generateState } from "../../utils/state";
import { generateValidators } from "../../utils/validator";
import { fail } from "assert";
import { StubbedBeaconDb } from "../../utils/stub";
<<<<<<<
dbStub.state.get.resolves(state);
forkChoiceStub.getJustified.returns({} as Checkpoint);
=======
dbStub.stateCache.get.resolves(state);
forkChoiceStub.getJustified.returns({});
>>>>>>>
dbStub.stateCache.get.resolves(state);
forkChoiceStub.getJustified.returns({} as Checkpoint);
<<<<<<<
dbStub.state.get.resolves(state);
forkChoiceStub.getJustified.returns({} as Checkpoint);
=======
dbStub.stateCache.get.resolves(state);
forkChoiceStub.getJustified.returns({})
>>>>>>>
dbStub.stateCache.get.resolves(state);
forkChoiceStub.getJustified.returns({} as Checkpoint)
<<<<<<<
state.genesisTime = state.genesisTime - config.params.SECONDS_PER_SLOT;
dbStub.state.getJustified.resolves(state);
=======
state.genesisTime = state.genesisTime - config.params.SECONDS_PER_SLOT
dbStub.stateCache.get.resolves(state);
>>>>>>>
state.genesisTime = state.genesisTime - config.params.SECONDS_PER_SLOT
dbStub.stateCache.getJustified.resolves(state); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.