Best JavaScript code snippet using pact-foundation-pact
UserDashboard.js
Source:UserDashboard.js
1'use strict'2const Cache = use('Cache')3const AnnotationModel = use('App/Models/Annotation')4const StringHelper = use('App/Helpers/StringHelper')5const AnnotationCommentModel = use('App/Models/AnnotationComment')6const AnnotationRateModel = use('App/Models/AnnotationRate')7const AnnotationCommentRateModel = use('App/Models/AnnotationCommentRate')8const DatabaseHelper = use('App/Helpers/DatabaseHelper')9class UserDashboard {10 register(Model) {11 12 Model.prototype.getAnnotationsInStep = async function (webpage, start_timestamp, end_timestamp) {13 let cacheKey = Cache.key(`User.getAnnotationsInStep`, start_timestamp, end_timestamp)14 15 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {16 let query = AnnotationModel17 .query()18 .with('notes')19 .where('deleted', false)20 .whereNot('type', 'SectionMainIdea')21 .where('user_id', this.primaryKeyValue)22 .where('webpage_id', webpage.primaryKeyValue)23 if (typeof(start_timestamp) === 'number') {24 query.where('created_at_unixms', '>=', start_timestamp)25 }26 if (typeof(end_timestamp) === 'number') {27 query.where('created_at_unixms', '<=', end_timestamp)28 }29 let result = await query.fetch()30 return result.toJSON()31 })32 return output33 }34 35 Model.prototype.getSectionAnnotationsInStep = async function (webpage, start_timestamp, end_timestamp) {36 let cacheKey = Cache.key(`User.getSectionAnnotationsInStep`, start_timestamp, end_timestamp)37 38 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {39 let query = AnnotationModel40 .query()41 .with('notes')42 .with('anchorPositions')43 .where('deleted', false)44 .where('type', 'SectionMainIdea')45 .where('user_id', this.primaryKeyValue)46 .where('webpage_id', webpage.primaryKeyValue)47 if (typeof(start_timestamp) === 'number') {48 query.where('created_at_unixms', '>=', start_timestamp)49 }50 if (typeof(end_timestamp) === 'number') {51 query.where('created_at_unixms', '<=', end_timestamp)52 }53 let result = await query.fetch()54 return result.toJSON()55 })56 return output57 }58 59 Model.prototype.countAnnotations = async function (webpage, start_timestamp, end_timestamp) {60 let cacheKey = Cache.key(`User.countAnnotations`, start_timestamp, end_timestamp)61 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {62 let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)63 //console.log(annotations)64 return annotations.length65 })66 return output67 }68 69 Model.prototype.countAnnotationNoteWords = async function (webpage, start_timestamp, end_timestamp) {70 let cacheKey = Cache.key(`User.countAnnotationNoteWords`, start_timestamp, end_timestamp)71 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {72 let wordCount = 073 74 let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)75 //console.log(annotations.length)76 annotations.forEach((annotation) => {77 annotation.notes.forEach((note) => {78 let noteText = note.note79 noteText = StringHelper.htmlToText(noteText, true)80 wordCount = wordCount + StringHelper.countWords(noteText)81 })82 })83 84 return wordCount85 })86 return output87 }88 89 Model.prototype.countAnnotationTypes = async function (webpage, start_timestamp, end_timestamp) {90 let cacheKey = Cache.key(`User.countAnnotationTypes`, start_timestamp, end_timestamp)91 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {92 let types = {}93 94 let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)95 annotations.forEach((annotation) => {96 let type = annotation.type97 98 if (typeof(types[type]) !== 'number') {99 types[type] = 0100 }101 types[type]++102 })103 104 return types105 })106 return output107 }108 109 110 Model.prototype.getSectionNotes = async function (webpage, start_timestamp, end_timestamp) {111 let cacheKey = Cache.key(`User.getSectionNotes`, start_timestamp, end_timestamp)112 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {113 let notes = []114 115 let annotations = await this.getSectionAnnotationsInStep(webpage, start_timestamp, end_timestamp)116 annotations.forEach((annotation) => {117 let sectionID = annotation.anchorPositions[0].section_id118 notes[sectionID] = annotation.notes[0].note119 })120 121 return notes122 })123 return output124 }125 126 127 // -----------------------------------------128 129 Model.prototype.getCommentsInStep = async function (webpage, start_timestamp, end_timestamp) {130 let cacheKey = Cache.key(`User.getCommentsInStep`, start_timestamp, end_timestamp)131 132 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {133 let query = AnnotationCommentModel134 .query()135 .whereHas('annotation', (builder) => {136 builder.where('deleted', false)137 .where('webpage_id', webpage.primaryKeyValue)138 }, '>', 0)139 .with('annotation', (builder) => {140 builder.with('user')141 })142 .where('deleted', false)143 .where('user_id', this.primaryKeyValue)144 //.where('webpage_id', webpage.primaryKeyValue)145 if (typeof(start_timestamp) === 'number') {146 query.where('created_at_unixms', '>=', start_timestamp)147 }148 if (typeof(end_timestamp) === 'number') {149 query.where('created_at_unixms', '<=', end_timestamp)150 }151 let result = await query.fetch()152 let resultJSON = result.toJSON()153 154 resultJSON.sort((a, b) => {155 if (a.annotation.id !== b.annotation.id) {156 return a.annotation.id - b.annotation.id157 }158 })159 160 return resultJSON161 })162 return output163 }164 165 Model.prototype.getInteracts = async function (webpage, start_timestamp, end_timestamp) {166 let cacheKey = Cache.key(`User.getInteracts`, start_timestamp, end_timestamp)167 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {168 let interactTo = {}169 170 let initUser = (user) => {171 if (!interactTo[user.id]) {172 interactTo[user.id] = {173 avatar_url: user.avatar_url,174 name: user.display_name,175 count: 0,176 annotationIDList: []177 }178 }179 }180 181 // ----------------------------------------------182 183 let comments = await this.getCommentsInStep(webpage, start_timestamp, end_timestamp)184 185 let lastAnnotationID186 187 comments.forEach((comment) => {188 let annotationID = comment.annotation.id189 if (!lastAnnotationID || lastAnnotationID !== annotationID) {190 lastAnnotationID = annotationID191 }192 else {193 return false194 }195 196 //console.log(JSON.stringify(comment, null, 2))197 let user = comment.annotation.user198 199 initUser(user)200 if (interactTo[user.id].annotationIDList.indexOf(annotationID) === -1) {201 interactTo[user.id].count++202 interactTo[user.id].annotationIDList.push(annotationID)203 }204 })205 206 // ------------------------------------------207 208 let annotationRates = await this.getAnnotationRatesInStep(webpage, start_timestamp, end_timestamp)209 //console.log(annotationRates)210 annotationRates.forEach((rate) => {211 let user = rate.annotation.user212 let annotationID = rate.annotation.id213 initUser(user)214 if (interactTo[user.id].annotationIDList.indexOf(annotationID) === -1) {215 interactTo[user.id].count++216 interactTo[user.id].annotationIDList.push(annotationID)217 }218 })219 220 // ------------------------------------------221 222 let commentRates = await this.getAnnotationCommentRatesInStep(webpage, start_timestamp, end_timestamp)223 //console.log(commentRates)224 commentRates.forEach((rate) => {225 let user = rate.comment.user226 initUser(user)227 interactTo[user.id].count++228 })229 230 // ------------------------------------------231 232 return interactTo233 })234 return output235 }236 237 Model.prototype.getComments = async function (webpage, start_timestamp, end_timestamp) {238 let cacheKey = Cache.key(`User.getComments`, start_timestamp, end_timestamp)239 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {240 let commentTo = {}241 242 let comments = await this.getCommentsInStep(webpage, start_timestamp, end_timestamp)243 244 let lastAnnotationID245 246 comments.forEach((comment) => {247 let annotationID = comment.annotation.id248 if (!lastAnnotationID || annotationID !== comment.annotation.id) {249 lastAnnotationID = comment.annotation.id250 }251 else {252 return false253 }254 255 //console.log(JSON.stringify(comment, null, 2))256 let user = comment.annotation.user257 258 if (!commentTo[user.id]) {259 commentTo[user.id] = {260 avatar_url: user.avatar_url,261 name: user.display_name,262 count: 0263 }264 }265 commentTo[user.id].count++266 })267 268 return commentTo269 })270 return output271 }272 273 // -----------------------------------------274 275 Model.prototype.getCommentedInStep = async function (webpage, start_timestamp, end_timestamp) {276 let cacheKey = Cache.key(`User.getCommentedInStep`, start_timestamp, end_timestamp)277 278 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {279 let query = AnnotationCommentModel280 .query()281 .whereHas('annotation', (builder) => {282 builder.where('deleted', false)283 .where('user_id', this.primaryKeyValue)284 .where('webpage_id', webpage.primaryKeyValue)285 }, '>', 0)286 //.with('annotation', (builder) => {287 //builder.with('user')288 //})289 .with('user')290 .where('deleted', false)291 292 //.where('webpage_id', webpage.primaryKeyValue)293 if (typeof(start_timestamp) === 'number') {294 query.where('created_at_unixms', '>=', start_timestamp)295 }296 if (typeof(end_timestamp) === 'number') {297 query.where('created_at_unixms', '<=', end_timestamp)298 }299 let result = await query.fetch()300 let resultJSON = result.toJSON()301 302 resultJSON.sort((a, b) => {303 if (a.annotation.id !== b.annotation.id) {304 return a.annotation.id - b.annotation.id305 }306 })307 308 return resultJSON309 })310 return output311 }312 313 Model.prototype.getCommented = async function (webpage, start_timestamp, end_timestamp) {314 let cacheKey = Cache.key(`User.getCommented`, start_timestamp, end_timestamp)315 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {316 let output = {}317 318 let comments = await this.getCommentedInStep(webpage, start_timestamp, end_timestamp)319 comments.forEach((comment) => {320 //console.log(JSON.stringify(comment, null, 2))321 let user = comment.user322 323 if (!output[user.id]) {324 output[user.id] = {325 avatar_url: user.avatar_url,326 name: user.display_name,327 count: 0328 }329 }330 output[user.id].count++331 })332 333 return output334 })335 return output336 }337 338 // -----------------------------------------------------------------339 340 Model.prototype.getAnnotationRatesInStep = async function (webpage, start_timestamp, end_timestamp) {341 let cacheKey = Cache.key(`User.getAnnotationRatesInStep`, start_timestamp, end_timestamp)342 343 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {344 let query = AnnotationRateModel345 .query()346 .whereHas('annotation', (builder) => {347 builder.where('deleted', false)348 //.where('user_id', this.primaryKeyValue)349 .where('webpage_id', webpage.primaryKeyValue)350 }, '>', 0)351 .with('annotation', (builder) => {352 builder.with('user')353 })354 .where('user_id', this.primaryKeyValue)355 .where('deleted', false)356 //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')357 358 //.where('webpage_id', webpage.primaryKeyValue)359 let startOffset = ((new Date()).getTimezoneOffset()) * 60 * 1000360 let endOffset = startOffset361 //console.log(start_timestamp)362 if (start_timestamp < 1588077090978) {363 // å°æç¨å¼é¯èª¤ #507364 startOffset = ''365 }366 367 if (typeof(start_timestamp) === 'number') {368 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${startOffset}) >= ?`, [start_timestamp])369 //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) >= ?`, [start_timestamp])370 }371 if (typeof(end_timestamp) === 'number') {372 //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)373 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${endOffset}) <= ?`, [end_timestamp])374 //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) <= ?`, [end_timestamp])375 }376 //DatabaseHelper.consoleSQL(query)377 let result = await query.fetch()378 return result.toJSON()379 })380 return output381 }382 383 Model.prototype.getAnnotationCommentRatesInStep = async function (webpage, start_timestamp, end_timestamp) {384 let cacheKey = Cache.key(`User.getAnnotationCommentRatesInStep`, start_timestamp, end_timestamp)385 386 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {387 let query = AnnotationCommentRateModel388 .query()389 .whereHas('comment', (builder) => {390 builder.where('deleted', false)391 //.where('user_id', this.primaryKeyValue)392 .whereHas('annotation', (builder) => {393 builder.where('webpage_id', webpage.primaryKeyValue)394 .where('deleted', false)395 }, '>', 0)396 }, '>', 0)397 .with('comment', (builder) => {398 builder.with('user')399 })400 .where('user_id', this.primaryKeyValue)401 .where('deleted', false)402 //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')403 //.where('webpage_id', webpage.primaryKeyValue)404 let startOffset = ((new Date()).getTimezoneOffset()) * 60 * 1000405 let endOffset = startOffset406 //console.log(start_timestamp)407 if (start_timestamp < 1588077090978) {408 // å°æç¨å¼é¯èª¤ #507409 startOffset = ''410 //endOffset = ''411 }412 //offset = offset * -1413 //offset = '+' + offset414 //console.log(this.display_name, startOffset, endOffset)415 416 if (typeof(start_timestamp) === 'number') {417 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${startOffset} ) >= ?`, [start_timestamp])418 //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ) >= ?`, [start_timestamp])419 }420 if (typeof(end_timestamp) === 'number') {421 //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)422 423 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${endOffset}) <= ?`, [end_timestamp])424 //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) <= ?`, [end_timestamp])425 }426 //DatabaseHelper.consoleSQL(query)427 let result = await query.fetch()428 return result.toJSON()429 })430 return output431 }432 433 Model.prototype.getRates = async function (webpage, start_timestamp, end_timestamp) {434 let cacheKey = Cache.key(`User.getRates`, start_timestamp, end_timestamp)435 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {436 let rates437 438 let annotationRates = {}439 let commentRates = {}440 441 rates = await this.getAnnotationRatesInStep(webpage, start_timestamp, end_timestamp)442 //console.log(rates.length)443 rates.forEach((rate) => {444 //console.log(JSON.stringify(comment, null, 2))445 let type = rate.type446 let user = rate.annotation.user447 448 if (!annotationRates[type]) {449 annotationRates[type] = {}450 }451 452 //console.log(type, user.id)453 454 if (!annotationRates[type][user.id]) {455 annotationRates[type][user.id] = {456 avatar_url: user.avatar_url,457 name: user.display_name,458 count: 0459 }460 }461 annotationRates[type][user.id].count++462 })463 //console.log(JSON.stringify(annotationRates, null, 2))464 465 // --------------------------------------------------------------466 467 rates = await this.getAnnotationCommentRatesInStep(webpage, start_timestamp, end_timestamp)468 rates.forEach((rate) => {469 //console.log(JSON.stringify(comment, null, 2))470 let type = rate.type471 let user = rate.comment.user472 let userID = user.id + ''473 474 if (!commentRates[type]) {475 commentRates[type] = {}476 }477 478 //console.log(type, userID)479 if (!commentRates[type][userID]) {480 commentRates[type][userID] = {481 avatar_url: user.avatar_url,482 name: user.display_name,483 count: 0484 }485 }486 commentRates[type][userID].count++487 })488 // --------------------------------------------------------------489 490 return {491 annotation: annotationRates,492 comment: commentRates493 }494 })495 return output496 }497 498 499 // -----------------------------------------------------------------500 501 Model.prototype.getAnnotationRatedInStep = async function (webpage, start_timestamp, end_timestamp) {502 let cacheKey = Cache.key(`User.getAnnotationRatedInStep`, start_timestamp, end_timestamp)503 504 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {505 let query = AnnotationRateModel506 .query()507 .whereHas('annotation', (builder) => {508 builder.where('deleted', false)509 .where('user_id', this.primaryKeyValue)510 .where('webpage_id', webpage.primaryKeyValue)511 }, '>', 0)512 //.with('annotation', (builder) => {513 // builder.with('user')514 //})515 .with('rater')516 //.where('user_id', this.primaryKeyValue)517 .where('deleted', false)518 //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')519 520 //.where('webpage_id', webpage.primaryKeyValue)521 let offset = ((new Date()).getTimezoneOffset()) * 60 * 1000522 if (typeof(start_timestamp) === 'number') {523 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) >= ?`, [start_timestamp])524 }525 if (typeof(end_timestamp) === 'number') {526 //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)527 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) <= ?`, [end_timestamp])528 }529 //DatabaseHelper.consoleSQL(query)530 let result = await query.fetch()531 return result.toJSON()532 })533 return output534 }535 536 Model.prototype.getAnnotationCommentRatedInStep = async function (webpage, start_timestamp, end_timestamp) {537 let cacheKey = Cache.key(`User.getAnnotationCommentRatedInStep`, start_timestamp, end_timestamp)538 539 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {540 let query = AnnotationCommentRateModel541 .query()542 .whereHas('comment', (builder) => {543 builder.where('deleted', false)544 .where('user_id', this.primaryKeyValue)545 .whereHas('annotation', (builder) => {546 builder.where('webpage_id', webpage.primaryKeyValue)547 }, '>', 0)548 }, '>', 0)549 //.with('comment', (builder) => {550 // builder.with('user')551 //})552 .where('user_id', this.primaryKeyValue)553 .with('user')554 .where('deleted', false)555 //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')556 //.where('webpage_id', webpage.primaryKeyValue)557 let offset = ((new Date()).getTimezoneOffset()) * 60 * 1000558 if (typeof(start_timestamp) === 'number') {559 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) >= ?`, [start_timestamp])560 }561 if (typeof(end_timestamp) === 'number') {562 //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)563 query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) <= ?`, [end_timestamp])564 }565 let result = await query.fetch()566 return result.toJSON()567 })568 return output569 }570 571 Model.prototype.getRated = async function (webpage, start_timestamp, end_timestamp) {572 let cacheKey = Cache.key(`User.getRated`, start_timestamp, end_timestamp)573 let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {574 let rates575 576 let annotationRates = {}577 let commentRates = {}578 579 rates = await this.getAnnotationRatedInStep(webpage, start_timestamp, end_timestamp)580 //console.log(rates.length)581 rates.forEach((rate) => {582 //console.log(JSON.stringify(comment, null, 2))583 let type = rate.type584 let user = rate.rater585 586 if (!annotationRates[type]) {587 annotationRates[type] = {}588 }589 590 //console.log(type, user.id)591 592 if (!annotationRates[type][user.id]) {593 annotationRates[type][user.id] = {594 avatar_url: user.avatar_url,595 name: user.display_name,596 count: 0597 }598 }599 annotationRates[type][user.id].count++600 })601 //console.log(JSON.stringify(annotationRates, null, 2))602 603 // --------------------------------------------------------------604 605 rates = await this.getAnnotationCommentRatedInStep(webpage, start_timestamp, end_timestamp)606 rates.forEach((rate) => {607 //console.log(JSON.stringify(comment, null, 2))608 let type = rate.type609 let user = rate.user610 611 if (!commentRates[type]) {612 commentRates[type] = {}613 }614 615 if (!commentRates[type][user.id]) {616 commentRates[type][user.id] = {617 avatar_url: user.avatar_url,618 name: user.display_name,619 count: 0620 }621 }622 commentRates[type][user.id].count++623 })624 // --------------------------------------------------------------625 626 return {627 annotation: annotationRates,628 comment: commentRates629 }630 })631 return output632 }633 634 } // register (Model) {635}...
timestamp.js
Source:timestamp.js
1// Licensed under the Apache License, Version 2.0 (the "License");2// you may not use this file except in compliance with the License.3// You may obtain a copy of the License at4//5// http://www.apache.org/licenses/LICENSE-2.06//7// Unless required by applicable law or agreed to in writing, software8// distributed under the License is distributed on an "AS IS" BASIS,9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10// See the License for the specific language governing permissions and11// limitations under the License.12//13// Copyright 2009 Google Inc. All Rights Reserved14/**15 * This type is for INTERNAL use in MongoDB only and should not be used in applications.16 * The appropriate corresponding type is the JavaScript Date type.17 * 18 * Defines a Timestamp class for representing a 64-bit two's-complement19 * integer value, which faithfully simulates the behavior of a Java "Timestamp". This20 * implementation is derived from TimestampLib in GWT.21 *22 * Constructs a 64-bit two's-complement integer, given its low and high 32-bit23 * values as *signed* integers. See the from* functions below for more24 * convenient ways of constructing Timestamps.25 *26 * The internal representation of a Timestamp is the two given signed, 32-bit values.27 * We use 32-bit pieces because these are the size of integers on which28 * Javascript performs bit-operations. For operations like addition and29 * multiplication, we split each number into 16-bit pieces, which can easily be30 * multiplied within Javascript's floating-point representation without overflow31 * or change in sign.32 *33 * In the algorithms below, we frequently reduce the negative case to the34 * positive case by negating the input(s) and then post-processing the result.35 * Note that we must ALWAYS check specially whether those values are MIN_VALUE36 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as37 * a positive number, it overflows back into a negative). Not handling this38 * case would often result in infinite recursion.39 *40 * @class41 * @param {number} low the low (signed) 32 bits of the Timestamp.42 * @param {number} high the high (signed) 32 bits of the Timestamp.43 */44function Timestamp(low, high) {45 if (!(this instanceof Timestamp)) return new Timestamp(low, high);46 this._bsontype = 'Timestamp';47 /**48 * @type {number}49 * @ignore50 */51 this.low_ = low | 0; // force into 32 signed bits.52 /**53 * @type {number}54 * @ignore55 */56 this.high_ = high | 0; // force into 32 signed bits.57}58/**59 * Return the int value.60 *61 * @return {number} the value, assuming it is a 32-bit integer.62 */63Timestamp.prototype.toInt = function() {64 return this.low_;65};66/**67 * Return the Number value.68 *69 * @method70 * @return {number} the closest floating-point representation to this value.71 */72Timestamp.prototype.toNumber = function() {73 return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();74};75/**76 * Return the JSON value.77 *78 * @method79 * @return {string} the JSON representation.80 */81Timestamp.prototype.toJSON = function() {82 return this.toString();83};84/**85 * Return the String value.86 *87 * @method88 * @param {number} [opt_radix] the radix in which the text should be written.89 * @return {string} the textual representation of this value.90 */91Timestamp.prototype.toString = function(opt_radix) {92 var radix = opt_radix || 10;93 if (radix < 2 || 36 < radix) {94 throw Error('radix out of range: ' + radix);95 }96 if (this.isZero()) {97 return '0';98 }99 if (this.isNegative()) {100 if (this.equals(Timestamp.MIN_VALUE)) {101 // We need to change the Timestamp value before it can be negated, so we remove102 // the bottom-most digit in this base and then recurse to do the rest.103 var radixTimestamp = Timestamp.fromNumber(radix);104 var div = this.div(radixTimestamp);105 var rem = div.multiply(radixTimestamp).subtract(this);106 return div.toString(radix) + rem.toInt().toString(radix);107 } else {108 return '-' + this.negate().toString(radix);109 }110 }111 // Do several (6) digits each time through the loop, so as to112 // minimize the calls to the very expensive emulated div.113 var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));114 rem = this;115 var result = '';116 while (!rem.isZero()) {117 var remDiv = rem.div(radixToPower);118 var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();119 var digits = intval.toString(radix);120 rem = remDiv;121 if (rem.isZero()) {122 return digits + result;123 } else {124 while (digits.length < 6) {125 digits = '0' + digits;126 }127 result = '' + digits + result;128 }129 }130};131/**132 * Return the high 32-bits value.133 *134 * @method135 * @return {number} the high 32-bits as a signed value.136 */137Timestamp.prototype.getHighBits = function() {138 return this.high_;139};140/**141 * Return the low 32-bits value.142 *143 * @method144 * @return {number} the low 32-bits as a signed value.145 */146Timestamp.prototype.getLowBits = function() {147 return this.low_;148};149/**150 * Return the low unsigned 32-bits value.151 *152 * @method153 * @return {number} the low 32-bits as an unsigned value.154 */155Timestamp.prototype.getLowBitsUnsigned = function() {156 return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;157};158/**159 * Returns the number of bits needed to represent the absolute value of this Timestamp.160 *161 * @method162 * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp.163 */164Timestamp.prototype.getNumBitsAbs = function() {165 if (this.isNegative()) {166 if (this.equals(Timestamp.MIN_VALUE)) {167 return 64;168 } else {169 return this.negate().getNumBitsAbs();170 }171 } else {172 var val = this.high_ !== 0 ? this.high_ : this.low_;173 for (var bit = 31; bit > 0; bit--) {174 if ((val & (1 << bit)) !== 0) {175 break;176 }177 }178 return this.high_ !== 0 ? bit + 33 : bit + 1;179 }180};181/**182 * Return whether this value is zero.183 *184 * @method185 * @return {boolean} whether this value is zero.186 */187Timestamp.prototype.isZero = function() {188 return this.high_ === 0 && this.low_ === 0;189};190/**191 * Return whether this value is negative.192 *193 * @method194 * @return {boolean} whether this value is negative.195 */196Timestamp.prototype.isNegative = function() {197 return this.high_ < 0;198};199/**200 * Return whether this value is odd.201 *202 * @method203 * @return {boolean} whether this value is odd.204 */205Timestamp.prototype.isOdd = function() {206 return (this.low_ & 1) === 1;207};208/**209 * Return whether this Timestamp equals the other210 *211 * @method212 * @param {Timestamp} other Timestamp to compare against.213 * @return {boolean} whether this Timestamp equals the other214 */215Timestamp.prototype.equals = function(other) {216 return this.high_ === other.high_ && this.low_ === other.low_;217};218/**219 * Return whether this Timestamp does not equal the other.220 *221 * @method222 * @param {Timestamp} other Timestamp to compare against.223 * @return {boolean} whether this Timestamp does not equal the other.224 */225Timestamp.prototype.notEquals = function(other) {226 return this.high_ !== other.high_ || this.low_ !== other.low_;227};228/**229 * Return whether this Timestamp is less than the other.230 *231 * @method232 * @param {Timestamp} other Timestamp to compare against.233 * @return {boolean} whether this Timestamp is less than the other.234 */235Timestamp.prototype.lessThan = function(other) {236 return this.compare(other) < 0;237};238/**239 * Return whether this Timestamp is less than or equal to the other.240 *241 * @method242 * @param {Timestamp} other Timestamp to compare against.243 * @return {boolean} whether this Timestamp is less than or equal to the other.244 */245Timestamp.prototype.lessThanOrEqual = function(other) {246 return this.compare(other) <= 0;247};248/**249 * Return whether this Timestamp is greater than the other.250 *251 * @method252 * @param {Timestamp} other Timestamp to compare against.253 * @return {boolean} whether this Timestamp is greater than the other.254 */255Timestamp.prototype.greaterThan = function(other) {256 return this.compare(other) > 0;257};258/**259 * Return whether this Timestamp is greater than or equal to the other.260 *261 * @method262 * @param {Timestamp} other Timestamp to compare against.263 * @return {boolean} whether this Timestamp is greater than or equal to the other.264 */265Timestamp.prototype.greaterThanOrEqual = function(other) {266 return this.compare(other) >= 0;267};268/**269 * Compares this Timestamp with the given one.270 *271 * @method272 * @param {Timestamp} other Timestamp to compare against.273 * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.274 */275Timestamp.prototype.compare = function(other) {276 if (this.equals(other)) {277 return 0;278 }279 var thisNeg = this.isNegative();280 var otherNeg = other.isNegative();281 if (thisNeg && !otherNeg) {282 return -1;283 }284 if (!thisNeg && otherNeg) {285 return 1;286 }287 // at this point, the signs are the same, so subtraction will not overflow288 if (this.subtract(other).isNegative()) {289 return -1;290 } else {291 return 1;292 }293};294/**295 * The negation of this value.296 *297 * @method298 * @return {Timestamp} the negation of this value.299 */300Timestamp.prototype.negate = function() {301 if (this.equals(Timestamp.MIN_VALUE)) {302 return Timestamp.MIN_VALUE;303 } else {304 return this.not().add(Timestamp.ONE);305 }306};307/**308 * Returns the sum of this and the given Timestamp.309 *310 * @method311 * @param {Timestamp} other Timestamp to add to this one.312 * @return {Timestamp} the sum of this and the given Timestamp.313 */314Timestamp.prototype.add = function(other) {315 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.316 var a48 = this.high_ >>> 16;317 var a32 = this.high_ & 0xffff;318 var a16 = this.low_ >>> 16;319 var a00 = this.low_ & 0xffff;320 var b48 = other.high_ >>> 16;321 var b32 = other.high_ & 0xffff;322 var b16 = other.low_ >>> 16;323 var b00 = other.low_ & 0xffff;324 var c48 = 0,325 c32 = 0,326 c16 = 0,327 c00 = 0;328 c00 += a00 + b00;329 c16 += c00 >>> 16;330 c00 &= 0xffff;331 c16 += a16 + b16;332 c32 += c16 >>> 16;333 c16 &= 0xffff;334 c32 += a32 + b32;335 c48 += c32 >>> 16;336 c32 &= 0xffff;337 c48 += a48 + b48;338 c48 &= 0xffff;339 return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);340};341/**342 * Returns the difference of this and the given Timestamp.343 *344 * @method345 * @param {Timestamp} other Timestamp to subtract from this.346 * @return {Timestamp} the difference of this and the given Timestamp.347 */348Timestamp.prototype.subtract = function(other) {349 return this.add(other.negate());350};351/**352 * Returns the product of this and the given Timestamp.353 *354 * @method355 * @param {Timestamp} other Timestamp to multiply with this.356 * @return {Timestamp} the product of this and the other.357 */358Timestamp.prototype.multiply = function(other) {359 if (this.isZero()) {360 return Timestamp.ZERO;361 } else if (other.isZero()) {362 return Timestamp.ZERO;363 }364 if (this.equals(Timestamp.MIN_VALUE)) {365 return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;366 } else if (other.equals(Timestamp.MIN_VALUE)) {367 return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;368 }369 if (this.isNegative()) {370 if (other.isNegative()) {371 return this.negate().multiply(other.negate());372 } else {373 return this.negate()374 .multiply(other)375 .negate();376 }377 } else if (other.isNegative()) {378 return this.multiply(other.negate()).negate();379 }380 // If both Timestamps are small, use float multiplication381 if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) {382 return Timestamp.fromNumber(this.toNumber() * other.toNumber());383 }384 // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.385 // We can skip products that would overflow.386 var a48 = this.high_ >>> 16;387 var a32 = this.high_ & 0xffff;388 var a16 = this.low_ >>> 16;389 var a00 = this.low_ & 0xffff;390 var b48 = other.high_ >>> 16;391 var b32 = other.high_ & 0xffff;392 var b16 = other.low_ >>> 16;393 var b00 = other.low_ & 0xffff;394 var c48 = 0,395 c32 = 0,396 c16 = 0,397 c00 = 0;398 c00 += a00 * b00;399 c16 += c00 >>> 16;400 c00 &= 0xffff;401 c16 += a16 * b00;402 c32 += c16 >>> 16;403 c16 &= 0xffff;404 c16 += a00 * b16;405 c32 += c16 >>> 16;406 c16 &= 0xffff;407 c32 += a32 * b00;408 c48 += c32 >>> 16;409 c32 &= 0xffff;410 c32 += a16 * b16;411 c48 += c32 >>> 16;412 c32 &= 0xffff;413 c32 += a00 * b32;414 c48 += c32 >>> 16;415 c32 &= 0xffff;416 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;417 c48 &= 0xffff;418 return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);419};420/**421 * Returns this Timestamp divided by the given one.422 *423 * @method424 * @param {Timestamp} other Timestamp by which to divide.425 * @return {Timestamp} this Timestamp divided by the given one.426 */427Timestamp.prototype.div = function(other) {428 if (other.isZero()) {429 throw Error('division by zero');430 } else if (this.isZero()) {431 return Timestamp.ZERO;432 }433 if (this.equals(Timestamp.MIN_VALUE)) {434 if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) {435 return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE436 } else if (other.equals(Timestamp.MIN_VALUE)) {437 return Timestamp.ONE;438 } else {439 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.440 var halfThis = this.shiftRight(1);441 var approx = halfThis.div(other).shiftLeft(1);442 if (approx.equals(Timestamp.ZERO)) {443 return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;444 } else {445 var rem = this.subtract(other.multiply(approx));446 var result = approx.add(rem.div(other));447 return result;448 }449 }450 } else if (other.equals(Timestamp.MIN_VALUE)) {451 return Timestamp.ZERO;452 }453 if (this.isNegative()) {454 if (other.isNegative()) {455 return this.negate().div(other.negate());456 } else {457 return this.negate()458 .div(other)459 .negate();460 }461 } else if (other.isNegative()) {462 return this.div(other.negate()).negate();463 }464 // Repeat the following until the remainder is less than other: find a465 // floating-point that approximates remainder / other *from below*, add this466 // into the result, and subtract it from the remainder. It is critical that467 // the approximate value is less than or equal to the real value so that the468 // remainder never becomes negative.469 var res = Timestamp.ZERO;470 rem = this;471 while (rem.greaterThanOrEqual(other)) {472 // Approximate the result of division. This may be a little greater or473 // smaller than the actual value.474 approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));475 // We will tweak the approximate result by changing it in the 48-th digit or476 // the smallest non-fractional digit, whichever is larger.477 var log2 = Math.ceil(Math.log(approx) / Math.LN2);478 var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);479 // Decrease the approximation until it is smaller than the remainder. Note480 // that if it is too large, the product overflows and is negative.481 var approxRes = Timestamp.fromNumber(approx);482 var approxRem = approxRes.multiply(other);483 while (approxRem.isNegative() || approxRem.greaterThan(rem)) {484 approx -= delta;485 approxRes = Timestamp.fromNumber(approx);486 approxRem = approxRes.multiply(other);487 }488 // We know the answer can't be zero... and actually, zero would cause489 // infinite recursion since we would make no progress.490 if (approxRes.isZero()) {491 approxRes = Timestamp.ONE;492 }493 res = res.add(approxRes);494 rem = rem.subtract(approxRem);495 }496 return res;497};498/**499 * Returns this Timestamp modulo the given one.500 *501 * @method502 * @param {Timestamp} other Timestamp by which to mod.503 * @return {Timestamp} this Timestamp modulo the given one.504 */505Timestamp.prototype.modulo = function(other) {506 return this.subtract(this.div(other).multiply(other));507};508/**509 * The bitwise-NOT of this value.510 *511 * @method512 * @return {Timestamp} the bitwise-NOT of this value.513 */514Timestamp.prototype.not = function() {515 return Timestamp.fromBits(~this.low_, ~this.high_);516};517/**518 * Returns the bitwise-AND of this Timestamp and the given one.519 *520 * @method521 * @param {Timestamp} other the Timestamp with which to AND.522 * @return {Timestamp} the bitwise-AND of this and the other.523 */524Timestamp.prototype.and = function(other) {525 return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);526};527/**528 * Returns the bitwise-OR of this Timestamp and the given one.529 *530 * @method531 * @param {Timestamp} other the Timestamp with which to OR.532 * @return {Timestamp} the bitwise-OR of this and the other.533 */534Timestamp.prototype.or = function(other) {535 return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);536};537/**538 * Returns the bitwise-XOR of this Timestamp and the given one.539 *540 * @method541 * @param {Timestamp} other the Timestamp with which to XOR.542 * @return {Timestamp} the bitwise-XOR of this and the other.543 */544Timestamp.prototype.xor = function(other) {545 return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);546};547/**548 * Returns this Timestamp with bits shifted to the left by the given amount.549 *550 * @method551 * @param {number} numBits the number of bits by which to shift.552 * @return {Timestamp} this shifted to the left by the given amount.553 */554Timestamp.prototype.shiftLeft = function(numBits) {555 numBits &= 63;556 if (numBits === 0) {557 return this;558 } else {559 var low = this.low_;560 if (numBits < 32) {561 var high = this.high_;562 return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));563 } else {564 return Timestamp.fromBits(0, low << (numBits - 32));565 }566 }567};568/**569 * Returns this Timestamp with bits shifted to the right by the given amount.570 *571 * @method572 * @param {number} numBits the number of bits by which to shift.573 * @return {Timestamp} this shifted to the right by the given amount.574 */575Timestamp.prototype.shiftRight = function(numBits) {576 numBits &= 63;577 if (numBits === 0) {578 return this;579 } else {580 var high = this.high_;581 if (numBits < 32) {582 var low = this.low_;583 return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);584 } else {585 return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);586 }587 }588};589/**590 * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.591 *592 * @method593 * @param {number} numBits the number of bits by which to shift.594 * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.595 */596Timestamp.prototype.shiftRightUnsigned = function(numBits) {597 numBits &= 63;598 if (numBits === 0) {599 return this;600 } else {601 var high = this.high_;602 if (numBits < 32) {603 var low = this.low_;604 return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);605 } else if (numBits === 32) {606 return Timestamp.fromBits(high, 0);607 } else {608 return Timestamp.fromBits(high >>> (numBits - 32), 0);609 }610 }611};612/**613 * Returns a Timestamp representing the given (32-bit) integer value.614 *615 * @method616 * @param {number} value the 32-bit integer in question.617 * @return {Timestamp} the corresponding Timestamp value.618 */619Timestamp.fromInt = function(value) {620 if (-128 <= value && value < 128) {621 var cachedObj = Timestamp.INT_CACHE_[value];622 if (cachedObj) {623 return cachedObj;624 }625 }626 var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);627 if (-128 <= value && value < 128) {628 Timestamp.INT_CACHE_[value] = obj;629 }630 return obj;631};632/**633 * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.634 *635 * @method636 * @param {number} value the number in question.637 * @return {Timestamp} the corresponding Timestamp value.638 */639Timestamp.fromNumber = function(value) {640 if (isNaN(value) || !isFinite(value)) {641 return Timestamp.ZERO;642 } else if (value <= -Timestamp.TWO_PWR_63_DBL_) {643 return Timestamp.MIN_VALUE;644 } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {645 return Timestamp.MAX_VALUE;646 } else if (value < 0) {647 return Timestamp.fromNumber(-value).negate();648 } else {649 return new Timestamp(650 (value % Timestamp.TWO_PWR_32_DBL_) | 0,651 (value / Timestamp.TWO_PWR_32_DBL_) | 0652 );653 }654};655/**656 * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.657 *658 * @method659 * @param {number} lowBits the low 32-bits.660 * @param {number} highBits the high 32-bits.661 * @return {Timestamp} the corresponding Timestamp value.662 */663Timestamp.fromBits = function(lowBits, highBits) {664 return new Timestamp(lowBits, highBits);665};666/**667 * Returns a Timestamp representation of the given string, written using the given radix.668 *669 * @method670 * @param {string} str the textual representation of the Timestamp.671 * @param {number} opt_radix the radix in which the text is written.672 * @return {Timestamp} the corresponding Timestamp value.673 */674Timestamp.fromString = function(str, opt_radix) {675 if (str.length === 0) {676 throw Error('number format error: empty string');677 }678 var radix = opt_radix || 10;679 if (radix < 2 || 36 < radix) {680 throw Error('radix out of range: ' + radix);681 }682 if (str.charAt(0) === '-') {683 return Timestamp.fromString(str.substring(1), radix).negate();684 } else if (str.indexOf('-') >= 0) {685 throw Error('number format error: interior "-" character: ' + str);686 }687 // Do several (8) digits each time through the loop, so as to688 // minimize the calls to the very expensive emulated div.689 var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));690 var result = Timestamp.ZERO;691 for (var i = 0; i < str.length; i += 8) {692 var size = Math.min(8, str.length - i);693 var value = parseInt(str.substring(i, i + size), radix);694 if (size < 8) {695 var power = Timestamp.fromNumber(Math.pow(radix, size));696 result = result.multiply(power).add(Timestamp.fromNumber(value));697 } else {698 result = result.multiply(radixToPower);699 result = result.add(Timestamp.fromNumber(value));700 }701 }702 return result;703};704// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the705// from* methods on which they depend.706/**707 * A cache of the Timestamp representations of small integer values.708 * @type {Object}709 * @ignore710 */711Timestamp.INT_CACHE_ = {};712// NOTE: the compiler should inline these constant values below and then remove713// these variables, so there should be no runtime penalty for these.714/**715 * Number used repeated below in calculations. This must appear before the716 * first call to any from* function below.717 * @type {number}718 * @ignore719 */720Timestamp.TWO_PWR_16_DBL_ = 1 << 16;721/**722 * @type {number}723 * @ignore724 */725Timestamp.TWO_PWR_24_DBL_ = 1 << 24;726/**727 * @type {number}728 * @ignore729 */730Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;731/**732 * @type {number}733 * @ignore734 */735Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;736/**737 * @type {number}738 * @ignore739 */740Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;741/**742 * @type {number}743 * @ignore744 */745Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;746/**747 * @type {number}748 * @ignore749 */750Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;751/** @type {Timestamp} */752Timestamp.ZERO = Timestamp.fromInt(0);753/** @type {Timestamp} */754Timestamp.ONE = Timestamp.fromInt(1);755/** @type {Timestamp} */756Timestamp.NEG_ONE = Timestamp.fromInt(-1);757/** @type {Timestamp} */758Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0);759/** @type {Timestamp} */760Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);761/**762 * @type {Timestamp}763 * @ignore764 */765Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);766/**767 * Expose.768 */769module.exports = Timestamp;...
TimestampForm.js
Source:TimestampForm.js
1import React, { Fragment } from 'react';2import { Form as FinalForm, Field } from 'react-final-form';3import { Button, Form, Header, Search } from 'semantic-ui-react';4import TextInput from '../../app/common/form/TextInput';5import { FORM_ERROR } from 'final-form';6import { formatDateTime, reverseFormatDateTime } from '../../app/common/util';7import { combineValidators, isRequired } from 'revalidate';8import ErrorMessage from '../../app/common/form/ErrorMessage';9import DateTimeCustomInput from '../../app/common/form/DateTimeCustomInput';10import { Timestamps, Jobsites } from '../../app/api/agent';11import { useModalDispatch } from '../../app/context/modal/modalContext';12import { useAlertDispatch } from '../../app/context/alerts/alertContext';13import { setAlert } from '../../app/context/alerts/alertActions';14import { useTimestampDispatch } from '../../app/context/timestamps/timestampContext';15const validate = combineValidators({16 username: isRequired('Username'),17 moniker: isRequired('Moniker'),18 clockedInStamp: isRequired('Clocked In Time'),19 clockedOutStamp: isRequired('Clocked Out Time'),20});21// modal - form used to add/edit a timestamp22//if editTimestamp is true, will load form with data and prevent changing jobsite23const TimestampForm = ({ username, editTimestamp = false }) => {24 const modalDispatch = useModalDispatch();25 const alertDispatch = useAlertDispatch();26 const timestampDispatch = useTimestampDispatch();27 const pageSize = 10;28 const [timestamp, setTimestamp] = React.useState({29 username: username,30 moniker: '',31 clockedInStamp: '',32 clockedOutStamp: '',33 });34 React.useEffect(() => {35 if (editTimestamp) {36 setTimestamp({37 username: username,38 moniker: editTimestamp.moniker,39 clockedInStamp: reverseFormatDateTime(editTimestamp.clockedInStamp),40 clockedOutStamp: reverseFormatDateTime(editTimestamp.clockedOutStamp),41 });42 setSelectionValue(editTimestamp.moniker);43 }44 }, [editTimestamp, username]);45 const handleFinalFormSubmit = async (values) => {46 try {47 //format values into a timestamp48 const timestamp = {49 username: values.username,50 moniker: values.moniker,51 clockedInStamp: formatDateTime(values.clockedInStamp),52 clockedOutStamp: formatDateTime(values.clockedOutStamp),53 };54 //editing timestamp requires only two fields55 if (editTimestamp) {56 const clockedStamps = {57 clockedInStamp: timestamp.clockedInStamp,58 clockedOutStamp: timestamp.clockedOutStamp,59 };60 await Timestamps.editTimestamp(61 editTimestamp.timestampId,62 clockedStamps63 );64 modalDispatch({ type: 'CLOSE_MODAL' });65 timestampDispatch({ type: 'REFRESH' });66 setAlert(alertDispatch, `Timestamp Updated`, 'update');67 } else {68 await Timestamps.addTimestamp(timestamp);69 modalDispatch({ type: 'CLOSE_MODAL' });70 timestampDispatch({ type: 'REFRESH' });71 setAlert(alertDispatch, `New Timestamp added`, 'success');72 }73 } catch (error) {74 return { [FORM_ERROR]: error };75 }76 };77 //Ccode here supports the job search bar component----------------78 const [results, setResults] = React.useState([]);79 const [loading, setLoading] = React.useState(false);80 const [selectionValue, setSelectionValue] = React.useState('');81 const handleSearchChange = async (e, { value }) => {82 setSelectionValue(value);83 setLoading(true);84 let searchResults = await Jobsites.listJobsites(value, pageSize, 1);85 searchResults = searchResults.data;86 let newResults = [];87 searchResults.forEach((jobsite) => {88 newResults.push({89 title: jobsite.moniker,90 description: `${jobsite.name} - ${jobsite.location.cityTown}`,91 });92 });93 setLoading(false);94 setResults(newResults);95 };96 const handleResultSelect = (e, { result }) => {97 setSelectionValue(result.title);98 setTimestamp({ ...timestamp, moniker: result.title });99 };100 // end of job search bar component -----------------------------101 return (102 <Fragment>103 <FinalForm104 onSubmit={handleFinalFormSubmit}105 validate={validate}106 initialValues={timestamp}107 render={({108 handleSubmit,109 submitting,110 submitError,111 invalid,112 pristine,113 dirtySinceLastSubmit,114 form,115 }) => (116 <Form onSubmit={handleSubmit} error>117 <Header118 as='h2'119 content={editTimestamp ? 'Edit Timestamp' : 'Add Timestamp'}120 color='teal'121 textAlign='center'122 />123 <Field124 name='username'125 component={TextInput}126 placeholder='Username'127 value={timestamp.username}128 disabled129 />130 {!editTimestamp && pristine && (131 <p style={{ fontStyle: 'italic', color: 'red' }}>132 Choose a jobsite first133 </p>134 )}135 <Search136 placeholder='Search jobsites...'137 loading={loading}138 onResultSelect={handleResultSelect}139 onSearchChange={handleSearchChange}140 results={results}141 value={selectionValue}142 disabled={editTimestamp ? true : false}143 />144 <Field145 name='moniker'146 component={TextInput}147 placeholder='Moniker'148 value={timestamp.moniker}149 style={{ display: 'none' }}150 />151 <Field152 name='clockedInStamp'153 value={timestamp.clockedInStamp}154 component={DateTimeCustomInput}155 placeholder='Clocked In Time'156 dateFormat='MM-DD-YYYY'157 clearable158 closable159 />160 <Field161 name='clockedOutStamp'162 value={timestamp.clockedOutStamp}163 component={DateTimeCustomInput}164 placeholder='Clocked Out Time'165 dateFormat='MM-DD-YYYY'166 clearable167 closable168 />169 {submitError && !dirtySinceLastSubmit && (170 <ErrorMessage error={submitError} />171 )}172 <Button173 disabled={(invalid && !dirtySinceLastSubmit) || pristine}174 loading={submitting}175 color='teal'176 content='Submit'177 fluid178 />179 {/* <pre>{JSON.stringify(form.getState(), null, 2)}</pre> */}180 </Form>181 )}182 />183 </Fragment>184 );185};...
App.js
Source:App.js
...45 }46 insert_continue=(tx,event,lat1,long1,speed,bearing,timestamp,event_row)=>{47 tx.executeSql("Insert into Events "+event_query+" values('"+event+"',"+event_row.curr_timestamp+","+timestamp+",'"+event_row.curr_lat+"','"+lat1+"','"+event_row.curr_long+"','"+long1+"',"+event_row.curr_bearing+","+bearing+","+event_row.curr_speed+","+speed+");")48 }49 //insert event in non continious timestamp(next.current_timestamp == next.previous_timestamp)50 insert_new=(activity,timestamp,event_row,tx)=>{51 console.log("Incerting new")52 tx.executeSql("Insert into Events (activity,prev_timestamp,curr_timestamp,confidence) values('"+activity.type+"',"+timestamp+","+timestamp+","+activity.confidence+");")53 }54 componentDidMount(){55 //this.getLocation()56 }57 //extend the event58 update=(activity,timestamp,event_row,tx)=>{59 tx.executeSql("UPDATE Events set "+60 "activity ='"+activity.type+ "',"+61 "curr_timestamp ="+timestamp+ ","+62 "confidence ="+activity.confidence +63 " where id ="+event_row.id);...
Static_Images.js
Source:Static_Images.js
1function Update_Static_Images()2 {3 //Read the updated time4 var timestamp_year = parseInt(document.forms["TimeForm"]["latest_year"].value);5 var timestamp_month = parseInt(document.forms["TimeForm"]["latest_month"].value);6 var timestamp_day = parseInt(document.forms["TimeForm"]["latest_day"].value);7 if (timestamp_year <= 2008){Time_Period = "Historical";}8 else if (timestamp_year < 2011){Time_Period = "Catch_up";}9 else if (timestamp_year == 2011 && timestamp_month <= 9){Time_Period = "Catch_up";}10 else {Time_Period = "Realtime";}11 //Update the images12 var timestamp = sprintf("%04d",timestamp_year) + sprintf("%02d",timestamp_month) + sprintf("%02d",timestamp_day);13 var timestamp_str = sprintf("%02d",timestamp_day) + "/" + sprintf("%02d",timestamp_month) + "/" + sprintf("%04d",timestamp_year);14 var timestamp_str1 = sprintf("%04d",timestamp_year) + "/" + sprintf("%02d",timestamp_month) + "/" + sprintf("%02d",timestamp_day);15 document.getElementById("SMQALL").src = ""16 document.getElementById("PREC").src = "../IMAGES/"+timestamp_str1+"/PGF_prec_"+timestamp+".png"; 17 document.getElementById("EVAP").src = "Data/ADM_Data/" + Time_Period + "/evap_basic/evap_" + timestamp + ".png"; 18 document.getElementById("GAUGES_PERCENTILES").src = "Data/ADM_Data/" + Time_Period + "/gaugepct_basic/gaugepct_" + timestamp + ".png"; 19 document.getElementById("SMWET1").src = "Data/ADM_Data/" + Time_Period + "/smwet1_basic/smwet1_" + timestamp + ".png"; 20 document.getElementById("SMWET2").src = "Data/ADM_Data/" + Time_Period + "/smwet2_basic/smwet2_" + timestamp + ".png"; 21 document.getElementById("RUNOFF").src = "Data/ADM_Data/" + Time_Period + "/runoff_basic/runoff_" + timestamp + ".png"; 22 document.getElementById("TMAX").src = "Data/ADM_Data/" + Time_Period + "/tmax_basic/tmax_" + timestamp + ".png"; 23 document.getElementById("TMIN").src = "Data/ADM_Data/" + Time_Period + "/tmin_basic/tmin_" + timestamp + ".png"; 24 document.getElementById("WIND").src = "Data/ADM_Data/" + Time_Period + "/wind_basic/wind_" + timestamp + ".png"; 25 document.getElementById("Drought_Conditions").innerHTML = "Drought Conditions on " + timestamp_str;26 }27function Update_Static_Images_Step(flag_arrow)28 {29 var flag_arrow;30 var newtimestamp = new Array(3);31 //Read the current time32 var timestamp_year = parseInt(document.forms["TimeForm"]["latest_year"].value);33 var timestamp_month = parseInt(document.forms["TimeForm"]["latest_month"].value);34 var timestamp_day = parseInt(document.forms["TimeForm"]["latest_day"].value);35 var date_temp = new Date(timestamp_year,timestamp_month-1,timestamp_day);36 //Find the next or previous timestamp37 if (flag_arrow == 1)38 {39 date_temp.setDate(date_temp.getDate() + 1);40 newtimestamp = [date_temp.getFullYear(),date_temp.getMonth() + 1,date_temp.getDate()];41 }42 else 43 {44 date_temp.setDate(date_temp.getDate() - 1);45 newtimestamp = [date_temp.getFullYear(),date_temp.getMonth() + 1,date_temp.getDate()];46 }47 //Update the time string48 if (newtimestamp[0] <= 2008){Time_Period = "Historical";}49 else if (newtimestamp[0] < 2011){Time_Period = "Catch_up";}50 else if (newtimestamp[0] == 2011 && newtimestamp[1] <= 9){Time_Period = "Catch_up";}51 else {Time_Period = "Realtime";}52 document.forms["TimeForm"]["latest_year"].value = newtimestamp[0];53 document.forms["TimeForm"]["latest_month"].value = newtimestamp[1];54 document.forms["TimeForm"]["latest_day"].value = newtimestamp[2];55 var timestamp = sprintf("%04d",newtimestamp[0]) + sprintf("%02d",newtimestamp[1]) + sprintf("%02d",newtimestamp[2]);56 var timestamp_str = sprintf("%02d",newtimestamp[2]) + "/" + sprintf("%02d",newtimestamp[1]) + "/" + sprintf("%04d",newtimestamp[0]);57 document.getElementById("SMQALL").src = "Data/ADM_Data/" + Time_Period + "/smqall_basic/smqall_" + timestamp + ".png";58 document.getElementById("PREC").src = "Data/ADM_Data/" + Time_Period + "/prec_basic/prec_" + timestamp + ".png";59 document.getElementById("EVAP").src = "Data/ADM_Data/" + Time_Period + "/evap_basic/evap_" + timestamp + ".png";60 document.getElementById("GAUGES_PERCENTILES").src = "Data/ADM_Data/" + Time_Period + "/gaugepct_basic/gaugepct_" + timestamp + ".png";61 document.getElementById("SMWET1").src = "Data/ADM_Data/" + Time_Period + "/smwet1_basic/smwet1_" + timestamp + ".png"; 62 document.getElementById("SMWET2").src = "Data/ADM_Data/" + Time_Period + "/smwet2_basic/smwet2_" + timestamp + ".png"; 63 document.getElementById("RUNOFF").src = "Data/ADM_Data/" + Time_Period + "/runoff_basic/runoff_" + timestamp + ".png"; 64 document.getElementById("TMAX").src = "Data/ADM_Data/" + Time_Period + "/tmax_basic/tmax_" + timestamp + ".png"; 65 document.getElementById("TMIN").src = "Data/ADM_Data/" + Time_Period + "/tmin_basic/tmin_" + timestamp + ".png"; 66 document.getElementById("WIND").src = "Data/ADM_Data/" + Time_Period + "/wind_basic/wind_" + timestamp + ".png"; 67 document.getElementById("Drought_Conditions").innerHTML = "Drought Conditions on " + timestamp_str;68 }...
ReadingProgress.js
Source:ReadingProgress.js
1'use strict'2/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */3const Model = use('Model')4/**5table.integer('webpage_id').notNullable().unsigned().references('id').inTable('webpages').onDelete('cascade')6table.integer('user_id').notNullable().unsigned().references('id').inTable('users').onDelete('cascade')7table.string('step_name', 60).notNullable()8table.bigInteger('activity_seconds').defaultTo(0)9table.bigInteger('start_timestamp').notNullable()10table.bigInteger('end_timestamp')11table.json('log')12 */13class ReadingProgress extends Model {14 static boot () {15 super.boot()16 17 this.addTrait('JSONCase', 'log')18 }19 20 user () {21 return this.belongsTo('App/Models/User')22 }23 24 webpage () {25 return this.belongsTo('App/Models/Webpage')26 }27 28 getIsCompleted ({end_timestamp}) {29 //console.log(end_timestamp, typeof(end_timestamp))30 //return (isNaN(end_timestamp) === false)31 return (end_timestamp !== null && end_timestamp !== undefined)32 }33 34 static get computed () {35 return ['duration', 'isCompleted']36 }37 38 getDuration ({start_timestamp, end_timestamp}) {39 if (end_timestamp === null) {40 return null41 }42 else {43 if (typeof(start_timestamp) === 'string'44 && isNaN(start_timestamp) === false) {45 start_timestamp = parseInt(start_timestamp, 10)46 }47 if (typeof(end_timestamp) === 'string'48 && isNaN(end_timestamp) === false) {49 end_timestamp = parseInt(end_timestamp, 10)50 }51 52 if (typeof(end_timestamp) === 'number' 53 && typeof(start_timestamp) === 'number') {54 return end_timestamp - start_timestamp55 }56 else {57 return null58 }59 }60 }61 62 getStartTimestamp (timestamp) {63 if (timestamp === null) {64 return null65 }66 else if (isNaN(timestamp) === false) {67 return parseInt(timestamp, 10)68 }69 else {70 return null71 }72 }73 74 getEndTimestamp (timestamp) {75 if (timestamp === null) {76 return null77 }78 else if (isNaN(timestamp) === false) {79 //console.log(timestamp, isNaN(timestamp), typeof(timestamp))80 return parseInt(timestamp, 10)81 }82 return null83 }84}...
date.js
Source:date.js
1const convertTimestamp = (timestamp) => {2 return timestamp < 1000000000000 ? timestamp * 1000 : timestamp3};4export const getDate = (timestamp) => {5 try {6 timestamp = convertTimestamp(timestamp);7 8 const date = new Date(timestamp);9 10 return date.toLocaleDateString();11 12 } catch (error) {13 console.error(error);14 return '';15 }16};17export const getDateWithWeekday = (timestamp) => {18 try {19 timestamp = convertTimestamp(timestamp);20 21 const date = new Date(timestamp);22 23 const opts = { timeZone: 'UTC', weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };24 25 return date.toLocaleDateString(navigator.language, opts);26 27 } catch (error) {28 console.error(error);29 return '';30 }31};32export const getDateWithTime = (timestamp) => {33 try {34 timestamp = convertTimestamp(timestamp);35 36 const date = new Date(timestamp);37 38 return date.toLocaleString();39 40 } catch (error) {41 console.error(error);42 return '';43 }44};45export const getTime = (timestamp, keepUTC) => {46 try {47 timestamp = convertTimestamp(timestamp);48 49 const date = new Date(timestamp);50 51 if (keepUTC) {52 const opts = { timeZone: 'UTC', hour: '2-digit', minute: '2-digit' };53 return date.toLocaleTimeString(navigator.language, opts);54 }55 56 return date.toLocaleTimeString();57 58 } catch (error) {59 console.error(error);60 return '';61 }...
timestampContext.js
Source:timestampContext.js
1import React, { createContext, useReducer } from 'react';2import timestampReducer from './timestampReducer';3const TimestampStateContext = createContext();4const TimestampDispatchContext = createContext();5const TimestampProvider = ({ children }) => {6 const initialState = {7 timestamps: [],8 jobsiteTimestamps: [],9 timestampPagination: null,10 jobsitePagination: null,11 loading: false,12 fromDate: '',13 toDate: '',14 refresh: false,15 };16 const [state, dispatch] = useReducer(timestampReducer, initialState);17 return (18 <TimestampStateContext.Provider value={state}>19 <TimestampDispatchContext.Provider value={dispatch}>20 {children}21 </TimestampDispatchContext.Provider>22 </TimestampStateContext.Provider>23 );24};25const useTimestampState = () => {26 const timestampState = React.useContext(TimestampStateContext);27 return timestampState;28};29const useTimestampDispatch = () => {30 const timestampDispatch = React.useContext(TimestampDispatchContext);31 return timestampDispatch;32};...
Using AI Code Generation
1const pact = require('@pact-foundation/pact');2const timestamp = pact.timestamp();3console.log(timestamp);4const pact = require('pact');5const timestamp = pact.timestamp();6console.log(timestamp);
Using AI Code Generation
1const pact = require('pact-foundation/pact-node');2pact.timestamp().then(function (timestamp) {3 console.log(timestamp);4});5const pact = require('pact-foundation/pact-node');6pact.timestamp().then(function (timestamp) {7 console.log(timestamp);8});9npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Using AI Code Generation
1const { Matchers } = require('@pact-foundation/pact');2const { somethingLike } = Matchers;3const { like } = Matchers;4const { Pact } = require('@pact-foundation/pact');5const { assert } = require('chai');6const { getProviders } = require('./provider');7describe('Pact with Consumer and Provider', () => {8 const provider = getProviders();9 const EXPECTED_BODY = {10 };11 const EXPECTED_BODY2 = {12 };13 const EXPECTED_BODY3 = {14 };15 const EXPECTED_BODY4 = {16 };17 const EXPECTED_BODY5 = {18 };19 const EXPECTED_BODY6 = {20 };21 const EXPECTED_BODY7 = {22 };23 const EXPECTED_BODY8 = {24 };25 const EXPECTED_BODY9 = {26 };27 const EXPECTED_BODY10 = {28 };
Using AI Code Generation
1const Pact = require('@pact-foundation/pact').Pact;2const config = require('./pact-config.json');3const helper = require('./pact-helper.js');4const chai = require('chai');5const expect = chai.expect;6const provider = require('../provider.js');7const pact = new Pact(config);8const expectedInteraction = {9 withRequest: {10 headers: {11 }12 },13 willRespondWith: {14 headers: {15 },16 {17 },18 {19 }20 }21};22describe("GET /users", () => {23 before(() => {24 return pact.setup();25 });26 describe("when a list of users is available", () => {27 before(() => {28 return pact.addInteraction(expectedInteraction);29 });30 it("returns a successful body", () => {31 return provider.getUsers().then((response) => {32 expect(response.data).to.eql(expectedInteraction.willRespondWith.body);33 });34 });35 it("returns a successful body", () => {36 return provider.getUsers().then((response) => {37 expect(response.data).to.eql(expectedInteraction.willRespondWith.body);38 });39 });40 });41 after(() => {42 return pact.verify();43 });44});45after(() => {46 return pact.finalize();47});48{
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!