language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ModelSdkClientImpl { constructor(connectionConfig, modelConstructor) { this.connectionConfig = connectionConfig; this.modelConstructor = modelConstructor; const defaultConfig = { endPoint: "https://model.api.mendix.com" }; const sdkConfig = Object.assign(Object.assign({}, defaultConfig), connectionConfig); this.client = sdkConfig.client || new internal.ModelServerClientImpl(sdkConfig); } createWorkingCopy(workingCopyParameters, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.createWorkingCopy(workingCopyParameters, resolve, reject), callback, errorCallback); } createWorkingCopyFromTeamServer(workingCopyParameters, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.createWorkingCopyFromTeamServer(workingCopyParameters, resolve, reject), callback, errorCallback); } createAndOpenWorkingCopy(workingCopyParameters, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.createWorkingCopy(workingCopyParameters, workingCopyInfo => { this.openWorkingCopy(workingCopyInfo.id, resolve, reject); }, reject), callback, errorCallback); } openWorkingCopy(workingCopyId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { checkWorkingCopyId(workingCopyId); const model = new this.modelConstructor(this.client, errorCallback || (err => { throw err; }), this.connectionConfig); model.initializeFromModelServer(workingCopyId).then(() => resolve(model), reject); }, callback, errorCallback); } loadWorkingCopyMetaData(workingCopyId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { checkWorkingCopyId(workingCopyId); this.client.loadWorkingCopyMetaData(workingCopyId, resolve, reject); }, callback, errorCallback); } deleteWorkingCopy(workingCopyId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { checkWorkingCopyId(workingCopyId); this.client.deleteWorkingCopy(workingCopyId, resolve, reject); }, callback, errorCallback); } grantAccess(workingCopyId, memberOpenId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.grantAccess(workingCopyId, memberOpenId, resolve, reject); }, callback, errorCallback); } revokeAccess(workingCopyId, memberOpenId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.revokeAccess(workingCopyId, memberOpenId, resolve, reject); }, callback, errorCallback); } grantAccessByProject(projectId, memberOpenId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.grantAccessByProject(projectId, memberOpenId, resolve, reject); }, callback, errorCallback); } revokeAccessByProject(projectId, memberOpenId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.revokeAccessByProject(projectId, memberOpenId, resolve, reject); }, callback, errorCallback); } setProjectMembers(projectId, memberOpenids, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.setProjectMembers(projectId, memberOpenids, resolve, reject); }, callback, errorCallback); } checkAccess(workingCopyId, memberOpenId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.checkAccess(workingCopyId, memberOpenId, resolve, reject); }, callback, errorCallback); } exportMpk(workingCopyId, outFilePath, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.exportMpk(workingCopyId, outFilePath, resolve, reject), callback, errorCallback); } exportModuleMpk(workingCopyId, moduleId, outFilePath, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.exportModuleMpk(workingCopyId, moduleId, outFilePath, resolve, reject), callback, errorCallback); } getMyWorkingCopies(callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.getMyWorkingCopies(resolve, reject), callback, errorCallback); } getWorkingCopyByProject(projectId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.getWorkingCopyByProject(projectId, resolve, reject), callback, errorCallback); } updateWorkingCopyByProject(projectId, workingCopyId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.updateWorkingCopyByProject(projectId, workingCopyId, resolve, reject); }, callback, errorCallback); } deleteWorkingCopyByProject(projectId, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => { assertBackendAccess(this.connectionConfig); this.client.deleteWorkingCopyByProject(projectId, resolve, reject); }, callback, errorCallback); } lockWorkingCopy(workingCopyId, lockOptionsOrCallback, callbackOrErrorCallback, errorCallback) { let callback; let lockOptions; if (typeof lockOptionsOrCallback === "function") { callback = lockOptionsOrCallback; errorCallback = callbackOrErrorCallback; lockOptions = { lockType: "bidi" }; } else if (typeof lockOptionsOrCallback === "string") { lockOptions = { lockType: lockOptionsOrCallback }; callback = callbackOrErrorCallback; } else { lockOptions = lockOptionsOrCallback; callback = callbackOrErrorCallback; } if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.lockWorkingCopy(workingCopyId, lockOptions, resolve, reject), callback, errorCallback); } unlockWorkingCopy(workingCopyId, lockTypeOrCallback, callbackOrErrorCallback, errorCallback) { let lockType; let callback; if (typeof lockTypeOrCallback === "function") { callback = lockTypeOrCallback; errorCallback = callbackOrErrorCallback; } else { lockType = lockTypeOrCallback; callback = callbackOrErrorCallback; } if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.unlockWorkingCopy(workingCopyId, lockType, resolve, reject), callback, errorCallback); } commitToTeamServer(workingCopyId, options, callback, errorCallback) { if (callback) { checkCallbacks(callback, errorCallback); } return promiseOrCallbacks_1.promiseOrCallbacks((resolve, reject) => this.client.commitToTeamServer(workingCopyId, options, resolve, reject), callback, errorCallback); } }
JavaScript
class RFParty extends EventEmitter { constructor(divId) { super() this.showAllTracks = true this.showAwayTracks = false this.detailsViewer = null this.map = Leaflet.map(divId,{ attributionControl: false }).setView([47.6, -122.35], 13) Leaflet.tileLayer(TILE_SERVER_MAPBOX, TILE_SERVER_MAPBOX_CONFIG).addTo(this.map); //Leaflet.control.attribution({prefix: '<span id="map-attribution" class="map-attribution">Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a></span>' }) // .addTo(this.map) this.db = new Loki('session') // build session db this.db.addCollection('locationTrack', { indices: ['timestamp', 'lat', 'lon', 'filename', 'source'] }) this.db.addCollection('homeState', { indices: ['timestamp', 'filename'] }) this.db.addCollection('awayTime', { indices: ['starttime', 'endtime', 'bounds.min.x', 'bounds.min.y', 'bounds.max.x', 'bounds.max.y' ] }) this.db.addCollection('ble', { indices: ['firstseen', 'lastseen', 'address', 'duration', 'advertisement.localName', 'connectable', 'addressType', 'services', 'hasUnknownService', 'ibeacon.uuid', 'findmy.maintained', 'company', 'product', 'companyCode', 'productCode', 'appleContinuityTypeCode', 'appleIp'] }) this.db.addCollection('appleDevices', { indices: ['address', 'continuityCode', 'ip'] }) this.mobileSegments = [] this.srcs = {} this.deviceLayers = {} this.searchResults = null this.lastRender = null this.lastQuery = null this.scanDb = null this.gpx = {} this.gpxLines = {} this.gpxLayer = Leaflet.layerGroup() } async start() { console.log('starting') if(this.showAllTracks){ for(let name in this.gpxLines){ this.gpxLayer.addLayer(this.gpxLines[name]) } this.gpxLayer.addTo(this.map) } this.emit('search-start') let searchStartTime = new moment() let awayTime = this.db.getCollection('awayTime').find() console.log('found', awayTime.length, 'away time periods') this.lastQuery = {duration: { $gt: 30*60000 }} for (let away of awayTime) { let track = this.getTrackByTime(away.starttime, away.endtime) if(track.length == 0){continue} let latlngs = this.trackToLatLonArray(track) console.log('\trendering', latlngs.length, 'track points') if(this.showAwayTracks){ Leaflet.polyline(latlngs, { color: 'yellow', opacity: 0.74, weight: '2' }).addTo(this.map) } } await this.handleSearch('duration') this.map.on('moveend', ()=>{ if(!this.lastRender){ return } if(!this.lastQuery){ return } if(this.lastRender.drawable != this.lastRender.onscreen){ this.doQuery(this.lastQuery) } }) /*let searchEndTime = new moment() let searchDuration = searchEndTime.diff(searchStartTime) this.emit('search-finished', {devices, searchDuration}) let renderStartTime = new moment() this.emit('render-start') await this.renderBleDeviceList(devices) let renderEndTime = new moment() let renderDuration = renderEndTime.diff(renderStartTime) this.emit('render-finished', {devices, renderDuration}) let updateEndTime = new moment() let updateDuration = updateEndTime.diff(searchStartTime) this.emit('update-finished', {devices, updateDuration, searchDuration, renderDuration})*/ } async handleSearch(input){ let query = null let updateStartTime = new moment() if(input[0]=='{'){ console.log('raw query') const obj = JSON5.parse(input) console.log('parsed query', obj) query = obj }else{ const tokens = input.split(' ') let term = tokens.slice(1).join(' ') switch(tokens[0]){ case 'mac': case 'address': query = { 'address': {'$contains': term } } break case 'name': case 'localname': console.log('select by name', tokens) query = { 'advertisement.localName': {'$contains': term } } console.log('term['+term+']') break case 'company': console.log('select by company', tokens) query = { 'company': {'$contains': term } } break case 'product': console.log('select by product', tokens) query = { 'product': {'$contains': term } } break case 'unknown': case 'unknown-service': query = { 'hasUnknownService': {'$exists': true } } break case 'service': const serviceTerm = tokens[1] console.log('select by service', serviceTerm) let possibleServices = RFParty.reverseLookupService(serviceTerm) console.log('possible', possibleServices) query = { 'services': {'$containsAny': possibleServices }, ...this.parseServiceSearch(serviceTerm.toLowerCase(), tokens.slice(2)) } break case 'appleip': case 'appleIp': console.log('select by appleIp', tokens) if(tokens.length < 2){ query = { 'appleIp': {'$exists': true } } } else{ query = { 'appleIp': {'$contains': term } } } break case 'random': query = { 'addressType': {'$eq': 'random' } } break case 'public': query = { 'addressType': {'$eq': 'public' } } break case 'connectable': query = { 'connectable': {'$eq': true } } break case 'duration': query = { duration: { $gt: 30*60000 } } break case 'error': query = {'protocolError': {'$exists': true}} break default: console.log('unknown select type', tokens[0]) break } } if(!query){ let updateEndTime = new moment() let updateDuration = updateEndTime.diff(updateStartTime) this.emit('update-complete', {query, updateDuration}) return } await this.doQuery(query, updateStartTime) } async doQuery(query, updateStartTime=new moment()){ console.log('running query...', query) this.emit('search-start', {query}) let searchStartTime = new moment() const devices = this.db.getCollection('ble').chain().find(query).data() let searchEndTime = new moment() let searchDuration = searchEndTime.diff(searchStartTime) this.emit('search-finished', {query, render: {count: devices.length}, searchDuration}) let durations = {searchDuration} //console.log('rendering devices...', devices) if(devices != null){ this.emit('render-start') let renderStartTime = new moment() await delay(30) await this.renderBleDeviceList(devices) let renderEndTime = new moment() let renderDuration = renderEndTime.diff(renderStartTime) durations.renderDuration = renderDuration this.emit('render-finished', {query, render: this.lastRender, renderDuration}) } let updateEndTime = new moment() let updateDuration = updateEndTime.diff(updateStartTime) this.emit('update-finished', {query, render: this.lastRender, updateDuration, ...durations}) this.lastQuery = query } parseServiceSearch(service, terms){ let query = {} if(terms.length==0){ return } switch(service){ case 'ibeacon': query = { 'ibeacon.uuid': { $contains: terms[0] } } break case 'findmy': query = { 'findmy.maintained': { $eq: terms[0] == 'found'}} break default: break } return query } async renderBleDeviceList(bleDevices){ this.lastRender = { count: bleDevices.length, onscreen: 0, drawable: 0 } console.log('\trendering', bleDevices.length, 'ble devices') let restrictToBounds = this.restrictToBounds || bleDevices.length > 3000 let layer = Leaflet.layerGroup() let count = 0 for (let dev of bleDevices) { //if(dev.duration < 30*60000){ continue } count++ if((count % 500) == 0){ await delay(1) } let lastPt = dev.lastlocation let firstPt = dev.firstlocation if(!lastPt || !firstPt){ continue } let corner1 = new Leaflet.LatLng(lastPt.lat, lastPt.lon) let corner2 = new Leaflet.LatLng(firstPt.lat, firstPt.lon) let bounds = new Leaflet.LatLngBounds(corner1, corner2) this.lastRender.drawable++ if(restrictToBounds == true && !this.map.getBounds().intersects(bounds)) { continue } this.lastRender.onscreen++ if (lastPt) { let lastCircle = Leaflet.circle([lastPt.lat, lastPt.lon], { color: 'white', radius: 10, fill:true, weight:1, opacity: 1, fillOpacity:0.3, fillColor:'white' }) layer.addLayer(lastCircle) let onclick = (event)=>{ this.handleClick({ event, type: 'ble', value: dev.address, timestamp: dev.lastseen }) } lastCircle.on('click', onclick) if(firstPt){ let line = Leaflet.polyline([ this.trackToLatLonArray([firstPt, lastPt]) ], { color: 'blue', opacity: 0.5, weight: '5' }) layer.addLayer(line) line.on('click', onclick) let firstCircle = Leaflet.circle([firstPt.lat, firstPt.lon], { color: 'yellow', radius: 5, fill:true, weight:1, opacity: 1 }) layer.addLayer(firstCircle) firstCircle.on('click', (event)=>{ this.handleClick({ event, type: 'ble', value: dev.address, timestamp: dev.firstseen }) }) } } } layer.addTo(this.map) if(this.searchResults != null){ this.map.removeLayer(this.searchResults) delete this.searchResults } this.searchResults = layer return } getBLEDevice(mac){ return this.db.getCollection('ble').find({address:mac})[0] } updateDeviceInfoHud(){ let devices = Object.keys( this.deviceLayers ) if(devices.length == 0){ window.MainWindow.hideDiv('device-info') /*let deviceInfo = document.getElementById('device-info') deviceInfo.classList.add('hidden')*/ } else { let device = this.getBLEDevice(devices[0]) console.log('updateDeviceInfoHud', device) //document.getElementById('device-info-mac').textContent = reach(device, 'address') //document.getElementById('device-info-name').textContent = reach(device, 'advertisement.localName') let companyText = '' if(reach(device, 'company')){ if(!reach(device,'companyCode')){ companyText=reach(device, 'company') } else { companyText=reach(device, 'company') + '(' + reach(device, 'companyCode') + ')' } } else if(reach(device, 'companyCode')){ companyText='Unknown Company' + '(0x' + reach(device, 'companyCode') + ')' } if(reach(device, 'product')){ if(companyText.length > 0){ companyText+='\n' } companyText+=reach(device, 'product') } document.getElementById('device-info-address').textContent = reach(device, 'address') if(reach(device, 'advertisement.localName')){ document.getElementById('device-info-name').textContent = reach(device, 'advertisement.localName') window.MainWindow.showDiv('device-info-name') } else{ window.MainWindow.hideDiv('device-info-name') } document.getElementById('device-info-company').textContent = companyText //document.getElementById('device-info-company').textContent = companyText //document.getElementById('device-info-product').textContent = productText let serviceText = '' if(device.appleContinuityTypeCode){ let appleService = RFParty.lookupAppleService( device.appleContinuityTypeCode) if(appleService){ serviceText+= 'Apple ' + appleService + '(0x' + device.appleContinuityTypeCode + '); \n' } else{ serviceText+= 'Apple ' + '0x' + device.appleContinuityTypeCode + '; \n' } } if(device.appleIp){ serviceText+= 'Apple IP ' + device.appleIp + '; \n' } device.advertisement.serviceUuids.map(uuid=>{ let name = RFParty.lookupDeviceUuid(uuid) if(name){ serviceText += name + '(0x' + uuid + '); \n' } else { serviceText += '0x' + uuid + '; \n' } }) document.getElementById('device-info-services').textContent = serviceText let details = document.getElementById('device-info-detailscontainer') while (details.firstChild) { details.removeChild(details.firstChild) } this.detailsViewer = new JSONViewer({ container: details, data: JSON.stringify(device), theme: 'dark', expand: false }) // //! @todo window.MainWindow.showDiv('device-info') } } handleClick({type, value, timestamp, event}){ console.log('clicked type=', type, value, timestamp, event) if(type == 'ble'){ console.log('shift', event.originalEvent.shiftKey) //this.selectedLayers = [ value ] let layer = Leaflet.layerGroup() let device = this.getBLEDevice(value) let devicePathLL = [] for(let observation of device.seen){ let pt = this.getTrackPointByTime(observation.timestamp) if(pt){ devicePathLL.push([ pt.lat, pt.lon ]) let circle = Leaflet.circle([pt.lat, pt.lon], { color: 'green', radius: 8, fill:true, weight:1, opacity: 0.9 }) circle.on('click', (event)=>{ this.handleClick({ event, type: 'ble', value: device.address, timestamp: observation.timestamp }) }) layer.addLayer(circle) } } if(devicePathLL.length > 0){ let line = Leaflet.polyline(devicePathLL, { color: 'green', opacity: 0.9, weight: '4' }) line.on('click', (event)=>{ this.handleClick({ event, type: 'ble', value: device.address, timestamp: device.lastseen }) }) layer.addLayer(line) } if(!event.originalEvent.shiftKey){ for(let mac in this.deviceLayers){ let l = this.deviceLayers[mac] this.map.removeLayer(l) delete this.deviceLayers[mac] } } this.deviceLayers[ value ] = layer layer.addTo(this.map) this.updateDeviceInfoHud() } } getTrackPointByTime(timestamp) { let bestDeltaMs = null let bestPoint = null let track = this.getTrackByTime(timestamp - 1200000, timestamp + 6000) for (let point of track) { let deltaMs = Math.abs(moment(point.timestamp).diff(track.timestamp)) if (deltaMs < bestDeltaMs || bestDeltaMs == null) { bestDeltaMs = deltaMs bestPoint = point } } return bestPoint } getTrackByTime(starttime, endtime) { return this.db.getCollection('locationTrack').find({ timestamp: { $between: [starttime, endtime] } }) } trackToLatLonArray(track) { let llarr = [] for (let point of track) { llarr.push([ point.lat, point.lon ]) } return llarr } getTrackPointsByTime(start, end) { let llpoints = [] let track = this.getTrackByTime(start, end) for (let point of track) { llpoints.push(Leaflet.point(point.lat, point.lon)) } return llpoints } getTrackBoundsByTime(starttime, endtime) { let points = this.getTrackPointsByTime(starttime, endtime) return Leaflet.bounds(points) } async addScanDb(serializedDb, name) { //console.log('opening scan db', name, '...') let scanDb = new Loki(name) scanDb.loadJSON(serializedDb) //console.log('opened scan db', name) let homeState = this.db.getCollection('homeState') let bleColl = this.db.getCollection('ble') let scanDbWifi = scanDb.getCollection('wifi') let scanDbHomeState = scanDb.getCollection('homeState') let scanDbBle = scanDb.getCollection('ble') let dbInfo = scanDb.listCollections() //console.log(dbInfo) let parts = scanDbHomeState.count() + scanDbBle.count() + scanDbWifi.count() window.loadingState.startStep('index '+name, parts) console.log('importing home state . . .') let awayObj = null let isAway = false let count = 0 for (let state of scanDbHomeState.chain().find().simplesort('timestamp').data()) { homeState.insert({ timestamp: state.timestamp, isHome: state.isHome, filename: name }) window.loadingState.completePart('index '+name) count++ if(count%3000 == 0){ await delay(10) } if (!isAway && !state.isHome) { //! Device is now away awayObj = { starttime: state.timestamp, endtime: null, duration: null } isAway = true } else if (isAway && state.isHome) { //! Device is now home awayObj.endtime = state.timestamp awayObj.duration = moment(state.timestamp).diff(awayObj.starttime) let points = this.getTrackPointsByTime(awayObj.starttime, awayObj.endtime) if (points.length > 0) { let bounds = Leaflet.bounds(points) awayObj.bounds = { min: { x: bounds.min.x, y: bounds.min.y }, max: { x: bounds.max.x, y: bounds.max.y } } } this.db.getCollection('awayTime').insert(awayObj) //console.log('timeaway', awayObj) //console.log(moment(awayObj.starttime).format(), 'to', moment(awayObj.endtime).format()) awayObj = null isAway = false } } console.log('importing ble . . .') for (let device of scanDbBle.chain().find().data({ removeMeta: true })) { let start = device.seen[0].timestamp let end = device.seen[device.seen.length - 1].timestamp window.loadingState.completePart('index '+name) count++ if(count%500 == 0){ await delay(10) } let firstlocation = this.getTrackPointByTime(start) if(firstlocation){ firstlocation = {lat: firstlocation.lat, lon: firstlocation.lon} } let lastlocation = this.getTrackPointByTime(end) if(lastlocation){ lastlocation = {lat: lastlocation.lat, lon: lastlocation.lon} } let duration = Math.abs( moment(start).diff(end) ) let doc = { firstseen: start, lastseen: end, firstlocation: firstlocation, lastlocation, duration, product: [], services: [], //localname: device.advertisement.localname, ...device } device.advertisement.serviceUuids.map(uuid=>{ let found = RFParty.lookupDeviceUuid(uuid) if(!found){ if(!doc.hasUnknownService){ doc.hasUnknownService=[] } doc.hasUnknownService.push(uuid) } else if(found && found.indexOf('Product') != -1){ doc.product = found doc.services.push(found) } else if(found && found.indexOf('Service') != -1){ doc.services.push(found) } else if (!device.advertisement.manufacturerData && found){ doc.company = found } }) /*if(device.advertisement.serviceUuids.length > 0){ for(let uuid in ){ } }*/ if(device.advertisement.manufacturerData ){ const manufacturerData = Buffer.from(device.advertisement.manufacturerData) const companyCode = manufacturerData.slice(0, 2).toString('hex').match(/.{2}/g).reverse().join('') doc.companyCode = companyCode doc.company = RFParty.lookupDeviceCompany(companyCode) // Parse Apple Continuity Messages if(companyCode == '004c'){ const subType = manufacturerData.slice(2, 3).toString('hex') const subTypeLen = manufacturerData[3] doc.appleContinuityTypeCode = subType if( subTypeLen + 4 > manufacturerData.length){ //console.error(device + originalJSON) doc.protocolError = { appleContinuity: 'incorrect message length[' + subTypeLen +'] when ' + (manufacturerData.length-4) + ' (or less) was expected' } console.warn(doc.address + ' - ' + doc.protocolError.appleContinuity) //throw new Error('corrupt continuity message???') } let appleService = RFParty.lookupAppleService(subType) if(appleService){ doc.services.push( appleService ) } if(subType =='09'){ // Parse AirPlayTarget messages const devIP = manufacturerData.slice( manufacturerData.length-4, manufacturerData.length ) const appleIp = devIP[0] + '.' + devIP[1] + '.' + devIP[2] + '.' + devIP[3] doc.appleIp = appleIp } else if(subType == '02'){ // Parse iBeacon messages if(subTypeLen != 21){ doc.protocolError = { ibeacon: 'incorrect message length[' + subTypeLen +'] when 21 bytes was expected' } console.warn(doc.address + ' - ' + doc.protocolError.ibeacon) } else{ doc.ibeacon = { uuid: manufacturerData.slice(4, 19).toString('hex'), major: manufacturerData.slice(20, 21).toString('hex'), minor: manufacturerData.slice(22, 23).toString('hex'), txPower: manufacturerData.readInt8(24) } } } else if(subType == '12'){ // Parse FindMy messages const status = manufacturerData[4] const maintained = (0x1 & (status >> 2)) == 1 ? true : false doc.findmy = { maintained } } else if(subType == '10'){ // Parse NearbyInfo messages const flags = manufacturerData[4] >> 4 const actionCode = manufacturerData[4] & 0x0f const status = manufacturerData[5] doc.nearbyinfo = { flags: { unknownFlag1: Boolean((flags & 0x2) > 0), unknownFlag2: Boolean((flags & 0x8) > 0), primaryDevice: Boolean((flags & 0x1) > 0), airdropRxEnabled: Boolean((flags & 0x4) > 0), airpodsConnectedScreenOn: Boolean((status & 0x1) > 0), authTag4Bytes: Boolean((status & 0x02) > 0), wifiOn: Boolean((status & 0x4) > 0), hasAuthTag: Boolean((status & 0x10) > 0), watchLocked: Boolean((status & 0x20) > 0), watchAutoLock: Boolean((status & 0x40) > 0), autoLock: Boolean((status & 0x80) > 0) }, actionCode, action: DeviceIdentifiers.NearbyInfoActionCode[actionCode] } } else if (subType == '0f'){ // Parse NearbyAction messages const flags = manufacturerData[4] const action = manufacturerData[5] doc.nearbyaction = { type: DeviceIdentifiers.NearbyActionType[action] } } } } bleColl.insert(doc) } for (let device of scanDbWifi.chain().find().data({ removeMeta: true })){ window.loadingState.completePart('index '+name) count++ if(count%500 == 0){ await delay(1) } } console.log('importing wifi . . .') window.loadingState.completeStep('index '+name) await delay(200) //! @todo support a flag for whether sources should be kept after importing //this.scanDb = scanDb } async addGpx(obj, name) { console.log('adding gpx', name) let collection = this.db.getCollection('locationTrack') //this.gpx[name]=obj const trackPoints = JSONPath({ json: obj, path: '$..trkpt', flatten: true }) if(!trackPoints){ window.loadingState.startStep('index '+name, 1) window.loadingState.completeStep('index '+name) console.log('added gpx', name, 'with', undefined, 'points') return } window.loadingState.startStep('index '+name, trackPoints.length) let latlngs = [] let count = 0 for (let point of trackPoints) { const src = reach(point, 'src.value') const lat = reach(point, '_attributes.lat') const lon = reach(point, '_attributes.lon') const time = moment(reach(point, 'time.value')) window.loadingState.completePart('index '+name) count++ if(count%500 == 0){ await delay(0) } collection.insert({ filename: name, elevation: reach(point, 'ele.value'), course: reach(point, 'course.value'), speed: reach(point, 'speed.value'), source: reach(point, 'src.value'), timestamp: time.valueOf(), lat: lat, lon: lon }) latlngs.push([lat, lon]) if (!src) { continue } if (!this.srcs[src]) { this.srcs[src] = 1 } { this.srcs[src]++ } } //console.log('loaded gpx', name) if(this.showAllTracks){ this.gpxLines[name] = Leaflet.polyline(latlngs, { color: 'red', opacity: 0.4, weight: '2' }) //this.gpxLines[name].addLayer(this.gpxLayer) //this.gpxLayer.addLayer(this.gpxLines[name]) } window.loadingState.completeStep('index '+name) console.log('added gpx', name, 'with', trackPoints.length, 'points') //console.log('latlong', latlngs) //console.log('tracks', trackPoints) } static get Version() { return Pkg.version } static lookupDeviceCompany(code){ return MANUFACTURER_TABLE.Company[code] } static lookupAppleService(code){ return DeviceIdentifiers.APPLE_Continuity[code] } static lookupUuid16(uuid){ const types = Object.keys(UUID16_TABLES) for(let type of types){ let found = UUID16_TABLES[type][uuid] if(found){ return '/'+type+'/'+found } } } static lookupDeviceUuid(uuid){ let deviceType = null if(uuid.length == 4){ //deviceType = DeviceIdentifiers.UUID16[uuid] deviceType = RFParty.lookupUuid16(uuid) } else if(uuid.length == 32){ deviceType = DeviceIdentifiers.UUID[uuid] } return deviceType } static reverseLookupService(term){ let possibles = [] const types = Object.keys(UUID16_TABLES) for(let type of types){ possibles.push( ...(RFParty.reverseLookupByName( UUID16_TABLES[type], term, '/'+type+'/' ).map( name=>{return '/'+type+'/'+name }) ) ) } return possibles.concat( RFParty.reverseLookupByName(DeviceIdentifiers.APPLE_Continuity, term), RFParty.reverseLookupByName(DeviceIdentifiers.UUID, term) ) } static reverseLookupByName(map, text, prefix=''){ let names = [] const lowerText = text.toLowerCase() for(let code in map){ const name = map[code] const prefixedName = prefix+name const lowerName = prefixedName.toLowerCase() if(lowerName.indexOf(lowerText) != -1 ){ names.push(name) } } return names } }
JavaScript
class Mixable extends EventEmitter { static with(mixins) { assert(Array.isArray(mixins), '`mixins` should be an array of mixins'); let newClass = this; mixins.forEach(m => { newClass = m(newClass); }); return newClass; } }
JavaScript
class MessageRepository{ add(messageInstance) { return Promise.reject(new Error('not implemented')); } update(messageInstance) { return Promise.reject(new Error('not implemented')); } delete(messageInstance) { return Promise.reject(new Error('not implemented')); } getById(messageId) { return Promise.reject(new Error('not implemented')); } getByUserId(userId){ return Promise.reject(new Error('not implemented')); } getAll() { return Promise.reject(new Error('not implemented')); } // addRoom(messageInstance, room) { // return Promise.reject(new Error('not implemented')); // } }
JavaScript
class NormalisedEvent { constructor(refinedData, rawData) { this.body = refinedData; this.data = rawData; } id(){ return hash(this.data) } }
JavaScript
class GrowingMethodController { /** * Retrieve a Growing Method [GET /packhouse/sites/{siteId}/growing-methods/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Growing Method ID * @return {Promise<GrowingMethodModel>} */ static getOne(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/packhouse/sites/${siteId}/growing-methods/${id}`) .then((result) => { let resolveValue = (function(){ return GrowingMethodModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Update a Growing Method [PATCH /packhouse/sites/{siteId}/growing-methods/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Growing Method ID * @param {GrowingMethodController.UpdateData} updateData The Growing Method Update Data * @return {Promise<GrowingMethodModel>} */ static update(siteId, id, updateData) { return new Promise((resolve, reject) => { RequestHelper.patchRequest(`/packhouse/sites/${siteId}/growing-methods/${id}`, updateData) .then((result) => { let resolveValue = (function(){ return GrowingMethodModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Delete a Growing Method [DELETE /packhouse/sites/{siteId}/growing-methods/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Growing Method ID * @return {Promise<boolean>} */ static delete(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.deleteRequest(`/packhouse/sites/${siteId}/growing-methods/${id}`) .then((result) => { resolve(result ?? true); }) .catch(error => reject(error)); }); } /** * List all Growing Methods [GET /packhouse/sites/{siteId}/growing-methods] * * @static * @public * @param {number} siteId The Site ID * @param {GrowingMethodController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<GrowingMethodModel[]>} */ static getAll(siteId, queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/packhouse/sites/${siteId}/growing-methods`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ return GrowingMethodModel.fromJSON(resultItem); }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Create a Growing Method [POST /packhouse/sites/{siteId}/growing-methods] * * @static * @public * @param {number} siteId The Site ID * @param {GrowingMethodController.CreateData} createData The Growing Method Create Data * @return {Promise<GrowingMethodModel>} */ static create(siteId, createData) { return new Promise((resolve, reject) => { RequestHelper.postRequest(`/packhouse/sites/${siteId}/growing-methods`, createData) .then((result) => { let resolveValue = (function(){ return GrowingMethodModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } }
JavaScript
class KeyDto { /** * Create new key data. * @param {String} value - The key's value. */ constructor(value = '') { this.value = value; } /** * Serializes the key object. * @returns {object} A JSON representation of the key. */ toJSON() { return { value: this.value, }; } /** * Deserialize JSON data. * @param {object} object - The object to deserialize. * @returns {KeyDto} The key object from the JSON. */ static fromJSON(object) { return new KeyDto(object.value); } }
JavaScript
class UserModel extends BaseModel { /** * Constructor * @param {Object} props */ constructor(opts) { super(opts); this._table = constants.DB_TABLES.TBL_USERS; this._hasTimestamps = false; } /** * * @param {*} params * @returns Newly added user */ async addNewUser(params) { try { const conn = await this._initDbConnectionPool(); const { rows } = await conn.query( `INSERT INTO ${this._table} (username, email, password) VALUES ($1, $2, $3, $4, $5)`, params, ); return rows; } catch (err) { console.error(err); throw err; } } /** * * @param {*} params * @returns User Details */ async getUserDetails(params) { try { const conn = await this._initDbConnectionPool(); const { rows } = await conn.query( `SELECT * FROM ${this._table} WHERE id = $1`, params, ); return rows; } catch (err) { console.error(err); throw err; } } /** * * @param {*} params * @returns Updated User Details */ async updateUserDetails(params) { try { const conn = await this._initDbConnectionPool(); const { rows } = await conn.query( `UPDATE ${this._table} WHERE id = $1 `, params, ); return rows; } catch (err) { console.error(err); throw err; } } /** * * @param {*} params * @returns Delete user info */ async deleteUser(params) { try { const conn = await this._initDbConnectionPool(); const { rows } = await conn.query( `DELETE FROM ${this._table} WHERE id ? `, params, ); return rows; } catch (err) { console.error(err); throw err; } } }
JavaScript
class MulterProxyStorage { constructor (opts) { this.opts = opts } _handleFile (req, file, cb) { var form = new FormData() // Use filepath to specify the file's fullpath. If we use filename, it'll be cut down into only the filename form.append(this.opts.fileParamName || 'file', file.stream, {filepath: file.originalname}) form.pipe(concat({encoding: 'buffer'}, data => { axios.post( this.opts.serverPath, data, {headers: form.getHeaders(), timeout: UPLOAD_TIMEOUT} ).then(resp => { req.serverResp = resp.data cb(null) }).catch(err => { cb(err) }) })) } _removeFile (req, file, cb) { cb(null) } }
JavaScript
class AbstractProvider { constructor(config) { this.config = config || {}; } ////////////////////////////////////////////////////////////////////////////////////////////////////////// // // ABSTRACT METHODS // ////////////////////////////////////////////////////////////////////////////////////////////////////////// init(callback) { throw new Error("init() method is not implemented"); } register(channelId, user, callback) { throw new Error("register() method is not implemented"); } discover(channelId, callback) { throw new Error("discover() method is not implemented"); } expire(beforeMs, callback) { throw new Error("expire() method is not implemented"); } checkRegistered(channelId, userId, callback) { throw new Error("checkRegistered() method is not implemented"); } acquireLock(lockId, user, callback) { throw new Error("acquireLock() method is not implemented"); } releaseLock(lockId, userId, callback) { throw new Error("releaseLock() method is not implemented"); } lockInfo(lockId, callback) { throw new Error("lockInfo() method is not implemented"); } acquireSession(sessionId, callback) { throw new Error("acquireSession() method is not implemented"); } updateSession(sessionId, session, callback) { throw new Error("updateSession() method is not implemented"); } deleteSession(sessionId, callback) { throw new Error("deleteSession() method is not implemented"); } }
JavaScript
class AnimationOverlay extends Disposable { /** * Constructor. * @param {AnimationOverlayOptions=} opt_options Options. */ constructor(opt_options) { super(); var options = opt_options !== undefined ? opt_options : {}; /** * @type {!Array<!Feature>} * @private */ this.features_ = []; /** * @type {OLVectorSource} * @private */ this.source_ = new OLVectorSource({ features: this.features_, useSpatialIndex: false }); /** * @type {OLVectorLayer} * @private */ this.layer_ = new AnimationVector({ renderOrder: null, source: this.source_, updateWhileAnimating: true, updateWhileInteracting: true, zIndex: options.zIndex }); if (options.opacity != null) { this.setOpacity(options.opacity); } if (options.style != null) { this.setStyle(options.style); } if (options.features != null && Array.isArray(options.features)) { this.setFeatures(clone(options.features)); } if (options.map != null) { this.setMap(options.map); } } /** * @inheritDoc */ disposeInternal() { super.disposeInternal(); this.setMap(null); this.features_.length = 0; this.source_.dispose(); this.source_ = null; this.layer_.dispose(); this.layer_ = null; } /** * Fires a changed event on the source to trigger rendering. * * Performance note: Do NOT fire events while in 3D mode because this layer will be rendered by the 2D map since it is * not in the hidden root layer group. */ changed() { if (this.source_ && !getMapContainer().is3DEnabled()) { this.source_.changed(); } } /** * Get the features in the overlay. * * @return {!Array<!Feature>} Features collection. */ getFeatures() { return this.features_; } /** * Set the features rendered on the map. * * @param {Array<!Feature>|undefined} features Features collection. */ setFeatures(features) { // this function modifies the feature array directly instead of modifying the collection. this will prevent events // from being fired by the collection, and instead we call changed on the source once after the update. this.features_.length = 0; if (features && features.length > 0) { this.features_.length = features.length; for (var i = 0, n = features.length; i < n; i++) { this.features_[i] = features[i]; } } this.changed(); } /** * Set the map reference on the layer. * * @param {ol.PluggableMap} map Map. */ setMap(map) { if (this.layer_) { this.layer_.setMap(map); } } /** * Set the style for features. This can be a single style object, an array of styles, or a function that takes a * feature and resolution and returns an array of styles. * * @param {Style|Array<Style>|ol.StyleFunction} style Overlay style. */ setStyle(style) { if (this.layer_) { this.layer_.setStyle(style); } } /** * Sets the overall opacity on the overlay layer. * * @param {number} value */ setOpacity(value) { if (this.layer_) { this.layer_.setOpacity(value); } } /** * Sets the z-index on the overlay layer. * * @param {number} value */ setZIndex(value) { if (this.layer_) { this.layer_.setZIndex(value); } } }
JavaScript
class CalendarEvent { /** * @param {Object} calendarEvent */ constructor(calendarEvent) { this.calendarEvent = calendarEvent; } /** * get the start time for an event * @return {String} */ get startDateTime() { if (this.calendarEvent.start.date) { const dateTime = moment(this.calendarEvent.start.date); return dateTime.toISOString(); } return this.calendarEvent.start && this.calendarEvent.start.dateTime || this.calendarEvent.start || ''; } /** * get the end time for an event * @return {String} */ get endDateTime() { return this.calendarEvent.end && this.calendarEvent.end.dateTime || this.calendarEvent.end || ''; } /** * get the URL for an event * @return {String} */ get htmlLink() { return this.calendarEvent.htmlLink || ''; } /** * get the title for an event * @return {String} */ get title() { return this.calendarEvent.summary || this.calendarEvent.title || ''; } /** * get the description for an event * @return {String} */ get description() { return this.calendarEvent.description; } /** * parse location for an event * @return {String} */ get location() { if (!this.calendarEvent.location) return ''; return this.calendarEvent.location.split(',')[0] || ''; } /** * get location address for an event * @return {String} */ get locationAddress() { if (!this.calendarEvent.location) return ''; const address = this.calendarEvent.location.substring(this.calendarEvent.location.indexOf(',') + 1); return address.split(' ').join('+'); } /** * is the event a full day event? * @return {Boolean} */ get isFullDayEvent() { if (this.calendarEvent.start && this.calendarEvent.start.date) { return this.calendarEvent.start.date; } const start = moment(this.startDateTime); const end = moment(this.endDateTime); const diffInHours = end.diff(start, 'hours'); return diffInHours >= 24; } }
JavaScript
class Routine { /** * @param {!number} id */ constructor(id) { /** * Routine ID created when the routine is first requested to run. * @type { !number } * @const */ this.id = id; } /** * Sends |command| on this routine to the backend. * @param {!string} command * @return {!Promise<!dpsl.RoutineStatus>} * @private */ async _getRoutineUpdate(command) { const request = { id: this.id, command: command, }; return /** @type {!dpsl.RoutineStatus} */ ( chrome.os.diagnostics.getRoutineUpdate(request)); } /** * Returns current status of this routine. * @return { !Promise<!dpsl.RoutineStatus> } * @public */ async getStatus() { return this._getRoutineUpdate(ROUTINE_COMMAND_TYPE.GET_STATUS); } /** * Resumes this routine, e.g. when user prompts to run a waiting routine. * @return { !Promise<!dpsl.RoutineStatus> } * @public */ async resume() { return this._getRoutineUpdate(ROUTINE_COMMAND_TYPE.RESUME); } /** * Stops this routine, if running, or remove otherwise. * Note: The routine cannot be restarted again. * @return { !Promise<!dpsl.RoutineStatus> } * @public */ async stop() { this._getRoutineUpdate(ROUTINE_COMMAND_TYPE.CANCEL); return this._getRoutineUpdate(ROUTINE_COMMAND_TYPE.REMOVE); } }
JavaScript
class BatteryManager { /** * Runs battery capacity test. * @return { !Promise<!Routine> } * @public */ async runCapacityRoutine() { return chrome.os.diagnostics.runBatteryCapacityRoutine().then( (response) => new Routine(response.id)); } /** * Runs battery health test. * @return { !Promise<!Routine> } * @public */ async runHealthRoutine() { return chrome.os.diagnostics.runBatteryHealthRoutine().then( (response) => new Routine(response.id)); } /** * Runs battery capacity test. * @param {!dpsl.BatteryDischargeRoutineParams} params * @return { !Promise<!Routine> } * @public */ async runDischargeRoutine(params) { return chrome.os.diagnostics.runBatteryDischargeRoutine(params).then( (response) => new Routine(response.id)); } /** * Runs battery charge test. * @param {!dpsl.BatteryChargeRoutineParams} params * @return { !Promise<!Routine> } * @public */ async runChargeRoutine(params) { return chrome.os.diagnostics.runBatteryChargeRoutine(params).then( (response) => new Routine(response.id)); } }
JavaScript
class CpuManager { /** * Runs CPU cache test. * @param {!dpsl.CpuRoutineDurationParams} params * @return { !Promise<!Routine> } * @public */ async runCacheRoutine(params) { return chrome.os.diagnostics.runCpuCacheRoutine(params).then( (response) => new Routine(response.id)); } /** * Runs CPU stress test. * @param {!dpsl.CpuRoutineDurationParams} params * @return { !Promise<!Routine> } * @public */ async runStressRoutine(params) { return chrome.os.diagnostics.runCpuStressRoutine(params).then( (response) => new Routine(response.id)); } /** * Runs CPU floating point accuracy test. * @param {!dpsl.CpuRoutineDurationParams} params * @return { !Promise<!Routine> } * @public */ async runFloatingPointAccuracyRoutine(params) { return chrome.os.diagnostics.runCpuFloatingPointAccuracyRoutine(params) .then((response) => new Routine(response.id)); } /** * Runs CPU prime search test. * @param {!dpsl.CpuRoutineDurationParams} params * @return { !Promise<!Routine> } * @public */ async runPrimeSearchRoutine(params) { return chrome.os.diagnostics.runCpuPrimeSearchRoutine(params).then( (response) => new Routine(response.id)); } }
JavaScript
class MemoryManager { /** * Runs memory test. * @return { !Promise<!Routine> } * @public */ async runMemoryRoutine() { return chrome.os.diagnostics.runMemoryRoutine().then( (response) => new Routine(response.id)); } }
JavaScript
class DPSLDiagnosticsManager { /** * @constructor */ constructor() { /** * @type {!BatteryManager} * @public */ this.battery = new BatteryManager(); /** * @type {!CpuManager} * @public */ this.cpu = new CpuManager(); /** * @type {!MemoryManager} * @public */ this.memory = new MemoryManager(); } /** * Requests a list of available diagnostics routines. * @return { !Promise<!dpsl.AvailableRoutinesList> } * @public */ async getAvailableRoutines() { return chrome.os.diagnostics.getAvailableRoutines(); } }
JavaScript
class EmployeeFieldPicklistValues { /** * Constructs a new <code>EmployeeFieldPicklistValues</code>. * @alias module:model/EmployeeFieldPicklistValues */ constructor() { EmployeeFieldPicklistValues.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) {} /** * Constructs a <code>EmployeeFieldPicklistValues</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/EmployeeFieldPicklistValues} obj Optional instance to populate. * @return {module:model/EmployeeFieldPicklistValues} The populated <code>EmployeeFieldPicklistValues</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new EmployeeFieldPicklistValues(); if (data.hasOwnProperty("id")) { obj["id"] = ApiClient.convertToType(data["id"], "Number"); } if (data.hasOwnProperty("value")) { obj["value"] = ApiClient.convertToType(data["value"], "String"); } if (data.hasOwnProperty("position")) { obj["position"] = ApiClient.convertToType(data["position"], "Number"); } if (data.hasOwnProperty("pickable_type")) { obj["pickable_type"] = ApiClient.convertToType(data["pickable_type"], "String"); } if (data.hasOwnProperty("pickable_id")) { obj["pickable_id"] = ApiClient.convertToType(data["pickable_id"], "Number"); } } return obj; } }
JavaScript
class ManageButton extends React.Component { /** * Render function * @return {Component} A button */ render() { return ( <Button className={this.props.className} type='primary'> Manage </Button> ); } }
JavaScript
class NoFeedTour { /** * Show a tour styling, guiding the user to new feeds. */ show() { UserActivityLogger.log(USER_EVENT_SHOW); $(HTML_ID_EMPTY_ARTICLE_LIST).show(); $(HTML_CLASS_TOUR).addClass(HTML_CLASS_NAME_WIGGLE); $(HTML_CLASS_MDL_BURGER).addClass(HTML_CLASS_NAME_WIGGLE); } /** * Hides the tour styling. */ hide() { $(HTML_ID_EMPTY_ARTICLE_LIST).hide(); $(HTML_CLASS_TOUR).removeClass(HTML_CLASS_NAME_WIGGLE); $(HTML_CLASS_MDL_BURGER).removeClass(HTML_CLASS_NAME_WIGGLE); } }
JavaScript
class PostsShow extends Component { static contextTypes = { router: PropTypes.object } componentWillMount() { // pull id out of url, pass it to fetchPost, which makes the back-end request, resolves some data, reducer picks up resolved promise, then want to show it here this.props.fetchPost(this.props.params.id); } onDeleteClick() { // onClick handler to call AC this.props.deletePost(this.props.params.id) .then(() => { // navigate user back to index this.context.router.push('/'); }) } render() { // still working off of this.props.post const { post } = this.props; //^ equivalent to... // const post = this.props.post if (!post) { // can implement a spinner here... while loading return <div>Loading...</div> } return ( <div> <Link to="/">Back To Index</Link> <button className="btn btn-danger pull-xs-right" onClick={this.onDeleteClick.bind(this)}> Delete Post </button> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ) } }
JavaScript
class Controller { /** * Constructor. * @param {!angular.Scope} $scope * @param {!angular.JQLite} $element * @ngInject */ constructor($scope, $element) { /** * @type {?angular.Scope} * @private */ this.scope_ = $scope; /** * @type {?angular.JQLite} * @private */ this.element_ = $element; this.scope_['short'] = false; this.scope_['showFullDescription'] = false; this.updateIcons(); /** * @type {number|undefined} */ this['featureCount'] = undefined; var result = /** @type {plugin.descriptor.DescriptorResult} */ (this.scope_['result']); if (result && result.featureCount != null) { this['featureCount'] = result.featureCount; } $scope.$on('$destroy', this.destroy_.bind(this)); } /** * Clean up the controller. * * @private */ destroy_() { this.element_ = null; this.scope_ = null; } /** * Updates icons */ updateIcons() { var icons = this.element_.find('.js-card-title-icons'); // clear icons.children().remove(); // add icons.prepend(this.getField('icons')); } /** * @return {os.data.IDataDescriptor} the descriptor */ getDescriptor() { var result = /** @type {plugin.descriptor.DescriptorResult} */ (this.scope_['result']); return result ? result.getResult() : null; } /** * Get a field from the result. * * @param {string} field * @return {*} * @export */ getField(field) { var d = this.getDescriptor(); if (d) { switch (field.toLowerCase()) { case 'id': return d.getId(); case 'active': return d.isActive(); case 'icons': return d.getIcons(); case 'provider': return d.getProvider(); case 'tags': return d.getTags().join(', '); case 'title': return d.getTitle(); case 'type': return d.getSearchType(); case 'description': return d.getDescription(); default: break; } } return ''; } /** * Toggles the descriptor * @param {Event} event The click event. * * @export */ toggle(event) { event.preventDefault(); event.stopPropagation(); var d = this.getDescriptor(); if (d) { d.setActive(!d.isActive()); if (d.isActive()) { dispatcher.getInstance().dispatchEvent(new DescriptorEvent(DescriptorEventType.USER_TOGGLED, d)); } } } }
JavaScript
class ContactForm extends Component { constructor(props) { super(props); this.isCaptchaValid = false; this.state = { loading: false, swal: internals.swal }; this._bind('handleSubmit', 'handleReset', 'resetForm', 'toggleLoader', 'toggleAlert', 'verifyRecatpchaCallback'); // Add Recaptcha const gRecaptchaScript = document.createElement('script'); gRecaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'); document.head.appendChild(gRecaptchaScript); } handleSubmit(e) { e.preventDefault(); const { form, toggleLoader, toggleAlert, resetForm, isCaptchaValid } = this; let errors = {}; // Check if captcha is filled if (!isCaptchaValid) { const alertOpts = { show: true, type: 'warning', title: 'Are you a robot?', text: 'We need to verify you\'re not a robot, please check the ReCaptcha\'s checkbox.' }; toggleAlert(alertOpts); return false; } errors = form.validateAll(); // If there is an input with validations errors, show Alert if (Object.keys(errors).length > 0) { toggleAlert(Object.assign({}, internals.swal, { show: true })); return false; } toggleLoader(true); _fetch.post('/contact', form.components) .then((json) => { console.log(json); if (json.status === 'success') { toggleAlert({ show: true, type: 'success', title: 'Thank you!', text: 'We appreciate that you\'ve taken the time to write us. We\'ll get back to you very soon. Please come back and see us often.' }); resetForm(form.components); } else { toggleAlert(Object.assign({}, internals.swal, { show: true, text: `The server responded with the following error message: ${ json.message }` })); } }) .catch((error) => { toggleAlert(Object.assign({}, internals.swal, { show: true, text: `There has been a problem with your fetch operation: ${ error.message }` })); }) .then(() => { // Always run this toggleLoader(false); }); return true; } handleReset() { const { form, resetForm } = this; resetForm(form.components); } resetForm(components) { for (const key in components) { if ({}.hasOwnProperty.call(components, key)) { components[key].setState({ value: '' }); } } this.verifyRecatpchaCallback(false); } verifyRecatpchaCallback(response) { const isValid = (!(typeof response === 'boolean')) ? true : response; this.isCaptchaValid = isValid; } toggleLoader(bool) { this.setState({ loading: bool }); } toggleAlert(opts) { console.log(opts); const swal = Object.assign({}, internals.swal, opts); this.setState({ swal }); } render() { const { handleSubmit, handleReset, verifyRecatpchaCallback, state } = this; const { swal, loading } = state; return ( <Form className="container card card-white-green" ref={ f => { this.form = f; } } onSubmit={ handleSubmit } noValidate> <div className="row"> <div className="xs-12 md-offset-1 md-10 xl-offset-2 xl-8"> <p>Please complete the form below with the required information and our Customer Service Team will review and respond as quickly as possible.</p> <div className="field-wrap row"> <label className="form-label xs-12 lg-3">First Name*</label> <Input containerClassName="xs-12 lg-9" className="form-control" type="text" name="firstName" value="" validations={ ['required'] } /> </div> <div className="field-wrap row"> <label className="form-label xs-12 lg-3">Last Name*</label> <Input containerClassName="xs-12 lg-9" className="form-control" type="text" name="lastName" value="" validations={ ['required'] } /> </div> <div className="field-wrap row"> <label className="form-label xs-12 lg-3">Email*</label> <Input containerClassName="xs-12 lg-9" className="form-control" type="email" name="email" value="" validations={ ['required', 'email'] } /> </div> <div className="field-wrap row"> <label className="form-label xs-12 lg-3">Phone*</label> <Input containerClassName="xs-12 lg-9" className="form-control" type="text" name="phone" value="" validations={ ['required'] } /> </div> <div className="field-wrap row"> <label className="form-label xs-12">Type your message below*</label> <Textarea containerClassName="xs-12" className="form-control" type="text" name="message" value="" validations={ ['required'] } /> </div> <div className="row recaptcha-wrap"> <Recaptcha ref={ e => { this.recaptchaInstance = e; } } sitekey={ _app.recaptchaKey } render="explicit" onloadCallback={ () => { console.log('done'); } } verifyCallback={ verifyRecatpchaCallback } /> </div> <div className="row action-btns"> <div className="xs-12 lg-6 xl-offset-4 xl-4"> <Button type="button" className="btn btn-default btn-block" disabled={ false } onClick={ handleReset }>Clear Form</Button> </div> <div className="xs-12 lg-6 xl-4"> <Button className="btn btn-blue btn-block" disabled={ false }>Submit</Button> </div> </div> </div> </div> <SweetAlert show={ swal.show } title={ swal.title } type={ swal.type } text={ swal.text } onConfirm={ () => this.toggleAlert({ show: false }) } confirmButtonColor="#00a5e7" /> <Loader show={ loading } /> </Form> ); } }
JavaScript
class CollectionQueryRule { constructor(field, { sortOrder, filter, filterTo } = {}) { this._field = observable.box(field); this._sortOrder = observable.box(sortOrder); this._filter = observable.box(filter); this._filterTo = observable.box(filterTo); } get field() { return this._field.get(); } set field(val) { this._field.set(val); } get filter() { return this._filter.get(); } set filter(val) { this._filter.set(val); } get filterTo() { return this._filterTo.get(); } set filterTo(val) { this._filterTo.set(val); } get sortOrder() { return this._sortOrder.get(); } set sortOrder(val) { return this._sortOrder.set(val); } }
JavaScript
class HackBan extends Command { /** * @param {Client} client The instantiating client * @param {CommandData} data The data for the command */ constructor(bot) { super(bot, { name: 'hackban', guildOnly: true, dirname: __dirname, userPermissions: ['BAN_MEMBERS'], botPermissions: [ 'SEND_MESSAGES', 'EMBED_LINKS', 'BAN_MEMBERS'], description: 'Ban a user not in a server.', usage: 'hackban <user> [reason] [time]', cooldown: 5000, examples: ['hackban username spamming chat 4d', 'hackban username raiding'], }); } /** * Function for recieving message. * @param {bot} bot The instantiating client * @param {message} message The message that ran the command * @param {settings} settings The settings of the channel the command ran in * @readonly */ async run(bot, message, settings) { // Delete message if (settings.ModerationClearToggle && message.deletable) message.delete(); // check if a user was entered if (!message.args[0]) return message.channel.error('misc:INCORRECT_FORMAT', { EXAMPLE: settings.prefix.concat(message.translate('moderation/hackban:USAGE')) }).then(m => m.timedDelete({ timeout: 10000 })); // Get user and reason const reason = message.args[1] ? message.args.splice(1, message.args.length).join(' ') : message.translate('misc:NO_REASON'); // Get members mentioned in message const user = await message.client.users.fetch(args[0], true, true); // Make sure user isn't trying to punish themselves if (user == message.author) return message.channel.error('misc:SELF_PUNISH').then(m => m.timedDelete({ timeout: 10000 })); // Ban user with reason and check if timed ban try { // send DM to user try { const embed = new Embed(bot, message.guild) .setTitle('moderation/hackban:TITLE') .setColor(15158332) .setThumbnail(message.guild.iconURL()) .setDescription(message.translate('moderation/hackban:DESC', { NAME: message.guild.name })) .addField(message.translate('moderation/hackban:BAN_BY'), message.author.tag, true) .addField(message.translate('misc:REASON'), reason, true); await members[0].send({ embeds: [embed] }); // eslint-disable-next-line no-empty } catch (e) {} // Ban user from guild await message.guild.members.ban(user, { reason: reason }); message.channel.success('moderation/hackban:SUCCESS', { USER: members[0].user }).then(m => m.timedDelete({ timeout: 8000 })); // Check to see if this ban is a tempban const possibleTime = message.args[message.args.length - 1]; if (possibleTime.endsWith('d') || possibleTime.endsWith('h') || possibleTime.endsWith('m') || possibleTime.endsWith('s')) { const time = getTotalTime(possibleTime, message); if (!time) return; // connect to database const newEvent = await new timeEventSchema({ userID: members[0].user.id, guildID: message.guild.id, time: new Date(new Date().getTime() + time), channelID: message.channel.id, type: 'ban', }); await newEvent.save(); // unban user setTimeout(async () => { message.args[0] = members[0].user.id; await bot.commands.get('unban').run(bot, message, settings); // Delete item from database as bot didn't crash await timeEventSchema.findByIdAndRemove(newEvent._id, (err) => { if (err) console.log(err); }); }, time); } } catch (err) { if (message.deletable) message.delete(); bot.logger.error(`Command: '${this.help.name}' has error: ${err.message}.`); message.channel.error('misc:ERROR_MESSAGE', { ERROR: err.message }).then(m => m.timedDelete({ timeout: 5000 })); } } }
JavaScript
class PasswordManager extends React.Component { static navigationOptions = { title: 'Load Wallet' }; constructor(props) { super(props); this.state = { dataSource: 'nothing', }; AsyncStorage.getItem('passwords', (err, result) => { set.state({datasource: JSON.parse(result)}); console.log(result); }); } @autobind addPassword(url, name, username, pass, notes) { const newPassword = { url: url, name: name, username: username, password: pass, notes: notes, timestamp: Date.now() }; AsyncStorage.getItem('passwords', (err, result) => { if(result != undefined) { result = JSON.parse(result); result[result.length + 1] = newPassword; AsyncStorage.setItem('passwords', JSON.stringify(result), () => { }); } else { result = [ { url: url, name: name, username: username, password: pass, notes: notes, timestamp: Date.now() } ]; AsyncStorage.setItem('passwords', JSON.stringify(result), () => { }); } }); } render() { const { navigate, state: { params: { walletName, walletDescription } } } = this.props.navigation; return ( <View style={styles.container}> <Text style={styles.message}>Load the wallet from</Text> <View> <ListView dataSource={this.state.dataSource} renderRow={(data) => <Row {...data} />} /> </View> <View style={styles.buttonsContainer}> <Button children="Add new login details" onPress={() => navigate('LoadPrivateKey', { walletName, walletDescription })} /> <Button children="Mnemonics" onPress={() => navigate('LoadMnemonics', { walletName, walletDescription })} /> </View> </View> ); } }
JavaScript
class ImageReference { /** * Create a ImageReference. * @property {string} [publisher] The publisher of the Azure Virtual Machines * Marketplace Image. For example, Canonical or MicrosoftWindowsServer. * @property {string} [offer] The offer type of the Azure Virtual Machines * Marketplace Image. For example, UbuntuServer or WindowsServer. * @property {string} [sku] The SKU of the Azure Virtual Machines Marketplace * Image. For example, 18.04-LTS or 2019-Datacenter. * @property {string} [version] The version of the Azure Virtual Machines * Marketplace Image. A value of 'latest' can be specified to select the * latest version of an Image. If omitted, the default is 'latest'. * @property {string} [virtualMachineImageId] The ARM resource identifier of * the Virtual Machine Image or Shared Image Gallery Image. Computes Compute * Nodes of the Pool will be created using this Image Id. This is of either * the form * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName} * for Virtual Machine Image or * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{versionId} * for SIG image. This property is mutually exclusive with other * ImageReference properties. For Virtual Machine Image it must be in the * same region and subscription as the Azure Batch account. For SIG image it * must have replicas in the same region as the Azure Batch account. For * information about the firewall settings for the Batch Compute Node agent * to communicate with the Batch service see * https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. */ constructor() { } /** * Defines the metadata of ImageReference * * @returns {object} metadata of ImageReference * */ mapper() { return { required: false, serializedName: 'ImageReference', type: { name: 'Composite', className: 'ImageReference', modelProperties: { publisher: { required: false, serializedName: 'publisher', type: { name: 'String' } }, offer: { required: false, serializedName: 'offer', type: { name: 'String' } }, sku: { required: false, serializedName: 'sku', type: { name: 'String' } }, version: { required: false, serializedName: 'version', type: { name: 'String' } }, virtualMachineImageId: { required: false, serializedName: 'virtualMachineImageId', type: { name: 'String' } } } } }; } }
JavaScript
class Pins extends PureComponent { render() { const {onClick, mode} = this.props; if (this.props.public) { return this.props.clusters.map((cluster, index) => { const [longitude, latitude] = cluster.geometry.coordinates; const { cluster: isCluster, point_count: pointCount } = cluster.properties; if (isCluster) { return <Marker key={cluster.id} longitude={longitude} latitude={latitude}> <div className="cluster-marker" style={{ width: `${25 + (pointCount / this.props.volunteers.length) * 60}px`, height: `${25 + (pointCount / this.props.volunteers.length) * 60}px` }} onClick={()=> { const expansionZoom = Math.min(this.props.supercluster.getClusterExpansionZoom(cluster.id), 12); this.props.setViewport({ ...this.props.viewport, latitude, longitude, zoom: expansionZoom, transitionInterpolator: new FlyToInterpolator({ speed: 2 }), transitionDuration: 'auto' }) }}> </div> </Marker> } return <Marker key={cluster.properties.id} longitude={longitude} latitude={latitude}> <div className="cluster-marker" style={{width: `0px`,height: `0px`, padding: 5}} onClick={()=> { const expansionZoom = 12; this.props.setViewport({ ...this.props.viewport, latitude, longitude, zoom: expansionZoom, transitionInterpolator: new FlyToInterpolator({ speed: 2 }), transitionDuration: 'auto' }) }}> </div> </Marker> }); } var volunteerMarkers = this.props.volunteers.map((request, index) => { return <Marker key={`volunteer-${index}`} longitude={request.longitude} latitude={request.latitude}> <svg height={MARKER_SIZE} viewBox="0 0 24 24" onClick={() => (this.props.public) ? {} : onClick(request)} style={{ cursor: 'pointer', fill: '#2670FF', stroke: 'none', transform: `translate(${-MARKER_SIZE / 2}px,${-MARKER_SIZE}px)` }}> <path d={ICON}/> </svg> </Marker> }) var requests = filter_requests(this.props.allRequests, mode); var color = '#DB4B4B'; if (mode === current_tab.MATCHED) { color = '#8A8A8A'; } else if (mode === current_tab.COMPLETED) { color = '#28a745'; } var requesterMarkers = requests.map((request, index) => { const lat = request.location_info.coordinates[1]; const long = request.location_info.coordinates[0]; if (lat && long) { return <Marker key={`requester-${index}`} longitude={long} latitude={lat}> <svg height={MARKER_SIZE} viewBox="0 0 24 24" onClick={() => onClick(request)} style={{ cursor: 'pointer', fill: isInProgress(request) ? '#db9327': color, stroke: 'none', transform: `translate(${-MARKER_SIZE / 2}px,${-MARKER_SIZE}px)` }}> <path d={ICON} /> </svg> </Marker> } else { return <></> } }); if (this.props.requesterMap && this.props.volunteerMap) { volunteerMarkers.push(...requesterMarkers); return volunteerMarkers; } else if (this.props.requesterMap) { return requesterMarkers; } else if (this.props.volunteerMap) { return volunteerMarkers; } return <></>; } }
JavaScript
class BannerDao { async getBanner (id) { const banner = await Banner.findOne({ where: { id, delete_time: null } }) return banner } async createBanner (v) { const banner = await Banner.findOne({ where: { title: v.get('body.title'), delete_time: null } }); if (banner) { throw new Forbidden({ msg: '轮播已存在' }); } const bn = new Banner(); bn.title = v.get('body.title') bn.description = v.get('body.description') bn.type = 100 bn.artId = v.get('body.artId') bn.image = v.get('body.image') bn.save() } async updateBanner (v, id) { const banner = await Banner.findByPk(id); if (!banner) { throw new NotFound({ msg: '没有找到相关书籍' }); } banner.title = v.get('body.title'); banner.description = v.get('body.description') banner.type = 100 banner.artId = v.get('body.artId') banner.image = v.get('body.image'); banner.save(); } async deleteBanner (id) { const banner = await Banner.findOne({ where: { id, delete_time: null } }); if (!banner) { throw new NotFound({ msg: '没有找到相关书籍' }); } banner.destroy(); } }
JavaScript
class ProjectAPI extends BaseAPI { constructor() { super('writing/projects'); } }
JavaScript
class Button extends React.Component { constructor(properties){ super(properties); this.handleClick = () => { this.props.onClickFunction(this.props.incrementValue); }; } render(){ // When we use the wrapper or bind method, we are creating a new function for every render button // We can void this in this way: return ( <button onClick={this.handleClick}> +{this.props.incrementValue} </button> ); } }
JavaScript
class SettingsCategory extends _react.default.Component { render() { const children = Object.keys(this.props.packages).sort().map(pkgName => { const pkgData = this.props.packages[pkgName]; const settingsArray = getSortedSettingsArray(pkgData.settings, pkgName); const elements = settingsArray.map(settingName => { const settingData = pkgData.settings[settingName]; return _react.default.createElement( ControlGroup, { key: settingName }, _react.default.createElement((_SettingsControl || _load_SettingsControl()).default, { keyPath: settingData.keyPath, value: settingData.value, onChange: settingData.onChange, schema: settingData.schema }) ); }); // We create a control group for the whole group of controls and then another for each // individual one. Why? Because that's what Atom does in its settings view. return _react.default.createElement( ControlGroup, { key: pkgName }, _react.default.createElement( 'section', { className: 'sub-section' }, _react.default.createElement( 'h2', { className: 'sub-section-heading' }, pkgData.title ), _react.default.createElement( 'div', { className: 'sub-section-body' }, elements ) ) ); }); return _react.default.createElement( 'section', { className: 'section settings-panel' }, _react.default.createElement( 'h1', { className: 'block section-heading icon icon-gear' }, this.props.name, ' Settings' ), children ); } }
JavaScript
class OfferType { /** * Constructs a new <code>OfferType</code>. * @alias module:client/models/OfferType * @class * @param buyingPrice {module:client/models/PriceType} * @param regularPrice {module:client/models/MoneyType} * @param fulfillmentChannel {String} The fulfillment channel for the offer listing. Possible values: * Amazon - Fulfilled by Amazon. * Merchant - Fulfilled by the seller. * @param itemCondition {String} The item condition for the offer listing. Possible values: New, Used, Collectible, Refurbished, or Club. * @param itemSubCondition {String} The item subcondition for the offer listing. Possible values: New, Mint, Very Good, Good, Acceptable, Poor, Club, OEM, Warranty, Refurbished Warranty, Refurbished, Open Box, or Other. * @param sellerSKU {String} The seller stock keeping unit (SKU) of the item. */ constructor(buyingPrice, regularPrice, fulfillmentChannel, itemCondition, itemSubCondition, sellerSKU) { this['BuyingPrice'] = buyingPrice; this['RegularPrice'] = regularPrice; this['FulfillmentChannel'] = fulfillmentChannel; this['ItemCondition'] = itemCondition; this['ItemSubCondition'] = itemSubCondition; this['SellerSKU'] = sellerSKU; } /** * Constructs a <code>OfferType</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:client/models/OfferType} obj Optional instance to populate. * @return {module:client/models/OfferType} The populated <code>OfferType</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new OfferType(); if (data.hasOwnProperty('BuyingPrice')) { obj['BuyingPrice'] = PriceType.constructFromObject(data['BuyingPrice']); } if (data.hasOwnProperty('RegularPrice')) { obj['RegularPrice'] = MoneyType.constructFromObject(data['RegularPrice']); } if (data.hasOwnProperty('FulfillmentChannel')) { obj['FulfillmentChannel'] = ApiClient.convertToType(data['FulfillmentChannel'], 'String'); } if (data.hasOwnProperty('ItemCondition')) { obj['ItemCondition'] = ApiClient.convertToType(data['ItemCondition'], 'String'); } if (data.hasOwnProperty('ItemSubCondition')) { obj['ItemSubCondition'] = ApiClient.convertToType(data['ItemSubCondition'], 'String'); } if (data.hasOwnProperty('SellerSKU')) { obj['SellerSKU'] = ApiClient.convertToType(data['SellerSKU'], 'String'); } } return obj; } /** * @member {module:client/models/PriceType} BuyingPrice */ 'BuyingPrice' = undefined; /** * @member {module:client/models/MoneyType} RegularPrice */ 'RegularPrice' = undefined; /** * The fulfillment channel for the offer listing. Possible values: * Amazon - Fulfilled by Amazon. * Merchant - Fulfilled by the seller. * @member {String} FulfillmentChannel */ 'FulfillmentChannel' = undefined; /** * The item condition for the offer listing. Possible values: New, Used, Collectible, Refurbished, or Club. * @member {String} ItemCondition */ 'ItemCondition' = undefined; /** * The item subcondition for the offer listing. Possible values: New, Mint, Very Good, Good, Acceptable, Poor, Club, OEM, Warranty, Refurbished Warranty, Refurbished, Open Box, or Other. * @member {String} ItemSubCondition */ 'ItemSubCondition' = undefined; /** * The seller stock keeping unit (SKU) of the item. * @member {String} SellerSKU */ 'SellerSKU' = undefined; }
JavaScript
class ItemForm extends React.Component { constructor(props) { super(props); // The input field that will sets the new item _defineProperty(this, "keyEnter", evt => { if (evt.which == 13) { // Enter - save the item this.addNewItem(); } else if (evt.which == 27) { // Escape - clear the form without saving this.props.dispatch({ type: EDIT_ITEM, payload: '' }); this.inputRef.current.value = ''; } });_defineProperty(this, "addNewItem", () => { const item = this.inputRef.current.value.trim(); // check that the value is not empty if (item && this.props.items.list.indexOf(item) === -1) { // Add the item to the Redux store this.props.dispatch({ type: this.props.items.current ? UPDATE_ITEM : ADD_ITEM, payload: item }); } // reset the form this.inputRef.current.value = ''; this.inputRef.current.focus(); // undo the current setting if (this.props.items.current) { this.props.dispatch({ type: EDIT_ITEM, payload: '' }); } });this.inputRef = React.createRef();} // Add a new item when pressing enter inside the input // Update the form details with the currently selected item componentDidUpdate(prev) { if (prev.items.current != this.props.items.current) { this.inputRef.current.value = this.props.items.current; this.inputRef.current.focus(); } } // Render the form render() { let count = 0; return ( React.createElement("div", { className: "box" }, React.createElement("h5", null, "Add an item "), React.createElement("div", { className: "item-form" }, React.createElement("input", { onKeyUp: this.keyEnter, ref: this.inputRef }), React.createElement("button", { onClick: this.addNewItem })), "Escape to cancel")); }}
JavaScript
class ItemList extends React.Component { constructor(props) { super(props); // radio button handlers _defineProperty(this, "removeItem", event => { this.props.dispatch({ type: REMOVE_ITEM, payload: event.target.parentNode.dataset.value }); });_defineProperty(this, "updateItem", event => { this.props.dispatch({ type: EDIT_ITEM, payload: event.target.parentNode.dataset.value }); });this.handlers = { update: [], remove: [] };} // Removes the item from the Redux store // Sets the emoji to display based on the Redux store value showEmotion() { switch (this.props.emotions.current) { case 'happy': return '😃'; break; case 'sad': return '😢'; break; case 'angry': return '😡'; break; case 'scared': return '😲'; break;} return '😳'; } // Render the node render() { let clickMessage = this.props.items.list.length ? 'Click to edit' : 'There are no items in your list'; // Create the <div> nodes for each item const listBits = this.props.items.list.map((x, i) => React.createElement("div", { key: i, "data-value": x }, this.showEmotion(), " ", React.createElement("span", { title: "Edit Item", onClick: this.updateItem }, x), " ", React.createElement("a", { title: "Remove item", className: "remove", onClick: this.removeItem }))); return ( React.createElement("div", { className: "box" }, React.createElement("h5", null, "These are your items"), listBits, React.createElement("span", { className: "item-message" }, clickMessage))); }}
JavaScript
class EmotionOptions extends React.Component { constructor(props) { super(props); // radio button handlers _defineProperty(this, "doChange", name => { if (!this.handlers[name]) { this.handlers[name] = () => { this.props.dispatch({ type: SET_EMOTION, payload: name }); }; } return this.handlers[name]; });this.handlers = [];} // Check if the emotion matches the Redux current emotion getChecked(val) {return this.props.emotions.current == val ? 'checked' : '';} // Set the Redux current emotion // Caches the handlers to prevent duplicates on render // Render the options render() {// Create the list of checkboxes // THe best approach to onChange would be // <input type="radio" name="radio" value={x} onChange={this.doChange}/> // where doChange is set by method = () => {} in the class // I have done it this way to experiment with dynamic/multi method properties const options = this.props.emotions.list.map(x => React.createElement("label", { key: x, className: "radio" }, React.createElement("input", { type: "radio", name: "radio", checked: this.getChecked(x), onChange: this.doChange(x) }), React.createElement("span", null, x))); return ( React.createElement("div", { className: "box" }, React.createElement("h5", null, "How do you feel"), options)); }}
JavaScript
class PageApp extends React.Component { render() { return ( React.createElement(React.Fragment, null, React.createElement(Emoji, null), React.createElement(Form, null), React.createElement(Item, null))); }}
JavaScript
class DataProvider { /** * constructor data provider * @param {*} settings */ constructor(settings) { this.dataInfo = settings.datainfo this.datascales = settings.datascales this.datamode = TRANSFORM_MODE.seriesdata this.DEBUGMODE = settings.debugmode this.DEBUGDATA = settings.debugdata this.locale = window.Chart3.defaults.locale | "DE" this.ready = this._checkParam() this.version = "1.0.1" if (this.DEBUGMODE) { this.DEBUGDATA.PROFILER.DATAPROVIDER = { start: performance.now() } } } /** * check the settings and hass api call settings * @returns boolean */ _checkParam() { if (this.datascales && this.dataInfo.entity_items && Object.keys(this.dataInfo.entity_items)) { this.datascales.range = this.datascales.range || 24 this.datascales.aggregate = this.datascales.aggregate || "last" return true } return false } /** * all servicedata information * @param {*} _entity */ _setEntityServiceDataInformation(_entity) { if (_entity) { _entity.datascales.data_count = 0 _entity.datascales.servicemode = TRANSFORM_MODE.seriesdata } } /** * build the seriesdata based on the grouped data * @param {*} id * @param {*} data * @returns number data series */ _createTimeSeriesData(_entity, data) { _entity.seriesdata = _entity.seriesdata || [] _entity.seriesdata.data = _entity.seriesdata.data || [] _entity.seriesdata.data = Object.entries(data).map(function (row) { const _values = row[1].data if (_values && _values.length) { let _itemdata = { x: new Date(row[0]).getTime(), localedate: row[1].localedate, y: arrStatistics[_entity.aggregate || _entity.datascales.aggregate](_values) } if (_entity.datascales.useStatistics) { _itemdata.statistics = { current: _entity.state, first: _values[0], last: _values[_values.length - 1], max: arrStatistics.max(_values), min: arrStatistics.min(_values), sum: arrStatistics.sum(_values), avg: arrStatistics.mean(_values) } } return _itemdata } }) _entity.datascales.data_count = _entity.seriesdata.data.length return _entity.datascales.data_count } /** * get simple data for the entities * calculates the state data from the history devicestates * based on the aggreation methode. * @param {*} deviceStates */ getSimpleData(deviceStates) { if (deviceStates && deviceStates.length) { deviceStates.forEach((states) => { const _entityId = states[0].entity_id, _entity = this.dataInfo.entity_items[_entityId] this._setEntityServiceDataInformation(_entity) if (_entityId && _entity) { const _factor = _entity.factor || 1.0 const _values = states.map((item) => _entity.field ? (getAttributeValue(item, _entity.field) || 0.0) * _factor : item.state * _factor ) if (_entity.datascales.useStatistics) { let _itemdata = {} _itemdata.statistics = { current: _entity.state, first: _values[0], last: _values[_values.length - 1], max: arrStatistics.max(_values), min: arrStatistics.min(_values), sum: arrStatistics.sum(_values), avg: arrStatistics.mean(_values) } } /** * update the entity */ _entity.datascales.data_count = _values.length _entity.state = arrStatistics[_entity.datascales.aggregate](_values) } else { console.error(`Sensordata ${_entity} not found !`) } }) } if (this.DEBUGMODE) { this.DEBUGDATA.PROFILER.DATAPROVIDER.elapsed = msToTime(performance.now() - this.DEBUGDATA.PROFILER.DATAPROVIDER.start) } return true } /** * get seriesdata * @param {array} deviceStates from hass API call * @returns boolean */ getSeriesdata(deviceStates) { /** * first check the mode * bar, pie and doghunut can use simple data mode */ if (this.datamode === TRANSFORM_MODE.statebased) { if (this.DEBUGMODE) { this.DEBUGDATA.PROFILER.DATAPROVIDER.mode = "simpledata" } return this.getSimpleData(deviceStates) } /** * get seriesdata for all entities */ if (this.DEBUGMODE) { this.DEBUGDATA.PROFILER.DATAPROVIDER.mode = "seriesdata" } /** * dateformat * @param {*} datevalue * @param {*} mode * @param {*} format * @returns */ function formatDateLabel(datevalue, mode = "label", format = "day") { /** * group format must be a valid date/time format * otherwise the timeseries do not work */ const groupFormats = { millisecond: "yyyy/m/d H:M:ss.l", datetime: "yyyy/md/ H:M:s", second: "yyyy/m/d H:M:s", minute: "yyyy/m/d H:M:00", hour: "yyyy/m/d H:00:00", day: "yyyy/m/d", month: "yyyy/m/1", year: "yyyy/12/31" } if (mode == "group") { return formatdate(datevalue, groupFormats[format] || groupFormats["day"]) } return formatdate(datevalue, format) // return mode == "group" // ? datevalue.substring(0, DATEFILTERS[format].digits || DATEFILTERS["day"].digits) // : formatdate(datevalue, format) // return mode == "group" // ? datevalue.substring(0, DATEFILTERS[format].digits || DATEFILTERS["day"].digits) // : formatdate(datevalue, format) } /** * interate throw all devicestates and build * the result based on the settings (date format, aggregation) */ if (deviceStates && deviceStates.length) { /** * all states for each entity */ deviceStates.forEach((states) => { const _entityId = states[0].entity_id, _entity = this.dataInfo.entity_items[_entityId] if (_entity && _entityId) { const _factor = _entity.factor || 1.0 this._setEntityServiceDataInformation(_entity) if (!_entity.hasOwnProperty("ignoreZero")) _entity.ignoreZero = false _entity.datascales.states_count = states.length let _data = [] states.forEach(function (row) { const _index = formatDateLabel(row.last_changed, "group", _entity.datascales.unit) let _val = _entity.field ? +getAttributeValue(row, _entity.field) : +row.state if (validItem(_val, _entity.ignoreZero)) { _val = _val * _factor _data[_index] = _data[_index] || [] _data[_index]["data"] = _data[_index]["data"] || [] _data[_index]["localedate"] = formatDateLabel( row.last_changed, "label", _entity.datascales.format || _entity.datascales.unit ) _data[_index]["data"].push(_safeParseFloat(_val)) } }) /** * build the series data based on the grouped data series */ _entity.datascales.data_count = this._createTimeSeriesData(_entity, _data) } }) if (this.DEBUGMODE) { this.DEBUGDATA.PROFILER.DATAPROVIDER.elapsed = msToTime( performance.now() - this.DEBUGDATA.PROFILER.DATAPROVIDER.start ) } return true } } }
JavaScript
class IdentifierValue { /** * @param {Object} config * @param {BigInt} config.addend * @property {import('./symbols.js').Symbol} config.symbol * @property {Section} config.section * @property {Range} config.range * @property {RegData} config.regData * @property {Number[]} lineEnds */ constructor({ addend = null, symbol = null, section = pseudoSections.UND, range, regData = null, pcRelative = false, lineEnds = [] } = {}) { this.addend = addend; this.symbol = symbol; this.section = section; this.range = range; this.regData = regData; this.pcRelative = pcRelative; this.lineEnds = lineEnds; } isRelocatable() { return this.symbol && this.section != pseudoSections.ABS || this.pcRelative; } flatten() { let val = this, addend = this.addend; while(val.symbol && (val.section == pseudoSections.ABS || val.symbol.value.symbol && !val.symbol.bind) && val.symbol.value !== val) { val = val.symbol.value; addend += val.addend; } return new IdentifierValue({ ...val, addend }); } absoluteValue() { let val = this, total = this.addend; while(val.symbol && val.symbol.value !== val) { val = val.symbol.value; total += val.addend; } return total; } /** * @param {Statement} instr * @param {IdentifierValue} op1 * @param {string} func * @param {IdentifierValue} op2 */ apply(instr, func, op, allowPCRelative = true) { this.range = this.range.until(op.range); if(this.section == pseudoSections.ABS && op.section == pseudoSections.ABS) ; else if(func == '+' && this.section == pseudoSections.ABS && !this.pcRelative) { this.section = op.section; this.symbol = op.symbol; } else if((func == '+' || func == '-') && op.section == pseudoSections.ABS) ; else if(this.pcRelative || op.pcRelative) throw new ASMError("Bad operands", this.range); else if(func == '-' && this.section == op.section && (this.section != pseudoSections.UND && this.section != pseudoSections.COM || this.symbol == op.symbol)) { if(this.symbol) this.addend = this.absoluteValue(); if(op.symbol) op.addend = op.absoluteValue(); this.section = op.section = pseudoSections.ABS; this.symbol = op.symbol = null; } else if(func == '-' && allowPCRelative && op.section == instr.section) this.pcRelative = true; else throw new ASMError("Bad operands", this.range); if(this.regData || op.regData) { if(func != '+' && func != '-' && func != '*' || func == '-' && op.regData) throw new ASMError("Bad operands", this.range); let regOp = this.regData ? this : op; let nonRegOp = this.regData ? op : this; if(!this.regData) this.regData = op.regData; else if(op.regData) // Both operands are registers { if(func == '*') throw new ASMError("Bad operands", this.range); if(this.regData.regIndex && op.regData.regIndex) throw new ASMError("Can't have multiple index registers", this.range); if([this.regData, op.regData].some(data => data.regBase && data.regIndex)) throw new ASMError("Too many registers", this.range); if(this.regData.regBase && op.regData.regBase) { this.regData.regIndex = [this.regData.regBase, op.regData.regBase].find(reg => reg.reg != 4); if(this.regData.regIndex === undefined) throw new ASMError(`Can't have both registers be ${instr.syntax.prefix ? '%' : ''}rsp`, this.range); if(this.regData.regIndex == this.regData.regBase) this.regData.regBase = op.regData.regBase; } else if(op.regData.regIndex) { this.regData.regIndex = op.regData.regIndex; this.regData.shift = op.regData.shift; } else this.regData.regBase = op.regData.regBase; } if(func == '*') { if(nonRegOp.section != pseudoSections.ABS) throw new ASMError("Scale must be absolute", nonRegOp.range); if(regOp.regData.regIndex && regOp.regData.regBase) throw new ASMError("Can't scale both base and index registers", this.range); if(regOp.regData.regBase) { const scaled = regOp.regData.regBase; if(scaled.reg == 4) throw new ASMError(`Can't scale ${nameRegister('sp', scaled.size, instr.syntax)}`, this.range); if(scaled.type == OPT.IP) throw new ASMError(`Can't scale ${nameRegister('ip', scaled.size, instr.syntax)}`, this.range); this.regData.regIndex = scaled; this.regData.regBase = null; } this.regData.shift *= Number(nonRegOp.addend); this.addend = regOp.addend !== null ? nonRegOp.addend * regOp.addend : null; } else if(this.addend !== null || op.addend !== null) this.addend = operators[func].func(this.addend ?? 0n, op.addend ?? 0n); } else this.addend = operators[func].func(this.addend, op.addend); this.pcRelative = this.pcRelative || op.pcRelative; this.lineEnds = [...this.lineEnds, ...op.lineEnds].sort((a, b) => a - b); } }
JavaScript
class ShrineAPI { /** * Fetches the shrine of secrets. * @return {Promise<Shrine>} */ static async fetch() { const time = Math.floor(new Date().getTime() / 1000); // Read shrine cache. /** @type {Shrine} */ let shrine = await jsonfs.read(SHRINE_CACHE_PATH); let useEndpoint = (!shrine || time >= shrine.end); // Fetch from endpoint. if (useEndpoint) { let response = await fetch('https://dbd.onteh.net.au/api/shrine'); let data = await response.json(); if (shrine == null || shrine.id != data.id) { shrine = data; for (let i = 0; i < shrine.perks.length; i++) { shrine.perks[i].info = await ShrineAPI.fetchPerk(shrine.perks[i].id); } await jsonfs.write(SHRINE_CACHE_PATH, shrine); } } // Return result. shrine.current = time < shrine.end; return shrine; } /** * Fetches perk information. */ static async fetchPerk(perkId) { let response = await fetch(`https://dbd.onteh.net.au/api/perkinfo?perk=${perkId}`); return await response.json(); } /** * Converts a shrine to a string. * @param {Shrine} shrine * @returns {string} */ static toMessage(shrine) { let content = `${shrine.current ? 'Today' : 'Yesterday'}'s shrine of secrets is`; shrine.perks.forEach((perk, i) => { let quote = perk.shards > 2000 ? '***' : '**'; content += `${i > 0 ? ',' : ''} ${i == 3 ? 'and ' : ''}${quote}${perk.info.name}${quote}`; }); const embed = new MessageEmbed() .setColor('#FFFFFF') .setTitle('KΛIROS !K SHRINE') .setDescription(`${content}!`) .setFooter('© MiZaMo#9999') .setThumbnail('https://i.imgur.com/V4kH5hU.png'); return embed; //return `${content}!`; } }
JavaScript
class CLI { constructor() { this.employees = []; } run() { console.log("Please build your team"); this.createManager(); } createTeam() { inquirer .prompt([ { type: "list", name: "choice", message: "Which type of team member would you like to add?", choices: [ "Engineer", "Intern", "I don't want to add any more team members", ], default: "Engineer", }, ]) .then((answers) => { switch (answers.choice) { case "Engineer": return this.createEngineer(); case "Intern": return this.createIntern(); default: console.log("Have a nice day!"); return this.generateHtml(); process.exit(0); } }); } createManager() { inquirer .prompt([ { type: "input", name: "managername", message: "What is your manager's name?", }, { type: "input", name: "managerid", message: "What is your manager's id?", }, { type: "input", name: "manageremail", message: "What is your manager's email?", }, { type: "input", name: "officenumber", message: "What is your manager's office number?", }, ]) .then((answers) => { const { managername, managerid, manageremail, officenumber } = answers; const manager = new Manager( managername, managerid, manageremail, officenumber ); this.employees.push(manager); this.createTeam(); }); } createEngineer() { inquirer .prompt([ { type: "input", name: "engname", message: "What is your engineer's name?", }, { type: "input", name: "engid", message: "What is your engineer's id?", }, { type: "input", name: "engemail", message: "What is your engineer's email?", }, { type: "input", name: "enggithub", message: "What is your engineer's GitHub username?", }, ]) .then((answers) => { const { engname, engid, engemail, enggithub } = answers; const engineer = new Engineer(engname, engid, engemail, enggithub); this.employees.push(engineer); this.createTeam(); }); } createIntern() { inquirer .prompt([ { type: "input", name: "internname", message: "What is your intern's name?", }, { type: "input", name: "internid", message: "What is your intern's id?", }, { type: "input", name: "internemail", message: "What is your intern's email?", }, { type: "input", name: "school", message: "Where does your intern go to school??", }, ]) .then((answers) => { const { internname, internid, internemail, school } = answers; const intern = new Intern(internname, internid, internemail, school); this.employees.push(intern); this.createTeam(); }); } generateHtml() { const html = render(this.employees); const file = path.join(__dirname, "./output/team.html"); writeFileAsync(file, html) .then(() => { console.log(`Created ${file}.`); process.exit(0); }) .catch(() => { console.log(error); console.log("Unable to create team file. Try again."); }); } }
JavaScript
class ServiceBusMessage { /** * Create a ServiceBusMessage. * @member {object} [authentication] Gets or sets the Service Bus * authentication. * @member {string} [authentication.sasKey] Gets or sets the SAS key. * @member {string} [authentication.sasKeyName] Gets or sets the SAS key * name. * @member {string} [authentication.type] Gets or sets the authentication * type. Possible values include: 'NotSpecified', 'SharedAccessKey' * @member {object} [brokeredMessageProperties] Gets or sets the brokered * message properties. * @member {string} [brokeredMessageProperties.contentType] Gets or sets the * content type. * @member {string} [brokeredMessageProperties.correlationId] Gets or sets * the correlation ID. * @member {boolean} [brokeredMessageProperties.forcePersistence] Gets or * sets the force persistence. * @member {string} [brokeredMessageProperties.label] Gets or sets the label. * @member {string} [brokeredMessageProperties.messageId] Gets or sets the * message ID. * @member {string} [brokeredMessageProperties.partitionKey] Gets or sets the * partition key. * @member {string} [brokeredMessageProperties.replyTo] Gets or sets the * reply to. * @member {string} [brokeredMessageProperties.replyToSessionId] Gets or sets * the reply to session ID. * @member {date} [brokeredMessageProperties.scheduledEnqueueTimeUtc] Gets or * sets the scheduled enqueue time UTC. * @member {string} [brokeredMessageProperties.sessionId] Gets or sets the * session ID. * @member {moment.duration} [brokeredMessageProperties.timeToLive] Gets or * sets the time to live. * @member {string} [brokeredMessageProperties.to] Gets or sets the to. * @member {string} [brokeredMessageProperties.viaPartitionKey] Gets or sets * the via partition key. * @member {object} [customMessageProperties] Gets or sets the custom message * properties. * @member {string} [message] Gets or sets the message. * @member {string} [namespace] Gets or sets the namespace. * @member {string} [transportType] Gets or sets the transport type. Possible * values include: 'NotSpecified', 'NetMessaging', 'AMQP' */ constructor() { } /** * Defines the metadata of ServiceBusMessage * * @returns {object} metadata of ServiceBusMessage * */ mapper() { return { required: false, serializedName: 'ServiceBusMessage', type: { name: 'Composite', className: 'ServiceBusMessage', modelProperties: { authentication: { required: false, serializedName: 'authentication', type: { name: 'Composite', className: 'ServiceBusAuthentication' } }, brokeredMessageProperties: { required: false, serializedName: 'brokeredMessageProperties', type: { name: 'Composite', className: 'ServiceBusBrokeredMessageProperties' } }, customMessageProperties: { required: false, serializedName: 'customMessageProperties', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, message: { required: false, serializedName: 'message', type: { name: 'String' } }, namespace: { required: false, serializedName: 'namespace', type: { name: 'String' } }, transportType: { required: false, serializedName: 'transportType', type: { name: 'Enum', allowedValues: [ 'NotSpecified', 'NetMessaging', 'AMQP' ] } } } } }; } }
JavaScript
class PreloadScene extends Phaser.Scene { constructor() { super({ key: 'PreloadScene' }) } preload() { // priest anims: this.load.spritesheet('priest-idle', './assets/anims/priest_idle_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) // mage amims: this.load.spritesheet('mage-idle', './assets/anims/mage_idle_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('mage-run', './assets/anims/mage_run_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('mage-combat', './assets/anims/mage_combat_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) // mage sword anims (i know, its not a sword, TODO: change character.ANIM): this.load.spritesheet('mage-sword-idle', './assets/anims/mage_sword_idle_spritesheet.png', { frameWidth: 24, frameHeight: 36 } ) this.load.spritesheet('mage-sword-run', './assets/anims/mage_sword_run_spritesheet.png', { frameWidth: 24, frameHeight: 36 } ) this.load.spritesheet('mage-sword-stab', './assets/anims/mage_sword_stab_spritesheet.png', { frameWidth: 36, frameHeight: 24 } ) // barbarian anims: this.load.spritesheet('barbarian-idle', './assets/anims/barbarian_idle_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('barbarian-run', './assets/anims/barbarian_run_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('barbarian-combat', './assets/anims/barbarian_combat_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('barbarian-die', './assets/anims/barbarian_die_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) // barbarian sword anims: this.load.spritesheet('barbarian-sword-idle', './assets/anims/barbarian_sword_idle_spritesheet.png', { frameWidth: 24, frameHeight: 36 } ) this.load.spritesheet('barbarian-sword-stab', './assets/anims/barbarian_sword_stab_spritesheet.png', { frameWidth: 36, frameHeight: 24 } ) this.load.spritesheet('barbarian-sword-run', './assets/anims/barbarian_sword_run_spritesheet.png', { frameWidth: 24, frameHeight: 36 } ) // orc anims: this.load.spritesheet('orc-mask-idle', './assets/anims/orc_mask_idle_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('orc-mask-run', './assets/anims/orc_mask_run_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('orc-mask-combat', './assets/anims/orc_mask_combat_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('orc-mask-die', './assets/anims/orc_mask_die_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) this.load.spritesheet('orc-mask-stun', './assets/anims/orc_mask_stun_spritesheet.png', { frameWidth: 16, frameHeight: 16 } ) // orc sword anims: this.load.spritesheet('orc-sword-idle', './assets/anims/orc_sword_idle_spritesheet.png', { frameWidth: 24, frameHeight: 24 } ) this.load.spritesheet('orc-sword-stab', './assets/anims/orc_sword_stab_spritesheet.png', { frameWidth: 36, frameHeight: 24 } ) this.load.spritesheet('orc-sword-run', './assets/anims/orc_sword_run_spritesheet.png', { frameWidth: 24, frameHeight: 24 } ) // drink anim: this.load.spritesheet('small-red', './assets/anims/red_potion_small_spritesheet.png', { frameWidth: 40, frameHeight: 16 } ) // blood spray anim: this.load.spritesheet('blood', './assets/anims/blood_spritesheet.png', { frameWidth: 32, frameHeight: 32 } ) // snow? spell effect that kind of looks like snow... this.load.spritesheet('snow', './assets/anims/snow_spritesheet.png', { frameWidth: 32, frameHeight: 32 } ) // map data: this.load.tilemapTiledJSON('map', './assets/map/combat.json') this.load.image('v4', './assets/map/0x72_16x16DungeonTileset_extruded.v4.png') // icons: this.load.image('auto-attack', './assets/icons/auto_attack_icon.png') this.load.image('rush', './assets/icons/rush_icon.png') this.load.image('gore', './assets/icons/gore_icon.png') this.load.image('savage-blow', './assets/icons/strike_icon.png') this.load.image('shout', './assets/icons/shout_icon.png') // bitmap data: this.load.bitmapFont('font', './assets/fonts/font.png', './assets/fonts/font.fnt'); // ui: this.load.image('ui', './assets/ui/ui.png'); // load event: this.load.on('complete', ()=> { this.scene.start('MainScene') this.scene.start('UIScene') }) } create() { } }
JavaScript
class Common extends React.Component { constructor(props) { super(props); // Cell alias, its uniq ID this.alias = this.props.alias || null; this.appState = this.props.state; this.entriesType = this.props.entriesType; // If cell is heading, i.e. TH this.isHeading = this.props.isHeading || false; // Entry of current row this.entry = this.props.entry || null; } /** * Update entry after component update */ componentDidUpdate() { this.entry = this.props.entry || null; } isCellContentShouldBeWrapped() { return true; } render() { const attributes = this.getCellAttributes(); const caption = this.getHeadingCellValue(); attributes.classes = {}; return ( <TableCell component="div" variant="body" {...attributes}> {(() => { if(this.isCellContentShouldBeWrapped()) { return <div class="entries__cell-content"> { this.getCommonCellValue() } </div>; } return this.getCommonCellValue(); })()} {(() => { if(!caption) { return null; } return <div class="entries__cell-caption"> { this.getHeadingCellValue() } </div>; })()} </TableCell> ); } /** * Get classname and determine, check cell or not * * @return Object */ getCellAttributes() { const isCheck = this.isCurrentCellCheck(); const classes = this.getCellClasses(); const attributes = this.props.attributes || {}; attributes.className = classes.join(' '); if(isCheck) { attributes['data-check'] = 'trigger'; } return attributes; } /** * Return cell alias. If cell is check and user is not admin, * return separator instead. * * @return String */ getCellAlias() { const User = new UserEntity(); let alias = this.alias; if(!User.isAdmin()) { if(alias === 'check') { alias = 'separator'; } } return alias; } /** * Returns cell value for heading cell. * Usually this is title and sort trigger. * * @return JSX | null */ getHeadingCellValue() { const cellParams = this.getCellParams(); const alias = this.getCellAlias(); const { orderBy } = this.getSortParameters(); // return null if cell params is empty or not found if(!cellParams) { return null; } return cellParams.title; // Раскомментируй, и будет сортировка // // let cellValue = null; // cellValue = this.getSortTrigger({ // title: cellParams.title, // orderBy: cellParams.field || alias, // isActive: false // }); // // If user have sorting in current cell // if(cellParams.field === orderBy) { // cellValue = this.getSortTrigger({ // title: cellParams.title, // orderBy: cellParams.field || alias, // isActive: true // }); // } // return cellValue; } /** * Returns cell value for non-heading cells. * * @return JSX */ getCommonCellValue() { const cellParams = this.getCellParams(); const alias = this.getCellAlias(); const cellValue = this.getDefaultCellValue(); return cellValue; } /** * Returns raw cell value from entry. * * @return String | null */ getDefaultCellValue() { const cellParams = this.getCellParams(); const fieldBy = cellParams.field; if(fieldBy) { const parts = fieldBy.split('.'); let currentStack = this.entry; for(const index in parts) { currentStack = (currentStack && parts[index] in currentStack) ? currentStack[parts[index]] : null; } return currentStack; } return null; } /** * Determine what current cell have type `check` or not * * @return Boolean */ isCurrentCellCheck() { const { alias = null } = this.props; return alias === 'check'; } /** * Builds and returns cell classname by his alias and params * * @return Object */ getCellClasses() { const { alias = null, isHeading = false } = this.props; let classes = ['entries__cell']; if(alias) { classes.push('entries__' + alias); } if(isHeading) { classes.push('entries__cell_heading'); } return classes; } /** * Returns cell params from config repository. * * @return Object */ getCellParams() { const path = 'pages.' + this.entriesType + '.cells.' + this.alias; const cell = ConfigRepository.get(path); return cell; } /** * Returns unique entry ID. Usually this is uniq of entry, * but if in config there is `keyField` property, this is field value. * * @return Mixed */ getEntryKey() { const path = 'pages.' + this.entriesType; const page = ConfigRepository.get(path); if(page.keyField) { return this.entry[page.keyField] || null; } return this.entry._uniq || null; } /** * Just returns SortTrigger component * * @param title String * @param orderBy String * @param isActive Boolean * @return JSX */ getSortTrigger({ title, orderBy, isActive = false }) { const { order } = this.getSortParameters(); return <SortTrigger isActive={isActive} order={order} orderBy={orderBy} title={title} onClick={this.props.onSortTriggerClick} />; } /** * Get sort parameters for current entries type from Sorter Instance * * @return Object */ getSortParameters() { const SorterInstance = new Sorter(this.entriesType); return SorterInstance.getSortParameters(this.appState); } }
JavaScript
class ApiBase { // ajaxPost static ajaxPost(url, reqData, target) { return ApiBase._ajax(url, reqData, target, 'post') } // ajaxGet static ajaxGet(url, reqData, target) { return ApiBase._ajax(url, reqData, target, 'get') } // ajax static _ajax(url, reqData, target, type) { let func = type === 'post' ? ajax.createHttpPost : ajax.createHttpGet return new Promise((resolve, reject) => { func(url, reqData, target).then( resp => { switch (resp.status) { case returnStatus.NORMAL: // 正常数据 resolve(resp) break case returnStatus.NOT_LOGIN: // message.warn(resp.msg || '登录过期,即将跳转登录页...', 2, () => { // // 退出登录 // toLoginPage() // }) break default: throw new Error(resp.msg) } } ).catch(err => { // message.warning(err.msg || err.message || '未知错误') reject(err) }) }) } }
JavaScript
class InputManager { constructor() { this._canvas = null; /** * The keycodes of the keys currently pressed * @type {{int, boolean}} */ this.keysPressed = {}; this.mouseMoveListeners = []; this._locked = false; let caller = this; // This avoids misinterpreting 'this' inside the event as the function itself document.addEventListener('keydown', (evt) => caller.keyDownHandler(evt), false); document.addEventListener('keyup', (evt) => caller.keyUpHandler(evt), false); } set canvas(canvas) { if (this._canvas !== null) { // TODO: remove event listeners } this._canvas = canvas; // noinspection JSUnresolvedVariable canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock; // noinspection JSUnresolvedVariable document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; let caller = this; document.addEventListener('pointerlockchange', () => caller._lockChangeAlert(), false); document.addEventListener('mozpointerlockchange', () => caller._lockChangeAlert(), false); document.addEventListener('webkitpointerlockchange', () => caller._lockChangeAlert(), false); canvas.onclick = () => canvas.requestPointerLock(); } _lockChangeAlert() { let caller = this; // noinspection JSUnresolvedVariable if (document.pointerLockElement === this._canvas || document.mozPointerLockElement === this._canvas || document.webkitPointerLockElement === this._canvas ) { if (this._locked) return; this._locked = true; document.addEventListener("mousemove", e => caller._updatePosition(e), false); } else { if (!this._locked) return; this._locked = false; document.removeEventListener("mousemove", e => caller._updatePosition(e), false); } } _updatePosition(e) { if (!this._locked) return; this.mouseMoveListeners.forEach(l => l(e.movementX, e.movementY)) } keyDownHandler(event) { const code = event.key; this.keysPressed[code] = true; // The value is not important } keyUpHandler(event) { const code = event.key; if (code in this.keysPressed) { delete this.keysPressed[code]; } } isKeyDown(code) { return code in this.keysPressed; } }
JavaScript
class App extends Component { componentDidMount(){ this.props.getToken() } // function App() { render() { return ( <Router> <div className="App"> <Layout className="page"> <Navbar/> <Switch> <Route path="/attempts/:attemptId/comments" render={({match}) => (<CommentContainer match={match} />)} /> <Route path="/lessons/:lessonId/attempts" render={({match}) => (<AttemptContainer match={match} />)} /> <Route path="/topics/:topicId/lessons" render={({match}) => (<TopicLessonContainer match={match} />)} /> <Route path="/categories/:categoryId/topics" render={({match}) => (<CategoryTopicContainer match={match} />)} /> <Route path="/users/:userId" render={({match}) => (<ProfileContainer match={match} />)} /> <Route exact path="/attempts" component={AttemptContainer} /> <Route exact path="/lessons" component={LessonContainer} /> <Route exact path="/topics" component={TopicContainer} /> <Route exact path="/categories" component={CategoryContainer} /> <Route path="/profile" component={ProfileContainer} /> <Route path="/about" component={About} /> <Route path="/login" component={LoginContainer} /> <Route path="/signup" component={SignupContainer} /> <Route exact path="/" component={HomeContainer} /> <Route component={NotFound}/> </Switch> </Layout> </div> </Router> ); } }
JavaScript
class NewEra_DumpListUtil { /** * This will parse a listfile */ async parse_listfile(filename) { const [fileproperties, comment, content] = [{}, { mtime: [], parity: [], name: [] }, { sha256: [], name: [] }]; if (!await file_exists(filename)) { console.error('Error parsing listfile: File does not exist'); return false; } const filecontents = await readFile(filename, { encoding: 'utf8' }); filecontents.replace(/^; ([0-9]+) ([\w\d_-]{48}) ([*][^\r\n]+)/gm, (...m) => { comment.mtime.push(m[1]); comment.parity.push(m[2]); comment.name.push(m[3]); }); if (!comment.mtime.length) { console.error('Error parsing listfile: Unable to parse comments'); return false; } filecontents.replace(/^([0-9a-f]{64}) ([*][^\r\n]+)/gm, (...m) => { content.sha256.push(m[1]); content.name.push(m[2]); }); if (!content.sha256.length) { console.error('Error parsing listfile: Unable to parse contents'); return false; } if (comment['name'].length === content['name'].length) { for (let i = 0; i < comment['name'].length; i++) { if (comment['name'][i][0] == '*' && comment['name'][i] === content['name'][i]) { // Not an hack: We have to remove the asterisk in begining and restore ./ in path for Node.js to be able to work it out const file = './' + comment['name'][i].substr(1); fileproperties[`${file}`] = { 'mtime': comment['mtime'][i], 'parity': comment['parity'][i], 'sha256': content['sha256'][i] }; } else { console.error('Error parsing listfile: Invalid entry order'); return false; } } } else { console.error('Error parsing listfile: Invalid entry count'); return false; } return fileproperties; } /** This will generate a listfile */ generate_listfile(fileproperties) { // Init contents of list file let [comment, content] = ['', '']; // Sort file properties array and walk for (const file of Object.keys(fileproperties).sort(NewEra_Compare.prototype.sort_files_by_name)) { const properties = fileproperties[`${file}`]; // Not an hack: We have to replace ./ in path by an asterisk for other applications (QuickSFV, TeraCopy...) to be able to work it out const filename = '*' + file.substr(2); comment += `; ${properties['mtime']} ${properties['parity']} ${filename}\n`; content += properties['sha256'] + ' ' + filename + "\n"; } return (comment + content); } /** Array with the paths a dir contains */ async readdir_recursive(dir = '.', show_dirs = false, ignored = []) { // Set types for stack and return value const [stack, result] = [[], []]; // Initialize stack stack.push(dir); // Pop the first element of stack and evaluate it (do this until stack is fully empty) while (dir = stack.shift()) { // eslint-disable-line no-cond-assign const files = await readdir(dir); for (let path of files) { // Prepend dir to current path path = dir + '/' + path; // Stat the path to determine attributes const stats = await stat(path).catch(e => { console.error(e); return { isDirectory: () => false, isFile: () => false }; }); if (stats.isDirectory()) { // Check ignored dirs if (Array.isArray(ignored) && ignored.length && ignored.indexOf(path + '/') !== -1) { continue; } // Add dir to stack for reading stack.push(path); // If show_dirs is true, add dir path to result if (show_dirs) { result.push(path); } } else if (stats.isFile()) { // Check ignored files if (Array.isArray(ignored) && ignored.length && ignored.indexOf(path) !== -1) { continue; } // Add file path to result result.push(path); } } } // Sort the array using simple ordering result.sort(); // Now we can return it return result; } }
JavaScript
class NewEra_DumpList { /** Construct the object and perform actions */ constructor(listfile = './SHA256SUMS', ignored = []) { /** The file that holds the file list */ this.listfile = listfile; /** Ignored paths */ this.ignored = [ listfile, /* List file */ ...ignored /* Original ignored array */ ]; /** Simple file list array */ this.filelist = []; /** Detailed file list array */ this.fileproperties = []; // Check arguments count if (process.argv.length != 3) { die('Usage: node ' + basename(__filename) + " [--check|--test|--generate|--update|--touchdir]"); } // Fix argument const argument = process.argv[2].replace(/^[-]{1,2}/g, ''); // Process arguments switch (argument) { case 'test': this.dumplist_update(true, true, true); break; case 'check': this.dumplist_update(false, false, true); break; case 'generate': this.dumplist_generate(); break; case 'update': this.dumplist_update(false, false, false); break; case 'touchdir': this.dumplist_touchdir(); break; default: die('Usage: node ' + basename(__filename) + " [--check|--test|--generate|--update|--touchdir]"); } } /** Update dump file listing / Run the check on each file */ async dumplist_update(testsha256 = false, testparity = false, dryrun = false) { this.filelist = await NewEra_DumpListUtil.prototype.readdir_recursive('.', false, this.ignored); this.fileproperties = await NewEra_DumpListUtil.prototype.parse_listfile(this.listfile); if (!this.fileproperties) { return; } for (const file of this.filelist) { // Handle creation case if (!this.fileproperties.hasOwnProperty(file)) { console.log(`${file} is a new file.`); try { if (!dryrun) this.fileproperties[`${file}`] = { 'mtime': await filemtime(file), 'parity': await parity_file(file), 'sha256': await sha256_file(file) }; } catch (e) { console.error(e); } continue; } } // Save the keys to remove in case there is file deletion const keys_to_remove = []; // Handle each file in the properties list for (const file of Object.keys(this.fileproperties)) { const properties = this.fileproperties[`${file}`]; // Handle deletion (Save it, will delete the keys later) if (!await file_exists(file)) { console.log(`${file} does not exist.`); if (!dryrun) keys_to_remove.push(file); continue; } // Handle file modification if (dryrun && await filemtime(file) != properties['mtime']) { console.log(`${file} was modified.`); continue; } // Test file parity if required if (testparity) { const parity = await parity_file(file); if (parity != properties['parity']) { console.log(`${file} Expected parity: ${properties['parity']} Got: ${parity}.`); if (!dryrun) console.error(new Error('Parity mismatch, skiping update').stack); continue; } } // Test file sha256 if required if (testsha256) { const sha256 = await sha256_file(file); if (sha256 != properties['sha256']) { console.log(`${file} Expected sha256: ${properties['sha256']} Got: ${sha256}.`); if (!dryrun) console.error(new Error('SHA256 mismatch, skiping update').stack); continue; } } // Handle file modification if (!dryrun && await filemtime(file) != properties['mtime']) { console.log(`${file} was modified.`); try { this.fileproperties[`${file}`] = { 'mtime': await filemtime(file), 'parity': await parity_file(file), 'sha256': await sha256_file(file) }; } catch (e) { console.error(e); } continue; } } if (!dryrun) { // Handle deletion (Delete the keys now) if (keys_to_remove.length > 0) { for (const key of keys_to_remove) { this.fileproperties[key] = null; delete this.fileproperties[key]; } } const contents = NewEra_DumpListUtil.prototype.generate_listfile(this.fileproperties); await writeFile(this.listfile, contents); } } /** Generate dump file listing */ async dumplist_generate() { this.filelist = await NewEra_DumpListUtil.prototype.readdir_recursive('.', false, this.ignored); this.fileproperties = {}; for (const file of this.filelist) { try { this.fileproperties[`${file}`] = { mtime: await filemtime(file), parity: await parity_file(file), sha256: await sha256_file(file) }; } catch (e) { console.error(e); } } const contents = NewEra_DumpListUtil.prototype.generate_listfile(this.fileproperties); await writeFile(this.listfile, contents); } async dumplist_touchdir() { // Filelist including directories const list = await NewEra_DumpListUtil.prototype.readdir_recursive('.', true, this.ignored); // Easier with a bottom to top approach list.sort(NewEra_Compare.prototype.sort_files_by_level_dsc); // Handle list including directories. Then run // another pass with list without directories for (let i = 0; i < 2; i++) { // Reset internal variables state let [dir, time] = [null, null]; // Handle list for (const file of list) { // Ignore dir dates on pass two if (i === 1 && (await stat(file)).isDirectory()) { continue; } // Blacklist certain names if (file.toLowerCase().indexOf('/desktop.ini') !== -1 || file.indexOf('/.') != -1) { continue; } // Reset internal variables state when moving to another dir if (dir !== dirname(file)) { dir = dirname(file); time = 0; } // Save current time const mtime = await filemtime(file); // Only update when mtime is correctly set and higher than time // Also check for writability to prevent errors if (mtime > 0 && mtime > time && is_writable(dir)) { // Save new timestamp time = mtime; // Update timestamp await utimes(dir, time, time); } } } // I think we should be OK return true; } }
JavaScript
class CacheConfiguration { /** * Create a CacheConfiguration. * @member {string} [queryParameterStripDirective] Treatment of URL query * terms when forming the cache key. Possible values include: 'StripNone', * 'StripAll' * @member {string} [dynamicCompression] Whether to use dynamic compression * for cached content. Possible values include: 'Enabled', 'Disabled' */ constructor() { } /** * Defines the metadata of CacheConfiguration * * @returns {object} metadata of CacheConfiguration * */ mapper() { return { required: false, serializedName: 'CacheConfiguration', type: { name: 'Composite', className: 'CacheConfiguration', modelProperties: { queryParameterStripDirective: { required: false, serializedName: 'queryParameterStripDirective', type: { name: 'String' } }, dynamicCompression: { required: false, serializedName: 'dynamicCompression', type: { name: 'String' } } } } }; } }
JavaScript
class Blocktron { /** * The Blocktron Class properties constructor */ constructor() { this.chain = []; this.pendingTransactions = []; /** * Genesis block defaults * A genesis block is the first block of a block chain. Modern versions of Bitcoin number * it as block 0, though very early versions counted it as block 1. The genesis block is * almost always hardcoded into the software of the applications that utilize its block * chain. It is a special case in that it does not reference a previous block, and for Bitcoin * and almost all of its derivatives, it produces an unspendable subsidy. * @see {@link https://en.bitcoin.it/wiki/Genesis_block|Bitcoin Wiki} */ this.createNewBlock(1, '0', '0'); } /** * Blocktron methods */ /** * @function createNewBlock * Blocktron method to create a new block on to the blockchain * @param {String} nonce - The nonce obtained from proof-of-work * @param {String} previousHash - The hash of the previous block * @param {String} hash - The hash generated from this block's data * @returns {Object} - Returns the new block object */ createNewBlock(nonce, previousHash, hash) { /** * Validate the parameters */ nonce = nonce ? nonce : (function() { throw new Error('Nonce required'); })(); previousHash = previousHash ? previousHash : (function() { throw new Error('Previous hash required'); })(); hash = hash ? hash : (function() { throw new Error('Hash required'); })(); /** * @type {Object} * @const newBlock - An atomic block in the chain * @property {Number} index - The chronological position of this block in the chain * @property {String} timeStamp - The time of creation of the block * @property {String} transactions - The value of transaction to be recorded * @property {String} nonce - The nonce obtained from proof-of-work * @property {String} hash - The hash generated from this block's data * @property {String} previousHash - The hash of the previous block */ const newBlock = { index: this.chain.length + 1, timeStamp: Date.now(), transactions: this.pendingTransactions, nonce: nonce, hash: hash, previousHash: previousHash }; /** * Reset the pendingTransactions array back to empty after creating the new block, * so that the createNewBlock method can start over again from zero. */ this.pendingTransactions = []; /** * Then push the new block to the chain */ this.chain.push(newBlock); /** * Returns the newly created block */ return newBlock; } /** * @function getLastBlock * A method to retreive the penultimate block with respect to current block * @returns {Object} - Returns the block object */ getLastBlock() { /** * This method simply returns the block object from the data * structure at the penultimate position */ return this.chain[this.chain.length - 1]; } /** * @function createNewTransaction * A method to create a new transaction * @param {Number} amount - The amount/value to be recorded * @param {String} sender - The adress of the sender * @param {String} receiver - The address of the receiver * @returns {Object} - Returns the transaction object */ createNewTransaction(amount, sender, receiver) { /** * Validate the parameters */ amount = amount ? amount : (function() { throw new Error('Amount required'); })(); sender = sender ? sender : (function() { throw new Error('Sender required'); })(); receiver = receiver ? receiver : (function() { throw new Error('receiver required'); })(); /** * @type {Object} * @const newTransactions - An atomic transactions block in the chain * @property {Number} amount - The value/amount to be recorded * @property {String} sender - The adress of the sender * @property {String} receiver - The address of the receiver */ const newTransactions = { amount: amount, sender: sender, receiver: receiver }; /** * Push the new transaction to the chain */ this.pendingTransactions.push(newTransactions); /** * Returns the number of the block, this transaction will be added to */ return this.getLastBlock()['index'] + 1; } /** * @function hashBlock * A helper method to generate a hash string out of a blocks data * @param {String} previousBlockHash - The hash of the previous block * @param {Object} currentBlockData - The current block's data * @param {Number} nonce - The nonce of the block * @returns {String} - The hash string generated out of the block data */ hashBlock(previousBlockHash, currentBlockData, nonce) { /** * Validate the parameters */ previousBlockHash = previousBlockHash ? previousBlockHash : (function() { throw new Error('Previous block hash required'); })(); currentBlockData = currentBlockData ? currentBlockData : (function() { throw new Error('Current block data required'); })(); nonce = nonce ? nonce : ''; return hasher( previousBlockHash + nonce.toString() + JSON.stringify(currentBlockData) ); } /** * @function proofOfWork * An opinionated, standardized, and universally approved blockchain method * to validate random blocks added to the blockchain. * Process: * 1. Repeatedly hash the block data until it reaches the format: '0000<HF98WDYS89DCSD>'. * 2. Uses current block data as well as previous block hash. * 3. Continuously change the nonce until the correct hash is obtained. * 4. Return the nonce value which generates the correct hash. * The proofOfWork algorithm runs to a complexity of O(n). * @see {@link https://keepingstock.net/explaining-blockchain-how-proof-of-work-enables-trustless-consensus-2abed27f0845| Explaining blockchain} * @param {String} previousBlockHash - The hash of the previous block * @param {Object} currentBlockData - The current block's data * @returns {Number} - Returns the valid nonce number */ proofOfWork(previousBlockHash, currentBlockData) { /** * Use block scoping rather than constants, because there is a guarenteed rebinding of data to objects. */ let nonce = 0; let hashString = this.hashBlock(previousBlockHash, currentBlockData, nonce); /** * While-loop is prefered over for-loop or other looping constructs. * The loop exit point is unknown in this case. * @see {@link https://stackoverflow.com/questions/39969145/while-loops-vs-for-loops-in-javascript|While Loops vs. For Loops in JavaScript?} */ while (hashString.substring(0, 4) !== '0000') { nonce++; hashString = this.hashBlock(previousBlockHash, currentBlockData, nonce); } /** * Simple returns the nonce value which can generate the correct * hash string of pre-determined format, thus the proof. */ return nonce; } }
JavaScript
class TaskNearbyMap extends Component { /** * Invoked when an individual task marker is clicked by the user */ markerClicked = marker => { if (this.props.onTaskClick) { this.props.onTaskClick(marker.options.challengeId, marker.options.isVirtualChallenge, marker.options.taskId) } } /** * Invoked when user clicks the map instead of a marker */ mapClicked = () => { if (this.props.onMapClick) { this.props.onMapClick() } } render() { if (!this.props.task) { return null } const currentCenterpoint = AsMappableTask(this.props.task).calculateCenterPoint() const hasTaskMarkers = _get(this.props, 'taskMarkers.length', 0) > 0 let coloredMarkers = null if (hasTaskMarkers) { coloredMarkers = _map(this.props.taskMarkers, marker => { const isRequestedMarker = marker.options.taskId === this.props.requestedNextTask const markerData = _cloneDeep(marker) markerData.options.title = `Task ${marker.options.taskId}` const markerStyle = { fill: TaskStatusColors[_get(marker.options, 'status', 0)], stroke: isRequestedMarker ? colors.yellow : colors['grey-leaflet'], strokeWidth: isRequestedMarker ? 2 : 0.5, } return ( <Marker key={marker.options.taskId} {...markerData} icon={markerIconSvg(_get(marker.options, 'priority', 0), markerStyle)} zIndexOffset={isRequestedMarker ? 1000 : undefined} onClick={() => this.markerClicked(markerData)} > <Tooltip> <div> <FormattedMessage {...messages.priorityLabel} /> { this.props.intl.formatMessage( messagesByPriority[_get(marker.options, 'priority', 0)]) } </div> <div> <FormattedMessage {...messages.statusLabel} /> { this.props.intl.formatMessage( messagesByStatus[_get(marker.options, 'status', 0)]) } </div> </Tooltip> </Marker> ) }) } const overlayLayers = buildLayerSources( this.props.visibleOverlays, _get(this.props, 'user.settings.customBasemaps'), (layerId, index, layerSource) => <SourcedTileLayer key={layerId} source={layerSource} zIndex={index + 2} /> ) if (!coloredMarkers) { return ( <div className="mr-h-full"> <FormattedMessage {...messages.noTasksAvailableLabel} /> </div> ) } return ( <div className="mr-h-full"> <LayerToggle {...this.props} /> <EnhancedMap onClick={this.props.clearNextTask} center={currentCenterpoint} zoom={18} minZoom={2} maxZoom={19} zoomControl={false} animate={true} worldCopyJump={true} > <ZoomControl position='topright' /> <VisibleTileLayer {...this.props} zIndex={1} /> {overlayLayers} <Marker position={currentCenterpoint} icon={starIconSvg} title={this.props.intl.formatMessage(messages.currentTaskTooltip)} /> {coloredMarkers.length > 0 && <MarkerClusterGroup key={Date.now()} maxClusterRadius={5}> {coloredMarkers} </MarkerClusterGroup> } </EnhancedMap> {this.props.hasMoreToLoad && <div className="mr-absolute mr-bottom-0 mr-mb-8 mr-w-full mr-text-center"> <button className="mr-button mr-button--small mr-button--blue-fill" onClick={() => this.props.increaseTaskLimit()}> <FormattedMessage {...messages.loadMoreTasks} /> </button> </div> } {!!this.props.tasksLoading && <BusySpinner mapMode big />} </div> ) } }
JavaScript
class RowsList extends Component { constructor(props) { super(props); // Each time rows are updated, we will call our action creator socket.on('rows', (rows) => { console.log(rows) this.props.getResults(rows); }) } render() { if (!this.props.rows) { return ( <p> Loading... </p> ) } return ( <ul> {this.props.rows.map((row, i) => <Row key={i} row={row} />)} </ul> ); } }
JavaScript
class History extends EventTarget { /** * Create a new history object. */ constructor() { super(); /** @const @private @type {?string} */ this.current_ = null; /** @const @private @type {!Html5History} */ var history = this.history_ = new Html5History(); history.setUseFragment(false); events.listen(history, HistoryEventType.NAVIGATE, this.handleNavigate.bind(this)); events.listen(goog.global.document, EventType.CLICK, this.handleDocumentClick.bind(this)); } /** * @param {boolean} b */ setEnabled(b) { this.history_.setEnabled(b); } /** * @param {!events.BrowserEvent} e */ handleDocumentClick(e) { //console.log("history; click!"); // Element that was clicked could be a child of of the <a>, so // look up through the ancestry chain. let anchor = /** @type {?HTMLAnchorElement} */ ( dom.getAncestor(asserts.assertElement(e.target), el => el instanceof HTMLElement && el.tagName === TagName.A.toString(), true) ); if (!anchor) { return; } let hash = anchor.hash; if (!hash) { return; } if (!strings.startsWith(hash, '#/')) { return; } if (e.ctrlKey || e.metaKey) { return; } e.preventDefault(); hash = hash.substring(2); //this.history_.replaceToken(hash); //this.replaceToken(hash); //if (!hash.startsWith("/")) { // hash = window.location.href + "/" + hash; //} //this.history_.setToken(hash); this.setLocation(hash); } /** * @param {string} token */ replaceToken(token) { console.log('Replace token', token); this.history_.replaceToken(token); } /** * @param {string} token */ setLocation(token) { this.history_.setToken(token); } /** * @param {!HistoryEvent} e */ handleNavigate(e) { var target = this.history_.getToken(); // target = decodeURIComponent(target); //console.log(`handleNavigate target = "${target}", token="${this.history_.getToken()}"`); if (target != this.current_) { this.dispatchEvent(e); } else { console.log('Skipping navigate (no difference)', target); } } /** * @override */ disposeInternal() { super.disposeInternal(); this.history_.dispose(); } }
JavaScript
class CbcsDrmConfiguration { /** * Create a CbcsDrmConfiguration. * @member {object} [fairPlay] Fairplay configurations * @member {string} [fairPlay.customLicenseAcquisitionUrlTemplate] The * template for a customer service to deliver keys to end users. Not needed * if using the built in Key Delivery service. * @member {boolean} [fairPlay.allowPersistentLicense] All license to be * persistent or not * @member {object} [playReady] PlayReady configurations * @member {string} [playReady.customLicenseAcquisitionUrlTemplate] The * template for a customer service to deliver keys to end users. Not needed * if using the built in Key Delivery service. * @member {string} [playReady.playReadyCustomAttributes] Custom attributes * for PlayReady * @member {object} [widevine] Widevine configurations * @member {string} [widevine.customLicenseAcquisitionUrlTemplate] The * template for a customer service to deliver keys to end users. Not needed * if using the built in Key Delivery service. */ constructor() { } /** * Defines the metadata of CbcsDrmConfiguration * * @returns {object} metadata of CbcsDrmConfiguration * */ mapper() { return { required: false, serializedName: 'CbcsDrmConfiguration', type: { name: 'Composite', className: 'CbcsDrmConfiguration', modelProperties: { fairPlay: { required: false, serializedName: 'fairPlay', type: { name: 'Composite', className: 'StreamingPolicyFairPlayConfiguration' } }, playReady: { required: false, serializedName: 'playReady', type: { name: 'Composite', className: 'StreamingPolicyPlayReadyConfiguration' } }, widevine: { required: false, serializedName: 'widevine', type: { name: 'Composite', className: 'StreamingPolicyWidevineConfiguration' } } } } }; } }
JavaScript
class Indoex extends Driver { /** * @augments Driver.fetchTickers * @returns {Promise.Array<Ticker>} Returns a promise of an array with tickers. */ async fetchTickers() { const { marketdetails: tickers } = await request('https://api.indoex.io/getMarketDetails/'); return tickers.map((ticker) => { const [base, quote] = ticker.pair.split('_'); return new Ticker({ base, quote, // Yes, Indoex confuses Base and Quote quoteVolume: parseToFloat(ticker.baseVolume), close: parseToFloat(ticker.last), }); }); } }
JavaScript
class CommentCount extends Component { static propTypes = { post: PropTypes.object.isRequired } componentDidMount() { const { fetchCommentsIfNeeded, post } = this.props fetchCommentsIfNeeded(post.id) } render(){ const { commentCount } = this.props return( <span className="post__comment-count"> {commentCount} comments </span> ) } }
JavaScript
class Automaton { /* this class refers to a single cell. It should function as a basic struct and/or * grouping of values. The interaction between automata should be defined inside the * Automata class. * * Public methods: * constructor(value) * get_value() * set_value(val) * get_count() * set_count(val) */ constructor(value, count) { this.value = value; this.count = count; } get_value() { return this.value; } set_value(val) { this.value = val; } get_count() { return this.count; } set_count(val) { this.count = val; } }
JavaScript
class DebugPatternTable { constructor() { WithContext.apply(this); } /** * Renders the tile `id` from `patternTableId` in (`startX`, `startY`), * by using the `plot`(x, y, bgrColor) function. */ renderTile(patternTableId, id, plot, startX = 0, startY = 0) { this.requireContext(); this.context.inDebugMode(() => { const startAddress = START_ADDRESS + patternTableId * PATTERN_TABLE_SIZE; const memory = this.context.memoryBus.ppu; const firstPlane = id * TILE_SIZE; const secondPlane = firstPlane + TILE_SIZE / 2; for (let y = 0; y < TILE_LENGTH; y++) { const row1 = memory.readAt(startAddress + firstPlane + y); const row2 = memory.readAt(startAddress + secondPlane + y); for (let x = 0; x < TILE_LENGTH; x++) { const column = TILE_LENGTH - 1 - x; const lsb = Byte.getBit(row1, column); const msb = Byte.getBit(row2, column); const color = (msb << 1) | lsb; plot(startX + x, startY + y, TEST_PALETTE[color]); } } }); } }
JavaScript
class Base { /** * */ constructor() { this.parent = null; } //!!! (2020/12/12 Remarked) This object is tended to be created new every time. There is no need to reset. // /** Dummy. Do nothing. Sub-class should override this method. */ // resetValue() { // } /** * @return {Percentage.Base} The root Percentage.Base of the whole Percentage hierarchy. The root's valuePercentage represents the whole percentage. */ getRoot() { if ( this.parent ) return this.parent.getRoot(); return this; // If no parent, this is the root. } /** * Dummy. * @return {number} Always 0. Sub-class should override this method. */ get valuePercentage() { return 0; } /** @return {number} Always 100. Sub-class should NOT override this method. */ get maxPercentage() { return 100; } }
JavaScript
class Concrete extends Base { /** * @param {number} max * The possible maximum value of this.value. If negative, indicates not initialized. This is different from maxPercentage. * The maxPercentage is always 100. The this.max, however, could be zero or any positive value. If max is negative, the * the valuePercentage will always be 0 (to avoid Aggregate.valuePercentage immediately 100). If max is zero, the * valuePercentage will always be 100 (to avoid divide by zero and avoid Aggregate.valuePercentage never 100). */ constructor( max = -1 ) { super(); this.value = 0; this.max = max; // Negative indicates not initialized. } //!!! (2020/12/12 Remarked) This object is tended to be created new every time. There is no need to reset. // /** Reset this.value to 0. */ // resetValue() { // this.value = 0; // } /** * @return {number} * The progress as number between [0, 100] inclusive. * Always 0, if this.max is negative. * Always 100, if this.max is zero. * Otherwise, return the ratio of ( this.value / this.max ). */ get valuePercentage() { if (this.max < 0) return 0; // If max is negative (i.e. not initialized), return 0 (to avoid Aggregate.valuePercentage immediately 100). if (this.max == 0) return 100; // If max is indeed zero, return 100 (to avoid divide by zero and avoid Aggregate.valuePercentage never 100). let value = Math.max( 0, Math.min( this.value, this.max ) ); // Restrict between [0, total]. let percentage = ( value / this.max ) * 100; return percentage; } }
JavaScript
class Aggregate extends Base { /** * @param {Percentage.Base[]} children * An array of Percentage.Base which will be aggregated. Their parent will be set to this Percentage.Aggregate. */ constructor( children = [] ) { super(); this.children = children; for ( let i = 0; i < this.children.length; ++i ) { let child = this.children[ i ]; if ( child ) child.parent = this; } } /** * @param {Percentage.Base} child * Another Percentage.Base object. Its parent will be set to this object. * * @return {Percentage.Base} Return the child for cascading easily. */ addChild( child ) { if ( !child ) return null; this.children.push( child ); child.parent = this; return child; } //!!! (2020/12/12 Remarked) This object is tended to be created new every time. There is no need to reset. // /** Reset all children's this.value to 0. */ // resetValue() { // for ( let i = 0; i < this.children.length; ++i ) { // let child = this.children[ i ]; // if ( child ) { // child.resetValue(); // } // } // } /** * @return {number} The sum of all children's ( valuePercentage / maxPercentage ) as number between [0, 100] inclusive. */ get valuePercentage() { let valueSum = 0, maxSum = 0; // Use integer array index is faster than iterator. //for (let child of this.children) { for ( let i = 0; i < this.children.length; ++i ) { let child = this.children[ i ]; if ( !child ) continue; let partMax = child.maxPercentage; if ( partMax <= 0 ) continue; // Skip illegal progress. (This is impossible because maxPercentage is always 100.) let partValue = child.valuePercentage; partValue = Math.max( 0, Math.min( partValue, partMax ) ); // Restrict between [0, partMax]. valueSum += partValue; maxSum += partMax; } if ( maxSum <= 0 ) return 0; // Return zero if the total max is illegal. (to avoid divide by zero.) let percentage = ( valueSum / maxSum ) * 100; return percentage; } }
JavaScript
class Endpoints { /** * Create a Endpoints. * @param {CdnManagementClient} client Reference to the service client. */ constructor(client) { this.client = client; this._listByProfile = _listByProfile; this._get = _get; this._create = _create; this._update = _update; this._deleteMethod = _deleteMethod; this._start = _start; this._stop = _stop; this._purgeContent = _purgeContent; this._loadContent = _loadContent; this._validateCustomDomain = _validateCustomDomain; this._listResourceUsage = _listResourceUsage; this._beginCreate = _beginCreate; this._beginUpdate = _beginUpdate; this._beginDeleteMethod = _beginDeleteMethod; this._beginStart = _beginStart; this._beginStop = _beginStop; this._beginPurgeContent = _beginPurgeContent; this._beginLoadContent = _beginLoadContent; this._listByProfileNext = _listByProfileNext; this._listResourceUsageNext = _listResourceUsageNext; } /** * Lists existing CDN endpoints. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EndpointListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listByProfileWithHttpOperationResponse(resourceGroupName, profileName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByProfile(resourceGroupName, profileName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Lists existing CDN endpoints. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {EndpointListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EndpointListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByProfile(resourceGroupName, profileName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByProfile(resourceGroupName, profileName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByProfile(resourceGroupName, profileName, options, optionalCallback); } } /** * Gets an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ getWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._get(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Gets an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._get(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._get(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Creates a new CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpoint Endpoint properties * * @param {string} [endpoint.originHostHeader] The host header value sent to * the origin with each request. If you leave this blank, the request hostname * determines this value. Azure CDN origins, such as Web Apps, Blob Storage, * and Cloud Services require this host header value to match the origin * hostname by default. * * @param {string} [endpoint.originPath] A directory path on the origin that * CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. * * @param {array} [endpoint.contentTypesToCompress] List of content types on * which compression applies. The value should be a valid MIME type. * * @param {boolean} [endpoint.isCompressionEnabled] Indicates whether content * compression is enabled on CDN. Default value is false. If compression is * enabled, content will be served as compressed if user requests for a * compressed version. Content won't be compressed on CDN when requested * content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpoint.isHttpAllowed] Indicates whether HTTP traffic is * allowed on the endpoint. Default value is true. At least one protocol (HTTP * or HTTPS) must be allowed. * * @param {boolean} [endpoint.isHttpsAllowed] Indicates whether HTTPS traffic * is allowed on the endpoint. Default value is true. At least one protocol * (HTTP or HTTPS) must be allowed. * * @param {string} [endpoint.queryStringCachingBehavior] Defines how CDN caches * requests that include query strings. You can ignore any query strings when * caching, bypass caching to prevent requests that contain query strings from * being cached, or cache every request with a unique URL. Possible values * include: 'IgnoreQueryString', 'BypassCaching', 'UseQueryString', 'NotSet' * * @param {string} [endpoint.optimizationType] Specifies what scenario the * customer wants this CDN endpoint to optimize for, e.g. Download, Media * services. With this information, CDN can apply scenario driven optimization. * Possible values include: 'GeneralWebDelivery', 'GeneralMediaStreaming', * 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpoint.probePath] Path to a file hosted on the origin * which helps accelerate delivery of the dynamic content and calculate the * most optimal routes for the CDN. This is relative to the origin path. * * @param {array} [endpoint.geoFilters] List of rules defining the user's geo * access within a CDN endpoint. Each geo filter defines an access rule to a * specified path or content, e.g. block APAC for path /pictures/ * * @param {object} [endpoint.deliveryPolicy] A policy that specifies the * delivery rules to be used for an endpoint. * * @param {string} [endpoint.deliveryPolicy.description] User-friendly * description of the policy. * * @param {array} endpoint.deliveryPolicy.rules A list of the delivery rules. * * @param {array} endpoint.origins The source of the content being delivered * via CDN. * * @param {string} endpoint.location Resource location. * * @param {object} [endpoint.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ createWithHttpOperationResponse(resourceGroupName, profileName, endpointName, endpoint, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._create(resourceGroupName, profileName, endpointName, endpoint, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Creates a new CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpoint Endpoint properties * * @param {string} [endpoint.originHostHeader] The host header value sent to * the origin with each request. If you leave this blank, the request hostname * determines this value. Azure CDN origins, such as Web Apps, Blob Storage, * and Cloud Services require this host header value to match the origin * hostname by default. * * @param {string} [endpoint.originPath] A directory path on the origin that * CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. * * @param {array} [endpoint.contentTypesToCompress] List of content types on * which compression applies. The value should be a valid MIME type. * * @param {boolean} [endpoint.isCompressionEnabled] Indicates whether content * compression is enabled on CDN. Default value is false. If compression is * enabled, content will be served as compressed if user requests for a * compressed version. Content won't be compressed on CDN when requested * content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpoint.isHttpAllowed] Indicates whether HTTP traffic is * allowed on the endpoint. Default value is true. At least one protocol (HTTP * or HTTPS) must be allowed. * * @param {boolean} [endpoint.isHttpsAllowed] Indicates whether HTTPS traffic * is allowed on the endpoint. Default value is true. At least one protocol * (HTTP or HTTPS) must be allowed. * * @param {string} [endpoint.queryStringCachingBehavior] Defines how CDN caches * requests that include query strings. You can ignore any query strings when * caching, bypass caching to prevent requests that contain query strings from * being cached, or cache every request with a unique URL. Possible values * include: 'IgnoreQueryString', 'BypassCaching', 'UseQueryString', 'NotSet' * * @param {string} [endpoint.optimizationType] Specifies what scenario the * customer wants this CDN endpoint to optimize for, e.g. Download, Media * services. With this information, CDN can apply scenario driven optimization. * Possible values include: 'GeneralWebDelivery', 'GeneralMediaStreaming', * 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpoint.probePath] Path to a file hosted on the origin * which helps accelerate delivery of the dynamic content and calculate the * most optimal routes for the CDN. This is relative to the origin path. * * @param {array} [endpoint.geoFilters] List of rules defining the user's geo * access within a CDN endpoint. Each geo filter defines an access rule to a * specified path or content, e.g. block APAC for path /pictures/ * * @param {object} [endpoint.deliveryPolicy] A policy that specifies the * delivery rules to be used for an endpoint. * * @param {string} [endpoint.deliveryPolicy.description] User-friendly * description of the policy. * * @param {array} endpoint.deliveryPolicy.rules A list of the delivery rules. * * @param {array} endpoint.origins The source of the content being delivered * via CDN. * * @param {string} endpoint.location Resource location. * * @param {object} [endpoint.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName, profileName, endpointName, endpoint, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._create(resourceGroupName, profileName, endpointName, endpoint, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._create(resourceGroupName, profileName, endpointName, endpoint, options, optionalCallback); } } /** * Updates an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. Only tags and Origin * HostHeader can be updated after creating an endpoint. To update origins, use * the Update Origin operation. To update custom domains, use the Update Custom * Domain operation. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpointUpdateProperties Endpoint update properties * * @param {object} [endpointUpdateProperties.tags] Endpoint tags. * * @param {string} [endpointUpdateProperties.originHostHeader] The host header * value sent to the origin with each request. If you leave this blank, the * request hostname determines this value. Azure CDN origins, such as Web Apps, * Blob Storage, and Cloud Services require this host header value to match the * origin hostname by default. * * @param {string} [endpointUpdateProperties.originPath] A directory path on * the origin that CDN can use to retrieve content from, e.g. * contoso.cloudapp.net/originpath. * * @param {array} [endpointUpdateProperties.contentTypesToCompress] List of * content types on which compression applies. The value should be a valid MIME * type. * * @param {boolean} [endpointUpdateProperties.isCompressionEnabled] Indicates * whether content compression is enabled on CDN. Default value is false. If * compression is enabled, content will be served as compressed if user * requests for a compressed version. Content won't be compressed on CDN when * requested content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpointUpdateProperties.isHttpAllowed] Indicates whether * HTTP traffic is allowed on the endpoint. Default value is true. At least one * protocol (HTTP or HTTPS) must be allowed. * * @param {boolean} [endpointUpdateProperties.isHttpsAllowed] Indicates whether * HTTPS traffic is allowed on the endpoint. Default value is true. At least * one protocol (HTTP or HTTPS) must be allowed. * * @param {string} [endpointUpdateProperties.queryStringCachingBehavior] * Defines how CDN caches requests that include query strings. You can ignore * any query strings when caching, bypass caching to prevent requests that * contain query strings from being cached, or cache every request with a * unique URL. Possible values include: 'IgnoreQueryString', 'BypassCaching', * 'UseQueryString', 'NotSet' * * @param {string} [endpointUpdateProperties.optimizationType] Specifies what * scenario the customer wants this CDN endpoint to optimize for, e.g. * Download, Media services. With this information, CDN can apply scenario * driven optimization. Possible values include: 'GeneralWebDelivery', * 'GeneralMediaStreaming', 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpointUpdateProperties.probePath] Path to a file hosted * on the origin which helps accelerate delivery of the dynamic content and * calculate the most optimal routes for the CDN. This is relative to the * origin path. * * @param {array} [endpointUpdateProperties.geoFilters] List of rules defining * the user's geo access within a CDN endpoint. Each geo filter defines an * access rule to a specified path or content, e.g. block APAC for path * /pictures/ * * @param {object} [endpointUpdateProperties.deliveryPolicy] A policy that * specifies the delivery rules to be used for an endpoint. * * @param {string} [endpointUpdateProperties.deliveryPolicy.description] * User-friendly description of the policy. * * @param {array} endpointUpdateProperties.deliveryPolicy.rules A list of the * delivery rules. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ updateWithHttpOperationResponse(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._update(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Updates an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. Only tags and Origin * HostHeader can be updated after creating an endpoint. To update origins, use * the Update Origin operation. To update custom domains, use the Update Custom * Domain operation. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpointUpdateProperties Endpoint update properties * * @param {object} [endpointUpdateProperties.tags] Endpoint tags. * * @param {string} [endpointUpdateProperties.originHostHeader] The host header * value sent to the origin with each request. If you leave this blank, the * request hostname determines this value. Azure CDN origins, such as Web Apps, * Blob Storage, and Cloud Services require this host header value to match the * origin hostname by default. * * @param {string} [endpointUpdateProperties.originPath] A directory path on * the origin that CDN can use to retrieve content from, e.g. * contoso.cloudapp.net/originpath. * * @param {array} [endpointUpdateProperties.contentTypesToCompress] List of * content types on which compression applies. The value should be a valid MIME * type. * * @param {boolean} [endpointUpdateProperties.isCompressionEnabled] Indicates * whether content compression is enabled on CDN. Default value is false. If * compression is enabled, content will be served as compressed if user * requests for a compressed version. Content won't be compressed on CDN when * requested content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpointUpdateProperties.isHttpAllowed] Indicates whether * HTTP traffic is allowed on the endpoint. Default value is true. At least one * protocol (HTTP or HTTPS) must be allowed. * * @param {boolean} [endpointUpdateProperties.isHttpsAllowed] Indicates whether * HTTPS traffic is allowed on the endpoint. Default value is true. At least * one protocol (HTTP or HTTPS) must be allowed. * * @param {string} [endpointUpdateProperties.queryStringCachingBehavior] * Defines how CDN caches requests that include query strings. You can ignore * any query strings when caching, bypass caching to prevent requests that * contain query strings from being cached, or cache every request with a * unique URL. Possible values include: 'IgnoreQueryString', 'BypassCaching', * 'UseQueryString', 'NotSet' * * @param {string} [endpointUpdateProperties.optimizationType] Specifies what * scenario the customer wants this CDN endpoint to optimize for, e.g. * Download, Media services. With this information, CDN can apply scenario * driven optimization. Possible values include: 'GeneralWebDelivery', * 'GeneralMediaStreaming', 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpointUpdateProperties.probePath] Path to a file hosted * on the origin which helps accelerate delivery of the dynamic content and * calculate the most optimal routes for the CDN. This is relative to the * origin path. * * @param {array} [endpointUpdateProperties.geoFilters] List of rules defining * the user's geo access within a CDN endpoint. Each geo filter defines an * access rule to a specified path or content, e.g. block APAC for path * /pictures/ * * @param {object} [endpointUpdateProperties.deliveryPolicy] A policy that * specifies the delivery rules to be used for an endpoint. * * @param {string} [endpointUpdateProperties.deliveryPolicy.description] * User-friendly description of the policy. * * @param {array} endpointUpdateProperties.deliveryPolicy.rules A list of the * delivery rules. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._update(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._update(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, optionalCallback); } } /** * Deletes an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Deletes an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._deleteMethod(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Starts an existing CDN endpoint that is on a stopped state. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ startWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._start(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Starts an existing CDN endpoint that is on a stopped state. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._start(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._start(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Stops an existing running CDN endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ stopWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._stop(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Stops an existing running CDN endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._stop(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._stop(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Removes a content from CDN. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be purged. Can * describe a file path or a wild card directory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ purgeContentWithHttpOperationResponse(resourceGroupName, profileName, endpointName, contentPaths, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._purgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Removes a content from CDN. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be purged. Can * describe a file path or a wild card directory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ purgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._purgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._purgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback); } } /** * Pre-loads a content to CDN. Available for Verizon Profiles. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be loaded. Path * should be a relative file URL of the origin. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ loadContentWithHttpOperationResponse(resourceGroupName, profileName, endpointName, contentPaths, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._loadContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Pre-loads a content to CDN. Available for Verizon Profiles. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be loaded. Path * should be a relative file URL of the origin. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ loadContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._loadContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._loadContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback); } } /** * Validates the custom domain mapping to ensure it maps to the correct CDN * endpoint in DNS. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {string} hostName The host name of the custom domain. Must be a * domain name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ValidateCustomDomainOutput>} - The deserialized result object. * * @reject {Error} - The error object. */ validateCustomDomainWithHttpOperationResponse(resourceGroupName, profileName, endpointName, hostName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._validateCustomDomain(resourceGroupName, profileName, endpointName, hostName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Validates the custom domain mapping to ensure it maps to the correct CDN * endpoint in DNS. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {string} hostName The host name of the custom domain. Must be a * domain name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ValidateCustomDomainOutput} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ValidateCustomDomainOutput} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ validateCustomDomain(resourceGroupName, profileName, endpointName, hostName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._validateCustomDomain(resourceGroupName, profileName, endpointName, hostName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._validateCustomDomain(resourceGroupName, profileName, endpointName, hostName, options, optionalCallback); } } /** * Checks the quota and usage of geo filters and custom domains under the given * endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceUsageListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listResourceUsageWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listResourceUsage(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Checks the quota and usage of geo filters and custom domains under the given * endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ResourceUsageListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ResourceUsageListResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listResourceUsage(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listResourceUsage(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listResourceUsage(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Creates a new CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpoint Endpoint properties * * @param {string} [endpoint.originHostHeader] The host header value sent to * the origin with each request. If you leave this blank, the request hostname * determines this value. Azure CDN origins, such as Web Apps, Blob Storage, * and Cloud Services require this host header value to match the origin * hostname by default. * * @param {string} [endpoint.originPath] A directory path on the origin that * CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. * * @param {array} [endpoint.contentTypesToCompress] List of content types on * which compression applies. The value should be a valid MIME type. * * @param {boolean} [endpoint.isCompressionEnabled] Indicates whether content * compression is enabled on CDN. Default value is false. If compression is * enabled, content will be served as compressed if user requests for a * compressed version. Content won't be compressed on CDN when requested * content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpoint.isHttpAllowed] Indicates whether HTTP traffic is * allowed on the endpoint. Default value is true. At least one protocol (HTTP * or HTTPS) must be allowed. * * @param {boolean} [endpoint.isHttpsAllowed] Indicates whether HTTPS traffic * is allowed on the endpoint. Default value is true. At least one protocol * (HTTP or HTTPS) must be allowed. * * @param {string} [endpoint.queryStringCachingBehavior] Defines how CDN caches * requests that include query strings. You can ignore any query strings when * caching, bypass caching to prevent requests that contain query strings from * being cached, or cache every request with a unique URL. Possible values * include: 'IgnoreQueryString', 'BypassCaching', 'UseQueryString', 'NotSet' * * @param {string} [endpoint.optimizationType] Specifies what scenario the * customer wants this CDN endpoint to optimize for, e.g. Download, Media * services. With this information, CDN can apply scenario driven optimization. * Possible values include: 'GeneralWebDelivery', 'GeneralMediaStreaming', * 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpoint.probePath] Path to a file hosted on the origin * which helps accelerate delivery of the dynamic content and calculate the * most optimal routes for the CDN. This is relative to the origin path. * * @param {array} [endpoint.geoFilters] List of rules defining the user's geo * access within a CDN endpoint. Each geo filter defines an access rule to a * specified path or content, e.g. block APAC for path /pictures/ * * @param {object} [endpoint.deliveryPolicy] A policy that specifies the * delivery rules to be used for an endpoint. * * @param {string} [endpoint.deliveryPolicy.description] User-friendly * description of the policy. * * @param {array} endpoint.deliveryPolicy.rules A list of the delivery rules. * * @param {array} endpoint.origins The source of the content being delivered * via CDN. * * @param {string} endpoint.location Resource location. * * @param {object} [endpoint.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName, profileName, endpointName, endpoint, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, profileName, endpointName, endpoint, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Creates a new CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpoint Endpoint properties * * @param {string} [endpoint.originHostHeader] The host header value sent to * the origin with each request. If you leave this blank, the request hostname * determines this value. Azure CDN origins, such as Web Apps, Blob Storage, * and Cloud Services require this host header value to match the origin * hostname by default. * * @param {string} [endpoint.originPath] A directory path on the origin that * CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. * * @param {array} [endpoint.contentTypesToCompress] List of content types on * which compression applies. The value should be a valid MIME type. * * @param {boolean} [endpoint.isCompressionEnabled] Indicates whether content * compression is enabled on CDN. Default value is false. If compression is * enabled, content will be served as compressed if user requests for a * compressed version. Content won't be compressed on CDN when requested * content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpoint.isHttpAllowed] Indicates whether HTTP traffic is * allowed on the endpoint. Default value is true. At least one protocol (HTTP * or HTTPS) must be allowed. * * @param {boolean} [endpoint.isHttpsAllowed] Indicates whether HTTPS traffic * is allowed on the endpoint. Default value is true. At least one protocol * (HTTP or HTTPS) must be allowed. * * @param {string} [endpoint.queryStringCachingBehavior] Defines how CDN caches * requests that include query strings. You can ignore any query strings when * caching, bypass caching to prevent requests that contain query strings from * being cached, or cache every request with a unique URL. Possible values * include: 'IgnoreQueryString', 'BypassCaching', 'UseQueryString', 'NotSet' * * @param {string} [endpoint.optimizationType] Specifies what scenario the * customer wants this CDN endpoint to optimize for, e.g. Download, Media * services. With this information, CDN can apply scenario driven optimization. * Possible values include: 'GeneralWebDelivery', 'GeneralMediaStreaming', * 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpoint.probePath] Path to a file hosted on the origin * which helps accelerate delivery of the dynamic content and calculate the * most optimal routes for the CDN. This is relative to the origin path. * * @param {array} [endpoint.geoFilters] List of rules defining the user's geo * access within a CDN endpoint. Each geo filter defines an access rule to a * specified path or content, e.g. block APAC for path /pictures/ * * @param {object} [endpoint.deliveryPolicy] A policy that specifies the * delivery rules to be used for an endpoint. * * @param {string} [endpoint.deliveryPolicy.description] User-friendly * description of the policy. * * @param {array} endpoint.deliveryPolicy.rules A list of the delivery rules. * * @param {array} endpoint.origins The source of the content being delivered * via CDN. * * @param {string} endpoint.location Resource location. * * @param {object} [endpoint.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName, profileName, endpointName, endpoint, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, profileName, endpointName, endpoint, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginCreate(resourceGroupName, profileName, endpointName, endpoint, options, optionalCallback); } } /** * Updates an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. Only tags and Origin * HostHeader can be updated after creating an endpoint. To update origins, use * the Update Origin operation. To update custom domains, use the Update Custom * Domain operation. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpointUpdateProperties Endpoint update properties * * @param {object} [endpointUpdateProperties.tags] Endpoint tags. * * @param {string} [endpointUpdateProperties.originHostHeader] The host header * value sent to the origin with each request. If you leave this blank, the * request hostname determines this value. Azure CDN origins, such as Web Apps, * Blob Storage, and Cloud Services require this host header value to match the * origin hostname by default. * * @param {string} [endpointUpdateProperties.originPath] A directory path on * the origin that CDN can use to retrieve content from, e.g. * contoso.cloudapp.net/originpath. * * @param {array} [endpointUpdateProperties.contentTypesToCompress] List of * content types on which compression applies. The value should be a valid MIME * type. * * @param {boolean} [endpointUpdateProperties.isCompressionEnabled] Indicates * whether content compression is enabled on CDN. Default value is false. If * compression is enabled, content will be served as compressed if user * requests for a compressed version. Content won't be compressed on CDN when * requested content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpointUpdateProperties.isHttpAllowed] Indicates whether * HTTP traffic is allowed on the endpoint. Default value is true. At least one * protocol (HTTP or HTTPS) must be allowed. * * @param {boolean} [endpointUpdateProperties.isHttpsAllowed] Indicates whether * HTTPS traffic is allowed on the endpoint. Default value is true. At least * one protocol (HTTP or HTTPS) must be allowed. * * @param {string} [endpointUpdateProperties.queryStringCachingBehavior] * Defines how CDN caches requests that include query strings. You can ignore * any query strings when caching, bypass caching to prevent requests that * contain query strings from being cached, or cache every request with a * unique URL. Possible values include: 'IgnoreQueryString', 'BypassCaching', * 'UseQueryString', 'NotSet' * * @param {string} [endpointUpdateProperties.optimizationType] Specifies what * scenario the customer wants this CDN endpoint to optimize for, e.g. * Download, Media services. With this information, CDN can apply scenario * driven optimization. Possible values include: 'GeneralWebDelivery', * 'GeneralMediaStreaming', 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpointUpdateProperties.probePath] Path to a file hosted * on the origin which helps accelerate delivery of the dynamic content and * calculate the most optimal routes for the CDN. This is relative to the * origin path. * * @param {array} [endpointUpdateProperties.geoFilters] List of rules defining * the user's geo access within a CDN endpoint. Each geo filter defines an * access rule to a specified path or content, e.g. block APAC for path * /pictures/ * * @param {object} [endpointUpdateProperties.deliveryPolicy] A policy that * specifies the delivery rules to be used for an endpoint. * * @param {string} [endpointUpdateProperties.deliveryPolicy.description] * User-friendly description of the policy. * * @param {array} endpointUpdateProperties.deliveryPolicy.rules A list of the * delivery rules. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginUpdate(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Updates an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. Only tags and Origin * HostHeader can be updated after creating an endpoint. To update origins, use * the Update Origin operation. To update custom domains, use the Update Custom * Domain operation. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} endpointUpdateProperties Endpoint update properties * * @param {object} [endpointUpdateProperties.tags] Endpoint tags. * * @param {string} [endpointUpdateProperties.originHostHeader] The host header * value sent to the origin with each request. If you leave this blank, the * request hostname determines this value. Azure CDN origins, such as Web Apps, * Blob Storage, and Cloud Services require this host header value to match the * origin hostname by default. * * @param {string} [endpointUpdateProperties.originPath] A directory path on * the origin that CDN can use to retrieve content from, e.g. * contoso.cloudapp.net/originpath. * * @param {array} [endpointUpdateProperties.contentTypesToCompress] List of * content types on which compression applies. The value should be a valid MIME * type. * * @param {boolean} [endpointUpdateProperties.isCompressionEnabled] Indicates * whether content compression is enabled on CDN. Default value is false. If * compression is enabled, content will be served as compressed if user * requests for a compressed version. Content won't be compressed on CDN when * requested content is smaller than 1 byte or larger than 1 MB. * * @param {boolean} [endpointUpdateProperties.isHttpAllowed] Indicates whether * HTTP traffic is allowed on the endpoint. Default value is true. At least one * protocol (HTTP or HTTPS) must be allowed. * * @param {boolean} [endpointUpdateProperties.isHttpsAllowed] Indicates whether * HTTPS traffic is allowed on the endpoint. Default value is true. At least * one protocol (HTTP or HTTPS) must be allowed. * * @param {string} [endpointUpdateProperties.queryStringCachingBehavior] * Defines how CDN caches requests that include query strings. You can ignore * any query strings when caching, bypass caching to prevent requests that * contain query strings from being cached, or cache every request with a * unique URL. Possible values include: 'IgnoreQueryString', 'BypassCaching', * 'UseQueryString', 'NotSet' * * @param {string} [endpointUpdateProperties.optimizationType] Specifies what * scenario the customer wants this CDN endpoint to optimize for, e.g. * Download, Media services. With this information, CDN can apply scenario * driven optimization. Possible values include: 'GeneralWebDelivery', * 'GeneralMediaStreaming', 'VideoOnDemandMediaStreaming', 'LargeFileDownload', * 'DynamicSiteAcceleration' * * @param {string} [endpointUpdateProperties.probePath] Path to a file hosted * on the origin which helps accelerate delivery of the dynamic content and * calculate the most optimal routes for the CDN. This is relative to the * origin path. * * @param {array} [endpointUpdateProperties.geoFilters] List of rules defining * the user's geo access within a CDN endpoint. Each geo filter defines an * access rule to a specified path or content, e.g. block APAC for path * /pictures/ * * @param {object} [endpointUpdateProperties.deliveryPolicy] A policy that * specifies the delivery rules to be used for an endpoint. * * @param {string} [endpointUpdateProperties.deliveryPolicy.description] * User-friendly description of the policy. * * @param {array} endpointUpdateProperties.deliveryPolicy.rules A list of the * delivery rules. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginUpdate(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginUpdate(resourceGroupName, profileName, endpointName, endpointUpdateProperties, options, optionalCallback); } } /** * Deletes an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Deletes an existing CDN endpoint with the specified endpoint name under the * specified subscription, resource group and profile. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginDeleteMethod(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Starts an existing CDN endpoint that is on a stopped state. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginStart(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Starts an existing CDN endpoint that is on a stopped state. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginStart(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginStart(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Stops an existing running CDN endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Endpoint>} - The deserialized result object. * * @reject {Error} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName, profileName, endpointName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginStop(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Stops an existing running CDN endpoint. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Endpoint} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Endpoint} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName, profileName, endpointName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginStop(resourceGroupName, profileName, endpointName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginStop(resourceGroupName, profileName, endpointName, options, optionalCallback); } } /** * Removes a content from CDN. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be purged. Can * describe a file path or a wild card directory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginPurgeContentWithHttpOperationResponse(resourceGroupName, profileName, endpointName, contentPaths, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginPurgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Removes a content from CDN. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be purged. Can * describe a file path or a wild card directory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginPurgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginPurgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginPurgeContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback); } } /** * Pre-loads a content to CDN. Available for Verizon Profiles. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be loaded. Path * should be a relative file URL of the origin. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginLoadContentWithHttpOperationResponse(resourceGroupName, profileName, endpointName, contentPaths, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginLoadContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Pre-loads a content to CDN. Available for Verizon Profiles. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} profileName Name of the CDN profile which is unique within * the resource group. * * @param {string} endpointName Name of the endpoint under the profile which is * unique globally. * * @param {array} contentPaths The path to the content to be loaded. Path * should be a relative file URL of the origin. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginLoadContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginLoadContent(resourceGroupName, profileName, endpointName, contentPaths, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginLoadContent(resourceGroupName, profileName, endpointName, contentPaths, options, optionalCallback); } } /** * Lists existing CDN endpoints. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EndpointListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listByProfileNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByProfileNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Lists existing CDN endpoints. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {EndpointListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EndpointListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByProfileNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByProfileNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByProfileNext(nextPageLink, options, optionalCallback); } } /** * Checks the quota and usage of geo filters and custom domains under the given * endpoint. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResourceUsageListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listResourceUsageNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listResourceUsageNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Checks the quota and usage of geo filters and custom domains under the given * endpoint. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ResourceUsageListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ResourceUsageListResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listResourceUsageNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listResourceUsageNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listResourceUsageNext(nextPageLink, options, optionalCallback); } } }
JavaScript
class MDCGridListFoundation extends MDCFoundation { static get strings() { return strings; } static get defaultAdapter() { return { getOffsetWidth: () => /* number */ 0, getNumberOfTiles: () => /* number */ 0, getOffsetWidthForTileAtIndex: (/* index: number */) => /* number */ 0, setStyleForTilesElement: (/* property: string, value: string */) => {}, registerResizeHandler: (/* handler: EventListener */) => {}, deregisterResizeHandler: (/* handler: EventListener */) => {}, }; } constructor(adapter) { super(Object.assign(MDCGridListFoundation.defaultAdapter, adapter)); this.resizeHandler_ = () => this.alignCenter(); this.resizeFrame_ = 0; } init() { this.alignCenter(); this.adapter_.registerResizeHandler(this.resizeHandler_); } destroy() { this.adapter_.deregisterResizeHandler(this.resizeHandler_); } alignCenter() { if (this.resizeFrame_ !== 0) { cancelAnimationFrame(this.resizeFrame_); } this.resizeFrame_ = requestAnimationFrame(() => { this.alignCenter_(); this.resizeFrame_ = 0; }); } alignCenter_() { if (this.adapter_.getNumberOfTiles() == 0) { return; } const gridWidth = this.adapter_.getOffsetWidth(); const itemWidth = this.adapter_.getOffsetWidthForTileAtIndex(0); const tilesWidth = itemWidth * Math.floor(gridWidth / itemWidth); this.adapter_.setStyleForTilesElement('width', `${tilesWidth}px`); } }
JavaScript
class AuthorizationError extends Error { /** * Creates an authorization error object. * * @param {string} [message] - Human-readable description of the error. * @param {...*} [params] - Optional interpolation parameters of the message. */ constructor( message, ...params ) { super(); /** * The name of the error type. * @member {string} bo.rules.AuthorizationError#name * @default DaoError */ this.name = this.constructor.name; /** * Human-readable description of the error. * @member {string} bo.rules.AuthorizationError#message */ this.message = t( ...arguments ); } }
JavaScript
class BookDetail extends Component { render() { if (!this.props.book) { return <div>Select a book to get started</div>; } return ( <div> <h3>Details for:</h3> <div>Title: {this.props.book.title}</div> <div>Pages: {this.props.book.pages}</div> </div> ); } }
JavaScript
class CrosImageCapture { /** * @param {!MediaStreamTrack} videoTrack A video track whose still images will * be taken. */ constructor(videoTrack) { /** * The id of target media device. * @type {string} * @private */ this.deviceId_ = videoTrack.getSettings().deviceId; /** * The standard ImageCapture object. * @type {!ImageCapture} * @private */ this.capture_ = new ImageCapture(videoTrack); } /** * Gets the photo capabilities with the available options/effects. * @return {!Promise<!PhotoCapabilities>} Promise * for the result. */ async getPhotoCapabilities() { return this.capture_.getPhotoCapabilities(); } /** * Takes single or multiple photo(s) with the specified settings and effects. * The amount of result photo(s) depends on the specified settings and * effects, and the first promise in the returned array will always resolve * with the unreprocessed photo. The returned array will be resolved once it * received the shutter event. * @param {!PhotoSettings} photoSettings Photo settings for ImageCapture's * takePhoto(). * @param {!Array<!Effect>=} photoEffects Photo effects to be * applied. * @return {!Promise<!Array<!Promise<!Blob>>>} A promise of the array * containing promise of each blob result. */ async takePhoto(photoSettings, photoEffects = []) { const deviceOperator = await DeviceOperator.getInstance(); if (deviceOperator === null && photoEffects.length > 0) { throw new Error('Applying effects is not supported on this device'); } const takes = await deviceOperator.setReprocessOptions(this.deviceId_, photoEffects); if (deviceOperator !== null) { const onShutterDone = new WaitableEvent(); const shutterObserver = await deviceOperator.addShutterObserver(this.deviceId_, () => { onShutterDone.signal(); }); takes.unshift(this.capture_.takePhoto(photoSettings)); await onShutterDone.wait(); closeEndpoint(shutterObserver); return takes; } else { takes.unshift(this.capture_.takePhoto(photoSettings)); return takes; } } /** * @return {!Promise<!ImageBitmap>} */ grabFrame() { return this.capture_.grabFrame(); } /** * @return {!Promise<!Blob>} Returns jpeg blob of the grabbed frame. */ async grabJpegFrame() { const bitmap = await this.capture_.grabFrame(); return bitmapToJpegBlob(bitmap); } }
JavaScript
class DCChallengeCommand extends Command { constructor(ctx) { super(ctx); this.config = ctx.config; this.logger = ctx.logger; this.transport = ctx.transport; this.graphStorage = ctx.graphStorage; this.challengeService = ctx.challengeService; this.errorNotificationService = ctx.errorNotificationService; } /** * Executes command and produces one or more events * @param command - Command object * @param [transaction] - Optional database transaction */ async execute(command, transaction) { const { challenge_id, litigationPrivateKey, } = command.data; const challenge = await models.challenges.findOne({ where: { id: challenge_id, }, }); if (!challenge) { // this is in case that offer expired but old commands remained return Command.empty(); } this.logger.trace(`Sending challenge to ${challenge.dh_id}. Offer ID ${challenge.offer_id}, object_index ${challenge.object_index}, block_index ${challenge.block_index}.`); challenge.end_time = new Date().getTime() + constants.DEFAULT_CHALLENGE_RESPONSE_TIME_MILLS; try { await this.transport.challengeRequest({ payload: { offer_id: challenge.offer_id, data_set_id: challenge.data_set_id, object_index: challenge.object_index, block_index: challenge.block_index, challenge_id: challenge.id, litigator_id: this.config.identity, }, }, challenge.dh_id); } catch (e) { command.delay = this.config.dc_challenge_retry_delay_in_millis; throw new Error(`Peer with ID ${challenge.dh_id} could not be reached on challenge attempt ${5 - command.retries}`); } let checkCommandDelay = constants.DEFAULT_CHALLENGE_RESPONSE_TIME_MILLS; if (this.config.challengeResponseTimeMills) { checkCommandDelay = this.config.challengeResponseTimeMills; } return { commands: [ { name: 'dcChallengeCheckCommand', delay: checkCommandDelay, data: { dhId: challenge.dh_id, dhIdentity: challenge.dh_identity, offerId: challenge.offer_id, dataSetId: challenge.data_set_id, litigationPrivateKey, challengeId: challenge.id, }, retries: 3, transactional: false, }, ], }; } /** * Recover system from failure * @param command * @param err */ async recover(command, err) { const { challenge_id, litigationPrivateKey, } = command.data; const challenge = await models.challenges.findOne({ where: { id: challenge_id, }, }); if (challenge == null) { throw new Error(`Failed to find challenge ${challenge_id}`); } const errorMessage = `Failed to send challenge for object ${challenge.object_index} and block ${challenge.block_index} to DH ${challenge.dh_id}.`; this.logger.info(errorMessage); this.errorNotificationService.notifyError( errorMessage, { objectIndex: challenge.object_index, blockIndex: challenge.block_index, dhIdentity: challenge.dh_identity, offerId: challenge.offer_id, datasetId: challenge.data_set_id, }, constants.PROCESS_NAME.challengesHandling, ); return { commands: [ { name: 'dcLitigationInitiateCommand', period: 5000, data: { offerId: challenge.offer_id, objectIndex: challenge.object_index, blockIndex: challenge.block_index, dhIdentity: challenge.dh_identity, litigationPrivateKey, }, }, ], }; } /** * Builds default command * @param map * @returns {{add, data: *, delay: *, deadline: *}} */ default(map) { const command = { data: { }, name: 'dcChallengeCommand', transactional: false, }; Object.assign(command, map); return command; } }
JavaScript
class Request { constructor (options) { var URL = __nccwpck_require__(154) this.options = options || {} this.debug = options.debug this.debugHeaders = options.debugHeaders var url = URL(options.host || 'https://api.heroku.com') this.host = url.host this.port = url.port this.secure = url.secure this.partial = options.partial this.userAgent = options.userAgent if (!this.userAgent) { var pjson = __nccwpck_require__(260) this.userAgent = 'node-heroku-client/' + pjson.version } this.parseJSON = options.hasOwnProperty('parseJSON') ? options.parseJSON : true this.nextRange = 'id ..; max=1000' this.logger = options.logger this.middleware = options.middleware || function (_, cb) { cb() } this.certs = getCerts(this.debug) this.promise = new Promise((resolve, reject) => { this.resolve = resolve this.reject = reject }) if (process.env.HEROKU_HTTP_PROXY_HOST) { var tunnel = __nccwpck_require__(137) var tunnelFunc if (this.secure) { tunnelFunc = tunnel.httpsOverHttp } else { tunnelFunc = tunnel.httpOverHttp } var agentOpts = { proxy: { host: process.env.HEROKU_HTTP_PROXY_HOST, port: process.env.HEROKU_HTTP_PROXY_PORT || 8080, proxyAuth: process.env.HEROKU_HTTP_PROXY_AUTH }, rejectUnauthorized: options.rejectUnauthorized } if (this.certs.length > 0) { agentOpts.ca = this.certs } this.agent = tunnelFunc(agentOpts) } else { if (this.secure) { var https = __nccwpck_require__(211) this.agent = new https.Agent({ maxSockets: Number(process.env.HEROKU_CLIENT_MAX_SOCKETS) || 5000 }) } else { var http = __nccwpck_require__(605) this.agent = new http.Agent({ maxSockets: Number(process.env.HEROKU_CLIENT_MAX_SOCKETS) || 5000 }) } } } /* * Perform the actual API request. */ request () { var headers = Object.assign({ 'Accept': 'application/vnd.heroku+json; version=3', 'Content-type': 'application/json', 'User-Agent': this.userAgent, 'Range': this.nextRange }, this.options.headers) // remove null|undefined headers for (var k in Object.keys(headers)) { if (headers[k] === null || headers[k] === undefined) { delete headers[k] } } var requestOptions = { agent: this.agent, host: this.host, port: this.port, path: this.options.path, auth: this.options.auth || ':' + this.options.token, method: this.options.method || 'GET', rejectUnauthorized: this.options.rejectUnauthorized, headers: headers } if (this.certs.length > 0) { requestOptions.ca = this.certs } let req if (this.secure) { var https = __nccwpck_require__(211) req = https.request(requestOptions, this.handleResponse.bind(this)) } else { var http = __nccwpck_require__(605) req = http.request(requestOptions, this.handleResponse.bind(this)) } this.logRequest(req) this.writeBody(req) this.setRequestTimeout(req) req.on('error', this.handleError.bind(this)) req.end() return this.promise } /* * Handle an API response, returning the API response. */ handleResponse (res) { this.middleware(res, () => { this.logResponse(res) if (res.statusCode === 304) { this.updateAggregate(this.cachedResponse.body) this.resolve(this.aggregate) return } concat(res).then((data) => { debug(`<-- ${this.options.method} ${this.options.path}\n${data}`) debugHeaders('\n' + renderHeaders(res.headers)) if (this.debug) console.error('<-- ' + data) if (res.statusCode.toString().match(/^2\d{2}$/)) { this.handleSuccess(res, data) } else { this.handleFailure(res, data) } }).catch(this.reject) }) } isRetryAllowed (error) { const isRetryAllowed = __nccwpck_require__(841) if (!isRetryAllowed(error)) return false if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500) return false return true } handleError (error) { if (!this.retries) this.retries = 0 if (this.retries >= 4 || !this.isRetryAllowed(error)) return this.reject(error) let noise = Math.random() * 100 setTimeout(() => this.request(), (1 << this.retries) * 1000 + noise) this.retries++ } logRequest (req) { debug(`--> ${req.method} ${this.options.path}`) if (this.debug) console.error('--> ' + req.method + ' ' + req.path) let reqHeaders = req.getHeaders ? req.getHeaders() : req._headers // .getHeaders isn't defined in node versions < 8 if (!reqHeaders) return let headers = renderHeaders(reqHeaders) debugHeaders('\n' + headers) if (this.debugHeaders) console.error(headers) } /* * Log the API response. */ logResponse (res) { if (this.logger) { this.logger.log({ status: res.statusCode, content_length: res.headers['content-length'], request_id: res.headers['request-id'] }) } let headers = renderHeaders(res.headers) if (this.debug) console.error('<-- ' + res.statusCode + ' ' + res.statusMessage) if (this.debugHeaders) console.error(headers) } /* * If the request options include a body, * write the body to the request and set * an appropriate 'Content-length' header. */ writeBody (req) { if (this.options.body) { var body = this.options.body if (this.options.json !== false) { body = JSON.stringify(body) } if (this.debug) { console.error('--> ' + body) } req.setHeader('Content-length', Buffer.byteLength(body, 'utf8')) req.write(body) } else { req.setHeader('Content-length', 0) } } /* * If the request options include a timeout, * set the timeout and provide a callback * function in case the request exceeds the * timeout period. */ setRequestTimeout (req) { if (!this.options.timeout) return req.setTimeout(this.options.timeout, () => { var err = new Error('Request took longer than ' + this.options.timeout + 'ms to complete.') req.abort() this.reject(err) }) } /* * Get the request body, and parse it (or not) as appropriate. * - Parse JSON by default. * - If parseJSON is `false`, it will not parse. */ parseBody (body) { if (this.parseJSON) { return JSON.parse(body || '{}') } else { return body } } /* * In the event of a non-successful API request, * fail with an appropriate error message and * status code. */ handleFailure (res, buffer) { var message = 'Expected response to be successful, got ' + res.statusCode var err err = new Error(message) err.statusCode = res.statusCode try { err.body = this.parseBody(buffer) } catch (e) { err.body = buffer } this.reject(err) } /* * In the event of a successful API response, * respond with the response body. */ handleSuccess (res, buffer) { var body = this.parseBody(buffer) if (!this.partial && res.headers['next-range']) { this.nextRequest(res.headers['next-range'], body) } else { this.updateAggregate(body) this.resolve(this.aggregate) } } /* * Since this request isn't the full response (206 or * 304 with a cached Next-Range), perform the next * request for more data. */ nextRequest (nextRange, body) { this.updateAggregate(body) this.nextRange = nextRange // The initial range header passed in (if there was one), is no longer valid, and should no longer take precedence delete (this.options.headers.Range) this.request() } /* * If given an object, sets aggregate to object, * otherwise concats array onto aggregate. */ updateAggregate (aggregate) { if (aggregate instanceof Array) { this.aggregate = this.aggregate || [] this.aggregate = this.aggregate.concat(aggregate) } else { this.aggregate = aggregate } } }
JavaScript
class TypeAction extends AbstractAction { /** * @returns {string} 'type' */ static get id() { return 'type'; } /** * Checks if an elements is a typable input or textarea * @param {puppeteer.ElementHandle} element * @returns {boolean} */ static isActionAvailable(element) { return element.executionContext().evaluate((element) => { return element.matches( // Is typable input box 'input' + ':not([type="radio"])' + ':not([type="checkbox"])' + ':not([type="date"])' + ':not(:disabled)' + ':not([readonly])' + // Is typable textarea ', textarea' + ':not(:disabled)' + ':not([readonly])' ); }, element); } /** * Performs the type action with following wrappers: * - Hover over the element * (So that in preview mode, you will see the element before typing) * - Highlight the element (Only in headfull mode) * - Type the configured or random text into the element * @param {puppeteer.ElementHandle} element * @param {puppeteer.Page} page * @returns {Promise} Resolves when typing is done */ async action(element, page) { this._text = this._getText(); await element.hover(); if (this._config.headlessModeDisabled) { await this._actionsHelper.highlightElement(element); await page.waitForTimeout(this._config.previewModePauseTime); } await element.type(this._text, { delay: this._config.typeActionDelay }); } /** * @returns {string} Text from action config, * or random string the list of available texts */ _getText() { if (this._actionConfig && this._actionConfig.text) { return this._actionConfig.text; } return faker.fake(`{{${getRandomElementFromArray(this._config.typeActionTextTypes)}}}`); } /** * Adds info to the action results * @param {Object} results * @returns {Object} */ async updateResults(results) { results.config.text = this._text; results.message = `Type '${this._text}' into ${results.html} [selector:"${results.config.selector}"]`; return results; } }
JavaScript
class Filter extends InstancePlugin { //region Init static get $name() { return 'Filter'; } // Plugin configuration. This plugin chains some of the functions in Grid. static get pluginConfig() { return { chain : ['renderHeader', 'populateCellMenu', 'populateHeaderMenu', 'onElementClick'] }; } construct(grid, config) { const me = this; me.grid = grid; me.store = grid.store; me.closeFilterEditor = me.closeFilterEditor.bind(me); super.construct(grid, config); me.store.on({ filter : me.onStoreFilter }, me); if (config && typeof config === 'object') { me.store.filter(config, null, me.client.isConfiguring); } } //endregion //region Plugin config doDestroy() { const me = this; me.filterTip && me.filterTip.destroy(); me.filterEditorPopup && me.filterEditorPopup.destroy(); me.store.un({ sort : me.onStoreFilter }, me); super.doDestroy(); } //endregion //region Refresh headers /** * Update headers to match stores filters. Called on store load and grid header render. * @param reRenderRows Also refresh rows? * @private */ refreshHeaders(reRenderRows) { const me = this, grid = me.grid, element = grid.headerContainer; if (element) { // remove .latest from all filters, will be applied to actual latest DomHelper.children(element, '.b-filter-icon.b-latest').forEach(iconElement => iconElement.classList.remove('b-latest')); if (!me.filterTip) { me.filterTip = new Tooltip({ forElement : element, forSelector : '.b-filter-icon', getHtml({ activeTarget }) { return activeTarget.dataset.filterText; } }); } for (const column of grid.columns) { if (column.filterable !== false) { const filter = me.store.filters.getBy('property', column.field), headerEl = column.element; if (headerEl) { const textEl = column.textWrapper; let filterIconEl = textEl && textEl.querySelector('.b-filter-icon'), filterText; if (filter) { filterText = me.L('L{filter}') + ': ' + (typeof filter === 'string' ? filter : `${filter.operator} ${filter.displayValue || filter.value || ''}`); //TODO: filter.value needs to be formatted using column format or something } else { filterText = me.L('L{applyFilter}'); } if (!filterIconEl) { // putting icon in header text to have more options for positioning it filterIconEl = DomHelper.createElement({ parent : textEl, tag : 'div', className : 'b-filter-icon', dataset : { filterText : filterText } }); headerEl.classList.add('b-filterable'); } else { filterIconEl.dataset.filterText = filterText; } // latest applied filter distinguished with class to enable highlighting etc. if (column.field === me.store.latestFilterField) filterIconEl.classList.add('b-latest'); headerEl.classList[filter ? 'add' : 'remove']('b-filter'); // When IE11 support is dropped // headerEl.classList.toggle('b-filter', !!filter); } column.meta.isFiltered = !!filter; } } if (reRenderRows) { grid.refreshRows(); } } } //endregion //region Filter applyFilter(config) { const { store } = this, column = this.grid.columns.get(config.property); if (typeof column.filterable === 'function') { store.filter({ filterBy : record => column.filterable(Object.assign({}, config, { record })), // To be able to retrieve the value next time filtering popup is shown, not actually used by the filter value : config.value, property : config.property, operator : config.operator, displayValue : config.displayValue }); } else { store.filter(config); } } // TODO: break out as own views, registering with Filter the same way columns register with ColumnManager getPopupDateItems(fieldType, filter, initialValue, field, store, changeCallback, closeCallback) { const me = this, onClose = changeCallback, onClear = closeCallback; function onChange({ source, value }) { if (value == null) { closeCallback(); } else { me.applyFilter({ property : field, operator : source.operator, value, displayValue : source._value }); changeCallback(); } } return [{ type : 'date', ref : 'on', placeholder : 'L{on}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-equal"></i>', value : filter && filter.operator === '=' ? filter.value : initialValue, operator : '=', onChange, onClose, onClear }, { type : 'date', ref : 'before', placeholder : 'L{before}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-before"></i>', value : filter && filter.operator === '<' ? filter.value : null, operator : '<', onChange, onClose, onClear }, { type : 'date', ref : 'after', cls : 'b-last-row', placeholder : 'L{after}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-after"></i>', value : filter && filter.operator === '>' ? filter.value : null, operator : '>', onChange, onClose, onClear }]; } getPopupNumberItems(fieldType, filter, initialValue, field, store, changeCallback, closeCallback) { const me = this, onEsc = changeCallback, onClear = closeCallback; function onChange({ source, value }) { if (value == null) { closeCallback(); } else { me.applyFilter({ property : field, operator : source.operator, value }); changeCallback(); } } return [{ type : 'number', placeholder : 'L{Filter.equals}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-equal"></i>', value : filter && filter.operator === '=' ? filter.value : initialValue, operator : '=', onChange, onEsc, onClear }, { type : 'number', placeholder : 'L{lessThan}', localeClass : me, label : '<i class="b-fw-icon b-icon-filter-less"></i>', value : filter && filter.operator === '<' ? filter.value : null, operator : '<', onChange, onEsc, onClear }, { type : 'number', cls : 'b-last-row', placeholder : 'L{moreThan}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-more"></i>', value : filter && filter.operator === '>' ? filter.value : null, operator : '>', onChange, onEsc, onClear }]; } getPopupStringItems(fieldType, filter, initialValue, field, store, changeCallback, closeCallback) { const me = this; return [{ type : fieldType, cls : 'b-last-row', placeholder : 'L{filter}', localeClass : me, clearable : true, label : '<i class="b-fw-icon b-icon-filter-equal"></i>', value : filter ? filter.value || filter : initialValue, onChange : ({ value }) => { if (value === '') { closeCallback(); } else { me.applyFilter({ property : field, value }); changeCallback(); } }, onClose : changeCallback, onClear : closeCallback }]; } /** * Get fields to display in filter popup. * @param fieldType Type of field, number, date etc. * @param filter Current filter filter * @param initialValue * @param field Column * @param store Grid store * @param changeCallback Callback for when filter has changed * @param closeCallback Callback for when editor should be closed * @returns {*} * @private */ getPopupItems(fieldType, filter, initialValue, field, store, changeCallback, closeCallback) { switch (fieldType) { case 'date': return this.getPopupDateItems(...arguments); case 'number': return this.getPopupNumberItems(...arguments); default: return this.getPopupStringItems(...arguments); } } /** * Shows a popup where a filter can be edited. * @param {Grid.column.Column} column Column to show filter editor for * @param {*} value Value to init field with */ showFilterEditor(column, value) { const me = this, { store } = me, col = typeof column === 'string' ? me.grid.columns.getById(column) : column, headerEl = col.element, field = store.modelClass.fieldMap[col.field], filter = store.filters.getBy('property', col.field), type = field && field.type || col.filterType || col.type || 'string', fieldType = { string : 'text', number : 'number', date : 'date' }[type] || 'text'; if (col.filterable === false) { return; } // Destroy previous filter popup me.closeFilterEditor(); const items = me.getPopupItems( fieldType, filter, value, col.field, me.store, me.closeFilterEditor, () => { me.store.removeFilter(col.field); me.closeFilterEditor(); } ); // Localize placeholders items.forEach(item => item.placeholder = this.L(item.placeholder)); me.filterEditorPopup = WidgetHelper.openPopup(headerEl, { owner : this.grid, width : '16em', cls : 'b-filter-popup', scrollAction : 'realign', items }); } /** * Close the filter editor. */ closeFilterEditor() { const me = this; // Must defer the destroy because it may be closed by an event like a "change" event where // there may be plenty of code left to execute which must not execute on destroyed objects. me.filterEditorPopup && me.filterEditorPopup.setTimeout(me.filterEditorPopup.destroy); me.filterEditorPopup = null; } //endregion //region Context menu //TODO: break out together with getPopupXXItems() (see comment above) getMenuDateItems({ column, record, items }) { const me = this, property = column.field, value = record[property], filter = operator => { me.applyFilter({ property, operator, value, displayValue : column.formatValue ? column.formatValue(value) : value }); }; return { filterDateEquals : { text : 'L{on}', localeClass : me, icon : 'b-fw-icon b-icon-filter-equal', cls : column.meta.isFiltered ? '' : 'b-separator', name : 'filterDateEquals', weight : 20, disabled : me.disabled, onItem : () => filter('=') }, filterDateBefore : { text : 'L{before}', localeClass : me, icon : 'b-fw-icon b-icon-filter-before', name : 'filterDateBefore', weight : 30, disabled : me.disabled, onItem : () => filter('<') }, filterDateAfter : { text : 'L{after}', localeClass : me, icon : 'b-fw-icon b-icon-filter-after', name : 'filterDateAfter', weight : 40, disabled : me.disabled, onItem : () => filter('>') } }; } getMenuNumberItems({ column, record, items }) { const me = this, property = column.field, value = record[property], filter = operator => { me.applyFilter({ property, operator, value }); }; return { filterNumberEquals : { text : 'L{equals}', localeClass : me, icon : 'b-fw-icon b-icon-filter-equal', cls : column.meta.isFiltered ? '' : 'b-separator', name : 'filterNumberEquals', weight : 20, disabled : me.disabled, onItem : () => filter('=') }, filterNumberLess : { text : 'L{lessThan}', localeClass : me, icon : 'b-fw-icon b-icon-filter-less', name : 'filterNumberLess', weight : 30, disabled : me.disabled, onItem : () => filter('<') }, filterNumberMore : { text : 'L{moreThan}', localeClass : me, icon : 'b-fw-icon b-icon-filter-more', name : 'filterNumberMore', weight : 40, disabled : me.disabled, onItem : () => filter('>') } }; } getMenuStringItems({ column, record, items }) { const me = this, property = column.field, value = record[property]; return { filterStringEquals : { text : 'L{equals}', localeClass : me, icon : 'b-fw-icon b-icon-filter-equal', cls : column.meta.isFiltered ? '' : 'b-separator', name : 'filterStringEquals', weight : 20, disabled : me.disabled, onItem : () => me.applyFilter({ property, value }) } }; } /** * Add menu items for filtering. * @param {Object} options Contains menu items and extra data retrieved from the menu target. * @param {Grid.column.Column} options.column Column for which the menu will be shown * @param {Core.data.Model} options.record Record for which the menu will be shown * @param {Object} options.items A named object to describe menu items * @internal */ populateCellMenu({ column, record, items }) { const me = this; if (column.filterable !== false) { if (column.meta.isFiltered) { items.filterRemove = { text : 'L{removeFilter}', localeClass : me, icon : 'b-fw-icon b-icon-clear', cls : 'b-separator', weight : 10, name : 'filterRemove', disabled : me.disabled, onItem : () => me.store.removeFilter(column.field) }; } const field = record.getFieldDefinition(column.field), type = column.filterType || column.type || (field && field.type), getterName = type === 'date' ? 'getMenuDateItems' : (type === 'number' ? 'getMenuNumberItems' : 'getMenuStringItems'), moreItems = me[getterName](...arguments); ObjectHelper.merge(items, moreItems); } } /** * Add menu item for removing filter if column is filtered. * @param {Object} options Contains menu items and extra data retrieved from the menu target. * @param {Grid.column.Column} options.column Column for which the menu will be shown * @param {Object} options.items A named object to describe menu items * @returns {Object} items Menu items config * @internal */ populateHeaderMenu({ column, items }) { const me = this; if (column.meta.isFiltered) { items.editFilter = { text : 'L{editFilter}', localeClass : me, name : 'editFilter', icon : 'b-fw-icon b-icon-filter', cls : 'b-separator', disabled : me.disabled, onItem : () => me.showFilterEditor(column) }; items.removeFilter = { text : 'L{removeFilter}', localeClass : me, name : 'removeFilter', icon : 'b-fw-icon b-icon-remove', disabled : me.disabled, onItem : () => me.store.removeFilter(column.field) }; } else if (column.filterable !== false) { items.filter = { text : 'L{filter}', localeClass : me, name : 'filter', icon : 'b-fw-icon b-icon-filter', cls : 'b-separator', disabled : me.disabled, onItem : () => me.showFilterEditor(column) }; } return items; } //endregion //region Events /** * Store filtered; refresh headers. * @private */ onStoreFilter() { // Pass false to not refresh rows. // Store's refresh event will refresh the rows. this.refreshHeaders(false); } /** * Called after headers are rendered, make headers match stores initial sorters * @private */ renderHeader() { this.refreshHeaders(false); } /** * Called when user clicks on the grid. Only care about clicks on the filter icon. * @param {MouseEvent} event * @private */ onElementClick(event) { const target = event.target; if (this.filterEditorPopup) this.closeFilterEditor(); // Checks if click is on node expander icon, then toggles expand/collapse if (target.classList.contains('b-filter-icon')) { const headerEl = DomHelper.up(target, '.b-grid-header'); this.showFilterEditor(headerEl.dataset.columnId); return false; } } //endregion }
JavaScript
class Edge { constructor(vertex, weight) { this.vertex = vertex; this.weight = weight; } }
JavaScript
class EventPosition { constructor(event) { this.x = event.clientX; this.y = event.clientY; } }
JavaScript
class EijiroParser { constructor() { this.lines = []; this.currentHead = null; } addLine(line) { const hd = this.parseLine(line); if (hd === null) { return null; } let result = null; if (hd.head === this.currentHead) { this.lines.push(hd.desc); } else { if (this.currentHead && this.lines.length >= 1) { result = {}; result.head = this.currentHead; result.desc = this.lines.join("\n"); } this.currentHead = hd.head; this.lines = []; this.lines.push(hd.desc); } return result; } parseLine(line) { if (!line.startsWith("■")) { return null; } const delimiter = " : "; const didx = line.indexOf(delimiter); let head, desc; if (didx >= 1) { head = line.substring(1, didx); desc = line.substring(didx + delimiter.length); let didx2 = head.indexOf(" {"); if (didx2 >= 1) { head = line.substring(1, didx2 + 1); desc = line.substring(didx2 + 3); } } let hd = head && desc ? { head, desc } : null; return hd; } flush() { const data = {}; if (this.currentHead && this.lines.length >= 1) { data[this.currentHead] = this.lines.join("\n"); } this.currentHead = null; this.lines = []; return data; } }
JavaScript
class MMDVPDReader extends MMDReader { /** * * @access public * @constructor * @param {Buffer} data - * @param {string} directoryPath - */ constructor(data, directoryPath) { const isBinary = false const isBigEndian = false const encoding = 'sjis' super(data, directoryPath, isBinary, isBigEndian, encoding) /** * @access private * @type {CAAnimationGroup} */ this.workingAnimationGroup = null } /** * @access public * @param {Buffer} data - * @param {string} [directoryPath = ''] - * @returns {?CAAnimationGroup} - */ static getAnimation(data, directoryPath = '') { const reader = new MMDVPDReader(data, directoryPath) const animation = reader.loadVPDFile() return animation } /** * @access private * @returns {?CAAnimationGroup} - */ loadVPDFile() { const lines = this.binaryData.split('\r\n') this.workingAnimationGroup = new CAAnimationGroup() this.workingAnimationGroup.animations = [] const magic = lines[0] if(magic !== 'Vocaloid Pose Data file'){ console.error(`Unknown file format: ${magic}`) return null } const modelName = lines[2].split(';')[0] const numBonesText = lines[3].split(';')[0] const numBones = parseInt(numBonesText) if(isNaN(numBones)){ return null } let line = 5 for(let boneNo=0; boneNo<numBones; boneNo++){ const boneName = lines[line+0].split('{')[1] const posText = lines[line+1].split(';')[0].split(',') const rotText = lines[line+2].split(';')[0].split(',') const posX = this.getFloatFromText(posText[0]) const posY = this.getFloatFromText(posText[1]) const posZ = this.getFloatFromText(posText[2]) const pos = new SCNVector3(posX, posY, posZ) const rotX = this.getFloatFromText(rotText[0]) const rotY = this.getFloatFromText(rotText[1]) const rotZ = this.getFloatFromText(rotText[2]) const rotW = this.getFloatFromText(rotText[3]) const rot = new SCNVector4(-rotX, -rotY, rotZ, rotW) const posMotion = new CAKeyframeAnimation(`/${boneName}.transform.translation`) const rotMotion = new CAKeyframeAnimation(`/${boneName}.transform.quaternion`) posMotion.values = [pos] rotMotion.values = [rot] posMotion.keyTimes = [0.0] rotMotion.keyTimes = [0.0] this.workingAnimationGroup.animations.push(posMotion) this.workingANimationGroup.animations.push(rotMotion) line += 5 } this.workingAnimationGroup.duration = 0 this.workingAnimationGroup.usesSceneTimeBase = false this.workingAnimationGroup.isRemovedOnCompletion = false this.workingAnimationGroup.fillMode = kCAFillModeForwards return this.workingAnimationGroup } /** * @access private * @param {string} text - * @returns {Float} - */ getFloatFromText(text) { const value = parseFloat(text) if(!isNaN(value)){ return value } return 0 } }
JavaScript
class App extends React.Component { constructor(props) { super(props); injectTapEventPlugin(); } render() { const { keycloak } = this.props; return ( <MuiThemeProvider> <div className="app"> <HeaderContainer auth={keycloak}/> <div className="app__wrapper"> {this.props.children} </div> </div> </MuiThemeProvider> ); } }
JavaScript
class Maths{ constructor (number) { this.number = number; } }
JavaScript
class Rectangle extends Polygon { constructor(length=1, width=1) { super(); Polygon.call(this, length, width); } }
JavaScript
class Mask { /** * Creates an instance of this feature. * @param options are the options to configure this instance */ constructor(options = {}) { writeCache(this, CACHE_KEY_CONFIGURATION, Object.assign(Object.assign({}, DEFAULTS), options)); } /** * Returns the name of this feature. */ get name() { return FEATURE_NAME; } /** * Returns the rendered element that wraps the carousel. If not enabled, this * returns `null`. * @return the mask element, otherwise `null` if disabled. */ get el() { var _a; return (_a = fromCache(this, CACHE_KEY_MASK)) !== null && _a !== void 0 ? _a : null; } /** * Initializes this feature. This function will be called by the carousel * instance and should not be called manually. * @internal * @param proxy the proxy instance between carousel and feature */ init(proxy) { writeCache(this, CACHE_KEY_PROXY, proxy); // Create a singleton instance of scrollbar for all carousel instances: __scrollbar = __scrollbar !== null && __scrollbar !== void 0 ? __scrollbar : new Scrollbar(); this._render(); } /** * Destroys this feature. This function will be called by the carousel instance * and should not be called manually. * @internal */ destroy() { this._remove(); clearFullCache(this); } /** * This triggers the feature to update its inner state. This function will be * called by the carousel instance and should not be called manually. The * carousel passes a event object that includes the update reason. This can be * used to selectively/partially update sections of the feature. * @internal * @param event event that triggered the update * @param event.reason is the update reason (why this was triggered) */ update(event) { switch (event.type) { case UpdateType.RESIZE: case UpdateType.FORCED: clearCache(this, CACHE_KEY_HEIGHT); this._render(); break; default: this._render(); break; } } /** * Renders the mask element, wraps the carousel element and crops the * height of the browsers scrollbar. * @internal */ _render() { const { enabled, className, tagName } = fromCache(this, CACHE_KEY_CONFIGURATION); if (!enabled) { return; } const proxy = fromCache(this, CACHE_KEY_PROXY); const element = proxy.el; let { height } = __scrollbar.dimensions; if (element.scrollWidth <= element.clientWidth) { // If the contents are not scrollable because their width are less // than the container, there will be no visible scrollbar. In this // case, the scrollbar height is 0: height = 0; } // Use fromCache factory to render mask element only once: fromCache(this, CACHE_KEY_MASK, () => { var _a; const mask = document.createElement(tagName); mask.className = className; mask.style.overflow = 'hidden'; mask.style.height = '100%'; (_a = element.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(mask, element); mask.appendChild(element); return mask; }); const cachedHeight = fromCache(this, CACHE_KEY_HEIGHT); if (height === cachedHeight) { return; } writeCache(this, CACHE_KEY_HEIGHT, height); element.style.height = `calc(100% + ${height}px)`; element.style.marginBottom = `${height * -1}px`; } /** * Removes the mask element and unwraps the carousel element. * @internal */ _remove() { var _a, _b; const { el } = fromCache(this, CACHE_KEY_PROXY); const mask = fromCache(this, CACHE_KEY_MASK); (_a = mask === null || mask === void 0 ? void 0 : mask.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(el, mask); (_b = mask === null || mask === void 0 ? void 0 : mask.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(mask); el.removeAttribute('style'); } }
JavaScript
class FfCalendarEvent { constructor(eventType, startEndTime) { this.type = eventType; this.startTime = startEndTime[0]; this.endTime = startEndTime[1]; } getStartTime() { return this.startTime; } getEndTime() { return this.endTime; } getType() { return this.type; } }
JavaScript
class Settings { constructor() { this.spreadsheet = SpreadsheetApp.getActive(); this.settings = {}; this.populateSettings(); } // Reads settings from the sheet and populates member structure. Input range // to read is defined in SETTINGS_RANGE. populateSettings() { const settingValues = this.spreadsheet.getRange(SETTINGS_RANGE).getValues(); settingValues.forEach((setting) => { const [settingKey, settingVal] = setting; if (settingKey != "") { this.settings[settingKey] = settingVal; } }); } getWorkdayStartHour() { return ( this.settings["workday_start_hour"]?.getHours() || DEFAULT_WORKDAY_START_HOUR ); } // TODO there's a bug when the workday_end_hour is >= 9PM PT. this is because // the date is implicitly stored in ET, and so the end hour falls on the next // day, and is before the start hour (i.e., it's Sun Dec 31 1899 00:00:00 // GMT-0500 (Eastern Standard Time)) getWorkdayEndHour() { return ( this.settings["workday_end_hour"]?.getHours() || DEFAULT_WORKDAY_END_HOUR ); } getLunchtimeStartHour() { return ( this.settings["lunchtime_start_hour"]?.getHours() || DEFAULT_LUNCHTIME_START_HOUR ); } getLunchtimeEndHour() { return ( this.settings["lunchtime_end_hour"]?.getHours() || DEFAULT_LUNCHTIME_END_HOUR ); } }
JavaScript
class PollingJobQueueStrategy extends injectable_job_queue_strategy_1.InjectableJobQueueStrategy { constructor(concurrencyOrConfig, maybePollInterval) { var _a, _b, _c, _d; super(); this.activeQueues = new queue_name_process_storage_1.QueueNameProcessStorage(); if (concurrencyOrConfig && shared_utils_1.isObject(concurrencyOrConfig)) { this.concurrency = (_a = concurrencyOrConfig.concurrency) !== null && _a !== void 0 ? _a : 1; this.pollInterval = (_b = concurrencyOrConfig.pollInterval) !== null && _b !== void 0 ? _b : 200; this.backOffStrategy = (_c = concurrencyOrConfig.backoffStrategy) !== null && _c !== void 0 ? _c : (() => 1000); this.setRetries = (_d = concurrencyOrConfig.setRetries) !== null && _d !== void 0 ? _d : ((_, job) => job.retries); } else { this.concurrency = concurrencyOrConfig !== null && concurrencyOrConfig !== void 0 ? concurrencyOrConfig : 1; this.pollInterval = maybePollInterval !== null && maybePollInterval !== void 0 ? maybePollInterval : 200; this.setRetries = (_, job) => job.retries; } } async start(queueName, process) { if (!this.hasInitialized) { this.started.set(queueName, process); return; } if (this.activeQueues.has(queueName, process)) { return; } const active = new ActiveQueue(queueName, process, this); active.start(); this.activeQueues.set(queueName, process, active); } async stop(queueName, process) { const active = this.activeQueues.getAndDelete(queueName, process); if (!active) { return; } await active.stop(); } async cancelJob(jobId) { const job = await this.findOne(jobId); if (job) { job.cancel(); await this.update(job); return job; } } }
JavaScript
class Login extends Component { constructor(props) { super(props); var localloginComponent = []; localloginComponent.push( <MuiThemeProvider key={"theme"}> <div> <TextField hintText="User name" floatingLabelText="Tenant Id" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> ) this.state = { username: '', password: '', menuValue: 1, loginComponent: localloginComponent, loginRole: 'Tenant', } } componentWillMount() { // console.log("willmount prop values",this.props); if (this.props.role !== undefined) { var localloginComponent = [] if (this.props.role === 'Tenant') { // console.log("in Tenant componentWillMount"); localloginComponent.push( <MuiThemeProvider> <div> <TextField hintText="Enter your name" floatingLabelText="Tenant Id" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> ) this.setState({ menuValue: 1, loginComponent: localloginComponent, loginRole: 'Tenant' }) } else if (this.props.role === 'Host') { // console.log("in Host componentWillMount"); localloginComponent.push( <MuiThemeProvider> <div> <TextField hintText="Enter your name" floatingLabelText="Host Id" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> ) this.setState({ menuValue: 2, loginComponent: localloginComponent, loginRole: 'Host' }) } } } handleClick(event) { var apiBaseUrl = settings.apiBaseUrl; var self = this; // if (this.state.loginRole === "Tenant") { // self.props.history.push("/tenant") // } // else { // self.props.history.push("/host") // } var payload={ "username":this.state.username, "password":this.state.password, // "role":this.state.loginRole } axios.post(apiBaseUrl+'/loginUser', payload) .then(function (response) { console.log(response); if(response.status === 200){ console.log("Login successfull"); console.log(self.state) localStorage.setItem("token", response.data.token) if (response.data.role === 'Tenant' && self.state.menuValue === 1 ){ var id = ":"+ response.data.id self.props.history.push("/home/"+id) } else if(response.data.role === 'Host' && self.state.menuValue === 2) { var id = ":"+ response.data.id self.props.history.push("/home/"+id) } else{ alert("Bạn chưa có tài khoản hoặc bạn chọn sai tư cách đăng nhập") } // var uploadScreen=[]; // uploadScreen.push(<UploadPage appContext={self.props.appContext} role={self.state.loginRole}/>) // self.props.appContext.setState({loginPage:[],uploadScreen:uploadScreen}) } else if(response.status === 204){ console.log("Username password do not match"); alert(response.data.success) } else{ console.log("Username does not exists"); alert("Username does not exist"); } }) .catch(function (error) { console.log(error); }); } handleMenuChange(value) { // console.log("menuvalue",value); var loginRole; var localloginComponent = [] if (value === 1) { // var localloginComponent=[]; loginRole = 'Tenant'; localloginComponent.push( <MuiThemeProvider> <div> <TextField hintText="Enter your name" floatingLabelText="Tenant Id" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> ) } else if (value === 2) { // var localloginComponent=[]; loginRole = 'Host'; localloginComponent.push( <MuiThemeProvider> <div> <TextField hintText="Enter your name" floatingLabelText="Host Id" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> ) } this.setState({ menuValue: value, loginComponent: localloginComponent, loginRole: loginRole }) } render() { return ( <div className="row"> <TopBar /> <div className="col-xl-5 col-lg-6 col-md-8 col-sm-10 mx-auto text-center form p-4" style={{ marginTop: 8 + 'em' }}> <div> <MuiThemeProvider> <AppBar title="Login" /> </MuiThemeProvider> <MuiThemeProvider> <div> <p>Login as:</p> <DropDownMenu value={this.state.menuValue} onChange={(event, index, value) => this.handleMenuChange(value)}> <MenuItem value={1} primaryText="Người thuê trọ" /> <MenuItem value={2} primaryText="Chủ trọ" /> </DropDownMenu> </div> </MuiThemeProvider> {this.state.loginComponent} </div> </div> </div> ); } }
JavaScript
class AbstractJsBuilder extends BaseBuilder { buildFloat() { return this.buildInteger() } buildCommentBlock(lines/*: string[]*/) { return [{ type: 'CommentBlock', value: `*\n${lines.filter((e) => !!e).map((line) => ` * ${line}`).join('\n')}\n `, }] } buildCommentSeeLink(link/*: string*/) { return `@see ${link}` } }
JavaScript
class SDK { /** * Checks if the specified directory is an Android SDK. * * @param {String} dir - The directory to check for an Android SDK. * @access public */ constructor(dir) { if (typeof dir !== 'string' || !dir) { throw new TypeError('Expected directory to be a valid string'); } dir = expandPath(dir); if (!isDir(dir)) { throw new Error('Directory does not exist'); } let toolsDir = path.join(dir, 'tools'); if (!isDir(toolsDir)) { // are we in a subdirectory already in the SDK? throw new Error('Directory does not contain a "tools" directory'); } const toolsProps = readPropertiesFile(path.join(toolsDir, 'source.properties')); if (!toolsProps) { throw new Error('Directory contains bad "tools/source.properties" file'); } const version = toolsProps['Pkg.Revision']; if (!version) { throw new Error('Directory contains invalid "tools/source.properties" (missing Pkg.Revision)'); } const executables = this.findExecutables(toolsDir, { android: `android${bat}`, emulator: `emulator${exe}`, sdkmanager: `bin/sdkmanager${bat}` }); // check the emulator directory const emulatorExe = path.join(dir, 'emulator', `emulator${exe}`); if (isFile(emulatorExe)) { executables.emulator = emulatorExe; } if (!isFile(executables.emulator)) { throw new Error('Directory missing "emulator" executable'); } this.addons = []; this.buildTools = []; this.path = dir; this.platforms = []; this.platformTools = { executables: {}, path: null, version: null }; this.systemImages = {}; this.tools = { executables, path: toolsDir, version }; /** * Detect build tools */ const buildToolsDir = path.join(dir, 'build-tools'); if (isDir(buildToolsDir)) { for (const name of fs.readdirSync(buildToolsDir)) { const dir = path.join(buildToolsDir, name); if (isDir(dir)) { const dxFile = path.join(dir, 'lib', 'dx.jar'); const buildToolsProps = readPropertiesFile(path.join(dir, 'source.properties')); if (buildToolsProps) { this.buildTools.push({ dx: isFile(dxFile) ? dxFile : null, executables: this.findExecutables(dir, { aapt: `aapt${exe}`, aapt2: `aapt2${exe}`, aidl: `aidl${exe}`, zipalign: `zipalign${exe}` }), path: dir, version: buildToolsProps && buildToolsProps['Pkg.Revision'] || null }); } } } } /** * Detect platform tools */ const platformToolsDir = path.join(dir, 'platform-tools'); if (isDir(platformToolsDir)) { const platformToolsProps = readPropertiesFile(path.join(platformToolsDir, 'source.properties')); if (platformToolsProps) { this.platformTools = { executables: this.findExecutables(platformToolsDir, { adb: `adb${exe}` }), path: platformToolsDir, version: platformToolsProps && platformToolsProps['Pkg.Revision'] || null }; } } /** * Detect system images */ const systemImagesDir = path.join(dir, 'system-images'); if (isDir(systemImagesDir)) { for (const platform of fs.readdirSync(systemImagesDir)) { const platformDir = path.join(systemImagesDir, platform); if (isDir(platformDir)) { for (const tag of fs.readdirSync(platformDir)) { const tagDir = path.join(platformDir, tag); if (isDir(tagDir)) { for (const abi of fs.readdirSync(tagDir)) { const abiDir = path.join(tagDir, abi); const props = readPropertiesFile(path.join(abiDir, 'source.properties')); if (props && props['AndroidVersion.ApiLevel'] && props['SystemImage.TagId'] && props['SystemImage.Abi']) { const imageDir = path.relative(systemImagesDir, abiDir).replace(/\\/g, '/'); const skinsDir = path.join(abiDir, 'skins'); this.systemImages[imageDir] = { abi: props['SystemImage.Abi'], sdk: `android-${props['AndroidVersion.CodeName'] || props['AndroidVersion.ApiLevel']}`, skins: isDir(skinsDir) ? fs.readdirSync(skinsDir).map(name => { return isFile(path.join(skinsDir, name, 'hardware.ini')) ? name : null; }).filter(x => x) : [], type: props['SystemImage.TagId'] }; } } } } } } } /** * Detect platforms */ const platformsDir = path.join(dir, 'platforms'); if (isDir(platformsDir)) { for (const name of fs.readdirSync(platformsDir)) { const dir = path.join(platformsDir, name); const sourceProps = readPropertiesFile(path.join(dir, 'source.properties')); const apiLevel = sourceProps ? ~~sourceProps['AndroidVersion.ApiLevel'] : null; if (!sourceProps || !apiLevel || !isFile(path.join(dir, 'build.prop'))) { continue; } // read in the sdk properties, if exists const sdkProps = readPropertiesFile(path.join(dir, 'sdk.properties')); // detect the available skins const skinsDir = path.join(dir, 'skins'); const skins = isDir(skinsDir) ? fs.readdirSync(skinsDir).map(name => { return isFile(path.join(skinsDir, name, 'hardware.ini')) ? name : null; }).filter(x => x) : []; let defaultSkin = sdkProps && sdkProps['sdk.skin.default']; if (skins.indexOf(defaultSkin) === -1 && skins.indexOf(defaultSkin = 'WVGA800') === -1) { defaultSkin = skins[skins.length - 1] || null; } const apiName = sourceProps['AndroidVersion.CodeName'] || apiLevel; const sdk = `android-${apiName}`; let tmp; const abis = {}; for (const image of Object.values(this.systemImages)) { if (image.sdk === sdk) { if (!abis[image.type]) { abis[image.type] = []; } if (!abis[image.type].includes(image.abi)) { abis[image.type].push(image.abi); } for (const skin of image.skins) { if (!skins.includes(skin)) { skins.push(skin); } } } } this.platforms.push({ abis: abis, aidl: isFile(tmp = path.join(dir, 'framework.aidl')) ? tmp : null, androidJar: isFile(tmp = path.join(dir, 'android.jar')) ? tmp : null, apiLevel: apiLevel, codename: sourceProps['AndroidVersion.CodeName'] || null, defaultSkin: defaultSkin, minToolsRev: +sourceProps['Platform.MinToolsRev'] || null, name: `Android ${sourceProps['Platform.Version']}${sourceProps['AndroidVersion.CodeName'] ? ' (Preview)' : ''}`, path: dir, revision: +sourceProps['Layoutlib.Revision'] || null, sdk, skins: skins, version: sourceProps['Platform.Version'] }); } } /** * Detect addons */ const addonsDir = path.join(dir, 'add-ons'); if (isDir(addonsDir)) { for (const name of fs.readdirSync(addonsDir)) { const dir = path.join(addonsDir, name); const props = readPropertiesFile(path.join(dir, 'source.properties')) || readPropertiesFile(path.join(dir, 'manifest.ini')); if (!props) { continue; } const apiLevel = parseInt(props['AndroidVersion.ApiLevel'] || props.api); const vendorDisplay = props['Addon.VendorDisplay'] || props.vendor; const nameDisplay = props['Addon.NameDisplay'] || props.name; if (!apiLevel || isNaN(apiLevel) || !vendorDisplay || !nameDisplay) { continue; } let basedOn = null; for (const platform of this.platforms) { if (platform.codename === null && platform.apiLevel === apiLevel) { basedOn = platform; break; } } this.addons.push({ abis: basedOn && basedOn.abis || null, aidl: basedOn && basedOn.aidl || null, androidJar: basedOn && basedOn.androidJar || null, apiLevel: apiLevel, basedOn: basedOn ? { version: basedOn.version, apiLevel: basedOn.apiLevel } : null, codename: props['AndroidVersion.CodeName'] || props.codename || null, defaultSkin: basedOn && basedOn.defaultSkin || null, description: props['Pkg.Desc'] || props.description || null, minToolsRev: basedOn && basedOn.minToolsRev || null, name: nameDisplay, path: dir, revision: parseInt(props['Pkg.Revision'] || props.revision) || null, sdk: `${vendorDisplay}:${nameDisplay}:${apiLevel}`, skins: basedOn && basedOn.skins || null, vendor: vendorDisplay, version: basedOn && basedOn.version || null }); } } function sortFn(a, b) { if (a.codename === null) { if (b.codename !== null && a.apiLevel === b.apiLevel) { // sort GA releases before preview releases return -1; } } else if (a.apiLevel === b.apiLevel) { return b.codename === null ? 1 : a.codename.localeCompare(b.codename); } return a.apiLevel - b.apiLevel; } this.platforms.sort(sortFn); this.addons.sort(sortFn); } /** * Scans a directory for executables. * * @param {String} dir - The directory to look for executables in. * @param {Object} exes - A map of * @returns {Object} * @access private */ findExecutables(dir, exes) { const executables = {}; for (const name of Object.keys(exes)) { const file = path.join(dir, exes[name]); executables[name] = isFile(file) ? file : null; } return executables; } }
JavaScript
class HeroAnimated { /** * Creates an instance of HeroAnimated. * @param {HTMLElement} element – Hero HTML element. */ constructor(element) { // Create a set of constants to be reused throughout the class. const constants = { wrapperSelector: '.hero-animated__animation', animationItemClass: 'hero-animated__animation-item', animationDelay: 2000, animationName: 'Hero', }; constants.backgroundImageSelector = `img.${constants.animationItemClass}`; this.constants_ = Object.freeze(constants); this.elem_ = element; this.backgroundImage_ = this.elem_.querySelector(this.constants_.backgroundImageSelector); this.animation_ = {}; // Start the animation in case lottie loaded before the background image. if (!this.backgroundImage_.complete) { this.backgroundImage_.addEventListener('load', this.startIfReady_.bind(this)); } } /** * Loads the animation. * @param {Object} lottie - The lottie library. * @param {Object} animationData – The animation data. */ async loadAnimation(lottie, animationData) { this.lottie_ = lottie; /** @type {AnimationConfig} */ this.animationConfig_ = { container: this.elem_.querySelector(this.constants_.wrapperSelector), animType: 'svg', loop: true, animationData: animationData, autoplay: false, name: this.constants_.animationName, rendererSettings: { progressiveLoad: true, className: this.constants_.animationItemClass, }, }; this.init_(); } /** * Inits the animation and sets the event handlers. */ init_() { this.animation_ = this.lottie_.loadAnimation(this.animationConfig_); this.animation_.hide(); // Animation loaded handlers. this.animation_.addEventListener('DOMLoaded', () => { this.startIfReady_(this.animation_); }); // Something went wrong handlers. this.animation_.addEventListener('error', () => { console.error(`Something went wrong and the ${this.animation_.name} animation failed to load! 😭`); }); this.animation_.addEventListener('data_failed', () => { console.error(`Something went wrong and the ${this.animation_.name} animation data failed to load! 😭`); }); } /** * Starts the animation if the background image and the animation are loaded. */ startIfReady_() { if (this.backgroundImage_.complete && this.animation_.isLoaded) { setTimeout(() => { this.animation_.show(); this.animation_.play(); }, this.constants_.animationDelay); } } }
JavaScript
class DiskBlock { constructor(index, params) { this.data = null; this.index = index; this.BLOCK_SIZE = params.BLOCK_SIZE; } insert(data) { if (data.length > this.BLOCK_SIZE - 1) { this.data = data.slice(0, this.BLOCK_SIZE); return data.slice(this.BLOCK_SIZE, data.length); } this.data = data.slice(0, data.length); return false; } empty = () => { this.data = null; } }
JavaScript
class ROI { /* @constructor * @param{Scoord3D} scoord3d spatial coordinates * @param{Object} properties qualititative evaluations */ constructor(options) { if (!('scoord3d' in options)) { throw new Error('spatial coordinates are required for ROI') } if (!(typeof(options.scoord3d) === 'object' || options.scoord3d !== null)) { throw new Error('scoord3d of ROI must be a Scoord3D object') } if (!('uid' in options)) { this[_uid] = generateUID(); } else { if (!(typeof(options.uid) === 'string' || options.uid instanceof String)) { throw new Error('uid of ROI must be a string') } this[_uid] = options.uid; } this[_scoord3d] = options.scoord3d; this[_properties] = options.properties; // TODO: store SOPInstanceUID, SOPClassUID and FrameNumbers as reference } get uid() { return this[_uid]; } get scoord3d() { return this[_scoord3d]; } get properties() { return this[_properties]; } }
JavaScript
class Axis { /** X axis */ static get X() { return new _1.Vector3(1.0, 0.0, 0.0); } /** Y axis */ static get Y() { return new _1.Vector3(0.0, 1.0, 0.0); } /** Z axis */ static get Z() { return new _1.Vector3(0.0, 0.0, 1.0); } }
JavaScript
class Parser { constructor(){ this._queryString = ""; } set queryString(queryString){ this._queryString = queryString } get queryString(){ return this._queryString; } /** * Function that transforms a given string into an SQL query * @param {string} queryString - Optional argument. The string that will be converted into SQL. Defaults to the queryString parameter of the object that called the function. * @return {string} Returns a valid SQL query as a string. */ parse(queryString = this._queryString){ //Regular search, no special modifiers if(queryString.indexOf("#") < 0 && queryString.indexOf('"') < 0 && queryString.indexOf("|") < 0){ return "SELECT rolas.id_rola, rolas.id_performer, rolas.id_album, rolas.path, rolas.title, rolas.track, rolas.year, rolas.genre, albums.name as album, performers.name as performer "+ "FROM rolas, performers, albums "+ "WHERE rolas.id_performer = performers.id_performer "+ "AND rolas.id_album = albums.id_album "+ "AND (album like '%"+queryString+"%' OR performer like '%"+queryString+"%' OR title like '%"+queryString+"%');" } //Field specific search only one field if(queryString.indexOf("#") == 0 && queryString.indexOf("|") < 0){ var field = queryString.slice(1,queryString.indexOf(" ")); field = getDbField(field); if(!field) return ""; var search = queryString.slice(queryString.indexOf(" ")+1, queryString.length); var query = "SELECT rolas.id_rola, rolas.id_performer, rolas.id_album, rolas.path, rolas.title, rolas.track, rolas.year, rolas.genre, albums.name as album, performers.name as performer "+ "FROM rolas, performers, albums "+ "WHERE rolas.id_performer = performers.id_performer "+ "AND rolas.id_album = albums.id_album "+ "AND "+field+" "; if( search.indexOf('"') == 0 && search.lastIndexOf('"') == search.length-1 ){ //literal search query = query + "= '"+search.slice(1,search.length-1)+"';" }else{ //substring search query = query + "like '%"+search+"%';" } return query; } //Multiple field specific search if(queryString.indexOf("#") >= 0 && queryString.lastIndexOf("|") > 0){ var searchFields = queryString.split("|"); var query = "SELECT rolas.id_rola, rolas.id_performer, rolas.id_album, rolas.path, rolas.title, rolas.track, rolas.year, rolas.genre, albums.name as album, performers.name as performer "+ "FROM rolas, performers, albums "+ "WHERE rolas.id_performer = performers.id_performer "+ "AND rolas.id_album = albums.id_album " for(var i=0; i< searchFields.length; i++){ var search = searchFields[i].trim(); var field = search.slice(1,search.indexOf(" ")); field = getDbField(field); if(!field) continue; var searchValue = search.slice(search.indexOf(" ")+1, search.length); if( searchValue.indexOf('"') == 0 && searchValue.lastIndexOf('"') == searchValue.length-1 ){ //literal search query = query + "AND "+field+" = '"+searchValue.slice(1,searchValue.length-1)+"' " }else{ //substring search query = query + "AND "+field+" like '%"+searchValue+"%' " } }; return query.trim()+";"; } } }
JavaScript
class Env { constructor (appRoot) { const envLocation = this.getEnvPath() const options = { path: path.isAbsolute(envLocation) ? envLocation : path.join(appRoot, envLocation), encoding: process.env.ENV_ENCODING || 'utf8' } debug('loading .env file from %s', options.path) const env = dotenv.config(options) /** * Throwing the exception when ENV_SILENT is not set to true * and ofcourse there is an error */ if (env.error && process.env.ENV_SILENT !== 'true') { throw env.error } } /** * Returns the path from where the `.env` * file will be loaded. * * @method getEnvPath * * @return {String} */ getEnvPath () { if (!process.env.ENV_PATH || process.env.ENV_PATH.length === 0) { return '.env' } return process.env.ENV_PATH } /** * Get value for a given key from the `process.env` * object. * * @method get * * @param {String} key * @param {Mixed} [defaultValue = null] * * @return {Mixed} * * @example * ```js * Env.get('CACHE_VIEWS', false) * ``` */ get (key, defaultValue = null) { return _.get(process.env, key, defaultValue) } /** * Set value for a given key inside the `process.env` * object. If value exists, will be updated * * @method set * * @param {String} key * @param {Mixed} value * * @example * ```js * Env.set('PORT', 3333) * ``` */ set (key, value) { _.set(process.env, key, value) } }
JavaScript
class App extends Component { static propTypes = { children: PropTypes.object.isRequired, user: PropTypes.object, loading: PropTypes.bool, location: PropTypes.shape({ pathname: PropTypes.string }), // logout: PropTypes.func.isRequired, // pushState: PropTypes.func.isRequired }; static contextTypes = { store: PropTypes.object.isRequired, }; state = { loadingBarWidth: 0, compLoaded: false }; // componentWillReceiveProps(nextProps) { // if (!this.props.user && nextProps.user) { // // login // this.props.pushState('/loginSuccess'); // } else if (this.props.user && !nextProps.user) { // // logout // this.props.pushState('/'); // } // } // handleLogout = (event) => { // event.preventDefault(); // this.props.logout(); // }; componentDidMount = () => { ga.initialize('UA-81811986-1', {debug: false}); ga.pageview(this.props.location.pathname); }; componentWillUpdate = (nextProps) => { if (nextProps.location.pathname !== this.props.location.pathname) { ga.pageview(nextProps.location.pathname); } }; toggleNav = () => { this.refs.drawer.getWrappedInstance().closeDrawer(); }; render() { const {user} = this.props; // const {loadingBarWidth} = this.state; return ( <div className={styles.app}> <Drawer ref="drawer"/> <Helmet {...config.app.head}/> <LoadingBar className={styles.loader} updateTime={500}/> <Navbar fixedTop> <Navbar.Header> <i className="material-icons md-dark hidden-sm hidden-md hidden-lg" style={{float: 'left', marginRight: '10px'}} onClick={this.toggleNav}>menu</i> <Navbar.Brand> <IndexLink to="/in/trains/" title="Atmed Trains Home"> <nobr> <img src={'https://res.cloudinary.com/atmed/image/upload//c_scale,h_20,q_100/atmed_logo.png'} alt="atmed_logo" style={{maxHeight: '20px'}}/><span>&nbsp;Trains</span></nobr> </IndexLink> </Navbar.Brand> <Navbar.Toggle/> </Navbar.Header> <div style={{position: 'absolute', top: '18px', right: '0px'}}> <img src="https://res.cloudinary.com/atmed/image/upload/flag/in.png" alt="india-flag"/> </div> <Navbar.Collapse> <Nav navbar> {user && <LinkContainer to="/chat"> <NavItem eventKey={1}>Chat</NavItem> </LinkContainer>} {/* <LinkContainer to="/widgets"> <NavItem eventKey={2}>Widgets</NavItem> </LinkContainer> <LinkContainer to="/survey"> <NavItem eventKey={3}>Survey</NavItem> </LinkContainer> */} <LinkContainer to="/in/trains/pnr-status"> <NavItem eventKey={3} title="PNR Status">PNR Status</NavItem> </LinkContainer> <LinkContainer to="/in/trains/running-status-route"> <NavItem eventKey={3} title="Train Running status and Route">Train Live Status & Route</NavItem> </LinkContainer> <LinkContainer to="/in/trains/cancelled"> <NavItem eventKey={3} title="Cancelled trains">Cancelled Trains</NavItem> </LinkContainer> <LinkContainer to="/in/trains/station"> <NavItem eventKey={3} title="Station Information">Station Info</NavItem> </LinkContainer> {/* {!user && <LinkContainer to="/login"> <NavItem eventKey={5}>Login</NavItem> </LinkContainer>} {user && <LinkContainer to="/logout"> <NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}> Logout </NavItem> </LinkContainer>} */} </Nav> </Navbar.Collapse> </Navbar> <div className="container-fluid appContent"> <div className={styles.appContent}> {this.props.children} </div> <div className="push"></div> </div> <Footer/> </div> ); } }
JavaScript
class CalendarConnector { /** * Initializes the class. * @param {Number} maxResults */ constructor(maxResults = 20) { this.maxResults = maxResults; } /** * @return {Boolean} */ async init() { // Load client secrets from a local file. this._credentials = await readFile('./config/credentials.json'); // Authorize a client with credentials, then call the Google Calendar API. this._auth = await this.authorize(JSON.parse(this._credentials)); this._calendar = google.calendar({version: 'v3', auth: this._auth}); return true; } /** * Lists the next 10 events on the user's primary calendar. * @param {google.auth.OAuth2} auth An authorized OAuth2 client. */ async getEvents() { const response = await this._calendar.events.list({ calendarId: 'primary', timeMin: (new Date()).toISOString(), maxResults: this.maxResults * 3, singleEvents: true, orderBy: 'startTime', }); let events = response.data.items; events = events.filter((event) => { return event.summary.indexOf(MEETING_NAME) > -1; }); if (events.length) { events.forEach((event, i) => { event.dateString = (event.start.dateTime || event.start.date) .replace(/T.*/, ''); }); } else { console.log('No upcoming meetings found.'); } return events.slice(0, this.maxResults); } /** * * @param {*} event */ async updateEvent(event) { await this._calendar.events.patch({ calendarId: 'primary', eventId: event.id, resource: event, }); } /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. * @param {Object} credentials The authorization client credentials. * @param {function} callback The callback to call with the authorized client. */ async authorize(credentials) { // eslint-disable-next-line camelcase const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. let token; try { token = await readFile(TOKEN_PATH); } catch (err) { return await this.getAccessToken(oAuth2Client); } oAuth2Client.setCredentials(JSON.parse(token)); return oAuth2Client; } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for */ async getAccessToken(oAuth2Client) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES, }); console.log('Authorize this app by visiting this url:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const code = await rl.questionAsync('Enter the code from that page here: '); rl.close(); const {tokens} = await oAuth2Client.getToken(code); // if (err) return console.error('Error retrieving access token', err); oAuth2Client.setCredentials(tokens); // Store the token to disk for later program executions await writeFile(TOKEN_PATH, JSON.stringify(tokens)); console.log('Token stored to', TOKEN_PATH); return oAuth2Client; } }
JavaScript
class KeyCombinationMatcher { /** * Returns a new instance of KeyCombinationMatcher * @returns {KeyCombinationMatcher} */ constructor() { this._actionConfigs = {}; this._order = null; } /** * Adds a new ActionConfiguration and handler to those that can be used to match a * KeyCombination * @param {ActionConfiguration} actionConfig * @param {Function} handler Function to call if match is selected * @returns {void} */ addMatch(actionConfig, handler) { if (this._includesMatcherForCombination(actionConfig.id)) { const { keyEventType, actionName, id } = actionConfig; this._addHandlerToActionConfig(id, { keyEventType, actionName, handler }); } else { this._addNewActionConfig(actionConfig, handler); } } /** * Finds a MatchingActionConfig for a KeyCombination, ReactKeyName and * KeyEventType * @param {KeyCombination} keyCombination Record of key combinations * to use in the match * @param {ReactKeyName} keyName Name of the key to use in the match * @param {KeyEventType} keyEventType The type of key event to use in the match * @returns {MatchingActionConfig|null} A MatchingActionOptions that matches the * KeyCombination, ReactKeyName and KeyEventType */ findMatch(keyCombination, keyName, keyEventType) { lazyLoadAttribute(this, 'order', () => this._setOrder()); for(let combinationId of this._order) { const actionOptions = this._actionConfigs[combinationId]; if (this._matchesActionConfig(keyCombination, keyName, keyEventType, actionOptions)) { return actionOptions; } } return null; } /******************************************************************************** * Presentation ********************************************************************************/ /** * A plain JavaScript representation of the KeyCombinationMatcher, useful for * serialization or debugging * @returns {Object} Serialized representation of the key combination matcher */ toJSON() { return { actionConfigs: this._actionConfigs, order: this._order }; } /******************************************************************************** * Private methods ********************************************************************************/ _matchesActionConfig(keyCombination, keyName, eventType, actionOptions) { if (!canBeMatched(keyCombination, actionOptions) || !actionOptions.events[eventType]) { /** * If the combination does not have any actions bound to the key event we are * currently processing, we skip checking if it matches the current keys being * pressed. */ return false; } let keyCompletesCombination = false; const combinationKeys = Object.keys(actionOptions.keyDictionary); const combinationMatchesKeysPressed = combinationKeys.every((candidateKeyName) => { if (!keyCombination.isEventTriggered(candidateKeyName, eventType)) { return false; } if (keyName && (keyName === keyCombination.getNormalizedKeyName(candidateKeyName))) { keyCompletesCombination = !keyCombination.wasEventPreviouslyTriggered(candidateKeyName, eventType); } return true; }); return combinationMatchesKeysPressed && keyCompletesCombination; } _setOrder() { /** * The first time the component that is currently handling the key event has * its handlers searched for a match, order the combinations based on their * size so that they may be applied in the correct priority order */ const combinationsPartitionedBySize = objectValues(this._actionConfigs).reduce((memo, {id, size}) => { if (!memo[size]) { memo[size] = []; } memo[size].push(id); return memo; }, {}); this._order = Object.keys(combinationsPartitionedBySize).sort((a, b) => b - a).reduce((memo, key) => { return memo.concat(combinationsPartitionedBySize[key]); }, []); } _addNewActionConfig(combinationSchema, handler) { const { prefix, sequenceLength, id, keyDictionary, size, keyEventType, actionName } = combinationSchema; this._setCombinationMatcher(id, { prefix, sequenceLength, id, keyDictionary, size, events: { } }); this._addHandlerToActionConfig(id, { keyEventType, actionName, handler }) } _addHandlerToActionConfig(id, { keyEventType, actionName, handler }) { const combination = this._getCombinationMatcher(id); this._setCombinationMatcher(id, { ...combination, events: { ...combination.events, [keyEventType]: { actionName, handler } } }); } _setCombinationMatcher(id, combinationMatcher) { this._actionConfigs[id] = combinationMatcher; } _getCombinationMatcher(id) { return this._actionConfigs[id]; } _includesMatcherForCombination(id) { return !!this._getCombinationMatcher(id); } }
JavaScript
class CyclicProfiler { /** * @param {number} size Number of events to be measured. Memory used is * proportional to `size` and does not increase with * profiling time. Therefore, the profiler can always * be enabled in the background. * * @param {number} skipN skip the first N epochs. Each time all events occur * once is called an "epoch". Used for warm-up. */ constructor(size, skipN = 0) { this.epochs = 0; this.size = size; this.skipN = skipN; this.timings = new Array(size).fill(0); // get profiling generator this.profiler = this._initProfiler(); // start profiler. stop at the first yield stmt this.profiler.next(); } /** * Elapsed time of a single event is determined between a pair of calls to the * `startEvent()` and `endEvent()` */ startEvent() { this.profiler.next(); } endEvent() { this.profiler.next(); } /** * Flush out profiling results * * Note: It assumes that all events go through the same epochs for simplicity */ flush() { const actualEpochs = this.epochs - this.skipN; const avgTimings = this.timings.map((x) => x / actualEpochs); this.timings.fill(0); this.epochs = 0; return { epochs: actualEpochs, elpased: avgTimings }; } * _initProfiler() { for (this.epochs = 0; this.epochs < this.skipN; this.epochs++) { for (let i = 0; i < this.size; i++) { yield; // dummy startEvent yield; // dummy endEvent } } for (;;) { for (let i = 0; i < this.size; i++) { yield; // startEvent continues from here const start = performance.now(); yield; // endEvent continues from here const end = performance.now(); this.timings[i] += end - start; } this.epochs++; } } }
JavaScript
class Testimonio extends React.Component{ render(){ return( //Recuerda que utilizamos className no class <div className='contenedor-testimonio'> {/* Utilizamos una Self-Closing-Tag */} <img className='imagen-testimonio' // src='../images/testimonio-emma.png' // src={require('../images/testimonio-emma.png')} // Utilizaremos plantillas literales de JS utilizando ` src={require(`../images/testimonio-${this.props.imagen}.png`)} alt={`Foto de ${this.props.nombre}`} /> <div className='contenedor-texto-testimonio'> <p className='nombre-testimonio'> <strong>{this.props.nombre}</strong> en {this.props.pais} </p> <p className='cargo-testimonio'> {this.props.cargo} en <strong>{this.props.empresa}</strong> </p> <p className='texto-testimonio'>"{this.props.testimonio}"</p> </div> </div> ); } }
JavaScript
class Cache { constructor (options) { options = options || {} this.duration = options.duration || 3600000 this.clean = options.clean this.max = options.max || Infinity this.cache = new Map() this.times = new Map() } get size () { return this.cache.size } has (key) { return this.cache.has(key) } get (key) { this.times.set(key, Date.now()) this._clear(key) return this.cache.get(key) } set (key, data) { this.cache.set(key, data) this.times.set(key, Date.now()) this._clear(key) } delete (key) { this.times.delete(key) this.cache.delete(key) } push (key, ...items) { const data = this.cache.get(key) || [] data.concat(items) this.cache.set(key, data) this.times.set(key, Date.now()) this._clear(key) } reset (cb) { const keys = [...this.cache.keys()] const clean = cb || this.clean for (const key of keys) { if (clean)clean(this.cache.get(key)) } this.cache = new Map() this.times = new Map() } _clear (hit) { const self = this function clean (key) { if (self.clean)self.clean(self.cache.get(key)) self.cache.delete(key) self.times.delete(key) } let keys = [...this.cache.keys()] keys.forEach(key => { if (hit === key) return const time = self.times.get(key) if (Date.now() - time >= self.duration) { clean(key) } }) const exceed = self.cache.size - self.max if (exceed > 0) { keys = [...self.times.keys()].sort((a, b) => a - b) keys.slice(0, exceed).forEach(key => { clean(key) }) } } }
JavaScript
class SinglyLinkedList { constructor() { this.head = null; this.size = 0; } isEmpty() { return this.size === 0; } insert(value) { let newNode = new SinglyLinkedListNode(value); // Check if first node if (this.head === null) { this.head = newNode; } else { let current = this.head; while (current.next) current = current.next; current.next = newNode; } this.size++; } removeAtIndex(index) { if (this.head === null || index < 0) { throw new RangeError( "Index " + index + " doesn't exist in the list." ); } if (index === 0) { const data = this.head.data; this.head = this.head.next; return data; } let current = this.head; let previous = null; let i = 0; while (current && i < index) { previous = current; current = current.next; i++; } if (current) { previous.next = current.next; return current.data; } throw new RangeError("Index " + index + " doesn't exist in the list."); } get(index) { if (index > -1) { let current = this.head; let i = 0; while (current.next && i < index) { current = current.next; i++; } return current ? current.data : undefined; } return undefined; } *values() { let current = this.head; while (current) { yield current.data; current = current.next; } } [Symbol.iterator]() { return this.values(); } }
JavaScript
class VisualAutomaton { constructor () { this.graphics = { states: new Map(), transitions: new Map() } } highlightGraphics () { for (let graphic of [ ...Array.from(this.graphics.transitions.values()), ...Array.from(this.graphics.states.values()) ] ) { graphic.highlight(); } } resetGraphics () { for (let graphic of [ ...Array.from(this.graphics.transitions.values()), ...Array.from(this.graphics.states.values()) ] ) { graphic.reset(); } } prepareGraphics () { let stage = []; // First transitions for (let graphic of Array.from(this.graphics.transitions.values())) { stage.push(graphic); } // Then states for (let graphic of Array.from(this.graphics.states.values())) { stage.push(graphic); } console.log(stage); // (order matters) return stage; } clearGraphics () { this.graphics.states.clear(); this.graphics.transitions.clear(); } registerState (id, accepting) { this.graphics.states.set( id, new StateGraphic( id, accepting ) ); } unregisterState(id) { if (!this.graphics.states.has(id)) { throw new Error(`Could not unregister transition with id: ${key}`); } // Remove state graphic this.graphics.states.delete(id); // Remove all state related transitions for (const [key, graphic] of this.graphics.transitions.entries()) { if (graphic.sourceGraphic.id === id || graphic.targetGraphic.id === id) { this.graphics.transitions.delete(key); } } } transitionKey(sourceId, targetId, transitionString) { return sourceId + targetId + transitionString; } registerTransition (sourceId, targetId, transitionString) { let sourceGraphic = this.graphics.states.get(sourceId); if (!sourceGraphic) { throw new Error(`Could not find source graphic for id: ${sourceId}`); } let targetGraphic = this.graphics.states.get(targetId); if (!targetGraphic) { throw new Error(`Could not find target graphic for id: ${targetId}`); } // Key calculated by concatonation of the strings let key = this.transitionKey(sourceId, targetId, transitionString); this.graphics.transitions.set( key, new TransitionGraphic( sourceGraphic, targetGraphic, transitionString ) ); } unregisterTransition(sourceId, targetId, transitionString) { let key = this.transitionKey(sourceId, targetId, transitionString); if (!this.graphics.transitions.has(key)) { throw new Error(`Could not unregister transition with id: ${key}`); } this.graphics.transitions.delete(key); } async accept (string) { throw new Error("Not implemented!"); } addState () { throw new Error("Not implemented!"); } removeState () { throw new Error("Not implemented!"); } addTransition () { throw new Error("Not implemented!"); } removeTransition () { throw new Error("Not implemented!"); } verify () { throw new Error("Not implemented!"); } move () { throw new Error("Not implemented!"); } toString () { throw new Error("Not implemented"); } toMarkup () { throw new Error("Not implemented"); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = { latestArticles: [], recommendedArticles: [], readNow: [], readLater: [], likedSections: [], articleWireType: "latest", }; } componentDidMount() { fetch(LATEST_URL) .then(response => response.json()) .then(json => this.setState({ latestArticles: json.results, readNow: ls.get('readNow') || [], readLater: ls.get('readLater') || [], likedSections: ls.get('likedSections') || [], articleWireType: "latest", })); } fetchArticles = () => { fetch(LATEST_URL) .then(response=> response.json()) .then(json => json.results.map((newArt) => { if (!this.state.latestArticles.find((a) => a.title === newArt.title)) { this.setState((state, props) => { return { latestArticles: [newArt,... state.latestArticles] } }) } })) } fetchRecommendedArticles = () => { let currentState = this.state.recommendedArticles.slice(0) for (let sec of this.state.likedSections) { fetch(REC_URL(sec)) .then(response=> response.json()) .then(json => json.results.slice(0, 10).map((newArt) => { if (!this.state.recommendedArticles.find((a) => a.title === newArt.title) && !this.state.latestArticles.find((feed) => feed.title === newArt.title)) { this.setState((state, props) => { return { recommendedArticles: [newArt,...state.recommendedArticles] } }) } })) } } addNewToState = (articles, articleState) => { articles.filter((a) => !this.state[articleState].includes(a)) } startInterval = (fetchArticleFunction) => { this.interval = setInterval(fetchArticleFunction, 10000) } handleSaveArticleToReadLater = (art) => { let currentReadLaterState = this.state.readLater.slice(0) let currentLikedSections = this.state.likedSections.slice(0) let newReadLaterState = [...currentReadLaterState, art] if (!this.state.readLater.includes(art)) { this.setState({ readLater: newReadLaterState, }); ls.set('readLater', newReadLaterState) } if (!this.state.likedSections.includes(art.section)) { const newLikedSections = [...currentLikedSections, art.section]; this.setState({ likedSections: newLikedSections }) ls.set('likedSections', newLikedSections); } } handleReadArticle = (art) => { let currentLikedSections = this.state.likedSections.slice(0) let newLikedSections = [...currentLikedSections, art.section] if (!this.state.likedSections.includes(art.section)) { this.setState({ likedSections: newLikedSections }) ls.set('likedSections', newLikedSections) } if (this.state.readNow.length < 15) { let readNow = [...this.state.readNow, art]; this.setState({ readNow: readNow, }); ls.set('readNow', readNow) if (this.state.readLater.find((article) => article.title === art.title)) { this.handleDeleteArticle(art) } const win = window.open(art.url, '_blank'); win.focus(); } else { alert("Looks like you've hit your limit of 15 free articles this month. Please sign up for one of the subscription options offered by the Times.") } } handleOpenArticle = (article) => { window.open(`${article.url}`, "_blank") } handleDeleteArticle = (article) => { const truncatedList = this.state.readLater.slice(0) truncatedList.splice(truncatedList.indexOf(article), 1) this.setState({ readLater: truncatedList }) ls.set('readLater', truncatedList) } renderFeedComponent = () => { if (this.state.articleWireType === "latest") { this.fetchArticles return ( <ArticleContainer articles={this.state.latestArticles} fetchArticles={this.fetchArticles} startInterval={this.startInterval} readLater={this.state.readLater} handleSaveArticleToReadLater={this.handleSaveArticleToReadLater} handleReadArticle={this.handleReadArticle} /> ) } else { this.fetchRecommendedArticles return ( <RecommendationContainer fetchRecommendedArticles={this.fetchRecommendedArticles} recommendedArticles={this.state.recommendedArticles} readNow={this.state.readNow} readLater={this.state.readLater} likedSections={this.state.likedSections} handleSaveArticleToReadLater={this.handleSaveArticleToReadLater} handleReadArticle={this.handleReadArticle} startInterval={this.startInterval}/> ) } } toggleFeedType = (event) => { let v = event.target.value this.setState({ articleWireType: v, }) } toggleButtonId = (type) => { if (this.state.articleWireType === type) { return "active" } else { return "inactive" } } render() { return ( <div className="news-wire-top wrapper"> <div className="header"><span className="header-text">NYTimes NewsWire</span></div> <div className="app-container"> <div className="sidebar"> <div className="readLaterSection"> <div className="readLaterHeader">Saved Articles</div> <ReadLaterContainer readLater={this.state.readLater} handleReadArticle={this.handleReadArticle} handleDeleteArticle={this.handleDeleteArticle}/> </div> <div className="readNowSection"> <span className="viewHistoryHeader">Viewing History</span> {this.state.readNow.length >= 1 && <ReadNowContainer readNow={this.state.readNow} /> } </div> </div> <div className="article-section"> <div className="toggle-feed-buttons"> <button className="toggle-feed" id={this.toggleButtonId("latest")} onClick={this.toggleFeedType} value="latest">Latest</button> <span className="vl"></span> <button className="toggle-feed" id={this.toggleButtonId("recommended")} onClick={this.toggleFeedType} value="recommended">Recommended</button> </div> {this.renderFeedComponent()} </div> </div> </div> ); } }