_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4500
|
getSnippetsCompletions
|
train
|
function getSnippetsCompletions(editor, prefix) {
const syntax = detectSyntax(editor);
if (isStylesheet(syntax)) {
return getStylesheetSnippetsCompletions(editor, prefix);
} else
|
javascript
|
{
"resource": ""
}
|
q4501
|
train
|
function() {
this.$el.addClass('timeline-me-container');
if(this.settings.orientation == 'horizontal') {
this.$el.addClass('timeline-me-horizontal');
if(this.settings.scrollBar == false)
this.$el.addClass('no-x-scroll');
} else {
this.$el.addClass('timeline-me-vertical');
if(this.settings.scrollBar == false)
this.$el.addClass('no-y-scroll');
}
var timelineWrapper = $('<div class="timeline-me-wrapper">');
this.$el.append(timelineWrapper);
var track = $('<div class="timeline-me-track">');
timelineWrapper.append(track);
if(this.settings.scrollZones == true) {
var leftScroll = $('<div class="timeline-me-leftscroll">');
var rightScroll = $('<div class="timeline-me-rightscroll">');
timelineWrapper.before(leftScroll);
timelineWrapper.after(rightScroll);
bindScrollTo(leftScroll, rightScroll, timelineWrapper);
}
if(this.settings.scrollArrows == true) {
var leftScroll;
var rightScroll;
if(this.settings.leftArrowElm == undefined) {
leftScroll = $('<span class="timeline-me-leftarrow">');
} else {
leftScroll = $('<span class="timeline-me-leftarrow-c">');
leftScroll.html(this.settings.leftArrowElm);
}
if(this.settings.rightArrowElm == undefined) {
rightScroll = $('<span class="timeline-me-rightarrow">');
} else {
rightScroll = $('<span class="timeline-me-rightarrow-c">');
rightScroll.html(this.settings.rightArrowElm);
}
timelineWrapper.before(leftScroll);
timelineWrapper.after(rightScroll);
bindScrollTo(leftScroll, rightScroll, timelineWrapper);
}
if(this.settings.items && this.settings.items.length > 0) {
|
javascript
|
{
"resource": ""
}
|
|
q4502
|
train
|
function(items) {
var hasRelativePositioning = hasNumberProperty(items, 'relativePosition');
if(hasRelativePositioning) {
items.sort(function(a, b) {
|
javascript
|
{
"resource": ""
}
|
|
q4503
|
train
|
function(items) {
var hasRelativePositioning = hasNumberProperty(items, 'relativePosition');
for(var i = 0; i < items.length; i++) {
if(i == items.length - 1)
items[i].diffWithNextRelativePos = undefined;
|
javascript
|
{
"resource": ""
}
|
|
q4504
|
train
|
function(items) {
if(!items)
return;
var positions;
if(this.settings.orientation == 'horizontal')
positions = ['top', 'bottom'];
else
positions = ['left', 'right'];
for(var i = 0; i < this.content.length; i++) {
if(this.content[i].forcePosition && positions.indexOf(this.content[i].forcePosition) >= 0) {
this.content[i].position = this.content[i].forcePosition;
} else if(!this.content[i].position) {
switch(this.content[i].type) {
case 'milestone':
if(this.settings.orientation == 'horizontal')
this.content[i].position = 'top';
else
this.content[i].position = 'right';
break;
case 'smallItem':
if(i == 0)
this.content[i].position = this.settings.orientation == 'horizontal' ? 'top' : 'left';
else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'top')
this.content[i].position = 'bottom';
else if(this.settings.orientation == 'horizontal' && this.content[i - 1].position == 'bottom')
this.content[i].position = 'top';
|
javascript
|
{
"resource": ""
}
|
|
q4505
|
train
|
function(item) {
if(!item || (item && !item.element) || (item && !item.position))
return;
switch(item.position) {
case 'left':
item.element
.removeClass('timeline-me-top')
.removeClass('timeline-me-right')
.removeClass('timeline-me-bottom')
.addClass('timeline-me-left');
break;
case 'top':
item.element
.removeClass('timeline-me-left')
.removeClass('timeline-me-right')
.removeClass('timeline-me-bottom')
.addClass('timeline-me-top');
break;
case 'right':
item.element
.removeClass('timeline-me-top')
|
javascript
|
{
"resource": ""
}
|
|
q4506
|
train
|
function(item) {
var itemElm;
switch(item.type) {
case 'milestone':
itemElm = this._buildMilestoneElement(item);
break;
case 'smallItem':
itemElm = this._buildSmallItemElement(item);
break;
case 'bigItem':
itemElm = this._buildBigItemElement(item);
break;
}
item.element = itemElm;
this._refreshItemPosition(item);
|
javascript
|
{
"resource": ""
}
|
|
q4507
|
train
|
function(item) {
if(!item || !item.element)
return;
var pixelsRegex = /[0-9]+px$/;
// Following wrapper are only used in horizontal mode, in order to correctly display bigItems (with table display)
var itemWrapper = $('<div class="timeline-me-item-wrapper">');
var labelWrapper = $('<div class="timeline-me-label-wrapper">');
var contentWrapper = $('<div class="timeline-me-content-wrapper">');
var labelElm = $('<div class="timeline-me-label">');
item.labelElement = labelElm;
if(this.settings.orientation == 'horizontal' && this.settings.labelDimensionValue && pixelsRegex.test(this.settings.labelDimensionValue)) {
labelElm.css('width', this.settings.labelDimensionValue);
}
var pictoElm = $('<div class="timeline-me-picto">');
item.pictoElement = pictoElm;
labelWrapper.append(labelElm);
itemWrapper.append(labelWrapper);
if(item.type == 'smallItem' || item.type == 'bigItem') {
var contentContainer = $('<div class="timeline-me-content-container">');
var contentElm = $('<div class="timeline-me-content"></div>');
contentContainer.append(contentElm);
if(this.settings.orientation == 'horizontal' && this.settings.contentDimensionValue && pixelsRegex.test(this.settings.contentDimensionValue)) {
contentElm.css('width', this.settings.contentDimensionValue);
}
|
javascript
|
{
"resource": ""
}
|
|
q4508
|
train
|
function(item) {
if(!item || !item.type || !item.element)
return false;
switch(item.type) {
case 'milestone':
return (item.element.hasClass('timeline-milestone'));
break;
case 'smallItem':
return (item.element.hasClass('timeline-smallitem'));
break;
|
javascript
|
{
"resource": ""
}
|
|
q4509
|
train
|
function(leftScrollElm, rightScrollElm, elmToScroll, scrollSpeed) {
var scrollSpeed = scrollSpeed ? scrollSpeed : 5;
leftScrollElm.on('mouseenter', function() {
var timer = setInterval(function() {
elmToScroll.scrollLeft(elmToScroll.scrollLeft() - scrollSpeed);
}, 20);
leftScrollElm.on('mouseleave', function() {
clearInterval(timer);
});
});
rightScrollElm.on('mouseenter', function()
|
javascript
|
{
"resource": ""
}
|
|
q4510
|
train
|
function(element) {
if(!element) return;
var children = element.children();
if(children.length <= 0) return;
var totalWidth = 0;
for(var i = 0; i < children.length; i++) {
|
javascript
|
{
"resource": ""
}
|
|
q4511
|
train
|
function(element, args) {
if(!args)
args = {};
var refreshDelay = args.refreshDelay ? args.refreshDelay : 500;
var previousHeight = args.previousHeight;
var level = args.level ? args.level : 0;
var ret = new $.Deferred();
var elmHeight;
if(element)
elmHeight = element[0].getBoundingClientRect().height;
if(elmHeight && (!previousHeight || previousHeight != elmHeight)) {
ret.resolve(elmHeight, previousHeight, level);
} else {
args.previousHeight = elmHeight;
setTimeout(function () {
|
javascript
|
{
"resource": ""
}
|
|
q4512
|
train
|
function(items, propertyName) {
if(!items) return false;
var hasProperty = true;
for(var i = 0; i < items.length; i++) {
|
javascript
|
{
"resource": ""
}
|
|
q4513
|
train
|
function(items, propertyName) {
if(!items) return false;
var maxProperty;
for(var i = 0; i < items.length; i++) {
if(maxProperty == undefined)
|
javascript
|
{
"resource": ""
}
|
|
q4514
|
train
|
function(event) {
/**
* Set by the `selectionModelIgnore` directive
*
* Use `selectionModelIgnore` to cause `selectionModel` to selectively
* ignore clicks on elements. This is useful if you want to manually
* change a selection when certain things are clicked.
*/
if(event.selectionModelIgnore || (event.originalEvent && event.originalEvent.selectionModelIgnore)) {
return;
}
// Never handle a single click twice.
if(event.selectionModelClickHandled || (event.originalEvent && event.originalEvent.selectionModelClickHandled)) {
return;
}
event.selectionModelClickHandled = true;
if(event.originalEvent) {
event.originalEvent.selectionModelClickHandled = true;
}
var isCtrlKeyDown = event.ctrlKey || event.metaKey || isModeAdditive
, isShiftKeyDown = event.shiftKey
, target = event.target || event.srcElement
, isCheckboxClick = 'checkbox' === smType &&
'INPUT' === target.tagName &&
'checkbox' === target.type;
/**
* Guard against label + checkbox clicks
*
* Clicking a label will cause a click event to also be fired on the
* associated input element. If that input is nearby (i.e. under the
* selection model element) we'll suppress the click on the label to
* avoid duplicate click events.
*/
if('LABEL' === target.tagName) {
var labelFor = angular.element(target).attr('for');
if(labelFor) {
var childInputs = element[0].getElementsByTagName('INPUT'), ix;
for(ix = childInputs.length; ix--;) {
if(childInputs[ix].id === labelFor) {
return;
}
}
} else if(target.getElementsByTagName('INPUT').length) {
// Label has a nested input element, we'll handle the click on
// that element
return;
|
javascript
|
{
"resource": ""
}
|
|
q4515
|
train
|
function() {
if(angular.isArray(selectedItemsList)) {
var ixSmItem = selectedItemsList.indexOf(smItem);
if(smItem[selectedAttribute]) {
if(-1 === ixSmItem) {
selectedItemsList.push(smItem);
}
} else {
|
javascript
|
{
"resource": ""
}
|
|
q4516
|
runBeforeHooks
|
train
|
function runBeforeHooks(req, method, config, conn, cb){
var httpMethod = conn.connection.methods[method];
async.eachSeries(conn.connection.hooks.before, function (hook, nextHook) {
hook(req, httpMethod, config, conn, function (err) {
if(err) {
return nextHook(err);
}
if(!_.isEmpty(config.endpoint) && typeof req
|
javascript
|
{
"resource": ""
}
|
q4517
|
runAfterHooks
|
train
|
function runAfterHooks(connection, err, res, cb){
async.eachSeries(connection.hooks.after, function (hook,
|
javascript
|
{
"resource": ""
}
|
q4518
|
setRequestHeaders
|
train
|
function setRequestHeaders(connection, req) {
if(_.isObject(connection.headers)){
|
javascript
|
{
"resource": ""
}
|
q4519
|
handleResponse
|
train
|
function handleResponse(connection, err, res, cb) {
runAfterHooks(connection, err, res, function (errFromHooks) {
if(errFromHooks) {
return cb(errFromHooks, null);
|
javascript
|
{
"resource": ""
}
|
q4520
|
getResponseHandler
|
train
|
function getResponseHandler(connection, cb) {
return function (err, res) {
if (res && !err) {
err =
|
javascript
|
{
"resource": ""
}
|
q4521
|
castRecordDateFields
|
train
|
function castRecordDateFields(record) {
_.forEach(record, function (value,
|
javascript
|
{
"resource": ""
}
|
q4522
|
processResponse
|
train
|
function processResponse(err, res, cb){
if(!err) {
if(Array.isArray(res.body)){
res.body.forEach(function (body) {
castRecordDateFields(body);
});
|
javascript
|
{
"resource": ""
}
|
q4523
|
train
|
function (path, query, cb) {
var httpMethod = 'get',
config = User.datastore.config,
endpoint = url.format({
host: config.host,
pathname: path,
|
javascript
|
{
"resource": ""
}
|
|
q4524
|
train
|
function(callback) {
var stream = this;
// We don't need to write an empty file.
if (collectedErrors.length === 0) {
callback();
return;
}
var report = collectedErrors.join('\n\n').trim() + '\n';
// Write the error output to the defined file
fs.writeFile(options.path, report, function(err) {
if (err) {
stream.emit('error', new gutil.PluginError('gulp-phpcs', err));
callback();
return;
}
// Build console info message
var message = util.format(
|
javascript
|
{
"resource": ""
}
|
|
q4525
|
Rejson
|
train
|
function Rejson(opts) {
// Instantiation
if (!(this instanceof Rejson)) {
return new Rejson(opts);
}
EventEmitter.call(this);
opts = opts || {};
_.defaults(opts, Rejson.defaultOptions);
var redis = new Redis(opts);
// Add new commands
this.cmds = {};
for (var i in Rejson.commands) {
var command = Rejson.commands[i];
var cmd = redis.createBuiltinCommand(command);
|
javascript
|
{
"resource": ""
}
|
q4526
|
train
|
function(file, enc, callback) {
var report = file.phpcsReport || {};
if (report.error) {
phpcsError = true;
if (options.failOnFirst) {
var errorMessage = 'PHP Code Sniffer failed' +
' on ' + chalk.magenta(file.path);
this.emit('error', new gutil.PluginError('gulp-phpcs', errorMessage));
callback();
|
javascript
|
{
"resource": ""
}
|
|
q4527
|
train
|
function(callback) {
// We have to check "failOnFirst" flag to make sure we did not
// throw the error before.
if (phpcsError && !options.failOnFirst) {
this.emit('error', new gutil.PluginError(
|
javascript
|
{
"resource": ""
}
|
|
q4528
|
includes
|
train
|
function includes(array, element) {
if (!array) {
return false;
}
const length = array.length;
for (let i = 0; i < length; i++) {
|
javascript
|
{
"resource": ""
}
|
q4529
|
getMyIPs
|
train
|
function getMyIPs() {
var ips = [];
var ifs = os.networkInterfaces();
|
javascript
|
{
"resource": ""
}
|
q4530
|
train
|
function (contractAddress) {
// Helpful while deployement, since ENV variables are not set at that time
contractAddress = contractAddress || openSTUtilityContractAddr;
const oThis = this;
oThis.contractAddress = contractAddress;
|
javascript
|
{
"resource": ""
}
|
|
q4531
|
train
|
function (message) {
var newMessage = "";
if (requestNamespace) {
if (requestNamespace.get('reqId')) {
newMessage += "[" + requestNamespace.get('reqId') + "]";
}
|
javascript
|
{
"resource": ""
}
|
|
q4532
|
train
|
function (params) {
const oThis = this;
params = params || {};
oThis.erc20Address = params.erc20_address;
oThis.approverAddress = params.approver_address;
oThis.approverPassphrase = params.approver_passphrase;
oThis.approveeAddress =
|
javascript
|
{
"resource": ""
}
|
|
q4533
|
train
|
function (params) {
const oThis = this
;
params = params || {};
params.options = params.options || {};
if (params.options.returnType === 'txReceipt')
|
javascript
|
{
"resource": ""
}
|
|
q4534
|
train
|
async function (toApproveAmount) {
const oThis = this
;
const approveRsp = await simpleToken.approve(
stakerAddress,
stakerPassphrase,
|
javascript
|
{
"resource": ""
}
|
|
q4535
|
train
|
function () {
return simpleToken.balanceOf(stakerAddress)
.then(function (result) {
|
javascript
|
{
"resource": ""
}
|
|
q4536
|
train
|
function (params) {
this.contractAddress = params.contractAddress;
this.currContract = new
|
javascript
|
{
"resource": ""
}
|
|
q4537
|
train
|
function () {
const oThis = this;
const callback = async function (response) {
if (response.isFailure()) {
return
|
javascript
|
{
"resource": ""
}
|
|
q4538
|
train
|
function (methodName, args) {
const oThis = this
, btAddress = oThis.contractAddress
, scope = oThis.currContract.methods
, transactionObject = scope[methodName].apply(scope, (args || []))
, encodeABI = transactionObject.encodeABI()
, transactionOutputs = contractInteractHelper.getTransactionOutputs(transactionObject)
, resultData = {};
return contractInteractHelper.call(web3Provider, btAddress, encodeABI, {}, transactionOutputs)
.then(function (decodedResponse) {
return decodedResponse[0];
})
.then(function (response) {
resultData[methodName] = response;
return responseHelper.successWithData(resultData);
})
|
javascript
|
{
"resource": ""
}
|
|
q4539
|
train
|
function (contractAddress) {
this.contractAddress = contractAddress;
if (this.contractAddress) {
stPrimeContractObj.options.address
|
javascript
|
{
"resource": ""
}
|
|
q4540
|
train
|
async function () {
const oThis = this
, callMethodResult = await oThis._callMethod('uuid')
, response
|
javascript
|
{
"resource": ""
}
|
|
q4541
|
train
|
async function (senderName, customOptions) {
const oThis = this
, encodedABI = stPrimeContractObj.methods.initialize().encodeABI()
, stPrimeTotalSupplyInWei = web3Provider.utils.toWei(coreConstants.OST_UTILITY_STPRIME_TOTAL_SUPPLY, "ether");
var options = {gasPrice: UC_GAS_PRICE, value: stPrimeTotalSupplyInWei, gas: UC_GAS_LIMIT};
|
javascript
|
{
"resource": ""
}
|
|
q4542
|
train
|
async function (senderAddress, senderPassphrase, beneficiaryAddress) {
const oThis = this
, encodedABI = oThis.currContract.methods.claim(beneficiaryAddress).encodeABI()
, currentGasPrice = new BigNumber(await web3Provider.eth.getGasPrice())
;
const estimateGasObj = new EstimateGasKlass({
contract_name: stPrimeContractName,
contract_address: oThis.contractAddress,
chain: 'utility',
sender_address: senderAddress,
method_name: 'claim',
method_arguments: [beneficiaryAddress]
|
javascript
|
{
"resource": ""
}
|
|
q4543
|
train
|
function (params) {
const oThis = this
;
params = params || {};
oThis.transactionHash = params.transaction_hash;
|
javascript
|
{
"resource": ""
}
|
|
q4544
|
train
|
function (contractAddress) {
// Helpful while deployement, since ENV variables are not set at that time
contractAddress = contractAddress || openSTValueContractAddr;
this.contractAddress = contractAddress;
openSTValueContractObj.options.address = contractAddress;
|
javascript
|
{
"resource": ""
}
|
|
q4545
|
train
|
function (contractAddress) {
const oThis = this;
oThis.contractAddress = contractAddress;
utilityRegistrarContractObj.options.address =
|
javascript
|
{
"resource": ""
}
|
|
q4546
|
train
|
function() {
return new Promise(function(onResolve, onReject) {
const getBalance = async function(){
const getSTPBalanceResponse = await fundManager.getSTPrimeBalanceOf(utilityChainOwnerAddr);
if(getSTPBalanceResponse.isSuccess() && (new
|
javascript
|
{
"resource": ""
}
|
|
q4547
|
train
|
function (params) {
const oThis = this
;
oThis.contractName = params.contract_name;
oThis.contractAddress = params.contract_address;
oThis.chain = params.chain;
oThis.senderAddress =
|
javascript
|
{
"resource": ""
}
|
|
q4548
|
train
|
function (web3Provider, result) {
return new Promise(function (onResolve,
|
javascript
|
{
"resource": ""
}
|
|
q4549
|
train
|
function (web3Provider, result) {
return new Promise(function (onResolve, onReject) {
|
javascript
|
{
"resource": ""
}
|
|
q4550
|
train
|
function (web3Provider, transactionHash) {
return new Promise(function (onResolve, onReject) {
// number of times it will attempt to fetch
var maxAttempts = 50;
// time interval
const timeInterval = 15000;
var getReceipt = async function () {
if (maxAttempts > 0) {
const receipt = await web3Provider.eth.getTransactionReceipt(transactionHash);
if (receipt) {
return onResolve(responseHelper.successWithData({receipt: receipt}));
} else {
maxAttempts--;
setTimeout(getReceipt, timeInterval);
|
javascript
|
{
"resource": ""
}
|
|
q4551
|
train
|
function (params) {
const oThis = this
;
params = params || {};
|
javascript
|
{
"resource": ""
}
|
|
q4552
|
train
|
function () {
const oThis = this
, promiseArray = [];
return new Promise(async function (onResolve, onReject) {
for (var chain in setupConfig.chains) {
|
javascript
|
{
"resource": ""
}
|
|
q4553
|
train
|
function(chain) {
const retryAttempts = 100
, timerInterval = 5000
, chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0}
, provider = (chain == 'utility' ? web3UtilityProvider : web3ValueProvider)
;
return new Promise(function (onResolve, onReject) {
chainTimer['timer'] = setInterval(function () {
if (chainTimer['retryCounter'] <= retryAttempts) {
provider.eth.getBlockNumber(function (err, blocknumber) {
if (err) {
} else {
if (chainTimer['blockNumber']!=0 && chainTimer['blockNumber']!=blocknumber) {
logger.info("* Geth Checker - "
|
javascript
|
{
"resource": ""
}
|
|
q4554
|
train
|
async function () {
const oThis = this
, servicesList = [];
var cmd = "ps aux | grep dynamo | grep -v grep | tr -s ' ' | cut -d ' ' -f2";
let processId = shell.exec(cmd).stdout;
if (processId == '') {
// Start Dynamo DB in openST env
let startDynamo = new StartDynamo();
await startDynamo.perform();
}
// Start Value Chain
logger.step("** Start value chain");
var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-value.sh";
servicesList.push(cmd);
oThis._asyncCommand(cmd);
// Start Utility Chain
logger.step("** Start utility chain");
var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-utility.sh";
servicesList.push(cmd);
oThis._asyncCommand(cmd);
// Wait for 5 seconds for geth to come up
const sleep = function(ms) {
return new Promise(function(resolve) {setTimeout(resolve, ms)});
};
await sleep(5000);
// Check geths are up and running
logger.step("** Check chains are up and responding");
const statusObj = new platformStatus()
, servicesResponse = await statusObj.perform();
if (servicesResponse.isFailure()) {
logger.error("* Error ", servicesResponse);
process.exit(1);
} else {
logger.info("* Value Chain:", servicesResponse.data.chain.value, "Utility Chain:", servicesResponse.data.chain.utility);
}
// Start intercom processes in openST env
logger.step("** Start stake and mint inter-communication process");
var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-stake_and_mint.sh";
servicesList.push(cmd);
oThis._asyncCommand(cmd);
logger.step("** Start redeem and unstake inter-communication process");
var cmd = "sh " + setupHelper.binFolderAbsolutePath() + "/run-redeem_and_unstake.sh";
servicesList.push(cmd);
oThis._asyncCommand(cmd);
logger.step("** Start register branded token inter-communication process");
|
javascript
|
{
"resource": ""
}
|
|
q4555
|
train
|
function(purpose) {
const oThis = this;
// Create empty ENV file
fileManager.touch(setupConfig.env_vars_file, '#!/bin/sh');
fileManager.append(setupConfig.env_vars_file, '#################');
fileManager.append(setupConfig.env_vars_file, '# opentST Platform Environment file');
fileManager.append(setupConfig.env_vars_file, '#################');
logger.info('* writing env basic, geth, cache and addresses related
|
javascript
|
{
"resource": ""
}
|
|
q4556
|
train
|
function (purpose) {
const oThis = this;
for (var chain in setupConfig.chains) {
// Add comment to ENV
|
javascript
|
{
"resource": ""
}
|
|
q4557
|
train
|
function () {
const oThis = this;
// Add comment to ENV
fileManager.append(setupConfig.env_vars_file, "\n# Contracts");
for (var
|
javascript
|
{
"resource": ""
}
|
|
q4558
|
train
|
function () {
const oThis = this
, clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)/
;
Object.keys(require.cache).forEach(function (key) {
if (key.search(clearCacheOfExpr) !== -1) {
delete require.cache[key];
}
});
|
javascript
|
{
"resource": ""
}
|
|
q4559
|
train
|
async function () {
const oThis = this
;
try {
const highestBlock = await this.getChainHighestBlock();
// return if nothing more to do.
if (highestBlock - 6 <= oThis.lastProcessedBlock) return oThis.schedule();
// consider case in which last block was not processed completely
oThis.fromBlock = oThis.snmData.lastProcessedBlock + 1;
oThis.toBlock = highestBlock - 6;
const events = await oThis.completeContract.getPastEvents(
|
javascript
|
{
"resource": ""
}
|
|
q4560
|
train
|
function () {
const oThis = this;
process.on('SIGINT', function () {
logger.info("Received SIGINT, cancelling block scaning");
oThis.interruptSignalObtained = true;
});
|
javascript
|
{
"resource": ""
}
|
|
q4561
|
train
|
async function (events) {
const oThis = this
, promiseArray = []
;
// nothing to do
if (!events || events.length === 0) {
oThis.updateIntercomDataFile();
return Promise.resolve();
}
//TODO: last processed transaction index.
for (var i = 0; i < events.length; i++) {
const eventObj = events[i]
, j = i
;
// await oThis.processEventObj(eventObj);
if (oThis.parallelProcessingAllowed()) {
promiseArray.push(new Promise(function (onResolve, onReject) {
setTimeout(function () {
oThis.processEventObj(eventObj)
.then(onResolve)
.catch(function (error) {
logger.error('##### inside catch block #####: ', error);
return onResolve();
});
}, (j * 1000 + 100));
}));
|
javascript
|
{
"resource": ""
}
|
|
q4562
|
train
|
function () {
const oThis = this
;
oThis.snmData.lastProcessedBlock = oThis.toBlock;
fs.writeFileSync(
oThis.filePath,
JSON.stringify(oThis.snmData),
function (err) {
if (err)
logger.error(err);
|
javascript
|
{
"resource": ""
}
|
|
q4563
|
train
|
async function () {
const oThis = this
, statusResponse = {chain: {value: false, utility: false}};
// check geth status
for (var chainName in statusResponse.chain) {
var
|
javascript
|
{
"resource": ""
}
|
|
q4564
|
train
|
function (chain) {
const web3Provider = web3ProviderFactory.getProvider(chain, web3ProviderFactory.typeWS)
, retryAttempts = 100
, timerInterval = 5000
, chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0}
;
if (!web3Provider) {
// this is a error scenario.
let errObj = responseHelper.error({
internal_error_identifier: 's_u_ps_1',
api_error_identifier: 'invalid_chain',
error_config: basicHelper.fetchErrorConfig()
});
return Promise.reject(errObj);
}
return new Promise(function (onResolve, onReject) {
chainTimer['timer'] = setInterval(function () {
if (chainTimer['retryCounter'] <= retryAttempts) {
web3Provider.eth.getBlockNumber(function (err, blocknumber) {
if (err) {
logger.error("Geth Checker - " + chain + " fetch block number failed.", err);
chainTimer['retryCounter']++;
} else {
if (chainTimer['blockNumber'] != 0 && chainTimer['blockNumber'] != blocknumber) {
clearInterval(chainTimer['timer']);
onResolve(responseHelper.successWithData({}));
|
javascript
|
{
"resource": ""
}
|
|
q4565
|
train
|
function() {
const oThis = this;
// Remove old setup folder
logger.info("* Deleting old openST setup folder");
oThis.rm('');
// Create new setup folder
logger.info("* Creating new openST setup folder");
oThis.mkdir('');
// Create logs setup folder
logger.info("* Creating openST setup logs folder");
oThis.mkdir(setupHelper.logsFolder());
// Create intercom data files in logs folder
logger.info("* Creating openST intercom data files");
const intercomProcessIdentifiers = setupHelper.intercomProcessIdentifiers();
for (var i=0; i < intercomProcessIdentifiers.length; i++) {
|
javascript
|
{
"resource": ""
}
|
|
q4566
|
train
|
function(relativePath, fileContent) {
const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath;
|
javascript
|
{
"resource": ""
}
|
|
q4567
|
train
|
function(relativePath, line) {
const file = setupHelper.setupFolderAbsolutePath() + '/' + relativePath;
return
|
javascript
|
{
"resource": ""
}
|
|
q4568
|
train
|
function(fromFolder, toFolder, fileName) {
const src = setupHelper.setupFolderAbsolutePath() + '/' + fromFolder + '/' +
|
javascript
|
{
"resource": ""
}
|
|
q4569
|
train
|
function (params) {
const oThis = this
;
params = params || {};
oThis.senderAddress = params.sender_address;
oThis.senderPassphrase = params.sender_passphrase;
oThis.senderName = params.sender_name;
oThis.recipientAddress = params.recipient_address;
|
javascript
|
{
"resource": ""
}
|
|
q4570
|
train
|
function (params) {
const oThis = this;
params = params || {};
|
javascript
|
{
"resource": ""
}
|
|
q4571
|
train
|
function (params) {
const oThis = this
;
oThis.brandedTokenUuid = params.uuid;
oThis.amountToStakeInWeis = params.amount_to_stake_in_weis;
|
javascript
|
{
"resource": ""
}
|
|
q4572
|
train
|
function() {
const oThis = this
;
return new Promise(async function(onResolve, onReject) {
// NOTE: NOT Relying on CACHE - this is because for in process memory, this goes into infinite loop
const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
, brandedToken = new BrandedTokenKlass({ERC20: oThis.erc20Address});
const beforeBalanceResponse = await brandedToken._callMethod('balanceOf', [oThis.reserveAddr]);
const beforeBalance = new BigNumber(beforeBalanceResponse.data.balanceOf);
logger.info('Balance of Reserve for Branded Token before mint:', beforeBalance.toString(10));
const getBalance = async function(){
|
javascript
|
{
"resource": ""
}
|
|
q4573
|
train
|
function() {
const oThis = this
, web3UcProvider = web3ProviderFactory.getProvider('utility', 'ws')
;
return new Promise(async function(onResolve, onReject) {
const beforeBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr));
logger.info('Balance of Reserve for Simple Token Prime before mint:', beforeBalance.toString(10));
const getBalance = async function(){
const afterBalance = new BigNumber(await web3UcProvider.eth.getBalance(oThis.reserveAddr));
|
javascript
|
{
"resource": ""
}
|
|
q4574
|
addPath
|
train
|
function addPath(path, name) {
// This will add a path -> name mapping, so that paths may be later
// resolved to module names, as well as a filesystem full path to
// module mapping, in case the `paths` value contains relative paths
// (e.g. `../`, see issue #2).
|
javascript
|
{
"resource": ""
}
|
q4575
|
train
|
function (params) {
const oThis = this
;
params = params || {};
oThis.beneficiary = params.beneficiary;
|
javascript
|
{
"resource": ""
}
|
|
q4576
|
train
|
function (params) {
const oThis = this
;
params = params || {};
|
javascript
|
{
"resource": ""
}
|
|
q4577
|
train
|
function (deployPath) {
const envFilePath = setupHelper.setupFolderAbsolutePath() + '/' + setupConfig.env_vars_file
, clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)|(openst-platform\/services\/)/;
return new Promise(function (onResolve, onReject) {
// source env
shellSource(envFilePath, async function (err) {
if (err) {
throw err;
|
javascript
|
{
"resource": ""
}
|
|
q4578
|
train
|
function (params) {
const oThis = this
;
params = params || {};
oThis.name = params.name;
oThis.symbol = params.symbol;
|
javascript
|
{
"resource": ""
}
|
|
q4579
|
train
|
async function(senderAddr, senderPassphrase, recipient, amountInWei) {
// TODO: should we have isAsync with UUID (unlock account will take time) and also tag, publish events?
const oThis = this
, web3Provider = web3ProviderFactory.getProvider('value', 'ws')
, gasPrice = coreConstants.OST_VALUE_GAS_PRICE
, gas = coreConstants.OST_VALUE_GAS_LIMIT
;
// Validations
if (!basicHelper.isAddressValid(senderAddr)) {
let errObj = responseHelper.error({
internal_error_identifier: 't_s_fm_1',
api_error_identifier: 'invalid_address',
error_config: basicHelper.fetchErrorConfig()
});
return Promise.resolve(errObj);
}
if (!basicHelper.isAddressValid(recipient)) {
let errObj = responseHelper.error({
internal_error_identifier: 't_s_fm_2',
api_error_identifier: 'invalid_address',
error_config: basicHelper.fetchErrorConfig()
});
return Promise.resolve(errObj);
}
if (senderAddr.equalsIgnoreCase(recipient)) {
let errObj = responseHelper.error({
internal_error_identifier: 't_s_fm_3',
api_error_identifier: 'sender_and_recipient_same',
error_config: basicHelper.fetchErrorConfig()
});
return Promise.resolve(errObj);
}
if (!basicHelper.isNonZeroWeiValid(amountInWei)) {
let errObj = responseHelper.error({
internal_error_identifier: 't_s_fm_4',
api_error_identifier: 'invalid_amount',
error_config: basicHelper.fetchErrorConfig()
});
return Promise.resolve(errObj);
}
// Convert amount in BigNumber
var bigNumAmount = basicHelper.convertToBigNumber(amountInWei);
// Validate sender balance
const senderBalanceValidationResponse = await oThis.validateEthBalance(senderAddr,
|
javascript
|
{
"resource": ""
}
|
|
q4580
|
train
|
function(erc20Address, senderAddr, senderPassphrase, recipient, amountInWei) {
const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
, brandedToken =
|
javascript
|
{
"resource": ""
}
|
|
q4581
|
train
|
function (owner) {
const web3Provider = web3ProviderFactory.getProvider('value', 'ws')
;
// Validate addresses
if (!basicHelper.isAddressValid(owner)) {
let errObj = responseHelper.error({
internal_error_identifier: 't_s_fm_8',
api_error_identifier: 'invalid_address',
error_config: basicHelper.fetchErrorConfig()
|
javascript
|
{
"resource": ""
}
|
|
q4582
|
train
|
function (erc20Address, owner) {
const BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
, brandedToken =
|
javascript
|
{
"resource": ""
}
|
|
q4583
|
train
|
function (contractAddress) {
this.contractAddress = contractAddress;
valueRegistrarContractObj.options.address = this.contractAddress;
//valueRegistrarContractObj.setProvider(web3Provider.currentProvider);
|
javascript
|
{
"resource": ""
}
|
|
q4584
|
train
|
function (contractAddress, web3Provider, currContract, defaultGasPrice) {
this.contractAddress = contractAddress;
this.web3Provider = web3Provider;
this.currContract = currContract;
this.defaultGasPrice = defaultGasPrice;
this.currContract.options.address =
|
javascript
|
{
"resource": ""
}
|
|
q4585
|
train
|
function () {
const oThis = this
;
oThis.contractAddress = simpleTokenContractAddr;
simpleTokenContractObj.options.address = oThis.contractAddress;
//simpleTokenContractObj.setProvider(web3Provider.currentProvider);
|
javascript
|
{
"resource": ""
}
|
|
q4586
|
train
|
function () {
const oThis = this
;
return {
uuid: oThis.uuid,
erc20_address: oThis.erc20Address,
|
javascript
|
{
"resource": ""
}
|
|
q4587
|
train
|
function (params) {
const oThis = this;
oThis.btName = params.bt_name; // branded token name
oThis.btSymbol = params.bt_symbol; // branded token symbol
oThis.btConversionFactor = params.bt_conversion_factor; // branded token to OST conversion factor, 1
|
javascript
|
{
"resource": ""
}
|
|
q4588
|
train
|
async function () {
const oThis = this;
// Validate new branded token
logger.step("** Validating branded token");
await oThis._validateBrandedTokenDetails();
// Generate reserve address
logger.step("** Generating reserve address");
var addressRes = await oThis._generateAddress();
oThis.reserveAddress = addressRes.data.address;
logger.info("* address:", oThis.reserveAddress);
// Start the BT proposal
var proposeRes = await oThis._propose();
// Monitor the BT proposal response
var statusRes = await oThis._checkProposeStatus(proposeRes.data.transaction_hash);
var registrationStatus =
|
javascript
|
{
"resource": ""
}
|
|
q4589
|
train
|
async function() {
const oThis = this
;
const addressObj = new generateAddress({chain: 'utility', passphrase: oThis.reservePassphrase})
, addressResponse = await addressObj.perform();
if (addressResponse.isFailure()) {
logger.error("* Reserve
|
javascript
|
{
"resource": ""
}
|
|
q4590
|
train
|
async function() {
const oThis = this
;
logger.step("** Starting BT proposal");
logger.info("* Name:", oThis.btName, "Symbol:", oThis.btSymbol, "Conversion Factor:", oThis.btConversionFactor);
const proposeBTObj = new proposeBrandedToken(
|
javascript
|
{
"resource": ""
}
|
|
q4591
|
train
|
function(transaction_hash) {
const oThis = this
, timeInterval = 5000
, proposeSteps = {is_proposal_done: 0, is_registered_on_uc: 0, is_registered_on_vc: 0}
;
return new Promise(function(onResolve, onReject){
logger.step("** Monitoring BT proposal status");
const statusObj = new getRegistrationStatus({transaction_hash: transaction_hash});
var statusTimer = setInterval(async function () {
var statusResponse = await statusObj.perform();
if (statusResponse.isFailure()) {
logger.error(statusResponse);
clearInterval(statusTimer);
process.exit(1);
} else {
var registrationStatus = statusResponse.data.registration_status;
if (proposeSteps['is_proposal_done'] != registrationStatus['is_proposal_done']) {
logger.info('* BT proposal done on utility chain. Waiting for registration utility and value chain.');
proposeSteps['is_proposal_done'] = registrationStatus['is_proposal_done'];
}
|
javascript
|
{
"resource": ""
}
|
|
q4592
|
train
|
async function() {
const oThis = this
, existingBrandedTokens = await oThis._loadBrandedTokenConfig()
;
for (var uuid in existingBrandedTokens) {
var brandedToken = existingBrandedTokens[uuid];
if (oThis.btName.equalsIgnoreCase(brandedToken.Name)) {
logger.error("* Branded token name already registered and present in BT config file");
process.exit(1);
|
javascript
|
{
"resource": ""
}
|
|
q4593
|
train
|
async function() {
const oThis = this
, existingBrandedTokens = await oThis._loadBrandedTokenConfig()
;
if (existingBrandedTokens[oThis.uuid]) {
logger.error("* Branded token uuid already registered and present in BT config file");
process.exit(1);
}
existingBrandedTokens[oThis.uuid] = {
Name: oThis.btName,
Symbol: oThis.btSymbol,
ConversionFactor: oThis.btConversionFactor,
Reserve: oThis.reserveAddress,
|
javascript
|
{
"resource": ""
}
|
|
q4594
|
train
|
async function() {
const oThis = this
;
await new openSTStorage.TokenBalanceModel({
|
javascript
|
{
"resource": ""
}
|
|
q4595
|
train
|
function (address, addressToNameMap) {
const lcAddress = String(address).toLowerCase();
if (!addressToNameMap || !( addressToNameMap[address] || addressToNameMap[lcAddress] )) {
|
javascript
|
{
"resource": ""
}
|
|
q4596
|
subscribe
|
train
|
function subscribe() {
openSTNotification.subscribeEvent.rabbit(
['#'],
{queue: 'openst_platform'},
function (msgContent) {
|
javascript
|
{
"resource": ""
}
|
q4597
|
parse
|
train
|
function parse( lang, sample ) {
// TODO: this should be refactored
let ianaLang;
const language = {
desc: lang.trim(),
tag: lang.trim(),
src: lang
};
const parts = lang.match( /^([^(]+)\((.*)\)\s*$/ );
if ( parts && parts.length > 2 ) {
language.desc = parts[ 1 ].trim();
language.tag = parts[ 2 ].trim();
ianaLang = _getLangWithTag( language.tag );
} else {
// First check whether lang is a known IANA subtag like 'en' or 'en-GB'
ianaLang = _getLangWithTag( lang.split( '-' )[ 0 ] );
if ( ianaLang ) {
|
javascript
|
{
"resource": ""
}
|
q4598
|
_getLangWithDesc
|
train
|
function _getLangWithDesc( desc ) {
const results = ( desc ) ? tags.search( desc
|
javascript
|
{
"resource": ""
}
|
q4599
|
transform
|
train
|
function transform( survey ) {
let xformDoc;
const xsltParams = survey.includeRelevantMsg ? {
'include-relevant-msg': 1
} : {};
return _parseXml( survey.xform )
.then( doc => {
if ( typeof survey.preprocess === 'function' ) {
doc = survey.preprocess.call( libxmljs, doc );
}
return doc;
} )
.then( doc => {
xformDoc = doc;
return _transform( sheets.xslForm, xformDoc, xsltParams );
} )
.then( htmlDoc => {
htmlDoc = _replaceTheme( htmlDoc, survey.theme );
htmlDoc = _replaceMediaSources( htmlDoc, survey.media );
htmlDoc = _replaceLanguageTags( htmlDoc, survey );
if ( survey.markdown !== false ) {
survey.form = _renderMarkdown( htmlDoc );
} else {
survey.form = _docToString( htmlDoc );
}
return _transform( sheets.xslModel, xformDoc );
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.