language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class DrawingManager extends Observable {
/**
* @param {Map} map OpenLayers map instance
* @param {Object[]} tools Tools configuration
* @param {Object} Options
*/
constructor(map, tools, options = {}) {
super()
this.map = map
this.geojsonFormat = new GeoJSON({
featureProjection: this.map.getView().getProjection(),
})
this.kmlFormat = new KML()
this.gpxFormat = new GPX()
this.options = options
this.layer = new VectorLayer({
source: new VectorSource({ useSpatialIndex: false }),
})
this.source = this.layer.getSource()
this.measureManager = new MeasureManager(this.map, this.layer)
this.tools = {}
this.sketchPoints = 0
for (let [type, options] of Object.entries(tools)) {
// use the default styling if no specific draw style is set
const drawOptions = Object.assign(
{
style: (feature) => featureStyle(feature),
},
options.drawOptions
)
const tool = new DrawInteraction({
...drawOptions,
source: this.source,
})
tool.set('type', type)
tool.setActive(false)
const overlaySource = tool.getOverlay().getSource()
overlaySource.on('addfeature', (event) => this.onAddFeature_(event, options.properties))
tool.on('change:active', (event) => this.onDrawActiveChange_(event))
tool.on('drawstart', (event) => this.onDrawStart_(event))
tool.on('drawend', (event) => this.onDrawEnd_(event))
this.tools[type] = tool
}
this.select = new SelectInteraction({
style: this.options.editingStyle,
toggleCondition: () => false,
layers: [this.layer],
})
const selected = this.select.getFeatures()
selected.on('add', (event) => this.onSelectChange_(event))
selected.on('remove', (event) => this.onSelectChange_(event))
this.modify = new ModifyInteraction({
features: selected,
style: this.options.editingStyle,
deleteCondition: (event) => noModifierKeys(event) && singleClick(event),
})
this.modify.on('modifystart', (event) => this.onModifyStart_(event))
this.modify.on('modifyend', (event) => this.onModifyEnd_(event))
this.snap = new SnapInteraction({
source: this.source,
})
this.pointerCoordinate = null
this.map.on('pointerup', (event) => (this.pointerCoordinate = event.coordinate))
this.activeInteraction = null
this.onKeyUpFunction_ = this.onKeyUp_.bind(this)
this.onPointerMoveFunction_ = this.onPointerMove_.bind(this)
this.tooltipOverlay = new Overlay({
element: this.options.helpPopupElement,
offset: [15, 15],
positioning: 'top-left',
// so that the tooltip is not on top of the style popup (and its children popup)
stopEvent: false,
insertFirst: true,
})
/**
* Whether the polygon was finished by a click on the first point of the geometry.
*
* @type {boolean}
*/
this.isFinishOnFirstPoint_ = false
}
// API
activate() {
for (const id in this.tools) {
this.map.addInteraction(this.tools[id])
}
if (!this.options.noModify) {
this.map.addInteraction(this.select)
this.map.addInteraction(this.modify)
}
this.map.addLayer(this.layer)
this.map.addInteraction(this.snap)
document.addEventListener('keyup', this.onKeyUpFunction_)
this.map.addOverlay(this.tooltipOverlay)
this.map.on('pointermove', this.onPointerMoveFunction_)
}
// API
deactivate() {
for (const id in this.tools) {
this.map.removeInteraction(this.tools[id])
}
this.map.removeInteraction(this.select)
this.map.removeInteraction(this.modify)
this.map.removeInteraction(this.snap)
this.map.removeLayer(this.layer)
this.map.un('pointermove', this.onPointerMoveFunction_)
this.map.removeOverlay(this.tooltipOverlay)
document.removeEventListener('keyup', this.onKeyUpFunction_)
}
/**
* Activate a specific tool. If an other tool was already active it is deactivated.
*
* @param {string} tool Tool name
*/
toggleTool(tool) {
if (this.activeInteraction) {
this.activeInteraction.setActive(false)
}
if (tool) {
this.deselect()
this.activeInteraction = this.tools[tool]
if (this.activeInteraction) {
this.activeInteraction.setActive(true)
}
this.updateHelpTooltip(tool, false)
}
}
// API
deselect() {
this.select.getFeatures().clear()
}
deleteSelected() {
this.select.getFeatures().forEach((f) => {
this.source.removeFeature(f)
})
this.deselect()
this.dispatchChangeEvent_()
}
createGeoJSON() {
// todo Do we need overlays in geoJson? it makes loop during state update
const features = this.source.getFeatures().map((f) => {
const feature = f.clone()
feature.set('overlays', undefined)
return feature
})
return this.geojsonFormat.writeFeaturesObject(features)
}
createGPX() {
const features = this.source.getFeatures().map((feature) => {
const clone = feature.clone()
const geom = clone.getGeometry()
// convert polygon to line because gpx doesn't support polygons
if (geom instanceof Polygon) {
const coordinates = geom.getLinearRing().getCoordinates()
clone.setGeometry(new LineString(coordinates))
}
return clone
})
return this.gpxFormat.writeFeatures(features, {
featureProjection: this.map.getView().getProjection(),
})
}
createKML() {
let kmlString = '<kml></kml>'
let exportFeatures = []
this.source.forEachFeature(function (f) {
const clone = f.clone()
clone.set('type', clone.get('type').toLowerCase())
clone.setId(f.getId())
clone.getGeometry().setProperties(f.getGeometry().getProperties())
clone.getGeometry().transform('EPSG:3857', 'EPSG:4326')
let styles = clone.getStyleFunction() || this.layer.getStyleFunction()
styles = styles(clone)
const newStyle = {
fill: styles[0].getFill(),
stroke: styles[0].getStroke(),
text: styles[0].getText(),
image: styles[0].getImage(),
zIndex: styles[0].getZIndex(),
}
if (newStyle.image instanceof Circle) {
newStyle.image = null
}
// If only text is displayed we must specify an image style with scale=0
if (newStyle.text && !newStyle.image) {
newStyle.image = new Icon({
src: 'noimage',
scale: 0,
})
}
const myStyle = new Style(newStyle)
clone.setStyle(myStyle)
exportFeatures.push(clone)
})
if (exportFeatures.length > 0) {
if (exportFeatures.length === 1) {
// force the add of a <Document> node
exportFeatures.push(new Feature())
}
kmlString = this.kmlFormat.writeFeatures(exportFeatures)
// Remove no image hack
kmlString = kmlString.replace(/<Icon>\s*<href>noimage<\/href>\s*<\/Icon>/g, '')
// Remove empty placemark added to have <Document> tag
kmlString = kmlString.replace(/<Placemark\/>/g, '')
kmlString = kmlString.replace(/<Document>/, `<Document><name>${nameInKml}</name>`)
}
return kmlString
}
dispatchChangeEvent_() {
this.dispatchEvent(new ChangeEvent())
}
dispatchSelectEvent_(feature, modifying) {
this.dispatchEvent(new SelectEvent(feature, this.pointerCoordinate, modifying))
}
dispatchDrawEndEvent_() {
this.dispatchEvent(new DrawEndEvent())
}
onKeyUp_(event) {
if (this.activeInteraction && event.key == 'Delete') {
this.activeInteraction.removeLastPoint()
}
}
onAddFeature_(event, properties) {
const feature = event.feature
feature.setId(getUid(feature))
feature.setProperties(
Object.assign({ type: this.activeInteraction.get('type') }, properties)
)
this.updateDrawHelpTooltip(feature)
}
onDrawActiveChange_(event) {
this.select.setActive(!event.target.getActive())
}
onDrawStart_(event) {
event.feature.set('isDrawing', true)
if (event.target.get('type') === 'MEASURE') this.measureManager.addOverlays(event.feature)
}
onDrawEnd_(event) {
event.feature.unset('isDrawing')
event.feature.setStyle((feature) => featureStyle(feature))
this.source.once('addfeature', (event) => {
this.polygonToLineString(event.feature)
if (event.feature.get('type') === 'MEASURE')
this.measureManager.addOverlays(event.feature)
this.dispatchChangeEvent_(event.feature)
})
// deactivate drawing tool
event.target.setActive(false)
this.select.getFeatures().push(event.feature)
this.sketchPoints = 0
// remove the area tooltip.
this.measureManager.removeOverlays(event.feature)
this.dispatchDrawEndEvent_()
}
onModifyStart_(event) {
const features = event.features.getArray()
if (features.length) {
console.assert(features.length == 1)
const feature = features[0]
this.dispatchSelectEvent_(feature, true)
this.map.getTarget().classList.add('cursor-grabbing')
}
}
onModifyEnd_(event) {
if (event.features) {
const features = event.features.getArray()
if (features.length) {
console.assert(features.length == 1)
const feature = features[0]
this.dispatchSelectEvent_(feature, false)
this.dispatchChangeEvent_(feature)
this.map.getTarget().classList.remove('cursor-grabbing')
}
}
}
onSelectChange_(event) {
if (event.type === 'add') {
this.dispatchSelectEvent_(event.element, false)
} else if (event.type === 'remove') {
this.dispatchSelectEvent_(null, false)
}
}
onPointerMove_(event) {
this.tooltipOverlay.setPosition(event.coordinate)
if (this.select.get('active')) {
this.updateCursorAndTooltips(event)
}
}
// transform a Polygon to a LineString if the geometry was not closed by a click on the first point
polygonToLineString(feature) {
const geometry = feature.getGeometry()
if (geometry.getType() == 'Polygon' && !this.isFinishOnFirstPoint_) {
const coordinates = geometry.getLinearRing().getCoordinates()
coordinates.pop()
feature.setGeometry(new LineString(coordinates))
}
}
// Display an help tooltip when drawing
updateHelpTooltip(type, drawStarted, hasMinNbPoints, onFirstPoint, onLastPoint) {
if (!this.tooltipOverlay) {
return
}
type = typesInTranslation[type]
let helpMsgId = 'draw_start_'
if (drawStarted) {
if (type !== 'marker' && type !== 'annotation') {
helpMsgId = 'draw_next_'
}
if (onLastPoint) {
helpMsgId = 'draw_snap_last_point_'
}
if (onFirstPoint) {
helpMsgId = 'draw_snap_first_point_'
}
}
let msg = i18n.t(helpMsgId + type)
if (drawStarted && hasMinNbPoints) {
msg += '<br/>' + i18n.t('draw_delete_last_point')
}
this.tooltipOverlay.getElement().innerHTML = msg
}
// Display an help tooltip when drawing
updateDrawHelpTooltip(feature) {
const type = this.activeInteraction.get('type')
const geom = feature.getGeometry()
if (geom instanceof Polygon) {
// The sketched polygon is always closed, so we remove the last coordinate.
const lineCoords = geom.getCoordinates()[0].slice(0, -1)
if (this.sketchPoints !== lineCoords.length) {
// A point is added or removed
this.sketchPoints = lineCoords.length
} else if (lineCoords.length > 1) {
const firstPoint = lineCoords[0]
const lastPoint = lineCoords[lineCoords.length - 1]
const sketchPoint = lineCoords[lineCoords.length - 2]
// Checks is snapped to first point of geom
const isSnapOnFirstPoint =
lastPoint[0] === firstPoint[0] && lastPoint[1] === firstPoint[1]
// Checks is snapped to last point of geom
const isSnapOnLastPoint =
lastPoint[0] === sketchPoint[0] && lastPoint[1] === sketchPoint[1]
this.isFinishOnFirstPoint_ = !isSnapOnLastPoint && isSnapOnFirstPoint
this.updateHelpTooltip(
type,
true,
this.tools[type].minPoints_ < lineCoords.length,
this.isFinishOnFirstPoint_,
isSnapOnLastPoint
)
}
}
}
// Display an help tooltip when modifying
updateModifyHelpTooltip(type, onExistingVertex) {
if (!this.tooltipOverlay) {
return
}
type = typesInTranslation[type]
let helpMsgId = 'modify_new_vertex_'
if (onExistingVertex) {
helpMsgId = 'modify_existing_vertex_'
}
this.tooltipOverlay.getElement().innerHTML = i18n.t(helpMsgId + type)
}
// Display an help tooltip when selecting
updateSelectHelpTooltip(type) {
if (!this.tooltipOverlay) {
return
}
type = typesInTranslation[type]
let helpMsgId = 'select_no_feature'
if (type) {
helpMsgId = 'select_feature_' + type
}
this.tooltipOverlay.getElement().innerHTML = i18n.t(helpMsgId)
}
updateCursorAndTooltips(evt) {
const mapDiv = this.map.getTarget()
if (mapDiv.classList.contains(cssGrabbing)) {
mapDiv.classList.remove(cssGrab)
return
}
let hoverSelectableFeature = false
// todo find way to not use private
let hoverVertex = this.modify.snappedToVertex_
const hoverNewVertex = this.select.getFeatures().getLength() > 0
let selectableFeature
const selectFeatures = this.select.getFeatures()
this.map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
if (layer && !selectableFeature) {
selectableFeature = feature
hoverSelectableFeature = true
} else if (
selectFeatures.getLength() > 0 &&
selectFeatures.item(0).getId() === feature.getId() &&
selectableFeature
) {
selectableFeature = feature
}
})
if (!hoverSelectableFeature) {
// If the cursor is not hover a selectable feature.
mapDiv.classList.remove(cssPointer)
mapDiv.classList.remove(cssGrab)
this.updateSelectHelpTooltip()
} else if (hoverSelectableFeature && !hoverNewVertex && !hoverVertex) {
// If the cursor is hover a selectable feature.
mapDiv.classList.add(cssPointer)
mapDiv.classList.remove(cssGrab)
this.updateSelectHelpTooltip(selectableFeature.get('type'))
} else if (hoverNewVertex || hoverVertex) {
// If a feature is selected and if the cursor is hover a draggable
// vertex.
mapDiv.classList.remove(cssPointer)
mapDiv.classList.add(cssGrab)
this.updateModifyHelpTooltip(selectableFeature.get('type'), hoverVertex)
}
}
clearDrawing() {
this.source.clear()
this.deselect()
this.dispatchChangeEvent_()
}
async addKmlLayer(layer) {
const kml = await getKml(layer.kmlFileUrl)
const features = this.kmlFormat.readFeatures(kml, {
featureProjection: layer.projection,
})
features.forEach((f) => {
f.set('type', f.get('type').toUpperCase())
f.setStyle((feature) => featureStyle(feature))
if (f.get('type') === 'MEASURE') this.measureManager.addOverlays(f)
})
this.source.addFeatures(features)
}
} |
JavaScript | class DoublyLinkedList {
static createNode = (value, prev = null, next = null) => ({ value, prev, next })
constructor () { this.clear() }
get length () { return this.nodeSet.size }
clear () {
this.head = DoublyLinkedList.createNode(null)
this.tail = DoublyLinkedList.createNode(null)
this.head.next = this.tail
this.tail.prev = this.head
this.nodeSet = new Set()
}
insertAfter (node, prevNode) {
if (__DEV__ && this.nodeSet.has(node)) throw new Error('[DoublyLinkedList][insertAfter] already has node')
if (__DEV__ && prevNode !== this.head && !this.nodeSet.has(prevNode)) throw new Error('[DoublyLinkedList][insertAfter] invalid prevNode')
const { next } = prevNode
prevNode.next = next.prev = node
node.prev = prevNode
node.next = next
this.nodeSet.add(node)
}
insertBefore (node, nextNode) {
if (__DEV__ && this.nodeSet.has(node)) throw new Error('[DoublyLinkedList][insertBefore] already has node')
if (__DEV__ && nextNode !== this.tail && !this.nodeSet.has(nextNode)) throw new Error('[DoublyLinkedList][insertBefore] invalid nextNode')
const { prev } = nextNode
nextNode.prev = prev.next = node
node.prev = prev
node.next = nextNode
this.nodeSet.add(node)
}
remove (node) {
if (__DEV__ && !this.nodeSet.has(node)) throw new Error('[DoublyLinkedList][remove] invalid node')
const { prev, next } = node
prev.next = next
next.prev = prev
node.prev = node.next = null
this.nodeSet.delete(node)
}
removeBetween (fromNode, toNode) { // include both from & to node
if (__DEV__ && !this.nodeSet.has(fromNode)) throw new Error('[DoublyLinkedList][removeBetween] invalid fromNode')
if (__DEV__ && !this.nodeSet.has(toNode)) throw new Error('[DoublyLinkedList][removeBetween] invalid toNode')
const { prev } = fromNode
const { next } = toNode
prev.next = next
next.prev = prev
fromNode.prev = toNode.next = null
let node = fromNode
while (node) {
this.nodeSet.delete(node)
node = node.next
}
}
forEach (callback, thisArg = this) {
let node = this.head.next
let index = 0
while (node !== this.tail) {
callback(node, index)
callback.call(thisArg, node, index, this)
node = node.next
index++
}
}
forEachReverse (callback, thisArg = this) { // the index starts from length - 1
let node = this.tail.prev
let index = this.nodeSet.size - 1
while (node !== this.head) {
callback(node, index)
callback.call(thisArg, node, index, this)
node = node.prev
index--
}
}
reverse () {
let node = this.head.next
while (node !== this.tail) {
const { prev, next } = node
node.prev = next
node.next = prev
node = next
}
const { next } = this.head
const { prev } = this.tail
this.head.next = prev
this.tail.prev = next
prev.prev = this.head
next.next = this.tail
}
setFirst (node) {
if (__DEV__ && !this.nodeSet.has(node)) throw new Error('[DoublyLinkedList][setFirst] invalid node')
if (node === this.head.next) return
// pick
const { prev, next } = node
prev.next = next
next.prev = prev
// set
node.prev = this.head
node.next = this.head.next
this.head.next = node
}
setLast (node) {
if (__DEV__ && !this.nodeSet.has(node)) throw new Error('[DoublyLinkedList][setLast] invalid node')
if (node === this.tail.prev) return
// pick
const { prev, next } = node
prev.next = next
next.prev = prev
// set
node.prev = this.tail.prev
node.next = this.tail
this.tail.prev = node
}
push (node) { return this.insertBefore(node, this.tail) }
pop () { return this.remove(this.tail.prev) }
unshift (node) { return this.insertAfter(node, this.head) }
shift () { return this.remove(this.head.next) }
} |
JavaScript | class BaseContext {
/**
* Instantiates a new Context
* @param {StateContainer} state
* @param {string} type
*/
constructor(state, type) {
this.state = state;
this.type = type;
}
/**
* Base build method
* @return {Object}
*/
build() {
return {};
}
} |
JavaScript | class Bitmask {
/**
* Constructor
*/
constructor() {
this.keys = undefined;
this.values = undefined;
}
/**
* Set the keys (or labels) for
* each bit in the Bitmask
* @param {Array} keys an array of string keys
*/
setKeys(keys) {
this.keys = keys;
return this;
}
/**
* Set the bits in the Bitmask
* @param {*} values an array of boolean values
*/
setValues(values) {
this.values = values;
return this;
}
/**
* Appends a key-value pair to the Bitmask
*
* @param {String} key the string key
* @param {Boolean} value the boolean value
*/
addValue(key, value) {
if (!this.keys || this.keys === undefined) this.keys = [];
if (!this.values || this.values === undefined) this.values = [];
this.keys.push(key);
this.values.push(value);
return this;
}
/**
* Validates a Bitmask type, enforcing
* an equal number of keys and values, as well as types.
*
* @throws {Error} if the Bitmask is malformed
*/
validate() {
if (Array.isArray(this.keys) && Array.isArray(this.values)
&& this.keys.length > 0 && this.keys.length === this.values.length) {
const hasNonString = this.keys.some((e) => typeof e !== 'string');
if (hasNonString) throw new Error('Bitmask `keys` must be strings');
const hasNonBool = this.values.some((e) => typeof e !== 'boolean');
if (hasNonBool) throw new Error('Bitmask `values` must be booleans');
} else {
throw new Error('A Bitmask `value` object must contain `keys` and `values` lists of equal length');
}
}
} |
JavaScript | class Container extends Component {
/**
* constructor
* @param {object} props
*/
constructor(props) {
super(props);
/**
* @type {object}
* @property {string} fieldVal - searched IP
* @property {object} data - json result from API
* @property {string} address - API result, IP address
* @property {string} latitude - API result, latitude of the IP address
* @property {string} longitude - API result, longitude of the IP address
* @property {string} found - determined from API result by status code
* @property {string} hostname - API result, hostname of the IP address
* @property {string} continent - API result, continet of the IP address
* @property {string} region - API result, region of the IP address
* @property {string} city - API result, city of the IP address
* @property {string} postal - API result, postal code of the IP address
* @property {string} timeZone - API result, time zone of the IP address
* @property {string} asName - API result, autonomous system name
* @property {string} asNumber - API result, autonomous system number
* @property {string} asCountry - API result, autonomous system country
*/
this.state = {
fieldVal: "",
data: {},
address: "",
latitude: null,
longitude: null,
found: false,
hostname: "",
continent: "",
country: "",
region: "",
city: "",
postal: "",
timeZone: "",
asName: "",
asNumber: "",
asCountry: "",
};
this.ipSearch = this.ipSearch.bind(this);
}
/**
* handle submit form event
*/
componentDidMount() {
this.loadInitialData();
}
/**
* make an initial API call to populate the application with 'default' data
*/
loadInitialData(){
const badIpUrl = "https://api.apility.net/badip/8.8.8.8?token=" + process.env.REACT_APP_APILITY_KEY;
superagent
.get(badIpUrl)
.query(null)
.set('Accept', 'text/json')
.end((error, response) => {
if(response.ok){
this.setState({
found: true
})
}
else
{
this.setState({
found: false
})
}
})
const geoIpUrl = "https://api.apility.net/geoip/8.8.8.8?token=" + process.env.REACT_APP_APILITY_KEY;
superagent
.get(geoIpUrl)
.query(null)
.set('Accept', 'text/json')
.end((error, response) => {
const data = response.body.ip
this.setState({
data: data,
address: data.address,
latitude: parseFloat(data.latitude),
longitude: parseFloat(data.longitude),
hostname: data.hostname,
continent: data.continent,
country: data.country,
region: data.region,
city: data.city,
postal: data.postal,
timeZone: data.time_zone,
asNumber: data.as.asn,
asName: data.as.name,
asCountry: data.as.country
})
})
}
/**
* handle the submitted IP Address to search
* @param {object} val
*/
ipSearch(val){
/**
* Use external helper method to fetch a response from the API
*/
FetchBadIp(val)
.then( (res) => {
/**
* If the response of the API call is OK/200 then the IP address is blacklisted
*/
if(res.ok){
this.setState({
found: true
})
}
else
{
this.setState({
found: false
})
}
})
/**
* Use external helper method to fetch a json result from the API
*/
FetchGeoIp(val)
.then( (data) => {
const searchData = data.ip;
/**
* Update the state so child components inherit the new data
*/
this.setState({
ipData: searchData,
address: searchData.address,
latitude: parseFloat(searchData.latitude),
longitude: parseFloat(searchData.longitude),
hostname: searchData.hostname,
continent: searchData.continent,
country: searchData.country,
region: searchData.region,
city: searchData.city,
postal: searchData.postal,
timeZone: searchData.time_zone,
asNumber: searchData.as.asn,
asName: searchData.as.name,
asCountry: searchData.as.country
})
})
}
/**
* render
* @return {ReactElement} markup
*/
render (){
const center = {
lat: this.state.latitude,
lng: this.state.longitude
}
return (
<div>
<SearchInput onSubmission={this.ipSearch} />
<div style={{width: '100%', height: '30vh', background: 'grey'}}>
<GoogleMapsContainer center={center} zoom={10} />
</div>
<DataWrapper
found={this.state.found}
address={this.state.address}
hostname={this.state.hostname}
continenet={this.state.continent}
country={this.state.country}
region={this.state.region}
city={this.state.city}
postal={this.state.postal}
longitude={this.state.longitude}
latitude={this.state.latitude}
timeZone={this.state.timeZone}
asNumber={this.state.asNumber}
asName={this.state.asName}
asCountry={this.state.asCountry}
/>
</div>
)
}
} |
JavaScript | class ReplacePlaceholderForFile {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.done.tap('ReplacePlaceholderForFile', (stats) => {
const filepath = this.options.filepath;
// When the Node module is running, this plugin may be executed
// at the same time, which will result in incomplete content reading.
/*
@Other method:
try {
var data = fs.readFileSync('file.html', 'utf8');
console.log(data);
} catch(e) {
console.log('Error:', e.stack);
}
*/
fs.readFile(filepath, 'utf8', function (err, data) {
if (err) {
console.log(colors.fg.Red, err, colors.Reset);
} else {
if (data.length > 0 && data.indexOf('</html>') >= 0) {
data = tmplFormat(data);
fs.writeFile(filepath, data, (err) => {
if (err) {
console.log(colors.fg.Red, err, colors.Reset);
return;
}
//file written successfully
console.log(colors.bg.Green, colors.fg.White, `${filepath} written successfully!`, colors.Reset);
});
}
}
}); //end fs.readFile
});
}
} |
JavaScript | class BinarySearchTree {
constructor() {
this.rootNode = new Node(null);
}
root() {
return this.rootNode.data === null ? null : this.rootNode;
}
add(data) {
let node = this.rootNode
while (true) {
if (node.data === null) {
node.data = data;
return;
}
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data);
return
}
node = node.left
continue;
}
if (data > node.data) {
if (node.right === null) {
node.right = new Node(data);
return;
}
node = node.right
}
}
}
has(data) {
return this.findWithPrev(data)[0] !== null;
}
findWithPrev(data) {
let node = this.rootNode;
let prevNode = null;
while (node !== null) {
if (data === node.data) return [node, prevNode];
prevNode = node;
node = data > node.data ? node.right : node.left;
}
return [null, prevNode];
}
find(data) {
return this.findWithPrev(data)[0];
}
reassign(prevNode, node, data) {
if (data > prevNode.data) {
prevNode.right = node;
} else {
prevNode.left = node;
}
}
remove(data) {
const [node, prevNode] = this.findWithPrev(data);
if (node === null) return;
if (node.left === null && node.rigth === null) {
this.reassign(prevNode, null, node.data);
return;
}
if (node.left === null || node.right === null) {
this.reassign(prevNode, node.left === null ? node.right : node.left, node.data);
return;
}
let theMostRightLeft = node.left;
while (theMostRightLeft.right !== null) {
theMostRightLeft = theMostRightLeft.right;
}
node.data = theMostRightLeft.data;
theMostRightLeft.data = 'toDelete' + theMostRightLeft.data;
this.remove(theMostRightLeft.data);
}
min() {
let node = this.rootNode;
while (node.left !== null) {
node = node.left
}
return node.data;
}
max() {
let node = this.rootNode;
while (node.right !== null) {
node = node.right
}
return node.data;
}
} |
JavaScript | class Login extends Component {
static propTypes = {
auth: PropTypes.object,
history: PropTypes.object,
login: PropTypes.func,
dispatch: PropTypes.func
};
static defaultProps = {
isAuthenticated: false,
errorMessage: ''
};
/**
* Default constructor.
* @param props
*/
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
}
/**
* Handle change on field form.
* @param event
*/
handleChange(event) {
const state = {...this.state};
state[event.target.name] = event.target.value;
this.setState(state);
}
/**
* Handle change on submit form.
* @param e
*/
onSubmit(e) {
e.preventDefault();
this.props.login(this.state.email, this.state.password);
}
displayMessage() {
if (!this.props.auth.message) {
return '';
}
return (
<div className={`alert alert-${this.props.auth.isError ? 'danger' : 'success'}`} role="alert">
{this.props.auth.message}
</div>
);
}
/**
* Render
* @returns {XML}
*/
render() {
return (
<Grid fluid>
<Row className={`${styles['justify-content-center']} ${styles.row}`}>
<Col lg={4} md={8}>
<div className={`${styles['login-content']} ${styles.card}`}>
<div className={`${styles['login-form']}`}>
<Helmet title={`Sign In - ${config.app.title}`}/>
<h4>Login</h4>
<Form horizontal onSubmit={this.onSubmit.bind(this)}>
<FormGroup>
<Col sm={12}>
<ControlLabel>Email address</ControlLabel>
<FormControl
type="email"
name="email"
placeholder="Email"
value={this.state.email || ''}
onChange={this.handleChange.bind(this)}
/>
</Col>
</FormGroup>
<FormGroup>
<Col sm={12}>
<ControlLabel>Password</ControlLabel>
<FormControl
type="password"
name="password"
placeholder="Password"
value={this.state.password || ''}
onChange={this.handleChange.bind(this)}
/>
</Col>
</FormGroup>
{this.displayMessage()}
<button type="submit" className="btn btn-primary">Sign In</button>
</Form>
</div>
</div>
</Col>
</Row>
</Grid>
);
}
} |
JavaScript | class Selector {
/**
* Constructor
*
* @param {Array} tokens array of token objects
*/
constructor(tokens) {
this.setTokens(tokens);
}
/**
* Set tokens and calculate specificity.
*
* @param {Array} tokens array of token objects
*/
setTokens(tokens) {
if (!Array.isArray(tokens) || !tokens.length) {
throw new TypeError('Expecting a proper parsed array of tokens.');
}
Object.assign(this, {tokens, specificity: Selector.tallySpecificity(tokens)});
delete this.selectorString;
}
/**
* Calculate the specificity of a selector based on its tokens.
* Creates and/or modifies a specificity object.
*
* @param {Array} tokens array of tokens
* @param {Object} specificity specificity object with properties a,b,c,d
* @return {Object} specificity object
* @see: https://www.w3.org/TR/2009/CR-CSS2-20090908/cascade.html#specificity
*/
static tallySpecificity(tokens, specificity = {a: 0, b: 0, c: 0, d: 0}) {
// calculate the specificity
for (var i = 0; i < tokens.length; i++) {
if (tokens[i].specificityType && typeof specificity[tokens[i].specificityType] === 'number') {
specificity[tokens[i].specificityType]++;
} else if (Array.isArray(tokens[i].tokens)) {
this.tallySpecificity(tokens[i].tokens, specificity);
}
}
return specificity;
}
/**
* Turn an array of tokens into a string representation.
* @param {Array} tokens array of token objects
* @return {String} selector string
*/
static tokensToString(tokens) {
return tokens.map((token) => {
switch (token.type) {
case 'adjacentSiblingCombinator':
return ' + ';
case 'childCombinator':
return ' > ';
case 'generalSiblingCombinator':
return ' ~ ';
case 'descendantCombinator':
return ' ';
case 'universalSelector':
case 'typeSelector':
return namespaceString(token) + (token.type === 'universalSelector' ? '*' : CSS.escape(token.name));
case 'idSelector':
case 'classSelector':
return (token.type === 'idSelector' ? '#' : '.') + CSS.escape(token.name);
case 'attributePresenceSelector':
return '[' + namespaceString(token) + CSS.escape(token.name) + ']';
case 'attributeValueSelector':
return '[' + namespaceString(token) + CSS.escape(token.name) + token.operator + CSS.escapeString(token.value) + ']';
case 'pseudoElementSelector':
// no escape necessary since only identities are allowed
return '::' + token.name;
case 'pseudoClassSelector':
var expression = '';
if (token.expression) {
switch (token.expression.type) {
case 'identity':
expression = CSS.escape(token.expression.parsed);
break;
case 'string':
expression = CSS.escapeString(token.expression.parsed);
break;
case 'nthKeyword':
expression = token.expression.parsed;
break;
case 'nthFormula':
if (token.expression.parsed.a) {
if (Math.abs(token.expression.parsed.a) === 1) {
// omit the number
expression = token.expression.parsed.a < 0 ? '-n' : 'n';
} else {
expression = token.expression.parsed.a + 'n';
}
}
// if there is a b component, or there was no a component
if (token.expression.parsed.b || !expression) {
// add an explicit plus sign if there was an a component and b is positive
if (token.expression.parsed.b > 0 && expression) {
expression += '+';
}
expression += token.expression.parsed.b;
}
break;
}
expression = expression && ('(' + expression + ')');
}
return ':' + token.name + expression;
case 'negationSelector':
return ':not(' + this.tokensToString(token.tokens) + ')';
}
}).join('');
}
/**
* Reconstruct the selector tokens into a complete and valid selector.
* @return {String} selector string
*/
toString() {
// cache the selector string
if (!this.selectorString) {
this.selectorString = Selector.tokensToString(this.tokens);
}
return this.selectorString;
}
} |
JavaScript | class FlightChoicePrediction {
constructor(client) {
this.client = client;
}
/**
* Returns a list of flight offers with the probability to be chosen.
*
* @param {Object} params
* @return {Promise.<Response,ResponseError>} a Promise
*
* Returns flights from NYC to MAD with the probability to be chosen.
*
* ```js
* amadeus.shopping.flightOffersSearch.get({
* originLocationCode: 'SYD',
* destinationLocationCode: 'BKK',
* departureDate: '2020-08-01',
* adults: '2'
* }).then(function(response){
* return amadeus.shopping.flightOffers.prediction.post(
* JSON.stringify(response)
* );
* }).then(function(response){
* console.log(response.data);
* }).catch(function(responseError){
* console.log(responseError);
* });
* ```
*/
post(params = {}) {
return this.client.post('/v2/shopping/flight-offers/prediction', params);
}
} |
JavaScript | class Damper {
constructor(decayMilliseconds = DECAY_MILLISECONDS) {
this.velocity = 0;
this.naturalFrequency = 0;
this.setDecayTime(decayMilliseconds);
}
setDecayTime(decayMilliseconds) {
this.naturalFrequency =
1 / Math.max(MIN_DECAY_MILLISECONDS, decayMilliseconds);
}
update(x, xGoal, timeStepMilliseconds, xNormalization) {
const nilSpeed = 0.0002 * this.naturalFrequency;
if (x == null || xNormalization === 0) {
return xGoal;
}
if (x === xGoal && this.velocity === 0) {
return xGoal;
}
if (timeStepMilliseconds < 0) {
return x;
}
// Exact solution to a critically damped second-order system, where:
// acceleration = this.naturalFrequency * this.naturalFrequency * (xGoal
// - x) - 2 * this.naturalFrequency * this.velocity;
const deltaX = (x - xGoal);
const intermediateVelocity = this.velocity + this.naturalFrequency * deltaX;
const intermediateX = deltaX + timeStepMilliseconds * intermediateVelocity;
const decay = Math.exp(-this.naturalFrequency * timeStepMilliseconds);
const newVelocity = (intermediateVelocity - this.naturalFrequency * intermediateX) * decay;
const acceleration = -this.naturalFrequency * (newVelocity + intermediateVelocity * decay);
if (Math.abs(newVelocity) < nilSpeed * Math.abs(xNormalization) &&
acceleration * deltaX >= 0) {
// This ensures the controls settle and stop calling this function instead
// of asymptotically approaching their goal.
this.velocity = 0;
return xGoal;
}
else {
this.velocity = newVelocity;
return xGoal + intermediateX * decay;
}
}
} |
JavaScript | class PredictionResourceFormat extends models['ProxyResource'] {
/**
* Create a PredictionResourceFormat.
* @member {object} [description] Description of the prediction.
* @member {object} [displayName] Display name of the prediction.
* @member {array} [involvedInteractionTypes] Interaction types involved in
* the prediction.
* @member {array} [involvedKpiTypes] KPI types involved in the prediction.
* @member {array} [involvedRelationships] Relationships involved in the
* prediction.
* @member {string} negativeOutcomeExpression Negative outcome expression.
* @member {string} positiveOutcomeExpression Positive outcome expression.
* @member {string} primaryProfileType Primary profile type.
* @member {string} [provisioningState] Provisioning state. Possible values
* include: 'Provisioning', 'Succeeded', 'Expiring', 'Deleting',
* 'HumanIntervention', 'Failed'
* @member {string} [predictionName] Name of the prediction.
* @member {string} scopeExpression Scope expression.
* @member {string} [tenantId] The hub name.
* @member {boolean} autoAnalyze Whether do auto analyze.
* @member {object} mappings Definition of the link mapping of prediction.
* @member {string} [mappings.score] The score of the link mapping.
* @member {string} [mappings.grade] The grade of the link mapping.
* @member {string} [mappings.reason] The reason of the link mapping.
* @member {string} scoreLabel Score label.
* @member {array} [grades] The prediction grades.
* @member {object} [systemGeneratedEntities] System generated entities.
* @member {array} [systemGeneratedEntities.generatedInteractionTypes]
* Generated interaction types.
* @member {array} [systemGeneratedEntities.generatedLinks] Generated links.
* @member {object} [systemGeneratedEntities.generatedKpis] Generated KPIs.
*/
constructor() {
super();
}
/**
* Defines the metadata of PredictionResourceFormat
*
* @returns {object} metadata of PredictionResourceFormat
*
*/
mapper() {
return {
required: false,
serializedName: 'PredictionResourceFormat',
type: {
name: 'Composite',
className: 'PredictionResourceFormat',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
displayName: {
required: false,
serializedName: 'properties.displayName',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
involvedInteractionTypes: {
required: false,
serializedName: 'properties.involvedInteractionTypes',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
involvedKpiTypes: {
required: false,
serializedName: 'properties.involvedKpiTypes',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
involvedRelationships: {
required: false,
serializedName: 'properties.involvedRelationships',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
negativeOutcomeExpression: {
required: true,
serializedName: 'properties.negativeOutcomeExpression',
type: {
name: 'String'
}
},
positiveOutcomeExpression: {
required: true,
serializedName: 'properties.positiveOutcomeExpression',
type: {
name: 'String'
}
},
primaryProfileType: {
required: true,
serializedName: 'properties.primaryProfileType',
type: {
name: 'String'
}
},
provisioningState: {
required: false,
readOnly: true,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
predictionName: {
required: false,
serializedName: 'properties.predictionName',
type: {
name: 'String'
}
},
scopeExpression: {
required: true,
serializedName: 'properties.scopeExpression',
type: {
name: 'String'
}
},
tenantId: {
required: false,
readOnly: true,
serializedName: 'properties.tenantId',
type: {
name: 'String'
}
},
autoAnalyze: {
required: true,
serializedName: 'properties.autoAnalyze',
type: {
name: 'Boolean'
}
},
mappings: {
required: true,
serializedName: 'properties.mappings',
type: {
name: 'Composite',
className: 'PredictionMappings'
}
},
scoreLabel: {
required: true,
serializedName: 'properties.scoreLabel',
type: {
name: 'String'
}
},
grades: {
required: false,
serializedName: 'properties.grades',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'PredictionGradesItemElementType',
type: {
name: 'Composite',
className: 'PredictionGradesItem'
}
}
}
},
systemGeneratedEntities: {
required: false,
readOnly: true,
serializedName: 'properties.systemGeneratedEntities',
type: {
name: 'Composite',
className: 'PredictionSystemGeneratedEntities'
}
}
}
}
};
}
} |
JavaScript | class ReactWebApp extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<Grid className="react-web" style={divPadding}>
{this.props.children}
</Grid>
);
}
} |
JavaScript | class form extends div {
constructor(elem, gap = 2, col = 1) {
super({
padding: 0,
class: "container",
elem: new div({
gap: gap,
row: true,
rowcol: col,
elem: Array.isArray(elem)
? elem.map(function (i) {
return new div({ col: true, elem: i });
})
: new div({ col: true, elem: elem }),
}),
});
}
} |
JavaScript | class Race {
constructor({ id = 0 } = {}) {
this.id_ = id;
this.name_ = 'Unknown race';
this.timeLimit_ = 0;
this.laps_ = 1;
this.challengeDesk_ = null;
this.weather_ = 7;
this.time_ = [12, 0];
this.interior_ = 0;
this.spawnPositions_ = [];
this.checkpoints_ = [];
this.objects_ = [];
this.objectModels_ = new Set();
// Settings.
this.disableVehicleDamage_ = false;
this.allowLeaveVehicle_ = false;
this.unlimitedNos_ = false;
// To be dynamically loaded by the race manager.
this.bestRace_ = null;
}
// Gets or sets the id of this race. It must be a non-zero integer.
get id() { return this.id_; }
set id(value) {
this.id_ = value;
}
// Gets or changes the name of this race. It must be an non-zero-length string.
get name() { return this.name_; }
set name(value) {
this.name_ = value;
}
// Gets or sets the time limit for this game. A limit of zero implies that there is no limit.
get timeLimit() { return this.timeLimit_; }
set timeLimit(value) {
this.timeLimit_ = value;
}
// Gets or sets the number of laps for this race. It must be an integer larger than zero.
get laps() { return this.laps_; }
set laps(value) {
this.laps_ = value;
}
// Gets or sets the challenge desk location, which gives players the ability to perform the race
// by themselves, for a small fee, by talking to an actor at the given location. This is an object
// having an actorModel, position vector and rotation.
get challengeDesk() { return this.challengeDesk_; }
set challengeDesk(value) {
this.challengeDesk_ = value;
}
// Gets or sets the weather type for this race. It must be an interger.
get weather() { return this.weather_; }
set weather(value) {
this.weather_ = value;
}
// Gets or sets the time at which this race will take place. Must be an array with two entries,
// one for the hour (24-hour based) and one for the minute.
get time() { return this.time_; }
set time(value) {
this.time_ = value;
}
// Gets or sets the interior in which this race will take place.
get interior() { return this.interior_; }
set interior(value) {
this.interior_ = value;
}
// Returns the maximum number of players that can participate in this race.
get maxPlayers() { return this.spawnPositions_.length; }
// Returns the spawn positions available for this race.
get spawnPositions() { return this.spawnPositions_; }
// Registers a new spawn position for this race. There is no limit to the amount of spawn
// positions that may be associated with a single race.
addSpawnPosition(position, rotation, vehicle) {
this.spawnPositions_.push({ position, rotation, vehicle });
}
// Returns the checkpoints available for this race.
get checkpoints() { return this.checkpoints_; }
// Registers a new |checkpoint| for the race. There is no limit to the amount of checkpoints added
// to a given race. Each checkpoint must be an instance of the RaceCheckpoint class.
addCheckpoint(checkpoint) {
this.checkpoints_.push(checkpoint);
}
// Returns the objects that should be created for this race.
get objects() { return this.objects_; }
// Returns the number of unique object models that are required for the race.
get objectModelCount() { return this.objectModels_.size; }
// Registers a new object that's part of this race. The |model| must be the GTA model id used to
// describe the object, whereas |position| and |rotation| must be 3D vectors.
addObject(model, position, rotation) {
this.objects_.push({ model, position, rotation });
this.objectModels_.add(model);
}
// Gets or sets whether vehicle damage should be disabled for this race.
get disableVehicleDamage() { return this.disableVehicleDamage_; }
set disableVehicleDamage(value) {
this.disableVehicleDamage_ = value;
}
// Gets or sets whether players are allowed to leave their vehicles. This could be either by
// accident, for example falling off a motorcycle, or deliberately.
get allowLeaveVehicle() { return this.allowLeaveVehicle_; }
set allowLeaveVehicle(value) {
this.allowLeaveVehicle_ = value;
}
// Gets or sets whether players should get unlimited NOS during the race. This will trigger their
// NOS to be replaced with a new component every so often, skipping waiting times.
get unlimitedNos() { return this.unlimitedNos_; }
set unlimitedNos(value) {
this.unlimitedNos_ = value;
}
// Gets or sets the best race raced for this race. It must be an object having two properties,
// `time` for the time in seconds, and `name` for the name of the player who performed it.
get bestRace() { return this.bestRace_; }
set bestRace(value) {
this.bestRace_ = value;
}
} |
JavaScript | class ServerManager {
constructor() {
this._initClientOperationProcessorMap();
}
/**
* Invoca azione di un controller
* @param url Modulo/Controller/Azione/Parametri
*/
invokeActionController(url) {
let $this = this;
$.ajax({
type: "POST",
url: url,
success: function(data) {
$this._handleActionControllerResponse(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.status);
}
});
}
/**
* Inizializza mappa delle classi per elaborazione operazioni client
*/
_initClientOperationProcessorMap() {
this.clientOperationProcessorMap = new Map();
this.clientOperationProcessorMap.set('change_view', new ChangeViewClientOperationProcessor());
this.clientOperationProcessorMap.set('console_log', new ConsoleLogClientOperationProcessor());
this.clientOperationProcessorMap.set('create_dialog_with_content', new CreateDialogWithContentClientOperationProcessor());
this.clientOperationProcessorMap.set('close_dialog', new CloseDialogClientOperationProcessor());
this.clientOperationProcessorMap.set('reload_datatable', new ReloadDatatableClientOperationProcessor());
this.clientOperationProcessorMap.set('set_div_content', new SetDivContentClientOperationProcessor());
}
/**
* Gestione risposta azione controller
* @param data Stringa in formato json della risposta
*/
_handleActionControllerResponse(data) {
let $this = this;
let jsonData = JSON.parse(data);
if (!jsonData) {
return;
}
// Elabora tutte le operazioni client
jsonData.client_operations.forEach(function(operation) {
if ($this.clientOperationProcessorMap.has(operation.type)) {
$this.clientOperationProcessorMap.get(operation.type).process(operation);
} else {
console.error('Undefined operation: ' + operation.type);
}
});
}
} |
JavaScript | class ResultController {
/**
* @function takeTest
* @memberof QuestionController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static takeTest(req, res) {
const { userId } = req;
const { answers } = req.body;
const courseId = parseInt(req.params.id, 10);
let testScore = 0;
let scoreSheet = 0;
const testReady = process.env.TEST_AVAILABLE;
const activeUser = process.env.USER_ACTIVE;
db.task('check course', data => data.course.findById(courseId)
.then((courseFound) => {
if (!courseFound || courseFound.course_availability != testReady) {
return res.status(403).json({
success: 'false',
message: 'This test is not open yet',
});
}
return db.task('fetch user', data => data.users.findById(userId)
.then((user) => {
if (user.user_status != activeUser) {
return res.status(401).json({
success: 'false',
message: 'This account needs to be approved to take a test',
});
}
const serachValues = {
userId, courseId,
};
return db.task('check result', data => data.results.find(serachValues)
.then((resultFound) => {
if (resultFound) {
return res.status(400).json({
success: 'false',
message: 'You seem to have taken this test before',
});
}
return db.task('post default result', data => data.results.create({ userId, courseId, testScore })
.then((result) => {
const resultId = result.id;
for (let value of answers) {
const choiceChosen = value.choice.toLowerCase().toString().replace(/\s+/g, '');
const questionId = value.questionId;
db.task('find question', data => data.question.findById(questionId)
.then((questionFound) => {
if (!questionFound) {
testScore += 0;
}
const correctAnswer = questionFound[0].correct_answer.toLowerCase().toString().replace(/\s+/g, '');
const search = tcom.search(correctAnswer);
const synonyms = search.synonyms;
if (choiceChosen === correctAnswer) {
testScore += 1;
}
for (let synonym of synonyms) {
if (choiceChosen === synonym) {
testScore += 1;
}
testScore += 0;
}
scoreSheet = testScore - 1;
const updateResult = {
userId, courseId, scoreSheet,
};
db.task('update result', data => data.results.modify(updateResult, resultId)
.then(() => {
var last = answers[answers.length - 1]
if (value === last) {
return res.status(201).json({
success: 'true',
testScore: `You scored ${scoreSheet} point(s)`,
});
}
}))
})
)
}
}))
}))
}))
})
.catch((err) => {
return res.status(500).json({
success: 'false',
message: 'so sorry, try again later',
err: err.message,
});
}))
}
} |
JavaScript | class TerminalBox {
constructor(config) {
this.box = NeoBlessed.box(config);
}
} |
JavaScript | class TerminalItemBox extends TerminalBox {
constructor({ config, childConfig, bgBlur, bgFocus }) {
super(config);
this._childConfig = childConfig;
this._bgBlur = bgBlur;
this._bgFocus = bgFocus;
this._focusIndexer = new _FocusIndexer({
getIndexLimit: this._getNavigationLimit.bind(this)
});
}
_getHeight() {
// neo-blessed box has two invisible items prepended, so we need '-2'
return this.box.height - 2;
}
_getNavigationLimit() {
return Math.min(this.box.children.length - 1, this._getHeight());
}
_setActiveChildColor(color) {
const activeChild = this.box.children[this._focusIndexer.get()];
if (activeChild) {
activeChild.style.bg = color;
}
}
focus() {
this._setActiveChildColor(this._bgFocus);
this.box.focus();
}
blur() {
this._setActiveChildColor(this._bgBlur);
}
scroll(scrollKey) {
if (this.box.children.length === 1) {
return;
}
const unfocusedIndex = this._focusIndexer.get();
const unfocusedChild = this.box.children[unfocusedIndex];
unfocusedChild.style.bg = this._bgBlur;
if (scrollKey === keys.SCROLL_UP) {
this._focusIndexer.decr();
}
else if (scrollKey === keys.SCROLL_DOWN) {
this._focusIndexer.incr();
}
const focusedIndex = this._focusIndexer.get();
const focusedChild = this.box.children[focusedIndex];
focusedChild.style.bg = this._bgFocus;
}
_createBoxChild() {
throw new Error('_createBoxChild() method not implemented');
}
createBoxChildAndAppend(content) {
const boxChild = this._createBoxChild(content);
this.box.append(boxChild);
}
} |
JavaScript | class CrawlService extends _Service.default {
/**
* Start the crawl service to extract the domain urls.
*/
start() {
let urlsRepository = new _JsonUrlsRepository.default(this.getPathJsonUrlsFile());
let csvUrlsRepository = new _CsvUrlsRepository.default(this.getPathCsvUrlsFile());
let htmlRepository = new _HtmlRepository.default(this.getProjectPath());
let headersRepository = new _HeadersRepository.default(this.getProjectPath());
let crawlerRepository = new _CrawlerRepository.default(this.args, this.option, this.getProjectPath());
let crawlStatesRepository = new _SqliteCrawlStatesRepository.default(this.getProjectPath());
crawlerRepository.crawlStatesRepository = crawlStatesRepository;
const initUrl = this.args.getSingleUrl();
if (this.args.isSingle() && initUrl != null) {
crawlStatesRepository.initUrlsPool([initUrl]);
}
crawlerRepository.findAllUrls(progress => {
this.emitProgress(progress);
if (this.args.html && progress.url != null && progress.html != null) {
htmlRepository.save(progress.url, progress.html).then();
}
if (this.args.headers && progress.url != null && progress.headers != null) {
headersRepository.save(progress.url, progress.headers).then();
}
}).then(urls => {
urlsRepository.save(urls).then(() => this.emitComplete());
csvUrlsRepository.save(urls).then(() => this.emitComplete());
});
}
} |
JavaScript | class HttpController {
async get(baseURL, endpoint, params, headers) {
const url = endpoint ? baseURL.concat(endpoint) : baseURL;
const options = { params, headers };
return axios.get(url, options);
}
async post(baseURL, params, body, headers, asFormEncoded) {
const url = baseURL;
const options = {
params,
headers,
};
if (asFormEncoded && body) {
const bodyParams = new URLSearchParams();
for (const b of Object.keys(body)) {
bodyParams.append(b, body[b]);
}
body = bodyParams;
}
return axios.post(url, body, options);
}
async put(
baseURL,
// object!
data,
params,
headers,
) {
const url = baseURL;
const options = {
params,
headers,
};
return axios.put(url, data, options);
}
} |
JavaScript | class ActionList extends PureComponent {
static defaultProps = {
stretch: 'both',
};
render() {
const {children, stretch} = this.props;
const stretchAlign = stretch === 'both' || stretch === 'align';
const stretchFlex = stretch === 'both' || stretch === 'flex';
return (
<View
style={[
styles.root,
stretchAlign && styles.stretchAlign,
stretchFlex && styles.stretchFlex
]}>
{children}
</View>
);
}
} |
JavaScript | class IrcUser extends EventEmitter {
/**
* Constructs a new IrcUser for a given {@link IrcClient}.
*
* @access protected
* @hideconstructor
* @param {IrcClient} client The IrcClient instance.
*/
constructor (client) {
super()
this._client = client
this._isOnline = false
this._nickName = null
this._userName = null
this._realName = null
this._idleDuration = null
this._isOperator = false
this._serverName = null
this._serverInfo = null
this._isAway = false
this._awayMessage = null
this._hopCount = 0
}
/**
* Gets the client on which the user exists.
*
* @public
*/
get client () {
return this._client
}
/**
* Gets wheather the user is a local user.
*
* @public
* @return {boolean} True if the user is local; otherwise false.
*/
get isLocalUser () {
return false
}
/*
* Gets the name of the source, as understood by the IRC protocol.
*/
get name () {
return this.nickName
}
/**
* Gets whether the user is currently connected to the IRC network.
* This value may not be always be up-to-date.
*
* @public
*/
get isOnline () {
return this._isOnline
}
/**
* Sets whether the user is currently connected to the IRC network.
*
* @fires IrcUser#isOnline
*/
set isOnline (value) {
this._isOnline = value
this.emit('isOnline')
}
/**
* Gets the current nick name of the user.
*
* @public
*/
get nickName () {
return this._nickName
}
/**
* Sets the current nick name of the user
*
* @fires IrcUser#nickName
*/
set nickName (value) {
this._nickName = value
/**
* @event IrcUser#nickName
*/
this.emit('nickName')
}
/**
* Gets the current user name of the user. This value never changes until the user reconnects.
*
* @public
*/
get userName () {
return this._userName
}
/**
* Sets the current user name of the user
*
* @fires IrcUser#userName
*/
set userName (value) {
this._userName = value
/**
* @event IrcUser#userName
*/
this.emit('userName')
}
/**
* Gets the host name of the user.
*
* @public
*/
get realName () {
return this._realName
}
/**
* Sets the host name of the user
*
* @fires IrcUser#realName
*/
set realName (value) {
this._realName = value
/**
* @event IrcUser#realName
*/
this.emit('realName')
}
/**
* Gets the duration for which the user has been idle. This is set when a Who Is response is received.
*
* @public
*/
get idleDuration () {
return this._idleDuration
}
/**
* Sets the duration for which the user has been idle.
*
* @fires IrcUser#idleDuration
*/
set idleDuration (value) {
this._idleDuration = value
/**
* @event IrcUser#idleDuration
*/
this.emit('idleDuration')
}
/**
* Gets whether the user is a server operator.
*
* @public
*/
get isOperator () {
return this._isOperator
}
/**
* Sets whether the user is a server operator.
*
* @fires IrcUser#isOperator
*/
set isOperator (value) {
this._isOperator = value
/**
* @event IrcUser#isOperator
*/
this.emit('isOperator')
}
/**
* Gets the name of the server to which the user is connected.
*
* @public
*/
get serverName () {
return this._serverName
}
/**
* Sets the name of the server to which the user is connected.
*
* @fires IrcUser#serverName
*/
set serverName (value) {
this._serverName = value
/**
* @event IrcUser#serverName
*/
this.emit('serverName')
}
/**
* Gets arbitrary information about the server to which the user is connected.
*
* @public
*/
get serverInfo () {
return this._serverInfo
}
/**
* Sets the information about the server to which the user is connected.
*
* @fires IrcUser#serverInfo
*/
set serverInfo (value) {
this._serverInfo = value
/**
* @event IrcUser#serverInfo
*/
this.emit('serverInfo')
}
/**
* Gets whether the user has been been seen as away. This value is always up-to-date for the local user;
* though it is only updated for remote users when a private message is sent to them or a Who Is response
* is received for the user.
*
* @public
*/
get isAway () {
return this._isAway
}
/**
* Sets wheather the user should be seen as away.
*
* @fires IrcUser#isAway
*/
set isAway (value) {
this._isAway = value
/**
* @event IrcUser#isAway
*/
this.emit('isAway')
}
/**
* Gets the current away message received when the user was seen as away.
*
* @public
*/
get awayMessage () {
return this._awayMessage
}
/**
* Sets the users away message.
*
* @fires IrcUser#awayMessage
*/
set awayMessage (value) {
this._awayMessage = value
/**
* @event IrcUser#awayMessage
*/
this.emit('awayMessage')
}
/**
* Gets the hop count of the user, which is the number of servers between the user and the server on which the
* client is connected, within the network.
*
* @public
*/
get hopCount () {
return this._hopCount
}
/**
* Sets the hop count of the user.
*
* @fires IrcUser#hopCount
*/
set hopCount (value) {
this._hopCount = value
/**
* @event IrcUser#hopCount
*/
this.emit('hopCount')
}
/**
* Sends a Who Is query to server for the user.
*
* @public
*/
whoIs () {
this.client.queryWhoIs(this._nickName)
}
/**
* Sends a Who Was query to server for the user.
*
* @public
* @param {Int} [entriesCount] The maximum number of entries that the server should return. Specify -1 for unlimited.
*/
whoWas (entriesCount = -1) {
this.client.queryWhoWas([this._nickName], entriesCount)
}
/**
* Gets a array of all channel users that correspond to the user.
* Each IrcChannelUser represents a channel of which the user is currently a member.
*
* @public
* @return {IrcChannelUser[]} A array of all IrcChannelUser object that correspond to the IrcUser.
*/
getChannelUsers () {
let channelUsers = []
this.client.channels.forEach(channel => {
channel.users.forEach(channelUser => {
if (channelUser.user === this) {
channelUsers.push(channelUser)
}
})
})
return channelUsers
}
/**
* Returns a string representation of this instance.
*
* @public
* @return {string} A string that represents this instance.
*/
toString () {
return this.nickName
}
quit (comment) {
let allChannelUsers = []
this.client.channels.forEach(channel => {
channel.users.forEach(channelUser => {
if (channelUser.user === this) {
allChannelUsers.push(channelUser)
}
})
})
allChannelUsers.forEach(cu => cu.channel.userQuit(cu, comment))
/**
* @event IrcUser#quit
* @param {string} comment
*/
this.emit('quit', comment)
}
joinChannel (channel) {
/**
* @event IrcUser#joinedChannel
* @param {IrcChannel} channel
*/
this.emit('joinedChannel', channel)
}
partChannel (channel) {
/**
* @event IrcUser#partedChannel
* @param {IrcChannel} channel
*/
this.emit('partedChannel', channel)
}
inviteReceived (source, channel) {
/**
* @event IrcUser#invite
* @param {IrcChannel} channel
* @param {IrcUser} source
*/
this.emit('invite', channel, source)
}
actionReceived (source, targets, messageText) {
/**
* @event IrcUser#action
* @param {IrcUser|IrcChannel} source
* @param {string} messageText
*/
this.emit('action', source, messageText)
}
messageReceived (source, targets, messageText) {
let previewMessageEventArgs = { 'handled': false, 'source': source, 'targets': targets, 'text': messageText }
/**
* @event IrcUser#previewMessage
* @property {boolean} handled
* @property {IrcUser|IrcChannel} source
* @property {string[]} targets
* @property {string} messageText
*/
this.emit('previewMessage', previewMessageEventArgs)
if (!previewMessageEventArgs.handled) {
/**
* @event IrcUser#message
* @param {IrcUser|IrcChannel} source
* @param {string} messageText
*/
this.emit('message', source, targets, messageText)
}
}
noticeReceived (source, targets, noticeText) {
let previewNoticeEventArgs = { 'handled': false, 'source': source, 'targets': targets, 'text': noticeText }
/**
* @event IrcUser#previewNotice
* @property {boolean} handled
* @property {IrcUser|IrcChannel} source
* @property {string[]} targets
* @property {string} noticeText
*/
this.emit('previewNotice', previewNoticeEventArgs)
if (!previewNoticeEventArgs.handled) {
/**
* @event IrcUser#notice
* @param {IrcUser|IrcChannel} source
* @param {string} noticeText
*/
this.emit('notice', source, targets, noticeText)
}
}
} |
JavaScript | class Parser {
/**
* Initialize an parser for CoAP.
*/
constructor() {
this.id = 'CoAP';
this.payload = 'payload';
this.nexts = nexts;
}
/**
* Parse a buffer.
*
* @param {Buffer} buf The buffer to parse.
* @param {Object} packet The packet providing the buffer.
*
* @return {Object} The parsed data.
*/
parse(buf, packet) {
let p = coapPacket.parse(buf);
let options = new Map();
if (p.options) {
for (let opt of p.options) {
if (options.has(opt.name)) {
options.get(opt.name).push(opt.value);
} else {
options.set(opt.name, [opt.value]);
}
}
}
// uri-path
if (options.has(kUriPath)) {
let uriPath = options.get(kUriPath);
options.set(kUriPath, uriPath.map((it) => it.toString()).join('/'));
}
return {
header: {
code: p.code,
type: p.confirmable && 'CON' || p.reset && 'RST' ||
p.ack && 'ACK' || 'NON',
messageId: p.messageId,
token: p.token,
options: [...options],
},
payload: p.payload,
};
}
} |
JavaScript | class Toolbar extends FoundationElement {
constructor() {
super(...arguments);
/**
* The internal index of the currently focused element.
*
* @internal
*/
this._activeIndex = 0;
/**
* The text direction of the toolbar.
*
* @internal
*/
this.direction = Direction.ltr;
/**
* The orientation of the toolbar.
*
* @public
* @remarks
* HTML Attribute: `orientation`
*/
this.orientation = Orientation.horizontal;
}
/**
* The index of the currently focused element, clamped between 0 and the last element.
*
* @internal
*/
get activeIndex() {
Observable.track(this, "activeIndex");
return this._activeIndex;
}
set activeIndex(value) {
if (this.$fastController.isConnected) {
this._activeIndex = limit(0, this.focusableElements.length - 1, value);
Observable.notify(this, "activeIndex");
}
}
slottedItemsChanged() {
if (this.$fastController.isConnected) {
this.reduceFocusableElements();
}
}
/**
* Set the activeIndex when a focusable element in the toolbar is clicked.
*
* @internal
*/
clickHandler(e) {
var _a;
const activeIndex = (_a = this.focusableElements) === null || _a === void 0 ? void 0 : _a.indexOf(e.target);
if (activeIndex > -1 && this.activeIndex !== activeIndex) {
this.setFocusedElement(activeIndex);
}
return true;
}
/**
* @internal
*/
connectedCallback() {
super.connectedCallback();
this.direction = getDirection(this);
}
/**
* When the toolbar receives focus, set the currently active element as focused.
*
* @internal
*/
focusinHandler(e) {
const relatedTarget = e.relatedTarget;
if (!relatedTarget || this.contains(relatedTarget)) {
return;
}
this.setFocusedElement();
}
/**
* Determines a value that can be used to iterate a list with the arrow keys.
*
* @param this - An element with an orientation and direction
* @param key - The event key value
* @internal
*/
getDirectionalIncrementer(key) {
var _a, _b, _c, _d, _e;
return ((_e = (_c = (_b = (_a = ToolbarArrowKeyMap[key]) === null || _a === void 0 ? void 0 : _a[this.orientation]) === null || _b === void 0 ? void 0 : _b[this.direction]) !== null && _c !== void 0 ? _c : (_d = ToolbarArrowKeyMap[key]) === null || _d === void 0 ? void 0 : _d[this.orientation]) !== null && _e !== void 0 ? _e : 0);
}
/**
* Handle keyboard events for the toolbar.
*
* @internal
*/
keydownHandler(e) {
const key = e.key;
if (!(key in ArrowKeys) || e.defaultPrevented || e.shiftKey) {
return true;
}
const incrementer = this.getDirectionalIncrementer(key);
if (!incrementer) {
return !e.target.closest("[role=radiogroup]");
}
const nextIndex = this.activeIndex + incrementer;
if (this.focusableElements[nextIndex]) {
e.preventDefault();
}
this.setFocusedElement(nextIndex);
return true;
}
/**
* get all the slotted elements
* @internal
*/
get allSlottedItems() {
return [
...this.start.assignedElements(),
...this.slottedItems,
...this.end.assignedElements(),
];
}
/**
* Prepare the slotted elements which can be focusable.
*
* @internal
*/
reduceFocusableElements() {
this.focusableElements = this.allSlottedItems.reduce(Toolbar.reduceFocusableItems, []);
this.setFocusableElements();
}
/**
* Set the activeIndex and focus the corresponding control.
*
* @param activeIndex - The new index to set
* @internal
*/
setFocusedElement(activeIndex = this.activeIndex) {
var _a;
this.activeIndex = activeIndex;
this.setFocusableElements();
(_a = this.focusableElements[this.activeIndex]) === null || _a === void 0 ? void 0 : _a.focus();
}
/**
* Reduce a collection to only its focusable elements.
*
* @param elements - Collection of elements to reduce
* @param element - The current element
*
* @internal
*/
static reduceFocusableItems(elements, element) {
var _a, _b, _c, _d;
const isRoleRadio = element.getAttribute("role") === "radio";
const isFocusableFastElement = (_b = (_a = element.$fastController) === null || _a === void 0 ? void 0 : _a.definition.shadowOptions) === null || _b === void 0 ? void 0 : _b.delegatesFocus;
const hasFocusableShadow = Array.from((_d = (_c = element.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelectorAll("*")) !== null && _d !== void 0 ? _d : []).some(x => isFocusable(x));
if (isFocusable(element) ||
isRoleRadio ||
isFocusableFastElement ||
hasFocusableShadow) {
elements.push(element);
return elements;
}
if (element.childElementCount) {
return elements.concat(Array.from(element.children).reduce(Toolbar.reduceFocusableItems, []));
}
return elements;
}
/**
* @internal
*/
setFocusableElements() {
if (this.$fastController.isConnected && this.focusableElements.length > 0) {
this.focusableElements.forEach((element, index) => {
element.tabIndex = this.activeIndex === index ? 0 : -1;
});
}
}
} |
JavaScript | class GetFixedDepositAccountsResponse {
/**
* Constructs a new <code>GetFixedDepositAccountsResponse</code>.
* GetFixedDepositAccountsResponse
* @alias module:model/GetFixedDepositAccountsResponse
*/
constructor() {
GetFixedDepositAccountsResponse.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>GetFixedDepositAccountsResponse</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/GetFixedDepositAccountsResponse} obj Optional instance to populate.
* @return {module:model/GetFixedDepositAccountsResponse} The populated <code>GetFixedDepositAccountsResponse</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GetFixedDepositAccountsResponse();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('accountNo')) {
obj['accountNo'] = ApiClient.convertToType(data['accountNo'], 'Number');
}
if (data.hasOwnProperty('clientId')) {
obj['clientId'] = ApiClient.convertToType(data['clientId'], 'Number');
}
if (data.hasOwnProperty('clientName')) {
obj['clientName'] = ApiClient.convertToType(data['clientName'], 'String');
}
if (data.hasOwnProperty('savingsProductId')) {
obj['savingsProductId'] = ApiClient.convertToType(data['savingsProductId'], 'Number');
}
if (data.hasOwnProperty('savingsProductName')) {
obj['savingsProductName'] = ApiClient.convertToType(data['savingsProductName'], 'String');
}
if (data.hasOwnProperty('fieldOfficerId')) {
obj['fieldOfficerId'] = ApiClient.convertToType(data['fieldOfficerId'], 'Number');
}
if (data.hasOwnProperty('status')) {
obj['status'] = GetFixedDepositAccountsStatus.constructFromObject(data['status']);
}
if (data.hasOwnProperty('timeline')) {
obj['timeline'] = GetFixedDepositAccountsTimeline.constructFromObject(data['timeline']);
}
if (data.hasOwnProperty('currency')) {
obj['currency'] = GetFixedDepositAccountsCurrency.constructFromObject(data['currency']);
}
if (data.hasOwnProperty('interestCompoundingPeriodType')) {
obj['interestCompoundingPeriodType'] = GetFixedDepositAccountsInterestCompoundingPeriodType.constructFromObject(data['interestCompoundingPeriodType']);
}
if (data.hasOwnProperty('interestPostingPeriodType')) {
obj['interestPostingPeriodType'] = GetFixedDepositAccountsInterestPostingPeriodType.constructFromObject(data['interestPostingPeriodType']);
}
if (data.hasOwnProperty('interestCalculationType')) {
obj['interestCalculationType'] = GetFixedDepositAccountsInterestCalculationType.constructFromObject(data['interestCalculationType']);
}
if (data.hasOwnProperty('interestCalculationDaysInYearType')) {
obj['interestCalculationDaysInYearType'] = GetFixedDepositAccountsInterestCalculationDaysInYearType.constructFromObject(data['interestCalculationDaysInYearType']);
}
if (data.hasOwnProperty('summary')) {
obj['summary'] = GetFixedDepositAccountsSummary.constructFromObject(data['summary']);
}
if (data.hasOwnProperty('interestFreePeriodApplicable')) {
obj['interestFreePeriodApplicable'] = ApiClient.convertToType(data['interestFreePeriodApplicable'], 'Boolean');
}
if (data.hasOwnProperty('preClosurePenalApplicable')) {
obj['preClosurePenalApplicable'] = ApiClient.convertToType(data['preClosurePenalApplicable'], 'Boolean');
}
if (data.hasOwnProperty('minDepositTerm')) {
obj['minDepositTerm'] = ApiClient.convertToType(data['minDepositTerm'], 'Number');
}
if (data.hasOwnProperty('maxDepositTerm')) {
obj['maxDepositTerm'] = ApiClient.convertToType(data['maxDepositTerm'], 'Number');
}
if (data.hasOwnProperty('minDepositTermType')) {
obj['minDepositTermType'] = GetFixedDepositAccountsMinDepositTermType.constructFromObject(data['minDepositTermType']);
}
if (data.hasOwnProperty('maxDepositTermType')) {
obj['maxDepositTermType'] = GetFixedDepositAccountsMaxDepositTermType.constructFromObject(data['maxDepositTermType']);
}
if (data.hasOwnProperty('depositAmount')) {
obj['depositAmount'] = ApiClient.convertToType(data['depositAmount'], 'Number');
}
if (data.hasOwnProperty('maturityAmount')) {
obj['maturityAmount'] = ApiClient.convertToType(data['maturityAmount'], 'Number');
}
if (data.hasOwnProperty('maturityDate')) {
obj['maturityDate'] = ApiClient.convertToType(data['maturityDate'], 'Date');
}
if (data.hasOwnProperty('depositPeriod')) {
obj['depositPeriod'] = ApiClient.convertToType(data['depositPeriod'], 'Number');
}
if (data.hasOwnProperty('depositPeriodFrequency')) {
obj['depositPeriodFrequency'] = GetFixedDepositAccountsDepositPeriodFrequency.constructFromObject(data['depositPeriodFrequency']);
}
}
return obj;
}
} |
JavaScript | class Hexagon extends HTMLElement {
// render function
get html() {
return `
<style>
:host {
display: inline-flex;
position: relative;
height: 36px;
width: 36px;
}
:host div,
:host div:before,
:host div:after {
background-color: var(--hexagon-color, orange);
}
div {
width: 30px;
height: 18px;
margin: 9px 3px;
position: absolute;
color: var(--hexagon-color, orange);
}
div:before, div:after {
content: '';
position: absolute;
width: 30px;
height: 18px;
}
div:before {
-webkit-transform: rotate(60deg);
transform: rotate(60deg);
}
div:after {
-webkit-transform: rotate(-60deg);
transform: rotate(-60deg);
}
</style>
<div></div>`;
}
/**
* Store the tag name to make it easier to obtain directly.
*/
static get tag() {
return "hex-a-gon";
}
/**
* life cycle
*/
constructor(delayRender = false) {
super(); // set tag for later use
this.tag = Hexagon.tag; // optional queue for future use
this._queue = [];
this.template = document.createElement("template");
this.attachShadow({
mode: "open"
});
if (!delayRender) {
this.render();
}
}
/**
* life cycle, element is afixed to the DOM
*/
connectedCallback() {
if (window.ShadyCSS) {
window.ShadyCSS.styleElement(this);
}
if (this._queue.length) {
this._processQueue();
}
}
_copyAttribute(name, to) {
const recipients = this.shadowRoot.querySelectorAll(to);
const value = this.getAttribute(name);
const fname = value == null ? "removeAttribute" : "setAttribute";
for (const node of recipients) {
node[fname](name, value);
}
}
_queueAction(action) {
this._queue.push(action);
}
_processQueue() {
this._queue.forEach(action => {
this[`_${action.type}`](action.data);
});
this._queue = [];
}
_setProperty({
name,
value
}) {
this[name] = value;
}
render() {
this.shadowRoot.innerHTML = null;
this.template.innerHTML = this.html;
if (window.ShadyCSS) {
window.ShadyCSS.prepareTemplate(this.template, this.tag);
}
this.shadowRoot.appendChild(this.template.content.cloneNode(true));
}
} |
JavaScript | class WebDavApi {
constructor(options) {
this.logger_ = new Logger();
this.options_ = options;
this.lastRequests_ = [];
}
logRequest_(request, responseText) {
if (this.lastRequests_.length > 10) this.lastRequests_.splice(0, 1);
const serializeRequest = (r) => {
const options = Object.assign({}, r.options);
if (typeof options.body === 'string') options.body = options.body.substr(0, 4096);
const output = [];
output.push(options.method ? options.method : 'GET');
output.push(r.url);
options.headers = Object.assign({}, options.headers);
if (options.headers['Authorization']) options.headers['Authorization'] = '********';
delete options.method;
output.push(JSON.stringify(options));
return output.join(' ');
};
this.lastRequests_.push({
timestamp: Date.now(),
request: serializeRequest(request),
response: responseText ? responseText.substr(0, 4096) : '',
});
}
lastRequests() {
return this.lastRequests_;
}
clearLastRequests() {
this.lastRequests_ = [];
}
setLogger(l) {
this.logger_ = l;
}
logger() {
return this.logger_;
}
authToken() {
if (!this.options_.username() || !this.options_.password()) return null;
try {
// Note: Non-ASCII passwords will throw an error about Latin1 characters - https://github.com/laurent22/joplin/issues/246
// Tried various things like the below, but it didn't work on React Native:
// return base64.encode(utf8.encode(this.options_.username() + ':' + this.options_.password()));
return base64.encode(`${this.options_.username()}:${this.options_.password()}`);
} catch (error) {
error.message = `Cannot encode username/password: ${error.message}`;
throw error;
}
}
baseUrl() {
return rtrimSlashes(this.options_.baseUrl());
}
relativeBaseUrl() {
const url = new URL(this.baseUrl());
return url.pathname + url.query;
}
async xmlToJson(xml) {
let davNamespaces = []; // Yes, there can be more than one... xmlns:a="DAV:" xmlns:D="DAV:"
const nameProcessor = name => {
if (name.indexOf('xmlns') !== 0) {
// Check if the current name is within the DAV namespace. If it is, normalise it
// by moving it to the "d:" namespace, which is what all the functions are using.
const p = name.split(':');
if (p.length == 2) {
const ns = p[0];
if (davNamespaces.indexOf(ns) >= 0) {
name = `d:${p[1]}`;
}
} else if (p.length === 1 && davNamespaces.indexOf('') >= 0) {
// Also handle the case where the namespace alias is empty.
// https://github.com/laurent22/joplin/issues/2002
name = `d:${name}`;
}
}
return name.toLowerCase();
};
const attrValueProcessor = (value, name) => {
// The namespace is ususally specified like so: xmlns:D="DAV:" ("D" being the alias used in the tag names)
// In some cases, the namespace can also be empty like so: "xmlns=DAV". In this case, the tags will have
// no namespace so instead of <d:prop> will have just <prop>. This is handled above in nameProcessor()
if (value.toLowerCase() === 'dav:') {
const p = name.split(':');
davNamespaces.push(p.length === 2 ? p[p.length - 1] : '');
}
};
const options = {
tagNameProcessors: [nameProcessor],
attrNameProcessors: [nameProcessor],
attrValueProcessors: [attrValueProcessor],
};
return new Promise((resolve) => {
parseXmlString(xml, options, (error, result) => {
if (error) {
resolve(null); // Error handled by caller which will display the XML text (or plain text) if null is returned from this function
return;
}
resolve(result);
});
});
}
valueFromJson(json, keys, type) {
let output = json;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// console.info(key, typeof key, typeof output, typeof output === 'object' && (key in output), Array.isArray(output));
if (typeof key === 'number' && !Array.isArray(output)) return null;
if (typeof key === 'string' && (typeof output !== 'object' || !(key in output))) return null;
output = output[key];
}
if (type === 'string') {
// If the XML has not attribute the value is directly a string
// If the XML node has attributes, the value is under "_".
// Eg for this XML, the string will be under {"_":"Thu, 01 Feb 2018 17:24:05 GMT"}:
// <a:getlastmodified b:dt="dateTime.rfc1123">Thu, 01 Feb 2018 17:24:05 GMT</a:getlastmodified>
// For this XML, the value will be "Thu, 01 Feb 2018 17:24:05 GMT"
// <a:getlastmodified>Thu, 01 Feb 2018 17:24:05 GMT</a:getlastmodified>
if (typeof output === 'object' && '_' in output) output = output['_'];
if (typeof output !== 'string') return null;
return output;
}
if (type === 'object') {
if (!Array.isArray(output) && typeof output === 'object') return output;
return null;
}
if (type === 'array') {
return Array.isArray(output) ? output : null;
}
return null;
}
stringFromJson(json, keys) {
return this.valueFromJson(json, keys, 'string');
}
objectFromJson(json, keys) {
return this.valueFromJson(json, keys, 'object');
}
arrayFromJson(json, keys) {
return this.valueFromJson(json, keys, 'array');
}
resourcePropByName(resource, outputType, propName) {
const propStats = resource['d:propstat'];
let output = null;
if (!Array.isArray(propStats)) throw new Error('Missing d:propstat property');
for (let i = 0; i < propStats.length; i++) {
const props = propStats[i]['d:prop'];
if (!Array.isArray(props) || !props.length) continue;
const prop = props[0];
if (Array.isArray(prop[propName])) {
output = prop[propName];
break;
}
}
if (outputType === 'string') {
// If the XML has not attribute the value is directly a string
// If the XML node has attributes, the value is under "_".
// Eg for this XML, the string will be under {"_":"Thu, 01 Feb 2018 17:24:05 GMT"}:
// <a:getlastmodified b:dt="dateTime.rfc1123">Thu, 01 Feb 2018 17:24:05 GMT</a:getlastmodified>
// For this XML, the value will be "Thu, 01 Feb 2018 17:24:05 GMT"
// <a:getlastmodified>Thu, 01 Feb 2018 17:24:05 GMT</a:getlastmodified>
output = output[0];
if (typeof output === 'object' && '_' in output) output = output['_'];
if (typeof output !== 'string') return null;
return output;
}
if (outputType === 'array') {
return output;
}
throw new Error(`Invalid output type: ${outputType}`);
}
async execPropFind(path, depth, fields = null, options = null) {
if (fields === null) fields = ['d:getlastmodified'];
let fieldsXml = '';
for (let i = 0; i < fields.length; i++) {
fieldsXml += `<${fields[i]}/>`;
}
// To find all available properties:
//
// const body=`<?xml version="1.0" encoding="utf-8" ?>
// <propfind xmlns="DAV:">
// <propname/>
// </propfind>`;
const body =
`<?xml version="1.0" encoding="UTF-8"?>
<d:propfind xmlns:d="DAV:">
<d:prop xmlns:oc="http://owncloud.org/ns">
${fieldsXml}
</d:prop>
</d:propfind>`;
return this.exec('PROPFIND', path, body, { Depth: depth }, options);
}
requestToCurl_(url, options) {
let output = [];
output.push('curl');
output.push('-v');
if (options.method) output.push(`-X ${options.method}`);
if (options.headers) {
for (let n in options.headers) {
if (!options.headers.hasOwnProperty(n)) continue;
output.push(`${'-H ' + '"'}${n}: ${options.headers[n]}"`);
}
}
if (options.body) output.push(`${'--data ' + '\''}${options.body}'`);
output.push(url);
return output.join(' ');
}
handleNginxHack_(jsonResponse, newErrorHandler) {
// Trying to fix 404 error issue with Nginx WebDAV server.
// https://github.com/laurent22/joplin/issues/624
// https://github.com/laurent22/joplin/issues/808
// Not tested but someone confirmed it worked - https://github.com/laurent22/joplin/issues/808#issuecomment-443552858
// and fix is narrowly scoped so shouldn't affect anything outside this particular edge case.
//
// The issue is that instead of an HTTP 404 status code, Nginx returns 200 but with this response:
//
// <?xml version="1.0" encoding="utf-8" ?>
// <D:multistatus xmlns:D="DAV:">
// <D:response>
// <D:href>/notes/ecd4027a5271483984b00317433e2c66.md</D:href>
// <D:propstat>
// <D:prop/>
// <D:status>HTTP/1.1 404 Not Found</D:status>
// </D:propstat>
// </D:response>
// </D:multistatus>
//
// So we need to parse this and find that it is in fact a 404 error.
//
// HOWEVER, some implementations also return 404 for missing props, for example SeaFile:
// (indicates that the props "getlastmodified" is not present, but this call is only
// used when checking the conf, so we don't really need it)
// https://github.com/laurent22/joplin/issues/1137
//
// <?xml version='1.0' encoding='UTF-8'?>
// <ns0:multistatus xmlns:ns0="DAV:">
// <ns0:response>
// <ns0:href>/seafdav/joplin/</ns0:href>
// <ns0:propstat>
// <ns0:prop>
// <ns0:getlastmodified/>
// </ns0:prop>
// <ns0:status>HTTP/1.1 404 Not Found</ns0:status>
// </ns0:propstat>
// <ns0:propstat>
// <ns0:prop>
// <ns0:resourcetype>
// <ns0:collection/>
// </ns0:resourcetype>
// </ns0:prop>
// <ns0:status>HTTP/1.1 200 OK</ns0:status>
// </ns0:propstat>
// </ns0:response>
// </ns0:multistatus>
//
// As a simple fix for now it's enough to check if ALL the statuses are 404 - in that case
// it really means that the file doesn't exist. Otherwise we can proceed as usual.
const responseArray = this.arrayFromJson(jsonResponse, ['d:multistatus', 'd:response']);
if (responseArray && responseArray.length === 1) {
const propStats = this.arrayFromJson(jsonResponse, ['d:multistatus', 'd:response', 0, 'd:propstat']);
if (!propStats.length) return;
let count404 = 0;
for (let i = 0; i < propStats.length; i++) {
const status = this.arrayFromJson(jsonResponse, ['d:multistatus', 'd:response', 0, 'd:propstat', i, 'd:status']);
if (status && status.length && status[0].indexOf('404') >= 0) count404++;
}
if (count404 === propStats.length) throw newErrorHandler('Not found', 404);
}
}
// curl -u admin:123456 'http://nextcloud.local/remote.php/dav/files/admin/' -X PROPFIND --data '<?xml version="1.0" encoding="UTF-8"?>
// <d:propfind xmlns:d="DAV:">
// <d:prop xmlns:oc="http://owncloud.org/ns">
// <d:getlastmodified/>
// </d:prop>
// </d:propfind>'
async exec(method, path = '', body = null, headers = null, options = null) {
if (headers === null) headers = {};
if (options === null) options = {};
if (!options.responseFormat) options.responseFormat = 'json';
if (!options.target) options.target = 'string';
const authToken = this.authToken();
if (authToken) headers['Authorization'] = `Basic ${authToken}`;
// On iOS, the network lib appends a If-None-Match header to PROPFIND calls, which is kind of correct because
// the call is idempotent and thus could be cached. According to RFC-7232 though only GET and HEAD should have
// this header for caching purposes. It makes no mention of PROPFIND.
// So possibly because of this, Seafile (and maybe other WebDAV implementations) responds with a "412 Precondition Failed"
// error when this header is present for PROPFIND call on existing resources. This is also kind of correct because there is a resource
// with this eTag and since this is neither a GET nor HEAD call, it is supposed to respond with 412 if the resource is present.
// The "solution", an ugly one, is to send a purposely invalid string as eTag, which will bypass the If-None-Match check - Seafile
// finds out that no resource has this ID and simply sends the requested data.
// Also add a random value to make sure the eTag is unique for each call.
if (['GET', 'HEAD'].indexOf(method) < 0) headers['If-None-Match'] = `JoplinIgnore-${Math.floor(Math.random() * 100000)}`;
const fetchOptions = {};
fetchOptions.headers = headers;
fetchOptions.method = method;
if (options.path) fetchOptions.path = options.path;
if (body) fetchOptions.body = body;
const url = `${this.baseUrl()}/${path}`;
let response = null;
// console.info('WebDAV Call', method + ' ' + url, headers, options);
// console.info(this.requestToCurl_(url, fetchOptions));
if (options.source == 'file' && (method == 'POST' || method == 'PUT')) {
if (fetchOptions.path) {
const fileStat = await shim.fsDriver().stat(fetchOptions.path);
if (fileStat) fetchOptions.headers['Content-Length'] = `${fileStat.size}`;
}
response = await shim.uploadBlob(url, fetchOptions);
} else if (options.target == 'string') {
if (typeof body === 'string') fetchOptions.headers['Content-Length'] = `${shim.stringByteLength(body)}`;
response = await shim.fetch(url, fetchOptions);
} else {
// file
response = await shim.fetchBlob(url, fetchOptions);
}
const responseText = await response.text();
this.logRequest_({ url: url, options: fetchOptions }, responseText);
// console.info('WebDAV Response', responseText);
// Creates an error object with as much data as possible as it will appear in the log, which will make debugging easier
const newError = (message, code = 0) => {
// Gives a shorter response for error messages. Useful for cases where a full HTML page is accidentally loaded instead of
// JSON. That way the error message will still show there's a problem but without filling up the log or screen.
const shortResponseText = (`${responseText}`).substr(0, 1024);
return new JoplinError(`${method} ${path}: ${message} (${code}): ${shortResponseText}`, code);
};
let responseJson_ = null;
const loadResponseJson = async () => {
if (!responseText) return null;
if (responseJson_) return responseJson_;
// eslint-disable-next-line require-atomic-updates
responseJson_ = await this.xmlToJson(responseText);
if (!responseJson_) throw newError('Cannot parse XML response', response.status);
return responseJson_;
};
if (!response.ok) {
// When using fetchBlob we only get a string (not xml or json) back
if (options.target === 'file') throw newError('fetchBlob error', response.status);
let json = null;
try {
json = await loadResponseJson();
} catch (error) {
// Just send back the plain text in newErro()
}
if (json && json['d:error']) {
const code = json['d:error']['s:exception'] ? json['d:error']['s:exception'].join(' ') : response.status;
const message = json['d:error']['s:message'] ? json['d:error']['s:message'].join('\n') : 'Unknown error 1';
throw newError(`${message} (Exception ${code})`, response.status);
}
throw newError('Unknown error 2', response.status);
}
if (options.responseFormat === 'text') return responseText;
// The following methods may have a response depending on the server but it's not
// standard (some return a plain string, other XML, etc.) and we don't check the
// response anyway since we rely on the HTTP status code so return null.
if (['MKCOL', 'DELETE', 'PUT', 'MOVE'].indexOf(method) >= 0) return null;
const output = await loadResponseJson();
this.handleNginxHack_(output, newError);
// Check that we didn't get for example an HTML page (as an error) instead of the JSON response
// null responses are possible, for example for DELETE calls
if (output !== null && typeof output === 'object' && !('d:multistatus' in output)) throw newError('Not a valid WebDAV response');
return output;
}
} |
JavaScript | class Resize extends Component {
constructor(graphics) {
super(componentNames.RESIZE, graphics);
/**
* Current dimensions
* @type {Object}
* @private
*/
this._dimensions = null;
/**
* Original dimensions
* @type {Object}
* @private
*/
this._originalDimensions = null;
/**
* Original positions
* @type {Array}
* @private
*/
this._originalPositions = null;
}
/**
* Get current dimensions
* @returns {object}
*/
getCurrentPositions() {
this._positions = this.getCanvas()
.getObjects()
.map(({ left, top, scaleX, scaleY }) => {
return { left, top, scaleX, scaleY };
});
return this._positions;
}
/**
* Get original dimensions
* @returns {object}
*/
getOriginalPositions() {
return this._originalPositions;
}
/**
* Set original positions
* @param {object} positions - Positions
*/
setOriginalPositions(positions) {
this._originalPositions = positions;
}
/**
* Get current dimensions
* @returns {object}
*/
getCurrentDimensions() {
const canvasImage = this.getCanvasImage();
if (!this._dimensions && canvasImage) {
const { width, height } = canvasImage;
this._dimensions = { width, height };
}
return this._dimensions;
}
/**
* Get original dimensions
* @returns {object}
*/
getOriginalDimensions() {
return this._originalDimensions;
}
/**
* Set original dimensions
* @param {object} dimensions - Dimensions
*/
setOriginalDimensions(dimensions) {
this._originalDimensions = dimensions;
}
/**
* Resize Image
* @param {Object} dimensions - Resize dimensions
* @returns {Promise}
*/
resize(dimensions) {
const canvas = this.getCanvas();
const canvasImage = this.getCanvasImage();
const { width, height } = dimensions;
const { width: originalWidth, height: originalHeight } = this.getOriginalDimensions();
const scaleX = width / originalWidth;
const scaleY = height / originalHeight;
if (width !== canvas.width || height !== canvas.height) {
const { width: startWidth, height: startHeight } = canvasImage.getOriginalSize();
canvasImage.scaleX = width / startWidth;
canvasImage.scaleY = height / startHeight;
this._dimensions = dimensions;
if (this._originalPositions) {
canvas.getObjects().forEach((obj, i) => {
const pos = this._originalPositions[i];
obj.scaleX = pos.scaleX * scaleX;
obj.scaleY = pos.scaleY * scaleY;
obj.left = pos.left * scaleX;
obj.top = pos.top * scaleY;
obj.setCoords();
});
}
canvas.setWidth(width);
canvas.setHeight(height);
}
return Promise.resolve();
}
/**
* Start resizing
*/
start() {
this.setOriginalDimensions(this.getCurrentDimensions());
this.setOriginalPositions(this.getCurrentPositions());
}
/**
* End resizing
*/
end() {}
} |
JavaScript | class LeafletMarker extends HTMLElement {
connectedCallback() {
this._map;
this.mapObj; // marker
this.options = {latlng: [51.505, -0.09]}; // default options
this.events = {};
this.initialize(this.map);
}
disconnectedCallback() {
this.map.removeLayer(this.mapObj);
}
get map() {
this._map = this._map || this.closest('mce-leaflet').map;
return this._map;
}
initialize(map){
if (!map) return;
let attrParsed = parseAttributes(this.attributes);
this.options = Object.assign(this.options, attrParsed.options);
this.events = attrParsed.events;
resolveLatLng(this.options.latlng)
.then(latlng => {
this.mapObj = new L.marker(latlng, this.options); // set options
this.mapObj.customElement = this;
for(let eventName in this.events) { // set events
this.mapObj.on(eventName, this.events[eventName]);
}
this.mapObj.addTo(map); // add to map
observeAttrChange(this, this.onAttrChange.bind(this));
});
}
// run setXXX if defined when attribute value changes
onAttrChange(name, val) {
if (name === 'latlng') {
resolveLatLng(val).then(latlng => this.mapObj.setLatLng(latlng));
} else if (!['class', 'tabindex', 'style'].includes(name)) {
callSetMethod(this.map, name, val);
}
}
} |
JavaScript | class ValueListFormatMetadata {
/**
* Constructs a new <code>ValueListFormatMetadata</code>.
* @alias module:model/ValueListFormatMetadata
* @class
*/
constructor() {}
/**
* Constructs a <code>ValueListFormatMetadata</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/ValueListFormatMetadata} obj Optional instance to populate.
* @return {module:model/ValueListFormatMetadata} The populated <code>ValueListFormatMetadata</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ValueListFormatMetadata();
if (data.hasOwnProperty('itemCount')) {
obj['itemCount'] = ApiClient.convertToType(data['itemCount'], 'Number');
}
if (data.hasOwnProperty('limit')) {
obj['limit'] = ApiClient.convertToType(data['limit'], 'Number');
}
if (data.hasOwnProperty('stats')) {
obj['stats'] = ApiClient.convertToType(data['stats'], {
String: Object,
});
}
if (data.hasOwnProperty('time')) {
obj['time'] = ApiClient.convertToType(data['time'], 'Number');
}
if (data.hasOwnProperty('message')) {
obj['message'] = ApiClient.convertToType(data['message'], 'String');
}
if (data.hasOwnProperty('query')) {
obj['query'] = ApiClient.convertToType(data['query'], 'String');
}
if (data.hasOwnProperty('status')) {
obj['status'] = ApiClient.convertToType(data['status'], 'Number');
}
}
return obj;
}
/**
* @member {Number} itemCount
*/
itemCount = undefined;
/**
* @member {Number} limit
*/
limit = undefined;
/**
* @member {Object.<String, Object>} stats
*/
stats = undefined;
/**
* @member {Number} time
*/
time = undefined;
/**
* @member {String} message
*/
message = undefined;
/**
* @member {String} query
*/
query = undefined;
/**
* @member {Number} status
*/
status = undefined;
} |
JavaScript | class Solarage {
constructor(bdayString) {
this.bday = new Date(bdayString);
this.now = new Date();
this.msAge = Math.abs(this.now - this.bday);
this.planets = {
"Mercury": 88,
"Venus": 225,
"Earth": 365,
"Mars": 687,
"Jupiter":(11.8*365),
"Saturn":(29.4*365),
"Uranus":(84*365),
"Neptune":(164*365)
};
}
ageInYears(){
return this.msAge/(365*24*60*60*1000);
}
ageInDays(){
return this.msAge/(24*60*60*1000);
}
getPlanet(planetsKey){
return this.planets[planetsKey];
}
//solar age will be calculated by days for a marginal
//gain in accuracy.
planetAge(planetsKey){
return Math.floor(this.ageInDays()/this.planets[planetsKey]);
}
yearsLeft(lifeExpectancyString, planetsKey){
let solarExpectancy = Math.floor(parseInt(lifeExpectancyString)*365/this.planets[planetsKey]);
return solarExpectancy - this.planetAge(planetsKey);
}
} |
JavaScript | class GalleryImageIdentifier {
/**
* Create a GalleryImageIdentifier.
* @member {string} [publisher] The gallery image publisher name.
* @member {string} [offer] The gallery image offer name.
* @member {string} [sku] The gallery image sku name.
*/
constructor() {
}
/**
* Defines the metadata of GalleryImageIdentifier
*
* @returns {object} metadata of GalleryImageIdentifier
*
*/
mapper() {
return {
required: false,
serializedName: 'GalleryImageIdentifier',
type: {
name: 'Composite',
className: 'GalleryImageIdentifier',
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'
}
}
}
}
};
}
} |
JavaScript | class SequenceCommand extends AbstractCommandSet {
/**
* Constructor.
*/
constructor() {
super();
/**
* Points to the index just after the last-executed command
* @type {number}
* @private
*/
this.current_ = -1;
}
/**
* Sets the set of commands
*
* @override
* @param {Array<ICommand>} set The set of commands
*/
setCommands(set) {
super.setCommands(set);
this.current_ = -1;
this.state = State.READY;
var n = set.length;
if (n <= 0) {
return;
}
for (var i = 0; i < n; i++) {
var cmd = set[i];
if (cmd.state === State.READY && this.current_ < 0) {
this.current_ = i;
} else if (cmd.state === State.SUCCESS || cmd.state === State.ERROR) {
if (this.current_ >= 0 && i >= this.current_) {
throw new Error('os.command.SequenceCommand: illegal state: ' +
'the first ready sub-command must follow all executed sub-commands: ' +
'first ready command [' + this.current_ + ']:' + set[this.current_].title +
' precedes ' + cmd.state + 'command [' + i + ']:' + set[i].title);
}
if (this.state !== State.ERROR) {
this.state = cmd.state;
}
}
}
if (this.current_ >= 0 && this.current_ < set.length && this.state !== State.ERROR) {
this.state = State.READY;
} else {
this.current_ = set.length;
}
}
/**
* @inheritDoc
*/
execute() {
if (this.state !== State.READY) {
return false;
}
this.state = State.EXECUTING;
return this.execute_();
}
/**
* @inheritDoc
*/
revert() {
if (this.state !== State.SUCCESS) {
return false;
}
this.current_--;
this.state = State.REVERTING;
return this.revert_();
}
/**
* Execute the sub-commands.
*
* @return {boolean} true if all sub-commands return true, or the first
* async sub-command returns true, false otherwise
* @private
*
* @todo
* add timeout logic to remove the listener and fail the sequence if the
* sub-command never fires EXECUTED
*/
execute_() {
/** @type {Array<ICommand>} */ var cmds = this.getCommands();
/** @type {number} */ var n = cmds.length;
while (this.current_ < n && this.state === State.EXECUTING) {
/** @type {ICommand} */ var cmd = cmds[this.current_];
/** @type {EventTarget} */ var cmdEvents = null;
if (cmd.isAsync) {
cmdEvents = /** @type {EventTarget} */ (cmd);
cmdEvents.listenOnce(EventType.EXECUTED, this.onCommandExecuted_, false, this);
}
var success = false;
try {
success = cmd.execute();
if (!success) {
this.updateCurrentCommandDetails_();
}
} catch (e) {
this.details = 'Error executing command ' + cmd.title + ': ' + String(e);
}
if (!success) {
if (cmdEvents) {
cmdEvents.unlisten(EventType.EXECUTED, this.onCommandExecuted_, false, this);
}
this.state = State.ERROR;
this.dispatchEvent(new GoogEvent(EventType.EXECUTED));
return false;
}
if (cmd.isAsync) {
return true;
}
this.current_++;
}
this.state = State.SUCCESS;
this.details = null;
this.dispatchEvent(new GoogEvent(EventType.EXECUTED));
return true;
}
/**
* Handle command executed.
*
* @private
*/
onCommandExecuted_() {
if (this.state !== State.EXECUTING) {
return;
}
this.updateCurrentCommandDetails_();
/** @type {ICommand} */
var cmd = this.getCommands()[this.current_];
if (cmd.state !== State.SUCCESS) {
this.state = State.ERROR;
this.dispatchEvent(new GoogEvent(EventType.EXECUTED));
return;
}
this.current_++;
Timer.callOnce(this.execute_.bind(this));
}
/**
* Begin the revert event loop.
*
* @return {boolean} true if successful, false if not
* @private
*/
revert_() {
while (this.current_ > -1 && this.state === State.REVERTING) {
/** @type {ICommand} */
var cmd = this.getCommands()[this.current_];
/** @type {EventTarget} */
var cmdEvents = null;
if (cmd.isAsync) {
cmdEvents = /** @type {EventTarget} */ (cmd);
cmdEvents.listenOnce(EventType.REVERTED, this.onCommandReverted_, false, this);
}
var success = false;
try {
success = cmd.revert();
if (!success) {
this.updateCurrentCommandDetails_();
}
} catch (e) {
this.details = 'Error reverting command ' + cmd.title + ': ' + String(e);
}
if (!success) {
this.state = State.ERROR;
this.dispatchEvent(new GoogEvent(EventType.REVERTED));
return false;
}
if (cmd.isAsync) {
return true;
}
this.current_--;
}
this.current_ = 0;
this.state = State.READY;
this.details = null;
this.dispatchEvent(new GoogEvent(EventType.REVERTED));
return true;
}
/**
* Handle command reverted.
*
* @private
*/
onCommandReverted_() {
if (this.state !== State.REVERTING) {
return;
}
this.updateCurrentCommandDetails_();
/** @type {ICommand} */
var cmd = this.getCommands()[this.current_];
if (cmd.state !== State.READY) {
this.state = State.ERROR;
this.dispatchEvent(new GoogEvent(EventType.REVERTED));
return;
}
this.current_--;
Timer.callOnce(this.revert_.bind(this));
}
/**
* Set the details message appropriately for the current command state and the state of
* the currently running command.
*
* @private
*/
updateCurrentCommandDetails_() {
var command = this.getCommands()[this.current_];
if (this.state === State.EXECUTING) {
if (command.state === State.ERROR) {
this.details = command.details ||
('Command ' + (command.title || this.title + '[' + this.current_ + ']') + ' failed');
} else {
this.details = 'Executing';
}
} else if (this.state === State.REVERTING) {
if (command.state === State.ERROR) {
this.details = command.details ||
('Reverting command ' + (command.title || this.title + '[' + this.current_ + ']') + ' failed');
} else {
this.details = 'Reverting';
}
} else {
this.details = null;
return;
}
}
} |
JavaScript | class PackageStats {
/**
* Create a new PackageStats object
* @param {string} directory path to the package-json files
* @param {{file: string, stat: fs.Stats}[]} files files and stats in this package
*/
constructor (directory, files) {
/**
* @type {string}
*/
this.directory = directory
/**
* @type {{file: string, stat: fs.Stats}[]}
*/
this.files = files
}
totalByteSize () {
if (!this._totalByteSize) {
this._totalByteSize = this.files.reduce((result, file) => result + file.stat.size, 0)
}
return this._totalByteSize
}
totalBlockSize () {
if (!this._totalBlockSize) {
this._totalBlockSize = this.files.reduce((result, file) => {
const blksize = file.stat.blksize || 4096 // On NTFS, the blksize is NaN (#5). In order to get a result at all, we assume 4kb for NaN and 0.
return result + Math.ceil(file.stat.size / blksize) * blksize
}, 0)
}
return this._totalBlockSize
}
/**
* Returns a new PackageStats-object with the same directory
* and the union of all files in this package and the other packages
* @param {PackageStats[]} packages
*/
merge (packages) {
var uniq = {}
// Merge files
this.files.forEach(file => { uniq[file.file] = file })
packages.forEach(pkg => {
pkg.files.forEach(file => { uniq[file.file] = file })
})
// Recreate file array
var files = Object.keys(uniq).map((key) => uniq[key])
return new PackageStats(this.directory, files)
}
/**
* Create PackageStats from the location of a package.json file
*
* @param packageJsonPath path to the package.json file
* @param {Promise<object>|object=} packageJson the parse package.json file,
* either directly or as Promise
* @return {Promise<PackageStats>} a promise for the PackageStats object
*/
static loadFrom (packageJsonPath, packageJson = {}) {
const directory = path.dirname(packageJsonPath)
return Promise.resolve(packageJson)
.then((packageJson) => validFiles(directory, packageJson))
// Add the directory itself
.then(files => files.map((file) => path.normalize(file)))
// Gather stats
.then(files => files.map(file => {
return {
file: path.join(directory, file),
stat: stat(path.join(directory, file))
}
}))
// Wait for promises
.then(deep)
// create PackageStats-object
.then((files) => new PackageStats(directory, files))
}
} |
JavaScript | class LoadJSON extends React.PureComponent {
constructor(props) {
super(props);
this.state = { loaded: false };
this.onLoad = this._onLoad.bind(this);
}
componentDidMount() {
this._load(this.props.path);
}
componentWillReceiveProps(props) {
// reload only if path changes
if (this.props.path !== props.path) {
this.setState({ loaded: false });
this._load(props.path);
}
}
render() {
if (!this.state.loaded) return null;
return React.createElement(
'div',
null,
embedProps(this.props.children, { sigma: this.props.sigma })
);
}
_load(url) {
sigma.parsers.json(this.props.path, this.props.sigma, this.onLoad);
}
_onLoad() {
if (this.props.sigma) this.props.sigma.refresh();
this.setState({ loaded: true });
if (this.props.onGraphLoaded) return this.props.onGraphLoaded();
}
} |
JavaScript | class SimpleSearchMatch extends LitElement {
static get tag() {
return "simple-search-match";
}
static get properties() {
return {
...super.properties,
matchNumber: {
type: Number,
reflect: true,
attribute: "match-number"
}
};
}
// render function
static get styles() {
return [
css`
:host {
margin-right: 4px;
font-family: var(--simple-search-match-font-family, unset);
color: var(--simple-search-match-text-color, #000);
background-color: var(--simple-search-match-bg-color, #f0f0f0);
border: var(--simple-search-match-border, 1px solid);
border-color: var(--simple-search-match-border-color, #ddd);
padding: var(--simple-search-match-padding, 0.16px 0px 0.16px 4px);
border-radius: var(--simple-search-match-border-radius, 0.16px);
font-weight: var(--simple-search-match-font-weight, bold);
}
`
];
}
render() {
return html`
<slot></slot>
`;
}
} |
JavaScript | class AuthService {
// get user data
getProfile() {
return decode(this.getToken());
}
// Check if user's logged in
isLoggedIn() {
// Checks if there is a saved token and whether or not it's still valid
const token = this.getToken();
return token && !this.isTokenExpired(token) ? true : false;
}
isTokenExpired(token) {
const decoded = decode(token);
if(decoded.exp < Date.now() / 1000) {
localStorage.removeItem('id_token');
return true;
}
return false;
}
getToken() {
return localStorage.getItem('id_token');
}
login(idToken) {
localStorage.setItem('id_token', idToken);
window.location.assign('/');
}
logout() {
localStorage.removeItem('id_token');
window.location.assign('/');
}
} |
JavaScript | class Categoria extends Component {
constructor(props) {
super(props);
this.state = {
descripcion: "",
errors: {},
disabled: false,
codigo: ""
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.onCheck = this.onCheck.bind(this);
}
componentDidMount() {
console.log("Inicalizando variables")
//componentDidMount() {
}
componentWillReceiveProps(nextProps) {
if (nextProps) {
this.setState({ errors: nextProps.errors });
}
}
onSubmit(e) {
e.preventDefault();
const tipoData = {
descripcion: this.state.descripcion,
codigo: this.state.codigo
};
this.props.addCategoria(tipoData, this.props.history);
//this.props.addTipos(tipoData, this.props._id);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onCheck(e) {
this.setState({
disabled: !this.state.disabled,
descripcion: !this.state.descripcion
});
}
render() {
const { errors } = this.state;
return (
<div className="App">
<h5 className="align center" >Operaciones Categorias</h5>
<div className="section container">
<form onSubmit={this.onSubmit} >
<TextInput
label="Codigo"
name="codigo"
value={this.state.codigo}
onChange={this.onChange}
error={errors.codigo}
/>
<TextInput
label="Descripcion"
name="descripcion"
value={this.state.descripcion}
onChange={this.onChange}
error={errors.descripcion}
/>
<Button type="submit" waves="light" className="btn-small blue">
Submit
<Icon >
lock
</Icon>
</Button>
</form>
</div>
</div>
);
}
} |
JavaScript | class StockNotationScreenerSearchMeta {
/**
* Constructs a new <code>StockNotationScreenerSearchMeta</code>.
* The meta member contains the meta information of the request.
* @alias module:model/StockNotationScreenerSearchMeta
*/
constructor() {
StockNotationScreenerSearchMeta.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>StockNotationScreenerSearchMeta</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/StockNotationScreenerSearchMeta} obj Optional instance to populate.
* @return {module:model/StockNotationScreenerSearchMeta} The populated <code>StockNotationScreenerSearchMeta</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new StockNotationScreenerSearchMeta();
if (data.hasOwnProperty('attributes')) {
obj['attributes'] = ApiClient.convertToType(data['attributes'], ['String']);
}
if (data.hasOwnProperty('language')) {
obj['language'] = ApiClient.convertToType(data['language'], 'String');
}
if (data.hasOwnProperty('sort')) {
obj['sort'] = ApiClient.convertToType(data['sort'], ['String']);
}
if (data.hasOwnProperty('pagination')) {
obj['pagination'] = StockNotationScreenerSearchMetaPagination.constructFromObject(data['pagination']);
}
}
return obj;
}
} |
JavaScript | class LotObject {
// ## constructor(prop)
constructor(prop) {
this.values = prop.value;
}
// ## get type()
get type() { return this.values[0]; }
set type(value) { this.values[0] = value; }
// ## get orientation()
get orientation() { return this.values[2]; }
set orientation(value) { this.values[2] = value; }
// ## get x()
get x() { return this.values[3]/scale; }
set x(value) { this.values[3] = Math.round(scale*value); }
// ## get y()
get y() { return this.values[4]/scale; }
set y(value) { this.values[4] = Math.round(scale*value); }
// ## get z()
get z() { return this.values[5]/scale; }
set z(value) { this.values[5] = Math.round(scale*value); }
get minX() { return signed(this.values[6])/scale; }
get minZ() { return signed(this.values[7])/scale; }
get maxX() { return signed(this.values[8])/scale; }
get maxZ() { return signed(this.values[9])/scale; }
get usage() { return this.values[10]; }
// ## get OID()
// The Object id is rep 12. The wiki says about this:
// 0xA0000000 = 0,2,4,6,8,a,c,e - Random one of these characters in case
// the other ID's are the same.
// 0x0BBBB000 = Object Family
// 0x00000CCC = Unique Object ID for this family. Incremental for similar
// objects.
get OID() {
return this.values[11];
}
// ## get IID()
get IID() {
return this.values[12];
}
// ## get IIDs()
// Note: every rep starting from 13 can be an IID, that's another way to
// create families. We should take this into account as well hence.
get IIDs() {
return this.values.slice(12);
}
} |
JavaScript | class Filters {
constructor(ctx) {
this.ctx = ctx
this.w = ctx.w
}
// create a re-usable filter which can be appended other filter effects and applied to multiple elements
getDefaultFilter(el, i) {
const w = this.w
el.unfilter(true)
let filter = new window.SVG.Filter()
filter.size('120%', '180%', '-5%', '-40%')
if (w.config.states.normal.filter !== 'none') {
this.applyFilter(
el,
i,
w.config.states.normal.filter.type,
w.config.states.normal.filter.value
)
} else {
if (w.config.chart.dropShadow.enabled) {
this.dropShadow(el, w.config.chart.dropShadow, i)
}
}
}
addNormalFilter(el, i) {
const w = this.w
if (w.config.chart.dropShadow.enabled) {
this.dropShadow(el, w.config.chart.dropShadow, i)
}
}
// appends dropShadow to the filter object which can be chained with other filter effects
addLightenFilter(el, i, attrs) {
const w = this.w
const { intensity } = attrs
if (Utils.isFirefox()) {
return
}
el.unfilter(true)
let filter = new window.SVG.Filter()
filter.size('120%', '180%', '-5%', '-40%')
el.filter((add) => {
const shadowAttr = w.config.chart.dropShadow
if (shadowAttr.enabled) {
filter = this.addShadow(add, i, shadowAttr)
} else {
filter = add
}
filter.componentTransfer({
rgb: { type: 'linear', slope: 1.5, intercept: intensity }
})
})
el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse')
}
// appends dropShadow to the filter object which can be chained with other filter effects
addDarkenFilter(el, i, attrs) {
const w = this.w
const { intensity } = attrs
if (Utils.isFirefox()) {
return
}
el.unfilter(true)
let filter = new window.SVG.Filter()
filter.size('120%', '180%', '-5%', '-40%')
el.filter((add) => {
const shadowAttr = w.config.chart.dropShadow
if (shadowAttr.enabled) {
filter = this.addShadow(add, i, shadowAttr)
} else {
filter = add
}
filter.componentTransfer({
rgb: { type: 'linear', slope: intensity }
})
})
el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse')
}
applyFilter(el, i, filter, intensity = 0.5) {
switch (filter) {
case 'none': {
this.addNormalFilter(el, i)
break
}
case 'lighten': {
this.addLightenFilter(el, i, {
intensity
})
break
}
case 'darken': {
this.addDarkenFilter(el, i, {
intensity
})
break
}
default:
// do nothing
break
}
}
// appends dropShadow to the filter object which can be chained with other filter effects
addShadow(add, i, attrs) {
const { blur, top, left, color, opacity } = attrs
let shadowBlur = add
.flood(Array.isArray(color) ? color[i] : color, opacity)
.composite(add.sourceAlpha, 'in')
.offset(left, top)
.gaussianBlur(blur)
.merge(add.source)
return add.blend(add.source, shadowBlur)
}
// directly adds dropShadow to the element and returns the same element.
// the only way it is different from the addShadow() function is that addShadow is chainable to other filters, while this function discards all filters and add dropShadow
dropShadow(el, attrs, i = 0) {
let { top, left, blur, color, opacity, noUserSpaceOnUse } = attrs
el.unfilter(true)
color = Array.isArray(color) ? color[i] : color
let filter = new window.SVG.Filter()
filter.size('120%', '180%', '-5%', '-40%')
el.filter(function(add) {
let shadowBlur = null
if (Utils.isSafari() || Utils.isFirefox() || Utils.isIE()) {
// safari/firefox has some alternative way to use this filter
shadowBlur = add
.flood(color, opacity)
.composite(add.sourceAlpha, 'in')
.offset(left, top)
.gaussianBlur(blur)
} else {
shadowBlur = add
.flood(color, opacity)
.composite(add.sourceAlpha, 'in')
.offset(left, top)
.gaussianBlur(blur)
.merge(add.source)
}
add.blend(add.source, shadowBlur)
})
if (!noUserSpaceOnUse) {
el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse')
}
return el
}
setSelectionFilter(el, realIndex, dataPointIndex) {
const w = this.w
if (typeof w.globals.selectedDataPoints[realIndex] !== 'undefined') {
if (
w.globals.selectedDataPoints[realIndex].indexOf(dataPointIndex) > -1
) {
el.node.setAttribute('selected', true)
let activeFilter = w.config.states.active.filter
if (activeFilter !== 'none') {
this.applyFilter(el, realIndex, activeFilter.type, activeFilter.value)
}
}
}
}
} |
JavaScript | class Satelite {
constructor(id, satname, intDesignator = "", launchDate = "", satlat = "", satlng = "", satalt = "") {
this.satid = id;
this.satname = satname;
this.intDesignator = intDesignator;
this.launchDate = launchDate;
this.satlat = satlat;
this.satlng = satlng;
this.satalt = satalt;
this.changeName = function (name) {
this.satname = name;
};
this.SatDesignation = function () {
return this.satname + " (" + this.id + ")";
};
}
} |
JavaScript | class Satelite {
constructor(id, satname, intDesignator = "", launchDate = "", satlat = "", satlng = "", satalt = "") {
this.satid = id;
this.satname = satname;
this.intDesignator = intDesignator;
this.launchDate = launchDate;
this.satlat = satlat;
this.satlng = satlng;
this.satalt = satalt;
this.changeName = function (name) {
this.satname = name;
};
this.SatDesignation = function () {
return this.satname + " (" + this.id + ")";
};
}
} |
JavaScript | class TestUtility {
/**
* Set's a basic DOM structure to test in
*/
setDOM = (divClass) => {
this.clear();
const wrapperDOM = document.createElement('div');
wrapperDOM.setAttribute("id", "root");
const keyboardDOM = document.createElement('div');
keyboardDOM.className = divClass || "simple-keyboard";
wrapperDOM.appendChild(keyboardDOM);
document.body.appendChild(wrapperDOM);
}
/**
* Clears DOM structure
*/
clear = () => {
document.body.innerHTML = "";
}
/**
* Test if standard buttons respect maxLength and do input a value
*/
testLayoutStdButtons = (keyboard) => {
let stdBtnCount = 0;
let fullInput = '';
this.iterateButtons((button) => {
let label = button.getAttribute("data-skbtn");
if(label.includes("{"))
return false;
// Click all standard buttons, respects maxLength
button.onclick();
// Recording fullInput, bypasses maxLength
fullInput = keyboard.utilities.getUpdatedInput(label, fullInput, keyboard.options, null);
stdBtnCount += label.length;
});
/**
* Check if maxLength is respected
*/
if(
(
typeof keyboard.options.maxLength === "object" &&
keyboard.getInput().length !== keyboard.options.maxLength[keyboard.options.layoutName]
) ||
(
typeof keyboard.options.maxLength !== "object" &&
keyboard.getInput().length !== keyboard.options.maxLength
)
)
throw new Error("MAX_LENGTH_ISSUE");
else
console.log("MAX_LENGTH PASSED:", keyboard.options.layoutName, keyboard.getInput().length, keyboard.options.maxLength);
/**
* Check if all standard buttons are inputting something
* (Regardless of maxLength)
*/
if(stdBtnCount !== fullInput.length)
throw new Error("STANDARD_BUTTONS_ISSUE");
else
console.log("STANDARD_BUTTONS PASSED:", keyboard.options.layoutName, stdBtnCount, fullInput.length);
}
/**
* Test if function buttons are interactive (have an onclick)
*/
testLayoutFctButtons = (callback) => {
let fctBtnCount = 0;
let fctBtnHasOnclickCount = 0;
this.iterateButtons((button) => {
let label = button.getAttribute("data-skbtn");
if(!label.includes("{") && !label.includes("}"))
return false;
fctBtnCount++;
if(button.onclick){
button.onclick();
fctBtnHasOnclickCount++;
}
callback(fctBtnCount, fctBtnHasOnclickCount);
});
}
/**
* Iterates on the keyboard buttons
*/
iterateButtons = (callback, selector) => {
let rows = document.body.querySelector(selector || '.simple-keyboard').children;
Array.from(rows).forEach(row => {
Array.from(row.children).forEach((button) => {
callback(button);
});
});
}
} |
JavaScript | class Wallet {
// Leave this as an empty constructor and generate the public Key and private Key when instantiating a new one
constructor(publicKey, privateKey) {
this.publicKey = publicKey
this.privateKey = privateKey
}
/**
* Generates a new wallet
*
* @return {Wallet} A new digital wallet
*/
static generateWallet() { }
get address() {
return this.publicKey
}
get [Symbol.for('version')]() {
return VERSION
}
balance(ledger) {
return /*#__PURE__*/ computeBalance(this.address)([...ledger])
}
[Symbol.for('toJSON')]() {
return JSON.stringify({
address: this.publicKey,
version: VERSION
}
)
}
} |
JavaScript | class X12EnvelopeSettings {
/**
* Create a X12EnvelopeSettings.
* @property {number} controlStandardsId The controls standards id.
* @property {boolean} useControlStandardsIdAsRepetitionCharacter The value
* indicating whether to use control standards id as repetition character.
* @property {string} senderApplicationId The sender application id.
* @property {string} receiverApplicationId The receiver application id.
* @property {string} controlVersionNumber The control version number.
* @property {number} interchangeControlNumberLowerBound The interchange
* control number lower bound.
* @property {number} interchangeControlNumberUpperBound The interchange
* control number upper bound.
* @property {boolean} rolloverInterchangeControlNumber The value indicating
* whether to rollover interchange control number.
* @property {boolean} enableDefaultGroupHeaders The value indicating whether
* to enable default group headers.
* @property {string} [functionalGroupId] The functional group id.
* @property {number} groupControlNumberLowerBound The group control number
* lower bound.
* @property {number} groupControlNumberUpperBound The group control number
* upper bound.
* @property {boolean} rolloverGroupControlNumber The value indicating
* whether to rollover group control number.
* @property {string} groupHeaderAgencyCode The group header agency code.
* @property {string} groupHeaderVersion The group header version.
* @property {number} transactionSetControlNumberLowerBound The transaction
* set control number lower bound.
* @property {number} transactionSetControlNumberUpperBound The transaction
* set control number upper bound.
* @property {boolean} rolloverTransactionSetControlNumber The value
* indicating whether to rollover transaction set control number.
* @property {string} [transactionSetControlNumberPrefix] The transaction set
* control number prefix.
* @property {string} [transactionSetControlNumberSuffix] The transaction set
* control number suffix.
* @property {boolean} overwriteExistingTransactionSetControlNumber The value
* indicating whether to overwrite existing transaction set control number.
* @property {string} groupHeaderDateFormat The group header date format.
* Possible values include: 'NotSpecified', 'CCYYMMDD', 'YYMMDD'
* @property {string} groupHeaderTimeFormat The group header time format.
* Possible values include: 'NotSpecified', 'HHMM', 'HHMMSS', 'HHMMSSdd',
* 'HHMMSSd'
* @property {string} usageIndicator The usage indicator. Possible values
* include: 'NotSpecified', 'Test', 'Information', 'Production'
*/
constructor() {
}
/**
* Defines the metadata of X12EnvelopeSettings
*
* @returns {object} metadata of X12EnvelopeSettings
*
*/
mapper() {
return {
required: false,
serializedName: 'X12EnvelopeSettings',
type: {
name: 'Composite',
className: 'X12EnvelopeSettings',
modelProperties: {
controlStandardsId: {
required: true,
serializedName: 'controlStandardsId',
type: {
name: 'Number'
}
},
useControlStandardsIdAsRepetitionCharacter: {
required: true,
serializedName: 'useControlStandardsIdAsRepetitionCharacter',
type: {
name: 'Boolean'
}
},
senderApplicationId: {
required: true,
serializedName: 'senderApplicationId',
type: {
name: 'String'
}
},
receiverApplicationId: {
required: true,
serializedName: 'receiverApplicationId',
type: {
name: 'String'
}
},
controlVersionNumber: {
required: true,
serializedName: 'controlVersionNumber',
type: {
name: 'String'
}
},
interchangeControlNumberLowerBound: {
required: true,
serializedName: 'interchangeControlNumberLowerBound',
type: {
name: 'Number'
}
},
interchangeControlNumberUpperBound: {
required: true,
serializedName: 'interchangeControlNumberUpperBound',
type: {
name: 'Number'
}
},
rolloverInterchangeControlNumber: {
required: true,
serializedName: 'rolloverInterchangeControlNumber',
type: {
name: 'Boolean'
}
},
enableDefaultGroupHeaders: {
required: true,
serializedName: 'enableDefaultGroupHeaders',
type: {
name: 'Boolean'
}
},
functionalGroupId: {
required: false,
serializedName: 'functionalGroupId',
type: {
name: 'String'
}
},
groupControlNumberLowerBound: {
required: true,
serializedName: 'groupControlNumberLowerBound',
type: {
name: 'Number'
}
},
groupControlNumberUpperBound: {
required: true,
serializedName: 'groupControlNumberUpperBound',
type: {
name: 'Number'
}
},
rolloverGroupControlNumber: {
required: true,
serializedName: 'rolloverGroupControlNumber',
type: {
name: 'Boolean'
}
},
groupHeaderAgencyCode: {
required: true,
serializedName: 'groupHeaderAgencyCode',
type: {
name: 'String'
}
},
groupHeaderVersion: {
required: true,
serializedName: 'groupHeaderVersion',
type: {
name: 'String'
}
},
transactionSetControlNumberLowerBound: {
required: true,
serializedName: 'transactionSetControlNumberLowerBound',
type: {
name: 'Number'
}
},
transactionSetControlNumberUpperBound: {
required: true,
serializedName: 'transactionSetControlNumberUpperBound',
type: {
name: 'Number'
}
},
rolloverTransactionSetControlNumber: {
required: true,
serializedName: 'rolloverTransactionSetControlNumber',
type: {
name: 'Boolean'
}
},
transactionSetControlNumberPrefix: {
required: false,
serializedName: 'transactionSetControlNumberPrefix',
type: {
name: 'String'
}
},
transactionSetControlNumberSuffix: {
required: false,
serializedName: 'transactionSetControlNumberSuffix',
type: {
name: 'String'
}
},
overwriteExistingTransactionSetControlNumber: {
required: true,
serializedName: 'overwriteExistingTransactionSetControlNumber',
type: {
name: 'Boolean'
}
},
groupHeaderDateFormat: {
required: true,
serializedName: 'groupHeaderDateFormat',
type: {
name: 'String'
}
},
groupHeaderTimeFormat: {
required: true,
serializedName: 'groupHeaderTimeFormat',
type: {
name: 'String'
}
},
usageIndicator: {
required: true,
serializedName: 'usageIndicator',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class SamplerArray2DArray{
/**
* Creates object.
* @param {Number} size - The number of Sampler2DArray elements in the array.
*/
constructor(size){
this.length = size;
this.storage = new Int32Array(size);
for(let i=0; i<size; i++){
const element = Object.create(Sampler2DArray.prototype);
element.glTexture = null;
element.storage = this.storage.subarray(i, (i+1));
Object.defineProperty(this, i, {value: element} );
}
}
/**
* @method at
* @memberof SamplerArray2DArray
* @description Returns a Sampler2D object that captures an element of the array. The sampler is a view on the original data, not a copy.
* @param index {Number} - Index of the element.
* @return {SamplerCube} view on one of the array's elements
*/
at(index){
return this[index];
}
/**
* @method set
* @memberof SamplerArray2DArray
* @description Assigns textures.
* @param {Object[] | WebGLTexture[]} textureArray - An array of WebGL textures, or of objects with the `glTexture` property that stores a WebGL texture.
*/
set(textureArray){
for(let i=0; i<this.size; i++){
this[i].set(textureArray[ Math.min(i, textureArray.length) ]);
}
}
/**
* @method commit
* @memberof SamplerArray2DArray
* @description Specifies, to WebGL, the texture unit indices of all samplers in the array, and binds textures of the array elements.
* @param {WebGLRenderingContext} gl - rendering context
* @param {WebGLUniformLocation} uniformLocation - location of the uniform variable in the currently used WebGL program
* @param {Number} baseTextureUnit - The texture unit index of the first element. Other elements are assigned to texture units contiguously.
*/
commit(gl, uniformLocation, baseTextureUnit){
for(let i=0; i<this.length; i++) {
this.storage[i] = baseTextureUnit + i;
gl.activeTexture(gl.TEXTURE0 + baseTextureUnit + i);
gl.bindTexture(gl.TEXTURE_2D_ARRAY, this[i].glTexture);
}
gl.uniform1iv(uniformLocation, this.storage);
}
} |
JavaScript | class MeasureBaseline extends Component {
constructor(graphics) {
super(consts.componentNames.MEASURE_BASELINE, graphics);
/**
* Brush width
* @type {number}
* @private
*/
this._width = 20;
/**
* fabric.Color instance for brush color
* @type {fabric.Color}
* @private
*/
this._oColor = new fabric.Color('rgba(255, 112, 112, 0.8)');
this._pColor = new fabric.Color('rgba(255, 112, 112, 1)');
this._initialized = false;
this._initialPosition = graphics.measureInitPosition;
this._createBaselineObjects();
}
/**
* Start drawing line mode
* @param {{width: ?number, color: ?string}} [setting] - Brush width & color
*/
start() {
const canvas = this.getCanvas();
canvas.defaultCursor = 'default';
canvas.forEachObject(obj => {
obj.set({
evented: true
});
});
if (this._initialized) {
this.setVisible(true);
} else {
this._initialized = true;
this._createBaseline();
}
}
/**
* End drawing line mode
*/
end() {
}
setInit(initialPosition = {}) {
this._initialized = false;
this._initialPosition = initialPosition;
}
setVisible(flag) {
const canvas = this.getCanvas();
this._start.set({
visible: flag
});
this._end.set({
visible: flag
});
this._line.set({
visible: flag
});
// this._text.set({
// visible: flag
// });
canvas.renderAll();
}
_createBaselineObjects() {
const canvas = this.getCanvas();
const {width, height} = canvas;
const xlen = 300;
const ylen = 300;
if (this._initialized) {
if (this._initialPosition.width !== width ||
this._initialPosition.height !== height) {
this._initialPosition = {};
}
}
const {x1 = (width / 2) - xlen,
y1 = (height / 2) - ylen,
x2 = (width / 2) + xlen,
y2 = (height / 2) + ylen} = this._initialPosition;
const opts = {
originX: 'center',
originY: 'center',
lockScalingX: true,
lockScalingY: true,
lockUniScaling: true,
lockRotation: true,
hasBorders: false,
hasControls: false,
type: 'measure_baseline'
};
this._start = new fabric.Triangle(extend({
left: x1,
top: y1,
width: this._width * 3,
height: this._width * 3,
fill: this._pColor.toRgba(),
padding: this._width * 2
}, opts));
this._end = new fabric.Triangle(extend({
left: x2,
top: y2,
width: this._width * 3,
height: this._width * 3,
fill: this._pColor.toRgba(),
padding: this._width * 2,
angle: 180
}, opts));
const startPoint = this._start.getCenterPoint();
const endPoint = this._end.getCenterPoint();
const points = [startPoint.x, startPoint.y, endPoint.x, endPoint.y];
this._line = new fabric.Line(points, extend(opts, {
stroke: this._oColor.toRgba(),
strokeWidth: this._width,
hasBorders: true,
borderColor: 'rgba(255,255,255,0.5)',
borderScaleFactor: '5'
}));
this._line.start = this._start;
this._line.end = this._end;
canvas.add(this._line, this._start, this._end);
}
_createBaseline() {
const canvas = this.getCanvas();
this._createBaselineObjects();
const startPoint = this._start.getCenterPoint();
const endPoint = this._end.getCenterPoint();
this._moveTriangle(startPoint, endPoint);
const param1 = this.graphics.createObjectProperties(this._line);
const param2 = this.graphics.createObjectProperties(this._start);
const param3 = this.graphics.createObjectProperties(this._end);
this.fire(eventNames.ADD_OBJECT, param1);
this.fire(eventNames.ADD_OBJECT, param2);
this.fire(eventNames.ADD_OBJECT, param3);
const self = this;
this._start.on({
moving(fEvent) {
const pointer = canvas.getPointer(fEvent.e);
const endPointer = {
x: self._end.left,
y: self._end.top
};
self._moveTriangle(pointer, endPointer);
},
moved() {
self.recalcMeasurelines();
}
});
this._end.on({
moving(fEvent) {
const pointer = canvas.getPointer(fEvent.e);
const startPointer = {
x: self._start.left,
y: self._start.top
};
self._moveTriangle(startPointer, pointer);
},
moved() {
self.recalcMeasurelines();
}
});
this._line.on({
moving() {
const line = self._line;
const oldCenterX = (line.x1 + line.x2) / 2;
const oldCenterY = (line.y1 + line.y2) / 2;
const deltaX = line.left - oldCenterX;
const deltaY = line.top - oldCenterY;
const startPointer = {
x: line.x1 + deltaX,
y: line.y1 + deltaY
};
const endPointer = {
x: line.x2 + deltaX,
y: line.y2 + deltaY
};
self._moveTriangle(startPointer, endPointer);
},
moved() {
self.recalcMeasurelines();
canvas.discardActiveObject();
canvas.renderAll();
}
});
}
recalcMeasurelines() {
const {length} = this.getBaseline();
this.graphics.recalcMeasurelines(length);
}
getBaseline() {
const {x1, y1, x2, y2} = this._line;
const length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) + (this._width * 3);
const canvas = this.getCanvas();
const {width, height} = canvas;
return {
x1,
y1,
x2,
y2,
length,
width,
height
};
}
_moveTriangle(start, end) {
const canvas = this.getCanvas();
const angle = (Math.atan2((end.y - start.y), (end.x - start.x)) * 180) / Math.PI;
this._start.set({
left: start.x,
top: start.y,
angle: angle - 90
});
this._end.set({
left: end.x,
top: end.y,
angle: angle + 90
});
this._line.set({
x1: start.x,
y1: start.y,
x2: end.x,
y2: end.y
});
this._start.setCoords();
this._end.setCoords();
this._line.setCoords();
canvas.renderAll();
}
} |
JavaScript | class World {
/**
Constructor takes parems that allow to override default values.
@param params object to override world defaults - all properties are copied to world properties
*/
constructor(params) {
/** World name, default null */
this.name = null;
/** Base URL of related content, default "" (current location) */
this.baseUrl = "";
/** World scene file name to load, default scene.gltf */
this.file = "scene.gltf";
/** World objects to load, default null */
this.worldObjects = null;
/** World objects json file, as saved by WorldEditor and AssetLoader, default null */
this.objectsFile = null;
/** Wheter gravity is enabled, default true */
this.gravityEnabled = true;
/** Wheter collisions are enabled, default true */
this.collisionsEnabled = true;
/** Progress indicator */
this.indicator = null;
/** Progress indicator functon */
this.onProgress = null;
/** Handy reference to VRSpaceUI */
this.VRSPACEUI = VRSPACEUI;
/** Reference to worldManager, set by WorldManager once that user goes online */
this.worldManager = null;
// now override defaults
if ( params ) {
for ( var param in params ) {
this[param] = params[param];
}
}
}
/** Create, load and and show the world.
Enables gravity and collisions, then executes createScene method, optionally creates load indicator,
registers render loop, crates terrain, and finally, executes load method. Every method executed can be overridden.
@param engine babylonjs engine
@param name world name
@param scene babylonjs scene, optional
@param callback to execute after the world has loaded
@param baseUrl folder to load scene from, default "", used only if not defined in constructor
@param file scene file to load, default scene.gltf, used only if not defined in constructor
@returns final scene
*/
async init(engine, name, scene, callback, baseUrl, file) {
this.canvas = engine.getInputElement();
this.engine = engine;
if ( name ) {
this.name = name;
}
this.scene = scene;
this.vrHelper = null;
if ( !this.baseUrl && baseUrl ) {
this.baseUrl = baseUrl;
}
if ( !this.file && file ) {
this.file = file;
}
await this.createScene(engine);
if ( ! this.onProgress ) {
this.indicator = VRSPACEUI.loadProgressIndicator(this.scene, this.camera);
this.onProgress = (evt, name) => this.indicator.progress( evt, name )
}
this.registerRenderLoop();
this.createTerrain();
this.load(callback);
return this.scene;
}
/**
Called from init.
If the scene does not exist, creates the scene first.
Then calls methods in this order:
createCamera, attachControl, createLights, createShadows, createSkybox, createGround, createEffects, createPhysics.
*/
async createScene(engine) {
if ( ! this.scene ) {
this.scene = new BABYLON.Scene(engine);
}
// TODO dispose of old camera(s)
var camera = await this.createCamera();
if ( camera ) {
this.camera = camera;
}
this.attachControl();
// TODO dispose of old lights
var light = await this.createLights();
if ( light ) {
this.light = light;
}
// TODO dispose of old shadow generator
var shadowGenerator = await this.createShadows();
if ( shadowGenerator ) {
this.shadowGenerator = shadowGenerator;
}
// TODO dispose of old skybox
var skyBox = await this.createSkyBox();
if ( skyBox ) {
this.skyBox = skyBox;
}
// TODO dispose of old ground
var ground = await this.createGround();
if ( ground ) {
this.ground = ground;
}
await this.createEffects();
await this.createPhysics();
}
/** An implementation must override this method and define at least one camera */
async createCamera() {
alert( 'Please override createCamera() method')
}
/** Optional, empty implementation, called from createScene. May return a Light */
async createLights() {}
/** Optional, empty implementation, called from createScene. Should return a ShadowGenerator. */
async createShadows() {}
/** Optional, empty implementation, called from createScene. Should return a sky Box. */
async createSkyBox() {}
/** Optional, empty implementation, called from createScene. Should return a mesh. */
async createGround() {}
/** Optional, empty implementation, called from createScene */
async createEffects() {};
/** Optional, empty implementation, called from createScene */
async createPhysics() {};
/** Optional, empty implementation, called from createScene */
async createTerrain() {}
/** Attach the control to the camera, called from createScene. */
attachControl() {
this.camera.attachControl(this.canvas, true);
}
/**
Optional, empty implementation, notification that the user has entered a multiuser world.
*/
async entered(welcome) {
}
/** */
/**
Utility method, creates a UniversalCamera and sets defaults: gravity, collisions, ellipsoid, keys.
@param pos Vector3 to position camera at
@param name optional camera name, default UniversalCamera
*/
universalCamera(pos, name) {
if ( !name ) {
name = "UniversalCamera";
}
var camera = new BABYLON.UniversalCamera(name, pos, this.scene);
camera.maxZ = 100000;
camera.minZ = 0;
camera.applyGravity = true;
camera.speed = 0.2;
// 1.8 m high:
camera.ellipsoid = new BABYLON.Vector3(.5, .9, .5);
// eyes at 1.6 m:
camera.ellipsoidOffset = new BABYLON.Vector3(0, .2, 0);
camera.checkCollisions = true;
camera.keysDown = [40, 83]; // down, S
camera.keysLeft = [37, 65]; // left, A
camera.keysRight = [39, 68]; // right, D
camera.keysUp = [38, 87]; // up, W
camera.keysUpward = [36, 33, 32]; // home, pgup, space
camera.touchAngularSensitivity = 5000;
return camera;
}
/**
Disposes of all objects returned by createLights, createCamera, createShadows, createSkybox
*/
async dispose() {
if ( this.camera ) {
this.camera.dispose();
this.camera = null;
}
if ( this.skyBox ) {
this.skyBox.dispose();
this.skyBox.material.dispose();
this.skyBox = null;
}
if ( this.light ) {
this.light.dispose();
this.light = null;
}
if ( this.shadowGenerator ) {
this.shadowGenerator.dispose();
this.shadowGenerator = null;
}
}
/** Creates a VRHelper if needed, and initializes it with the current world.
Normally called after world is loaded.
@param vrHelper optional existing vrHelper
*/
initXR(vrHelper) {
if ( vrHelper ) {
this.vrHelper = vrHelper;
}
if ( ! this.vrHelper ) {
this.vrHelper = new VRHelper();
}
this.vrHelper.initXR(this);
}
trackXrDevices() {
}
/**
Used in mesh selection predicate. Default implementation returns true for members of this.floorMeshes.
*/
isSelectableMesh(mesh) {
return this.floorMeshes && this.floorMeshes.includes(mesh);
}
/**
Returns this.floorMeshes or this.ground if exist, or empty array.
*/
getFloorMeshes() {
if ( this.floorMeshes ) {
return this.floorMeshes;
} else if ( this.ground ) {
return [ this.ground ];
}
return [];
}
/**
Enables or disables collisions in the world. This includes floorMeshes, sceneMeshes, and also applying gravity to camera.
@param state true or false
*/
collisions(state) {
this._collisions( this.floorMeshes, this.collisionsEnabled && state );
this._collisions( this.sceneMeshes, this.collisionsEnabled && state );
this.camera.applyGravity = this.gravityEnabled && state;
this.camera._needMoveForGravity = this.gravityEnabled && state;
}
/**
Utility method, enables or disables collisions on the given set of meshes.
@param meshes array of meshes
@param state true or false
*/
_collisions( meshes, state ) {
if ( meshes ) {
for ( var i=0; i<meshes.length; i++ ) {
this.setMeshCollisions( meshes[i], state );
}
}
}
/**
Enable or disable collisions for a mesh. Override to fine-tune collisions.
@param mesh
@param state
*/
setMeshCollisions(mesh, state) {
mesh.checkCollisions = state;
}
/**
Called on loading progress, executes whatever this.onProgress contains, by default LoadProgressListener.
@param evt
@param name
*/
loadProgress( evt, name ) {
if ( this.onProgress ) {
this.onProgress( evt, name );
}
}
/**
Called if loading the world fails. Passes the exception to this.onFailure handler if it exists,
otherwise logs it to the console.
@param exception whatever caused loading to fail
*/
loadFailed( exception ) {
if (this.onFailure) {
this.onFailure( exception );
} else {
console.log( "Error loading world "+this.name, exception);
}
if ( this.indicator ) {
this.indicator.remove(this.name);
}
}
/**
Called when loading starts. Calls this.indicator.add if available.
@param name
*/
loadingStart(name) {
if ( this.indicator ) {
this.indicator.add(name);
}
}
/**
Called when loading finishes. Calls this.indicator.remove if available.
@param name
*/
loadingStop(name) {
if ( this.indicator ) {
this.indicator.remove(name);
}
}
/** Load the world, then execute given callback passing self as argument.
Loads an AssetContainer from file specified by this.file, if any (by default scene.gltf), and adds it to the scene.
Then loads all world objects specified in this.objectsFile or this.worldObjects, if any - file takes precedence.
Takes care of loading progress.
Calls loadingStart, loaded, loadingStop, collisions - each may be overridden.
@param callback to execute after the content has loaded
@returns world object
*/
async load(callback) {
this.loadingStart(this.name);
var promises = [];
if ( this.file ) {
var scenePromise = VRSPACEUI.assetLoader.loadAsset( this.baseUrl+this.file,
// onSuccess:
(container) => {
this.sceneMeshes = container.meshes;
this.container = container;
// Adds all elements to the scene
var mesh = container.createRootMesh();
mesh.name = this.name;
container.addAllToScene();
this.loaded( this.file, mesh );
},
// onError:
exception => this.loadFailed( exception ),
// onProgress:
evt => this.loadProgress(evt, this.name)
);
promises.push(scenePromise);
}
if ( this.objectsFile ) {
var response = await fetch(this.baseUrl+this.objectsFile);
var json = response.json();
this.worldObjects = JSON.parse(json);
}
if ( this.worldObjects ) {
for ( var url in this.worldObjects ) {
var name = url;
var instances = this.worldObjects[url].instances;
if ( !url.startsWith("/") ) {
// relative url, make it relative to world script path
url = this.baseUrl+url;
}
instances.forEach( (instance) => {
var objPromise = VRSPACEUI.assetLoader.loadAsset(url,
// callback
(container,info,instances)=>{
if ( instances ) {
var mesh = obj.instantiatedEntries.rootNodes[0];
} else {
// Adds all elements to the scene
var mesh = container.createRootMesh();
mesh.name = name;
container.addAllToScene();
}
if ( instance.position ) {
mesh.position = new BABYLON.Vector3(instance.position.x, instance.position.y, instance.position.z);
}
if ( instance.rotation ) {
mesh.rotation = new BABYLON.Vector3(instance.rotation.x, instance.rotation.y, instance.rotation.z);
}
if ( instance.scale ) {
mesh.scaling = new BABYLON.Vector3(instance.scale.x, instance.scale.y, instance.scale.z);
}
},
// onError:
exception => this.loadFailed( exception ),
// onProgress:
evt => this.loadProgress(evt, name)
);
promises.push(objPromise);
});
}
}
Promise.all(promises).then(() => {
VRSPACEUI.log("World loaded");
this.loadingStop(this.name);
this.collisions(this.collisionsEnabled);
if ( callback ) {
callback(this);
}
});
return this;
}
/**
Called after assets are loaded. By default calls initXR().
Subclasses typically override this with some spatial manipulations, e.g. scaling the world.
Subclasses may, but are not required, call super.loaded()
@param file world file that has loaded
@param mesh root mesh of the world
*/
loaded( file, mesh ) {
this.initXR();
}
/** Register render loop. */
registerRenderLoop() {
// Register a render loop to repeatedly render the scene
var loop = () => {
if ( this.scene ) {
this.scene.render();
} else {
this.engine.stopRenderLoop(loop);
}
}
this.engine.runRenderLoop(loop);
}
/**
Utility method to fix the path and load the file, executes LoadAssetContainerAsync.
@param relativePath path relative to current world directory
@param file file name to load
*/
async loadAsset(relativePath, file) {
return VRSPACEUI.assetLoader.loadAsset(this.assetPath(relativePath)+file);
}
/**
Utility method, returns baseUrl+relativePath
@param relativePath path relative to current world directory
*/
assetPath(relativePath) {
return this.baseUrl+relativePath;
}
/**
Write some text to world chat. Usually text appears above avatar's head and/or in chat log,
but this method only sends own 'wrote' event.
@param text something to say
*/
write(text) {
if ( this.worldManager && text ) {
this.worldManager.sendMy({wrote:text});
}
}
} |
JavaScript | class DirectoryReader {
/**
* @param dir - The absolute or relative directory path to read
* @param [options] - User-specified options, if any (see `normalizeOptions()`)
* @param facade - sync or async function implementations
* @param emit - Indicates whether the reader should emit "file", "directory", and "symlink" events.
*/
constructor(dir, options, facade, emit = false) {
this.options = normalize_options_1.normalizeOptions(options, facade, emit);
// Indicates whether we should keep reading
// This is set false if stream.Readable.push() returns false.
this.shouldRead = true;
// The directories to read
// (initialized with the top-level directory)
this.queue = [{
path: dir,
basePath: this.options.basePath,
depth: 0
}];
// The number of directories that are currently being processed
this.pending = 0;
// The data that has been read, but not yet emitted
this.buffer = [];
this.stream = new stream_1.Readable({ objectMode: true });
this.stream._read = () => {
// Start (or resume) reading
this.shouldRead = true;
// If we have data in the buffer, then send the next chunk
if (this.buffer.length > 0) {
this.pushFromBuffer();
}
// If we have directories queued, then start processing the next one
if (this.queue.length > 0) {
this.readNextDirectory();
}
this.checkForEOF();
};
}
/**
* Reads the next directory in the queue
*/
readNextDirectory() {
let { facade } = this.options;
let dir = this.queue.shift();
this.pending++;
// Read the directory listing
call_1.safeCall(facade.fs.readdir, dir.path, (err, items) => {
if (err) {
// fs.readdir threw an error
this.emit("error", err);
return this.finishedReadingDirectory();
}
try {
// Process each item in the directory (simultaneously, if async)
facade.forEach(items, this.processItem.bind(this, dir), this.finishedReadingDirectory.bind(this, dir));
}
catch (err2) {
// facade.forEach threw an error
// (probably because fs.readdir returned an invalid result)
this.emit("error", err2);
this.finishedReadingDirectory();
}
});
}
/**
* This method is called after all items in a directory have been processed.
*
* NOTE: This does not necessarily mean that the reader is finished, since there may still
* be other directories queued or pending.
*/
finishedReadingDirectory() {
this.pending--;
if (this.shouldRead) {
// If we have directories queued, then start processing the next one
if (this.queue.length > 0) {
this.readNextDirectory();
}
this.checkForEOF();
}
}
/**
* Determines whether the reader has finished processing all items in all directories.
* If so, then the "end" event is fired (via {@Readable#push})
*/
checkForEOF() {
if (this.buffer.length === 0 && // The stuff we've already read
this.pending === 0 && // The stuff we're currently reading
this.queue.length === 0) { // The stuff we haven't read yet
// There's no more stuff!
this.stream.push(null);
}
}
/**
* Processes a single item in a directory.
*
* If the item is a directory, and `option.deep` is enabled, then the item will be added
* to the directory queue.
*
* If the item meets the filter criteria, then it will be emitted to the reader's stream.
*
* @param dir - A directory object from the queue
* @param item - The name of the item (name only, no path)
* @param done - A callback function that is called after the item has been processed
*/
processItem(dir, item, done) {
let stream = this.stream;
let options = this.options;
let itemPath = dir.basePath + item;
let fullPath = path.join(dir.path, item);
// If `options.deep` is a number, and we've already recursed to the max depth,
// then there's no need to check fs.Stats to know if it's a directory.
// If `options.deep` is a function, then we'll need fs.Stats
let maxDepthReached = dir.depth >= options.recurseDepth;
// Do we need to call `fs.stat`?
let needStats = !maxDepthReached || // we need the fs.Stats to know if it's a directory
options.stats || // the user wants fs.Stats objects returned
options.recurseFnNeedsStats || // we need fs.Stats for the recurse function
options.filterFnNeedsStats || // we need fs.Stats for the filter function
stream.listenerCount("file") || // we need the fs.Stats to know if it's a file
stream.listenerCount("directory") || // we need the fs.Stats to know if it's a directory
stream.listenerCount("symlink"); // we need the fs.Stats to know if it's a symlink
// If we don't need stats, then exit early
if (!needStats) {
if (this.filter({ path: itemPath })) {
this.pushOrBuffer({ data: itemPath });
}
return done();
}
// Get the fs.Stats object for this path
stat_1.stat(options.facade.fs, fullPath, (err, stats) => {
if (err) {
// fs.stat threw an error
this.emit("error", err);
return done();
}
try {
// Add the item's path to the fs.Stats object
// The base of this path, and its separators are determined by the options
// (i.e. options.basePath and options.sep)
stats.path = itemPath;
// Add depth of the path to the fs.Stats object for use this in the filter function
stats.depth = dir.depth;
if (this.shouldRecurse(stats, maxDepthReached)) {
// Add this subdirectory to the queue
this.queue.push({
path: fullPath,
basePath: itemPath + options.sep,
depth: dir.depth + 1,
});
}
// Determine whether this item matches the filter criteria
if (this.filter(stats)) {
this.pushOrBuffer({
data: options.stats ? stats : itemPath,
file: stats.isFile(),
directory: stats.isDirectory(),
symlink: stats.isSymbolicLink(),
});
}
done();
}
catch (err2) {
// An error occurred while processing the item
// (probably during a user-specified function, such as options.deep, options.filter, etc.)
this.emit("error", err2);
done();
}
});
}
/**
* Pushes the given chunk of data to the stream, or adds it to the buffer,
* depending on the state of the stream.
*/
pushOrBuffer(chunk) {
// Add the chunk to the buffer
this.buffer.push(chunk);
// If we're still reading, then immediately emit the next chunk in the buffer
// (which may or may not be the chunk that we just added)
if (this.shouldRead) {
this.pushFromBuffer();
}
}
/**
* Immediately pushes the next chunk in the buffer to the reader's stream.
* The "data" event will always be fired (via `Readable.push()`).
* In addition, the "file", "directory", and/or "symlink" events may be fired,
* depending on the type of properties of the chunk.
*/
pushFromBuffer() {
let stream = this.stream;
let chunk = this.buffer.shift();
// Stream the data
try {
this.shouldRead = stream.push(chunk.data);
}
catch (err) {
this.emit("error", err);
}
if (this.options.emit) {
// Also emit specific events, based on the type of chunk
chunk.file && this.emit("file", chunk.data);
chunk.symlink && this.emit("symlink", chunk.data);
chunk.directory && this.emit("directory", chunk.data);
}
}
/**
* Determines whether the given directory meets the user-specified recursion criteria.
* If the user didn't specify recursion criteria, then this function will default to true.
*
* @param stats - The directory's `Stats` object
* @param maxDepthReached - Whether we've already crawled the user-specified depth
*/
shouldRecurse(stats, maxDepthReached) {
let { recurseFn } = this.options;
if (maxDepthReached) {
// We've already crawled to the maximum depth. So no more recursion.
return false;
}
else if (!stats.isDirectory()) {
// It's not a directory. So don't try to crawl it.
return false;
}
else if (recurseFn) {
try {
// Run the user-specified recursion criteria
return !!recurseFn(stats);
}
catch (err) {
// An error occurred in the user's code.
// In Sync and Async modes, this will return an error.
// In Streaming mode, we emit an "error" event, but continue processing
this.emit("error", err);
}
}
else {
// No recursion function was specified, and we're within the maximum depth.
// So crawl this directory.
return true;
}
}
/**
* Determines whether the given item meets the user-specified filter criteria.
* If the user didn't specify a filter, then this function will always return true.
*
* @param stats - The item's `Stats` object, or an object with just a `path` property
*/
filter(stats) {
let { filterFn } = this.options;
if (filterFn) {
try {
// Run the user-specified filter function
return !!filterFn(stats);
}
catch (err) {
// An error occurred in the user's code.
// In Sync and Async modes, this will return an error.
// In Streaming mode, we emit an "error" event, but continue processing
this.emit("error", err);
}
}
else {
// No filter was specified, so match everything
return true;
}
}
/**
* Emits an event. If one of the event listeners throws an error,
* then an "error" event is emitted.
*/
emit(eventName, data) {
let stream = this.stream;
try {
stream.emit(eventName, data);
}
catch (err) {
if (eventName === "error") {
// Don't recursively emit "error" events.
// If the first one fails, then just throw
throw err;
}
else {
stream.emit("error", err);
}
}
}
} |
JavaScript | class Client {
/**
* Instantiate an FTP client.
*
* @param timeout Timeout in milliseconds, use 0 for no timeout. Optional, default is 30 seconds.
*/
constructor(timeout = 30000) {
/**
* Multiple commands to retrieve a directory listing are possible. This instance
* will try all of them in the order presented the first time a directory listing
* is requested. After that, `availableListCommands` will hold only the first
* entry that worked.
*/
this.availableListCommands = ["MLSD", "LIST -a", "LIST"];
this.ftp = new FtpContext_1.FTPContext(timeout);
this.prepareTransfer = this._enterFirstCompatibleMode([transfer_1.enterPassiveModeIPv6, transfer_1.enterPassiveModeIPv4]);
this.parseList = parseList_1.parseList;
this._progressTracker = new ProgressTracker_1.ProgressTracker();
}
/**
* Close the client and all open socket connections.
*
* Close the client and all open socket connections. The client can’t be used anymore after calling this method,
* you have to either reconnect with `access` or `connect` or instantiate a new instance to continue any work.
* A client is also closed automatically if any timeout or connection error occurs.
*/
close() {
this.ftp.close();
this._progressTracker.stop();
}
/**
* Returns true if the client is closed and can't be used anymore.
*/
get closed() {
return this.ftp.closed;
}
/**
* Connect (or reconnect) to an FTP server.
*
* This is an instance method and thus can be called multiple times during the lifecycle of a `Client`
* instance. Whenever you do, the client is reset with a new control connection. This also implies that
* you can reopen a `Client` instance that has been closed due to an error when reconnecting with this
* method. In fact, reconnecting is the only way to continue using a closed `Client`.
*
* @param host Host the client should connect to. Optional, default is "localhost".
* @param port Port the client should connect to. Optional, default is 21.
*/
connect(host = "localhost", port = 21) {
this.ftp.reset();
this.ftp.socket.connect({
host,
port,
family: this.ftp.ipFamily
}, () => this.ftp.log(`Connected to ${netUtils_1.describeAddress(this.ftp.socket)} (${netUtils_1.describeTLS(this.ftp.socket)})`));
return this._handleConnectResponse();
}
/**
* As `connect` but using implicit TLS. Implicit TLS is not an FTP standard and has been replaced by
* explicit TLS. There are still FTP servers that support only implicit TLS, though.
*/
connectImplicitTLS(host = "localhost", port = 21, tlsOptions = {}) {
this.ftp.reset();
this.ftp.socket = tls_1.connect(port, host, tlsOptions, () => this.ftp.log(`Connected to ${netUtils_1.describeAddress(this.ftp.socket)} (${netUtils_1.describeTLS(this.ftp.socket)})`));
this.ftp.tlsOptions = tlsOptions;
return this._handleConnectResponse();
}
/**
* Handles the first reponse by an FTP server after the socket connection has been established.
*/
_handleConnectResponse() {
return this.ftp.handle(undefined, (res, task) => {
if (res instanceof Error) {
// The connection has been destroyed by the FTPContext at this point.
task.reject(res);
}
else if (parseControlResponse_1.positiveCompletion(res.code)) {
task.resolve(res);
}
// Reject all other codes, including 120 "Service ready in nnn minutes".
else {
// Don't stay connected but don't replace the socket yet by using reset()
// so the user can inspect properties of this instance.
this.ftp.socket.destroy();
task.reject(new FtpContext_1.FTPError(res));
}
});
}
/**
* Send an FTP command and handle the first response.
*/
send(command, ignoreErrorCodesDEPRECATED = false) {
if (ignoreErrorCodesDEPRECATED) { // Deprecated starting from 3.9.0
this.ftp.log("Deprecated call using send(command, flag) with boolean flag to ignore errors. Use sendIgnoringError(command).");
return this.sendIgnoringError(command);
}
return this.ftp.request(command);
}
/**
* Send an FTP command and ignore an FTP error response. Any other kind of error or timeout will still reject the Promise.
*
* @param command
*/
sendIgnoringError(command) {
return this.ftp.handle(command, (res, task) => {
if (res instanceof FtpContext_1.FTPError) {
task.resolve({ code: res.code, message: res.message });
}
else if (res instanceof Error) {
task.reject(res);
}
else {
task.resolve(res);
}
});
}
/**
* Upgrade the current socket connection to TLS.
*
* @param options TLS options as in `tls.connect(options)`, optional.
* @param command Set the authentication command. Optional, default is "AUTH TLS".
*/
async useTLS(options = {}, command = "AUTH TLS") {
const ret = await this.send(command);
this.ftp.socket = await netUtils_1.upgradeSocket(this.ftp.socket, options);
this.ftp.tlsOptions = options; // Keep the TLS options for later data connections that should use the same options.
this.ftp.log(`Control socket is using: ${netUtils_1.describeTLS(this.ftp.socket)}`);
return ret;
}
/**
* Login a user with a password.
*
* @param user Username to use for login. Optional, default is "anonymous".
* @param password Password to use for login. Optional, default is "guest".
*/
login(user = "anonymous", password = "guest") {
this.ftp.log(`Login security: ${netUtils_1.describeTLS(this.ftp.socket)}`);
return this.ftp.handle("USER " + user, (res, task) => {
if (res instanceof Error) {
task.reject(res);
}
else if (parseControlResponse_1.positiveCompletion(res.code)) { // User logged in proceed OR Command superfluous
task.resolve(res);
}
else if (res.code === 331) { // User name okay, need password
this.ftp.send("PASS " + password);
}
else { // Also report error on 332 (Need account)
task.reject(new FtpContext_1.FTPError(res));
}
});
}
/**
* Set the usual default settings.
*
* Settings used:
* * Binary mode (TYPE I)
* * File structure (STRU F)
* * Additional settings for FTPS (PBSZ 0, PROT P)
*/
async useDefaultSettings() {
await this.send("TYPE I"); // Binary mode
await this.sendIgnoringError("STRU F"); // Use file structure
await this.sendIgnoringError("OPTS UTF8 ON"); // Some servers expect UTF-8 to be enabled explicitly
await this.sendIgnoringError("OPTS MLST type;size;modify;unique;unix.mode;unix.owner;unix.group;unix.ownername;unix.groupname;"); // Make sure MLSD listings include all we can parse
if (this.ftp.hasTLS) {
await this.sendIgnoringError("PBSZ 0"); // Set to 0 for TLS
await this.sendIgnoringError("PROT P"); // Protect channel (also for data connections)
}
}
/**
* Convenience method that calls `connect`, `useTLS`, `login` and `useDefaultSettings`.
*
* This is an instance method and thus can be called multiple times during the lifecycle of a `Client`
* instance. Whenever you do, the client is reset with a new control connection. This also implies that
* you can reopen a `Client` instance that has been closed due to an error when reconnecting with this
* method. In fact, reconnecting is the only way to continue using a closed `Client`.
*/
async access(options = {}) {
const useExplicitTLS = options.secure === true;
const useImplicitTLS = options.secure === "implicit";
let welcome;
if (useImplicitTLS) {
welcome = await this.connectImplicitTLS(options.host, options.port, options.secureOptions);
}
else {
welcome = await this.connect(options.host, options.port);
}
if (useExplicitTLS) {
await this.useTLS(options.secureOptions);
}
await this.login(options.user, options.password);
await this.useDefaultSettings();
return welcome;
}
/**
* Get the current working directory.
*/
async pwd() {
const res = await this.send("PWD");
// The directory is part of the return message, for example:
// 257 "/this/that" is current directory.
const parsed = res.message.match(/"(.+)"/);
if (parsed === null || parsed[1] === undefined) {
throw new Error(`Can't parse response to command 'PWD': ${res.message}`);
}
return parsed[1];
}
/**
* Get a description of supported features.
*
* This sends the FEAT command and parses the result into a Map where keys correspond to available commands
* and values hold further information. Be aware that your FTP servers might not support this
* command in which case this method will not throw an exception but just return an empty Map.
*/
async features() {
const res = await this.sendIgnoringError("FEAT");
const features = new Map();
// Not supporting any special features will be reported with a single line.
if (res.code < 400 && parseControlResponse_1.isMultiline(res.message)) {
// The first and last line wrap the multiline response, ignore them.
res.message.split("\n").slice(1, -1).forEach(line => {
// A typical lines looks like: " REST STREAM" or " MDTM".
// Servers might not use an indentation though.
const entry = line.trim().split(" ");
features.set(entry[0], entry[1] || "");
});
}
return features;
}
/**
* Set the working directory.
*/
async cd(path) {
const validPath = await this.protectWhitespace(path);
return this.send("CWD " + validPath);
}
/**
* Switch to the parent directory of the working directory.
*/
async cdup() {
return this.send("CDUP");
}
/**
* Get the last modified time of a file. This is not supported by every FTP server, in which case
* calling this method will throw an exception.
*/
async lastMod(path) {
const validPath = await this.protectWhitespace(path);
const res = await this.send(`MDTM ${validPath}`);
const date = res.message.slice(4);
return parseListMLSD_1.parseMLSxDate(date);
}
/**
* Get the size of a file.
*/
async size(path) {
const validPath = await this.protectWhitespace(path);
const command = `SIZE ${validPath}`;
const res = await this.send(command);
// The size is part of the response message, for example: "213 555555". It's
// possible that there is a commmentary appended like "213 5555, some commentary".
const size = parseInt(res.message.slice(4), 10);
if (Number.isNaN(size)) {
throw new Error(`Can't parse response to command '${command}' as a numerical value: ${res.message}`);
}
return size;
}
/**
* Rename a file.
*
* Depending on the FTP server this might also be used to move a file from one
* directory to another by providing full paths.
*/
async rename(srcPath, destPath) {
const validSrc = await this.protectWhitespace(srcPath);
const validDest = await this.protectWhitespace(destPath);
await this.send("RNFR " + validSrc);
return this.send("RNTO " + validDest);
}
/**
* Remove a file from the current working directory.
*
* You can ignore FTP error return codes which won't throw an exception if e.g.
* the file doesn't exist.
*/
async remove(path, ignoreErrorCodes = false) {
const validPath = await this.protectWhitespace(path);
return this.send(`DELE ${validPath}`, ignoreErrorCodes);
}
/**
* Report transfer progress for any upload or download to a given handler.
*
* This will also reset the overall transfer counter that can be used for multiple transfers. You can
* also call the function without a handler to stop reporting to an earlier one.
*
* @param handler Handler function to call on transfer progress.
*/
trackProgress(handler) {
this._progressTracker.bytesOverall = 0;
this._progressTracker.reportTo(handler);
}
/**
* Upload data from a readable stream or a local file to a remote file.
*
* @param source Readable stream or path to a local file.
* @param toRemotePath Path to a remote file to write to.
*/
async uploadFrom(source, toRemotePath, options = {}) {
return this._uploadWithCommand(source, toRemotePath, "STOR", options);
}
/**
* Upload data from a readable stream or a local file by appending it to an existing file. If the file doesn't
* exist the FTP server should create it.
*
* @param source Readable stream or path to a local file.
* @param toRemotePath Path to a remote file to write to.
*/
async appendFrom(source, toRemotePath, options = {}) {
return this._uploadWithCommand(source, toRemotePath, "APPE", options);
}
/**
* @protected
*/
async _uploadWithCommand(source, remotePath, command, options) {
if (typeof source === "string") {
return this._uploadLocalFile(source, remotePath, command, options);
}
return this._uploadFromStream(source, remotePath, command);
}
/**
* @protected
*/
async _uploadLocalFile(localPath, remotePath, command, options) {
const fd = await fsOpen(localPath, "r");
const source = fs_1.createReadStream("", {
fd,
start: options.localStart,
end: options.localEndInclusive,
autoClose: false
});
try {
return await this._uploadFromStream(source, remotePath, command);
}
finally {
await ignoreError(() => fsClose(fd));
}
}
/**
* @protected
*/
async _uploadFromStream(source, remotePath, command) {
const onError = (err) => this.ftp.closeWithError(err);
source.once("error", onError);
try {
const validPath = await this.protectWhitespace(remotePath);
await this.prepareTransfer(this.ftp);
// Keep the keyword `await` or the `finally` clause below runs too early
// and removes the event listener for the source stream too early.
return await transfer_1.uploadFrom(source, {
ftp: this.ftp,
tracker: this._progressTracker,
command,
remotePath: validPath,
type: "upload"
});
}
finally {
source.removeListener("error", onError);
}
}
/**
* Download a remote file and pipe its data to a writable stream or to a local file.
*
* You can optionally define at which position of the remote file you'd like to start
* downloading. If the destination you provide is a file, the offset will be applied
* to it as well. For example: To resume a failed download, you'd request the size of
* the local, partially downloaded file and use that as the offset. Assuming the size
* is 23, you'd download the rest using `downloadTo("local.txt", "remote.txt", 23)`.
*
* @param destination Stream or path for a local file to write to.
* @param fromRemotePath Path of the remote file to read from.
* @param startAt Position within the remote file to start downloading at. If the destination is a file, this offset is also applied to it.
*/
async downloadTo(destination, fromRemotePath, startAt = 0) {
if (typeof destination === "string") {
return this._downloadToFile(destination, fromRemotePath, startAt);
}
return this._downloadToStream(destination, fromRemotePath, startAt);
}
/**
* @protected
*/
async _downloadToFile(localPath, remotePath, startAt) {
const appendingToLocalFile = startAt > 0;
const fileSystemFlags = appendingToLocalFile ? "r+" : "w";
const fd = await fsOpen(localPath, fileSystemFlags);
const destination = fs_1.createWriteStream("", {
fd,
start: startAt,
autoClose: false
});
try {
return await this._downloadToStream(destination, remotePath, startAt);
}
catch (err) {
const localFileStats = await ignoreError(() => fsStat(localPath));
const hasDownloadedData = localFileStats && localFileStats.size > 0;
const shouldRemoveLocalFile = !appendingToLocalFile && !hasDownloadedData;
if (shouldRemoveLocalFile) {
await ignoreError(() => fsUnlink(localPath));
}
throw err;
}
finally {
await ignoreError(() => fsClose(fd));
}
}
/**
* @protected
*/
async _downloadToStream(destination, remotePath, startAt) {
const onError = (err) => this.ftp.closeWithError(err);
destination.once("error", onError);
try {
const validPath = await this.protectWhitespace(remotePath);
await this.prepareTransfer(this.ftp);
// Keep the keyword `await` or the `finally` clause below runs too early
// and removes the event listener for the source stream too early.
return await transfer_1.downloadTo(destination, {
ftp: this.ftp,
tracker: this._progressTracker,
command: startAt > 0 ? `REST ${startAt}` : `RETR ${validPath}`,
remotePath: validPath,
type: "download"
});
}
finally {
destination.removeListener("error", onError);
destination.end();
}
}
/**
* List files and directories in the current working directory, or from `path` if specified.
*
* @param [path] Path to remote file or directory.
*/
async list(path = "") {
const validPath = await this.protectWhitespace(path);
let lastError;
for (const candidate of this.availableListCommands) {
const command = validPath === "" ? candidate : `${candidate} ${validPath}`;
await this.prepareTransfer(this.ftp);
try {
const parsedList = await this._requestListWithCommand(command);
// Use successful candidate for all subsequent requests.
this.availableListCommands = [candidate];
return parsedList;
}
catch (err) {
const shouldTryNext = err instanceof FtpContext_1.FTPError;
if (!shouldTryNext) {
throw err;
}
lastError = err;
}
}
throw lastError;
}
/**
* @protected
*/
async _requestListWithCommand(command) {
const buffer = new StringWriter_1.StringWriter();
await transfer_1.downloadTo(buffer, {
ftp: this.ftp,
tracker: this._progressTracker,
command,
remotePath: "",
type: "list"
});
const text = buffer.getText(this.ftp.encoding);
this.ftp.log(text);
return this.parseList(text);
}
/**
* Remove a directory and all of its content.
*
* @param remoteDirPath The path of the remote directory to delete.
* @example client.removeDir("foo") // Remove directory 'foo' using a relative path.
* @example client.removeDir("foo/bar") // Remove directory 'bar' using a relative path.
* @example client.removeDir("/foo/bar") // Remove directory 'bar' using an absolute path.
* @example client.removeDir("/") // Remove everything.
*/
async removeDir(remoteDirPath) {
return this._exitAtCurrentDirectory(async () => {
await this.cd(remoteDirPath);
await this.clearWorkingDir();
if (remoteDirPath !== "/") {
await this.cdup();
await this.removeEmptyDir(remoteDirPath);
}
});
}
/**
* Remove all files and directories in the working directory without removing
* the working directory itself.
*/
async clearWorkingDir() {
for (const file of await this.list()) {
if (file.isDirectory) {
await this.cd(file.name);
await this.clearWorkingDir();
await this.cdup();
await this.removeEmptyDir(file.name);
}
else {
await this.remove(file.name);
}
}
}
/**
* Upload the contents of a local directory to the remote working directory.
*
* This will overwrite existing files with the same names and reuse existing directories.
* Unrelated files and directories will remain untouched. You can optionally provide a `remoteDirPath`
* to put the contents inside a directory which will be created if necessary including all
* intermediate directories. If you did provide a remoteDirPath the working directory will stay
* the same as before calling this method.
*
* @param localDirPath Local path, e.g. "foo/bar" or "../test"
* @param [remoteDirPath] Remote path of a directory to upload to. Working directory if undefined.
*/
async uploadFromDir(localDirPath, remoteDirPath) {
return this._exitAtCurrentDirectory(async () => {
if (remoteDirPath) {
await this.ensureDir(remoteDirPath);
}
return await this._uploadToWorkingDir(localDirPath);
});
}
/**
* @protected
*/
async _uploadToWorkingDir(localDirPath) {
const files = await fsReadDir(localDirPath);
for (const file of files) {
const fullPath = path_1.join(localDirPath, file);
const stats = await fsStat(fullPath);
if (stats.isFile()) {
await this.uploadFrom(fullPath, file);
}
else if (stats.isDirectory()) {
await this._openDir(file);
await this._uploadToWorkingDir(fullPath);
await this.cdup();
}
}
}
/**
* Download all files and directories of the working directory to a local directory.
*
* @param localDirPath The local directory to download to.
* @param remoteDirPath Remote directory to download. Current working directory if not specified.
*/
async downloadToDir(localDirPath, remoteDirPath) {
return this._exitAtCurrentDirectory(async () => {
if (remoteDirPath) {
await this.cd(remoteDirPath);
}
return await this._downloadFromWorkingDir(localDirPath);
});
}
/**
* @protected
*/
async _downloadFromWorkingDir(localDirPath) {
await ensureLocalDirectory(localDirPath);
for (const file of await this.list()) {
const localPath = path_1.join(localDirPath, file.name);
if (file.isDirectory) {
await this.cd(file.name);
await this._downloadFromWorkingDir(localPath);
await this.cdup();
}
else if (file.isFile) {
await this.downloadTo(localPath, file.name);
}
}
}
/**
* Make sure a given remote path exists, creating all directories as necessary.
* This function also changes the current working directory to the given path.
*/
async ensureDir(remoteDirPath) {
// If the remoteDirPath was absolute go to root directory.
if (remoteDirPath.startsWith("/")) {
await this.cd("/");
}
const names = remoteDirPath.split("/").filter(name => name !== "");
for (const name of names) {
await this._openDir(name);
}
}
/**
* Try to create a directory and enter it. This will not raise an exception if the directory
* couldn't be created if for example it already exists.
* @protected
*/
async _openDir(dirName) {
await this.sendIgnoringError("MKD " + dirName);
await this.cd(dirName);
}
/**
* Remove an empty directory, will fail if not empty.
*/
async removeEmptyDir(path) {
const validPath = await this.protectWhitespace(path);
return this.send(`RMD ${validPath}`);
}
/**
* FTP servers can't handle filenames that have leading whitespace. This method transforms
* a given path to fix that issue for most cases.
*/
async protectWhitespace(path) {
if (!path.startsWith(" ")) {
return path;
}
// Handle leading whitespace by prepending the absolute path:
// " test.txt" while being in the root directory becomes "/ test.txt".
const pwd = await this.pwd();
const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/";
return absolutePathPrefix + path;
}
async _exitAtCurrentDirectory(func) {
const userDir = await this.pwd();
try {
return await func();
}
finally {
if (!this.closed) {
await ignoreError(() => this.cd(userDir));
}
}
}
/**
* Try all available transfer strategies and pick the first one that works. Update `client` to
* use the working strategy for all successive transfer requests.
*
* @param strategies
* @returns a function that will try the provided strategies.
*/
_enterFirstCompatibleMode(strategies) {
return async (ftp) => {
ftp.log("Trying to find optimal transfer strategy...");
for (const strategy of strategies) {
try {
const res = await strategy(ftp);
ftp.log("Optimal transfer strategy found.");
this.prepareTransfer = strategy; // eslint-disable-line require-atomic-updates
return res;
}
catch (err) {
// Try the next candidate no matter the exact error. It's possible that a server
// answered incorrectly to a strategy, for example a PASV answer to an EPSV.
}
}
throw new Error("None of the available transfer strategies work.");
};
}
/**
* DEPRECATED, use `uploadFrom`.
* @deprecated
*/
async upload(source, toRemotePath, options = {}) {
this.ftp.log("Warning: upload() has been deprecated, use uploadFrom().");
return this.uploadFrom(source, toRemotePath, options);
}
/**
* DEPRECATED, use `appendFrom`.
* @deprecated
*/
async append(source, toRemotePath, options = {}) {
this.ftp.log("Warning: append() has been deprecated, use appendFrom().");
return this.appendFrom(source, toRemotePath, options);
}
/**
* DEPRECATED, use `downloadTo`.
* @deprecated
*/
async download(destination, fromRemotePath, startAt = 0) {
this.ftp.log("Warning: download() has been deprecated, use downloadTo().");
return this.downloadTo(destination, fromRemotePath, startAt);
}
/**
* DEPRECATED, use `uploadFromDir`.
* @deprecated
*/
async uploadDir(localDirPath, remoteDirPath) {
this.ftp.log("Warning: uploadDir() has been deprecated, use uploadFromDir().");
return this.uploadFromDir(localDirPath, remoteDirPath);
}
/**
* DEPRECATED, use `downloadToDir`.
* @deprecated
*/
async downloadDir(localDirPath) {
this.ftp.log("Warning: downloadDir() has been deprecated, use downloadToDir().");
return this.downloadToDir(localDirPath);
}
} |
JavaScript | class FileInfo {
constructor(name) {
this.name = name;
this.type = FileType.Unknown;
this.size = 0;
/**
* Unparsed, raw modification date as a string.
*
* If `modifiedAt` is undefined, the FTP server you're connected to doesn't support the more modern
* MLSD command for machine-readable directory listings. The older command LIST is then used returning
* results that vary a lot between servers as the format hasn't been standardized. Here, directory listings
* and especially modification dates were meant to be human-readable first.
*
* Be careful when still trying to parse this by yourself. Parsing dates from listings using LIST is
* unreliable. This library decides to offer parsed dates only when they're absolutely reliable and safe to
* use e.g. for comparisons.
*/
this.rawModifiedAt = "";
/**
* Parsed modification date.
*
* Available if the FTP server supports the MLSD command. Only MLSD guarantees dates than can be reliably
* parsed with the correct timezone and a resolution down to seconds. See `rawModifiedAt` property for the unparsed
* date that is always available.
*/
this.modifiedAt = undefined;
/**
* Unix permissions if present. If the underlying FTP server is not running on Unix this will be undefined.
* If set, you might be able to edit permissions with the FTP command `SITE CHMOD`.
*/
this.permissions = undefined;
/**
* Hard link count if available.
*/
this.hardLinkCount = undefined;
/**
* Link name for symbolic links if available.
*/
this.link = undefined;
/**
* Unix group if available.
*/
this.group = undefined;
/**
* Unix user if available.
*/
this.user = undefined;
/**
* Unique ID if available.
*/
this.uniqueID = undefined;
this.name = name;
}
get isDirectory() {
return this.type === FileType.Directory;
}
get isSymbolicLink() {
return this.type === FileType.SymbolicLink;
}
get isFile() {
return this.type === FileType.File;
}
/**
* Deprecated, legacy API. Use `rawModifiedAt` instead.
* @deprecated
*/
get date() {
return this.rawModifiedAt;
}
set date(rawModifiedAt) {
this.rawModifiedAt = rawModifiedAt;
}
} |
JavaScript | class FTPError extends Error {
constructor(res) {
super(res.message);
this.name = this.constructor.name;
this.code = res.code;
}
} |
JavaScript | class FTPContext {
/**
* Instantiate an FTP context.
*
* @param timeout - Timeout in milliseconds to apply to control and data connections. Use 0 for no timeout.
* @param encoding - Encoding to use for control connection. UTF-8 by default. Use "latin1" for older servers.
*/
constructor(timeout = 0, encoding = "utf8") {
this.timeout = timeout;
/** Debug-level logging of all socket communication. */
this.verbose = false;
/** IP version to prefer (4: IPv4, 6: IPv6, undefined: automatic). */
this.ipFamily = undefined;
/** Options for TLS connections. */
this.tlsOptions = {};
/** A multiline response might be received as multiple chunks. */
this._partialResponse = "";
this._encoding = encoding;
// Help Typescript understand that we do indeed set _socket in the constructor but use the setter method to do so.
this._socket = this.socket = this._newSocket();
this._dataSocket = undefined;
}
/**
* Close the context.
*/
close() {
// Internally, closing a context is always described with an error. If there is still a task running, it will
// abort with an exception that the user closed the client during a task. If no task is running, no exception is
// thrown but all newly submitted tasks after that will abort the exception that the client has been closed.
// In addition the user will get a stack trace pointing to where exactly the client has been closed. So in any
// case use _closingError to determine whether a context is closed. This also allows us to have a single code-path
// for closing a context making the implementation easier.
const message = this._task ? "User closed client during task" : "User closed client";
const err = new Error(message);
this.closeWithError(err);
}
/**
* Close the context with an error.
*/
closeWithError(err) {
// If this context already has been closed, don't overwrite the reason.
if (this._closingError) {
return;
}
this._closingError = err;
// Before giving the user's task a chance to react, make sure we won't be bothered with any inputs.
this._closeSocket(this._socket);
this._closeSocket(this._dataSocket);
// Give the user's task a chance to react, maybe cleanup resources.
this._passToHandler(err);
// The task might not have been rejected by the user after receiving the error.
this._stopTrackingTask();
}
/**
* Returns true if this context has been closed or hasn't been connected yet. You can reopen it with `access`.
*/
get closed() {
return this.socket.remoteAddress === undefined || this._closingError !== undefined;
}
/**
* Reset this contex and all of its state.
*/
reset() {
this.socket = this._newSocket();
}
/**
* Get the FTP control socket.
*/
get socket() {
return this._socket;
}
/**
* Set the socket for the control connection. This will only close the current control socket
* if the new one is not an upgrade to the current one.
*/
set socket(socket) {
// No data socket should be open in any case where the control socket is set or upgraded.
this.dataSocket = undefined;
this.tlsOptions = {};
// This being a soft reset, remove any remaining partial response.
this._partialResponse = "";
if (this._socket) {
// Only close the current connection if the new is not an upgrade.
const isUpgrade = socket.localPort === this._socket.localPort;
if (!isUpgrade) {
this._socket.destroy();
}
this._removeSocketListeners(this._socket);
}
if (socket) {
// Setting a completely new control socket is in essence something like a reset. That's
// why we also close any open data connection above. We can go one step further and reset
// a possible closing error. That means that a closed FTPContext can be "reopened" by
// setting a new control socket.
this._closingError = undefined;
// Don't set a timeout yet. Timeout for control sockets is only active during a task, see handle() below.
socket.setTimeout(0);
socket.setEncoding(this._encoding);
socket.setKeepAlive(true);
socket.on("data", data => this._onControlSocketData(data));
// Server sending a FIN packet is treated as an error.
socket.on("end", () => this.closeWithError(new Error("Server sent FIN packet unexpectedly, closing connection.")));
// Control being closed without error by server is treated as an error.
socket.on("close", hadError => { if (!hadError)
this.closeWithError(new Error("Server closed connection unexpectedly.")); });
this._setupDefaultErrorHandlers(socket, "control socket");
}
this._socket = socket;
}
/**
* Get the current FTP data connection if present.
*/
get dataSocket() {
return this._dataSocket;
}
/**
* Set the socket for the data connection. This will automatically close the former data socket.
*/
set dataSocket(socket) {
this._closeSocket(this._dataSocket);
if (socket) {
// Don't set a timeout yet. Timeout data socket should be activated when data transmission starts
// and timeout on control socket is deactivated.
socket.setTimeout(0);
this._setupDefaultErrorHandlers(socket, "data socket");
}
this._dataSocket = socket;
}
/**
* Get the currently used encoding.
*/
get encoding() {
return this._encoding;
}
/**
* Set the encoding used for the control socket.
*
* See https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings for what encodings
* are supported by Node.
*/
set encoding(encoding) {
this._encoding = encoding;
if (this.socket) {
this.socket.setEncoding(encoding);
}
}
/**
* Send an FTP command without waiting for or handling the result.
*/
send(command) {
const containsPassword = command.startsWith("PASS");
const message = containsPassword ? "> PASS ###" : `> ${command}`;
this.log(message);
this._socket.write(command + "\r\n", this.encoding);
}
/**
* Send an FTP command and handle the first response. Use this if you have a simple
* request-response situation.
*/
request(command) {
return this.handle(command, (res, task) => {
if (res instanceof Error) {
task.reject(res);
}
else {
task.resolve(res);
}
});
}
/**
* Send an FTP command and handle any response until you resolve/reject. Use this if you expect multiple responses
* to a request. This returns a Promise that will hold whatever the response handler passed on when resolving/rejecting its task.
*/
handle(command, responseHandler) {
if (this._task) {
// The user or client instance called `handle()` while a task is still running.
const err = new Error("User launched a task while another one is still running. Forgot to use 'await' or '.then()'?");
err.stack += `\nRunning task launched at: ${this._task.stack}`;
this.closeWithError(err);
// Don't return here, continue with returning the Promise that will then be rejected
// because the context closed already. That way, users will receive an exception where
// they called this method by mistake.
}
return new Promise((resolvePromise, rejectPromise) => {
const stack = new Error().stack || "Unknown call stack";
const resolver = {
resolve: (...args) => {
this._stopTrackingTask();
resolvePromise(...args);
},
reject: err => {
this._stopTrackingTask();
rejectPromise(err);
}
};
this._task = {
stack,
resolver,
responseHandler
};
if (this._closingError) {
// This client has been closed. Provide an error that describes this one as being caused
// by `_closingError`, include stack traces for both.
const err = new Error("Client is closed"); // Type 'Error' is not correctly defined, doesn't have 'code'.
err.stack += `\nClosing reason: ${this._closingError.stack}`;
err.code = this._closingError.code !== undefined ? this._closingError.code : "0";
this._passToHandler(err);
return;
}
// Only track control socket timeout during the lifecycle of a task. This avoids timeouts on idle sockets,
// the default socket behaviour which is not expected by most users.
this.socket.setTimeout(this.timeout);
if (command) {
this.send(command);
}
});
}
/**
* Log message if set to be verbose.
*/
log(message) {
if (this.verbose) {
// tslint:disable-next-line no-console
console.log(message);
}
}
/**
* Return true if the control socket is using TLS. This does not mean that a session
* has already been negotiated.
*/
get hasTLS() {
return "encrypted" in this._socket;
}
/**
* Removes reference to current task and handler. This won't resolve or reject the task.
* @protected
*/
_stopTrackingTask() {
// Disable timeout on control socket if there is no task active.
this.socket.setTimeout(0);
this._task = undefined;
}
/**
* Handle incoming data on the control socket. The chunk is going to be of type `string`
* because we let `socket` handle encoding with `setEncoding`.
* @protected
*/
_onControlSocketData(chunk) {
this.log(`< ${chunk}`);
// This chunk might complete an earlier partial response.
const completeResponse = this._partialResponse + chunk;
const parsed = parseControlResponse_1.parseControlResponse(completeResponse);
// Remember any incomplete remainder.
this._partialResponse = parsed.rest;
// Each response group is passed along individually.
for (const message of parsed.messages) {
const code = parseInt(message.substr(0, 3), 10);
const response = { code, message };
const err = code >= 400 ? new FTPError(response) : undefined;
this._passToHandler(err ? err : response);
}
}
/**
* Send the current handler a response. This is usually a control socket response
* or a socket event, like an error or timeout.
* @protected
*/
_passToHandler(response) {
if (this._task) {
this._task.responseHandler(response, this._task.resolver);
}
// Errors other than FTPError always close the client. If there isn't an active task to handle the error,
// the next one submitted will receive it using `_closingError`.
// There is only one edge-case: If there is an FTPError while no task is active, the error will be dropped.
// But that means that the user sent an FTP command with no intention of handling the result. So why should the
// error be handled? Maybe log it at least? Debug logging will already do that and the client stays useable after
// FTPError. So maybe no need to do anything here.
}
/**
* Setup all error handlers for a socket.
* @protected
*/
_setupDefaultErrorHandlers(socket, identifier) {
socket.once("error", error => {
error.message += ` (${identifier})`;
this.closeWithError(error);
});
socket.once("close", hadError => {
if (hadError) {
this.closeWithError(new Error(`Socket closed due to transmission error (${identifier})`));
}
});
socket.once("timeout", () => this.closeWithError(new Error(`Timeout (${identifier})`)));
}
/**
* Close a socket.
* @protected
*/
_closeSocket(socket) {
if (socket) {
socket.destroy();
this._removeSocketListeners(socket);
}
}
/**
* Remove all default listeners for socket.
* @protected
*/
_removeSocketListeners(socket) {
socket.removeAllListeners();
// Before Node.js 10.3.0, using `socket.removeAllListeners()` without any name did not work: https://github.com/nodejs/node/issues/20923.
socket.removeAllListeners("timeout");
socket.removeAllListeners("data");
socket.removeAllListeners("end");
socket.removeAllListeners("error");
socket.removeAllListeners("close");
socket.removeAllListeners("connect");
}
/**
* Provide a new socket instance.
*
* Internal use only, replaced for unit tests.
*/
_newSocket() {
return new net_1.Socket();
}
} |
JavaScript | class ProgressTracker {
constructor() {
this.bytesOverall = 0;
this.intervalMs = 500;
this.onStop = noop;
this.onHandle = noop;
}
/**
* Register a new handler for progress info. Use `undefined` to disable reporting.
*/
reportTo(onHandle = noop) {
this.onHandle = onHandle;
}
/**
* Start tracking transfer progress of a socket.
*
* @param socket The socket to observe.
* @param name A name associated with this progress tracking, e.g. a filename.
* @param type The type of the transfer, typically "upload" or "download".
*/
start(socket, name, type) {
let lastBytes = 0;
this.onStop = poll(this.intervalMs, () => {
const bytes = socket.bytesRead + socket.bytesWritten;
this.bytesOverall += bytes - lastBytes;
lastBytes = bytes;
this.onHandle({
name,
type,
bytes,
bytesOverall: this.bytesOverall
});
});
}
/**
* Stop tracking transfer progress.
*/
stop() {
this.onStop(false);
}
/**
* Call the progress handler one more time, then stop tracking.
*/
updateAndStop() {
this.onStop(true);
}
} |
JavaScript | class TransferResolver {
/**
* Instantiate a TransferResolver
*/
constructor(ftp, progress) {
this.ftp = ftp;
this.progress = progress;
this.response = undefined;
this.dataTransferDone = false;
}
/**
* Mark the beginning of a transfer.
*
* @param name - Name of the transfer, usually the filename.
* @param type - Type of transfer, usually "upload" or "download".
*/
onDataStart(name, type) {
// Let the data socket be in charge of tracking timeouts during transfer.
// The control socket sits idle during this time anyway and might provoke
// a timeout unnecessarily. The control connection will take care
// of timeouts again once data transfer is complete or failed.
if (this.ftp.dataSocket === undefined) {
throw new Error("Data transfer should start but there is no data connection.");
}
this.ftp.socket.setTimeout(0);
this.ftp.dataSocket.setTimeout(this.ftp.timeout);
this.progress.start(this.ftp.dataSocket, name, type);
}
/**
* The data connection has finished the transfer.
*/
onDataDone(task) {
this.progress.updateAndStop();
// Hand-over timeout tracking back to the control connection. It's possible that
// we don't receive the response over the control connection that the transfer is
// done. In this case, we want to correctly associate the resulting timeout with
// the control connection.
this.ftp.socket.setTimeout(this.ftp.timeout);
if (this.ftp.dataSocket) {
this.ftp.dataSocket.setTimeout(0);
}
this.dataTransferDone = true;
this.tryResolve(task);
}
/**
* The control connection reports the transfer as finished.
*/
onControlDone(task, response) {
this.response = response;
this.tryResolve(task);
}
/**
* An error has been reported and the task should be rejected.
*/
onError(task, err) {
this.progress.updateAndStop();
this.ftp.socket.setTimeout(this.ftp.timeout);
this.ftp.dataSocket = undefined;
task.reject(err);
}
/**
* Control connection sent an unexpected request requiring a response from our part. We
* can't provide that (because unknown) and have to close the contrext with an error because
* the FTP server is now caught up in a state we can't resolve.
*/
onUnexpectedRequest(response) {
const err = new Error(`Unexpected FTP response is requesting an answer: ${response.message}`);
this.ftp.closeWithError(err);
}
tryResolve(task) {
// To resolve, we need both control and data connection to report that the transfer is done.
const canResolve = this.dataTransferDone && this.response !== undefined;
if (canResolve) {
this.ftp.dataSocket = undefined;
task.resolve(this.response);
}
}
} |
JavaScript | class FilterValueKeyframes extends Keyframes {
filterId;
constructor({filterId, timings, keyframes, easings}) {
super({timings, keyframes, easings, features: ['left', 'right']});
this.filterId = filterId;
}
// getFrame() {
// const factor = this.factor;
// const start = this.getStartData();
// const end = this.getEndData();
// let frame = {};
// if (this.activeProps.value) {
// const valueLeft = factorInterpolator(start[0], end[0], end.ease);
// const valueRight = factorInterpolator(start[1], end[1], end.ease);
// frame.value = [valueLeft(factor), valueRight(factor)];
// }
// return frame;
// }
} |
JavaScript | class ButtonToolbar extends PureComponent {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string
};
render() {
const {className} = this.props;
const classes = classNames(styles.buttonToolbar, className);
return (
<div
{...this.props}
className={classes}
/>
);
}
} |
JavaScript | class AutoColumnSize extends BasePlugin {
static get CALCULATION_STEP() {
return 50;
}
static get SYNC_CALCULATION_LIMIT() {
return 50;
}
constructor(hotInstance) {
super(hotInstance);
privatePool.set(this, {
/**
* Cached column header names. It is used to diff current column headers with previous state and detect which
* columns width should be updated.
*
* @private
* @type {Array}
*/
cachedColumnHeaders: [],
});
/**
* Cached columns widths.
*
* @type {Number[]}
*/
this.widths = [];
/**
* Instance of {@link GhostTable} for rows and columns size calculations.
*
* @private
* @type {GhostTable}
*/
this.ghostTable = new GhostTable(this.hot);
/**
* Instance of {@link SamplesGenerator} for generating samples necessary for columns width calculations.
*
* @private
* @type {SamplesGenerator}
*/
this.samplesGenerator = new SamplesGenerator((row, column) => {
const cellMeta = this.hot.getCellMeta(row, column);
let cellValue = '';
if (!cellMeta.spanned) {
cellValue = this.hot.getDataAtCell(row, column);
}
let bundleCountSeed = 0;
if (cellMeta.label) {
const { value: labelValue, property: labelProperty } = cellMeta.label;
let labelText = '';
if (labelValue) {
labelText = typeof labelValue === 'function' ? labelValue(row, column, this.hot.colToProp(column), cellValue) : labelValue;
} else if (labelProperty) {
labelText = this.hot.getDataAtRowProp(row, labelProperty);
}
bundleCountSeed = labelText.length;
}
return { value: cellValue, bundleCountSeed };
});
/**
* `true` only if the first calculation was performed
*
* @private
* @type {Boolean}
*/
this.firstCalculation = true;
/**
* `true` if the size calculation is in progress.
*
* @type {Boolean}
*/
this.inProgress = false;
// moved to constructor to allow auto-sizing the columns when the plugin is disabled
this.addHook('beforeColumnResize', (col, size, isDblClick) => this.onBeforeColumnResize(col, size, isDblClick));
}
/**
* Checks if the plugin is enabled in the handsontable settings. This method is executed in {@link Hooks#beforeInit}
* hook and if it returns `true` than the {@link AutoColumnSize#enablePlugin} method is called.
*
* @returns {Boolean}
*/
isEnabled() {
return this.hot.getSettings().autoColumnSize !== false && !this.hot.getSettings().colWidths;
}
/**
* Enables the plugin functionality for this Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
const setting = this.hot.getSettings().autoColumnSize;
if (setting && setting.useHeaders !== null && setting.useHeaders !== void 0) {
this.ghostTable.setSetting('useHeaders', setting.useHeaders);
}
this.setSamplingOptions();
this.addHook('afterLoadData', () => this.onAfterLoadData());
this.addHook('beforeChange', changes => this.onBeforeChange(changes));
this.addHook('beforeRender', force => this.onBeforeRender(force));
this.addHook('modifyColWidth', (width, col) => this.getColumnWidth(col, width));
this.addHook('afterInit', () => this.onAfterInit());
super.enablePlugin();
}
/**
* Updates the plugin state. This method is executed when {@link Core#updateSettings} is invoked.
*/
updatePlugin() {
const changedColumns = this.findColumnsWhereHeaderWasChanged();
if (changedColumns.length) {
this.clearCache(changedColumns);
}
super.updatePlugin();
}
/**
* Disables the plugin functionality for this Handsontable instance.
*/
disablePlugin() {
super.disablePlugin();
}
/**
* Calculates a columns width.
*
* @param {Number|Object} colRange Column index or an object with `from` and `to` indexes as a range.
* @param {Number|Object} rowRange Row index or an object with `from` and `to` indexes as a range.
* @param {Boolean} [force=false] If `true` the calculation will be processed regardless of whether the width exists in the cache.
*/
calculateColumnsWidth(colRange = { from: 0, to: this.hot.countCols() - 1 }, rowRange = { from: 0, to: this.hot.countRows() - 1 }, force = false) {
const columnsRange = typeof colRange === 'number' ? { from: colRange, to: colRange } : colRange;
const rowsRange = typeof rowRange === 'number' ? { from: rowRange, to: rowRange } : rowRange;
rangeEach(columnsRange.from, columnsRange.to, (col) => {
if (force || (this.widths[col] === void 0 && !this.hot._getColWidthFromSettings(col))) {
const samples = this.samplesGenerator.generateColumnSamples(col, rowsRange);
arrayEach(samples, ([column, sample]) => this.ghostTable.addColumn(column, sample));
}
});
if (this.ghostTable.columns.length) {
this.ghostTable.getWidths((col, width) => {
this.widths[col] = width;
});
this.ghostTable.clean();
}
}
/**
* Calculates all columns width. The calculated column will be cached in the {@link AutoColumnSize#widths} property.
* To retrieve width for specyfied column use {@link AutoColumnSize#getColumnWidth} method.
*
* @param {Object|Number} rowRange Row index or an object with `from` and `to` properties which define row range.
*/
calculateAllColumnsWidth(rowRange = { from: 0, to: this.hot.countRows() - 1 }) {
let current = 0;
const length = this.hot.countCols() - 1;
let timer = null;
this.inProgress = true;
const loop = () => {
// When hot was destroyed after calculating finished cancel frame
if (!this.hot) {
cancelAnimationFrame(timer);
this.inProgress = false;
return;
}
this.calculateColumnsWidth({
from: current,
to: Math.min(current + AutoColumnSize.CALCULATION_STEP, length)
}, rowRange);
current = current + AutoColumnSize.CALCULATION_STEP + 1;
if (current < length) {
timer = requestAnimationFrame(loop);
} else {
cancelAnimationFrame(timer);
this.inProgress = false;
// @TODO Should call once per render cycle, currently fired separately in different plugins
this.hot.view.wt.wtOverlays.adjustElementsSize(true);
// tmp
if (this.hot.view.wt.wtOverlays.leftOverlay.needFullRender) {
this.hot.view.wt.wtOverlays.leftOverlay.clone.draw();
}
}
};
// sync
if (this.firstCalculation && this.getSyncCalculationLimit()) {
this.calculateColumnsWidth({ from: 0, to: this.getSyncCalculationLimit() }, rowRange);
this.firstCalculation = false;
current = this.getSyncCalculationLimit() + 1;
}
// async
if (current < length) {
loop();
} else {
this.inProgress = false;
}
}
/**
* Sets the sampling options.
*
* @private
*/
setSamplingOptions() {
const setting = this.hot.getSettings().autoColumnSize;
const samplingRatio = setting && hasOwnProperty(setting, 'samplingRatio') ? this.hot.getSettings().autoColumnSize.samplingRatio : void 0;
const allowSampleDuplicates = setting && hasOwnProperty(setting, 'allowSampleDuplicates') ? this.hot.getSettings().autoColumnSize.allowSampleDuplicates : void 0;
if (samplingRatio && !isNaN(samplingRatio)) {
this.samplesGenerator.setSampleCount(parseInt(samplingRatio, 10));
}
if (allowSampleDuplicates) {
this.samplesGenerator.setAllowDuplicates(allowSampleDuplicates);
}
}
/**
* Recalculates all columns width (overwrite cache values).
*/
recalculateAllColumnsWidth() {
if (this.hot.view && isVisible(this.hot.view.wt.wtTable.TABLE)) {
this.clearCache();
this.calculateAllColumnsWidth();
}
}
/**
* Gets value which tells how many columns should be calculated synchronously (rest of the columns will be calculated
* asynchronously). The limit is calculated based on `syncLimit` set to `autoColumnSize` option (see {@link Options#autoColumnSize}).
*
* @returns {Number}
*/
getSyncCalculationLimit() {
/* eslint-disable no-bitwise */
let limit = AutoColumnSize.SYNC_CALCULATION_LIMIT;
const colsLimit = this.hot.countCols() - 1;
if (isObject(this.hot.getSettings().autoColumnSize)) {
limit = this.hot.getSettings().autoColumnSize.syncLimit;
if (isPercentValue(limit)) {
limit = valueAccordingPercent(colsLimit, limit);
} else {
// Force to Number
limit >>= 0;
}
}
return Math.min(limit, colsLimit);
}
/**
* Gets the calculated column width.
*
* @param {Number} column Column index.
* @param {Number} [defaultWidth] Default column width. It will be picked up if no calculated width found.
* @param {Boolean} [keepMinimum=true] If `true` then returned value won't be smaller then 50 (default column width).
* @returns {Number}
*/
getColumnWidth(column, defaultWidth = void 0, keepMinimum = true) {
let width = defaultWidth;
if (width === void 0) {
width = this.widths[column];
if (keepMinimum && typeof width === 'number') {
width = Math.max(width, ViewportColumnsCalculator.DEFAULT_WIDTH);
}
}
return width;
}
/**
* Gets the first visible column.
*
* @returns {Number} Returns column index or -1 if table is not rendered.
*/
getFirstVisibleColumn() {
const wot = this.hot.view.wt;
if (wot.wtViewport.columnsVisibleCalculator) {
return wot.wtTable.getFirstVisibleColumn();
}
if (wot.wtViewport.columnsRenderCalculator) {
return wot.wtTable.getFirstRenderedColumn();
}
return -1;
}
/**
* Gets the last visible column.
*
* @returns {Number} Returns column index or -1 if table is not rendered.
*/
getLastVisibleColumn() {
const wot = this.hot.view.wt;
if (wot.wtViewport.columnsVisibleCalculator) {
return wot.wtTable.getLastVisibleColumn();
}
if (wot.wtViewport.columnsRenderCalculator) {
return wot.wtTable.getLastRenderedColumn();
}
return -1;
}
/**
* Collects all columns which titles has been changed in comparison to the previous state.
*
* @private
* @returns {Array} It returns an array of physical column indexes.
*/
findColumnsWhereHeaderWasChanged() {
const columnHeaders = this.hot.getColHeader();
const { cachedColumnHeaders } = privatePool.get(this);
const changedColumns = arrayReduce(columnHeaders, (acc, columnTitle, physicalColumn) => {
const cachedColumnsLength = cachedColumnHeaders.length;
if (cachedColumnsLength - 1 < physicalColumn || cachedColumnHeaders[physicalColumn] !== columnTitle) {
acc.push(physicalColumn);
}
if (cachedColumnsLength - 1 < physicalColumn) {
cachedColumnHeaders.push(columnTitle);
} else {
cachedColumnHeaders[physicalColumn] = columnTitle;
}
return acc;
}, []);
return changedColumns;
}
/**
* Clears cache of calculated column widths. If you want to clear only selected columns pass an array with their indexes.
* Otherwise whole cache will be cleared.
*
* @param {Number[]} [columns] List of physical column indexes to clear.
*/
clearCache(columns = []) {
if (columns.length) {
arrayEach(columns, (physicalIndex) => {
this.widths[physicalIndex] = void 0;
});
} else {
this.widths.length = 0;
}
}
/**
* Checks if all widths were calculated. If not then return `true` (need recalculate).
*
* @returns {Boolean}
*/
isNeedRecalculate() {
return !!arrayFilter(this.widths, item => (item === void 0)).length;
}
/**
* On before render listener.
*
* @private
*/
onBeforeRender() {
const force = this.hot.renderCall;
const rowsCount = this.hot.countRows();
// Keep last column widths unchanged for situation when all rows was deleted or trimmed (pro #6)
if (!rowsCount) {
return;
}
this.calculateColumnsWidth({ from: this.getFirstVisibleColumn(), to: this.getLastVisibleColumn() }, void 0, force);
if (this.isNeedRecalculate() && !this.inProgress) {
this.calculateAllColumnsWidth();
}
}
/**
* On after load data listener.
*
* @private
*/
onAfterLoadData() {
if (this.hot.view) {
this.recalculateAllColumnsWidth();
} else {
// first load - initialization
setTimeout(() => {
if (this.hot) {
this.recalculateAllColumnsWidth();
}
}, 0);
}
}
/**
* On before change listener.
*
* @private
* @param {Array} changes
*/
onBeforeChange(changes) {
const changedColumns = arrayMap(changes, ([, column]) => this.hot.propToCol(column));
this.clearCache(changedColumns);
}
/**
* On before column resize listener.
*
* @private
* @param {Number} col
* @param {Number} size
* @param {Boolean} isDblClick
* @returns {Number}
*/
onBeforeColumnResize(col, size, isDblClick) {
let newSize = size;
if (isDblClick) {
this.calculateColumnsWidth(col, void 0, true);
newSize = this.getColumnWidth(col, void 0, false);
}
return newSize;
}
/**
* On after Handsontable init fill plugin with all necessary values.
*
* @private
*/
onAfterInit() {
privatePool.get(this).cachedColumnHeaders = this.hot.getColHeader();
}
/**
* Destroys the plugin instance.
*/
destroy() {
this.ghostTable.clean();
super.destroy();
}
} |
JavaScript | class App extends React.Component {
constructor(props) {
super(props);
this.fooFn = () => console.log('AppContext fooFn clicked');
/* overwrite functions of the `<AppContext>` here
* before attaching the `appState` to `this.state`
*/
appState.fooFn = this.fooFn;
this.state = appState;
}
componentDidMount() {
this.state.debug && console.log("App componentDidMount");
/*
* Once the App Component is mounted, do a single request to the API to fetch initial data.
*
* To prevent the famous "Can't call setState on an unmounted component" warning we're using
* the cancellation API from axios. This
* 1) prevents calls to `setState` if an asynchronous fetch resolves after the component
* was already unmounted (saw this in tests, although it worked in prod with the previous
* approach of `setInterval` and `clearInterval`)
* 2) is the correct way to solve this issue. see
* https://github.com/facebook/react/issues/2787#issuecomment-304485634
*/
this.cancelSource = axios.CancelToken.source();
let cancelToken = this.cancelSource.token;
Api(cancelToken)
.get()
.then(response => {
this.state.debug && console.log(response);
})
.catch(error => {
this.state.debug && console.log('Error fetching Data');
});
}
componentWillUnmount() {
this.cancelSource.cancel();
}
componentWillReceiveProps(nextProps) {
/* convenient func for noticing when `<App>` will do a full rerender */
this.state.debug && console.log("App componentWillReceiveProps");
}
render() {
return (
<AppContext.Provider value={this.state}>
<Container fluid>
<Switch>
<Route path="/" exact={true} component={Dashboard} />
{/*
<Route
path="/namespaces/:namespaceName"
exact={true}
render={props => <Namespace {...props} {...this.state} />}
/>
*/}
</Switch>
</Container>
</AppContext.Provider>
);
}
} |
JavaScript | class SwitchFirstMapSubscriber extends OuterSubscriber {
/**
* @param {?} destination
* @param {?} project
* @param {?=} resultSelector
*/
constructor(destination, project, resultSelector) {
super(destination);
this.project = project;
this.resultSelector = resultSelector;
this.hasSubscription = false;
this.hasCompleted = false;
this.index = 0;
}
/**
* @param {?} value
* @return {?}
*/
_next(value) {
if (!this.hasSubscription) {
this.tryNext(value);
}
}
/**
* @param {?} value
* @return {?}
*/
tryNext(value) {
const /** @type {?} */ index = this.index++;
const /** @type {?} */ destination = this.destination;
try {
const /** @type {?} */ result = this.project(value, index);
this.hasSubscription = true;
this.add(subscribeToResult(this, result, value, index));
}
catch (err) {
destination.error(err);
}
}
/**
* @return {?}
*/
_complete() {
this.hasCompleted = true;
if (!this.hasSubscription) {
this.destination.complete();
}
}
/**
* @param {?} outerValue
* @param {?} innerValue
* @param {?} outerIndex
* @param {?} innerIndex
* @param {?} innerSub
* @return {?}
*/
notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
const { resultSelector, destination } = this;
if (resultSelector) {
this.trySelectResult(outerValue, innerValue, outerIndex, innerIndex);
}
else {
destination.next(innerValue);
}
}
/**
* @param {?} outerValue
* @param {?} innerValue
* @param {?} outerIndex
* @param {?} innerIndex
* @return {?}
*/
trySelectResult(outerValue, innerValue, outerIndex, innerIndex) {
const { resultSelector, destination } = this;
try {
const /** @type {?} */ result = resultSelector(outerValue, innerValue, outerIndex, innerIndex);
destination.next(result);
}
catch (err) {
destination.error(err);
}
}
/**
* @param {?} err
* @return {?}
*/
notifyError(err) {
this.destination.error(err);
}
/**
* @param {?} innerSub
* @return {?}
*/
notifyComplete(innerSub) {
this.remove(innerSub);
this.hasSubscription = false;
if (this.hasCompleted) {
this.destination.complete();
}
}
} |
JavaScript | class SpaceShip {
constructor(name, hull, firepower, accuracy) {
this.name = name;
this.hull = hull;
this.firepower = firepower;
this.accuracy = accuracy;
}
attack(enemy){
// if random value is less than accuracy, then attack first alien, alien.fleet[0]
if (Math.random() < this.accuracy) {
console.log(enemy.name, 'has been hit!');
// enemy.hull -= this.firepower;
enemy.takeDamage();
// else, log that you missed
// then call the enemy to retaliate
} else {
console.log('Oh no! You missed!');
enemy.attack();
}
}
takeDamage(enemy) {
// If alien ship survives or if missed attack, subtract alien's firepower from hull
this.hull -= enemy.firepower
if (this.hull > 0) {
console.log('You have been hit by', enemy.name, '! It has done', enemy.firepower, 'damage. You have', this.hull, 'hull left.');
this.attack(enemy)
}
// If hull remains > 0, attack again.
// If hull reaches 0, alert loss of game.
}
retreat() {
alert ('Afraid to die for your planet huh?');
}
} |
JavaScript | class Enemy {
constructor(name, hull, firepower, accuracy) {
this.name = name;
this.hull = hull;
this.firepower = firepower;
this.accuracy = accuracy;
}
attack() {
// if random number is less than this accuracy, hit ussSchwarzenegger
if (Math.random() < this.accuracy) {
ussSchwarzenegger.takeDamage(this)
} else {
console.log('Alien ship has missed his attack');
ussSchwarzenegger.attack(this)
}
// else log that alien missed
}
takeDamage() {
// subtract ussSchwarzenegger's firepower from hull
this.hull -= ussSchwarzenegger.firepower
// if hull is <= 0 alert destroyed, good job
if (this.hull <= 0) {
console.log('Alien ship destroyed. Nice work!');
} else {
console.log('Alien has', this.hull, 'hull left');
this.attack(ussSchwarzenegger);
}
// If hull is > 0 after first attack from ussSchwarzenegger, attack
}
} |
JavaScript | class DummyParser {
constructor(type) {
this.test_type = type;
}
} |
JavaScript | class Signup extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
password: '',
password_confirmation: '',
errors: []
};
}
handleChange = (event) => {
const { name, value } = event.target
this.setState({
[name]: value
})
};
handleSubmit = (event) => {
event.preventDefault()
const { name, email, password, password_confirmation } = this.state
let user = {
name: name,
email: email,
password: password,
password_confirmation: password_confirmation
}
//double check your Rails server port, mine is 3000 & React is on 3001
axios.post(SERVER_URL, { user }, { withCredentials: true }).then(response => {
if (response.data.status === 'created') {
this.props.handleLogin(response)
this.redirect()
} else {
console.log(response.data.errors);
this.setState({
errors: response.data.errors
})
}
})
.catch(error => console.log('api errors:', error))
};
redirect = () => {
this.props.history.push('/')
}
handleErrors = () => {
return (
<div>
<ul>
{this.state.errors.map((error) => {
return <li key={ error }>{ error }</li>
})}
</ul>
</div>
)
};
render() {
const { name, email, password, password_confirmation } = this.state
return (
<div>
<h1>Sign Up</h1>
{this.handleErrors()}
<form onSubmit={ this.handleSubmit }>
<input
placeholder='name'
type='text'
name='name'
value={ name }
onChange={ this.handleChange }
/>
<input
placeholder='email'
type='email'
name='email'
value={ email }
onChange={ this.handleChange }
/>
<input
placeholder='password'
type='password'
name='password'
value={ password }
onChange={ this.handleChange }
/>
<input
placeholder='password confirmation'
type='password'
name='password_confirmation'
value={ password_confirmation }
onChange={ this.handleChange }
/>
<button placeholder='submit' type='submit'>
Sign Up
</button>
</form>
</div>
);
}
} |
JavaScript | class Vector3 {
constructor ( x = 0, y = 0, z = 0 ) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
set ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
clone () {
return new Vector3(this.x, this.y, this.z);
}
copy ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
}
add ( v ) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
}
addScalar ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
}
sub ( v ) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
}
subScalar ( s ) {
this.x -= s;
this.y -= s;
this.z -= s;
return this;
}
subVectors ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
}
multiply ( v ) {
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
}
multiplyScalar ( s ) {
if ( isFinite(s) ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
}
divide ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
}
divideScalar ( s ) {
return this.multiplyScalar(1 / s);
}
dot ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
lengthSq () {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
length () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
}
setLength ( length ) {
return this.multiplyScalar(length / this.length());
}
normalize () {
return this.divideScalar(this.length());
}
distanceTo ( v ) {
return Math.sqrt(this.distanceToSquared(v));
}
distanceToSquared ( v ) {
const dx = this.x - v.x;
const dy = this.y - v.y;
const dz = this.z - v.z;
return dx * dx + dy * dy + dz * dz;
}
lerp ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
}
lerpVectors ( v1, v2, alpha ) {
return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
}
equals ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
}
} |
JavaScript | class UIElement extends BaseUIElement {
constructor(options={}) {
super();
this.children = [];
this.options = options; // TODO: this is a hack, to not break all the code that references this.options in setOptions
this.setOptions(options);
this.state = this.getDefaultState();
};
getDefaultOptions(options) {}
getDefaultState() {
return {};
}
getPreservedOptions() {}
setOptions(options) {
let defaultOptions = this.getDefaultOptions(options);
if (defaultOptions) {
options = Object.assign(defaultOptions, options);
}
this.options = options;
}
// TODO: should probably add a second arg, doRedraw=true - same for setOptions
updateOptions(options) {
this.setOptions(Object.assign(this.options, options));
// TODO: if the old options and the new options are deep equal, we can skip this redraw, right?
this.redraw();
}
updateState(state) {
this.state = {...this.state, ...state};
this.redraw();
}
setChildren(...args) {
this.updateOptions({children: unwrapArray(args)})
}
// Used when we want to reuse the current element, with the options from the passed in argument
// Is only called when element.canOverwrite(this) is true
copyState(element) {
let options = element.options;
let preservedOptions = this.getPreservedOptions();
if (preservedOptions) {
options = Object.assign({}, options, preservedOptions);
}
this.setOptions(options);
this.addListenersFromOptions();
}
getNodeType() {
return this.options.nodeType || "div";
}
static create(parentNode, options) {
const uiElement = new this(options);
uiElement.mount(parentNode, null);
uiElement.dispatch("mount", uiElement);
return uiElement;
}
// TODO: should be renamed to renderContent
getGivenChildren() {
return this.options.children || [];
}
render() {
return this.options.children;
};
createNode() {
this.node = document.createElement(this.getNodeType());
applyDebugFlags(this);
return this.node;
}
// Abstract, gets called when removing DOM node associated with the
cleanup() {
this.runCleanupJobs();
for (let child of this.children) {
child.destroyNode();
}
this.clearNode();
super.cleanup();
}
overwriteChild(existingChild, newChild) {
existingChild.copyState(newChild);
return existingChild;
}
getElementKeyMap(elements) {
if (!elements || !elements.length) {
return;
}
let childrenKeyMap = new Map();
for (let i = 0; i < elements.length; i += 1) {
let childKey = (elements[i].options && elements[i].options.key) || ("autokey" + i);
childrenKeyMap.set(childKey, elements[i]);
}
return childrenKeyMap;
}
getChildrenToRender() {
return this.render();
}
getChildrenForRedraw() {
UI.renderingStack.push(this);
let children = unwrapArray(this.getChildrenToRender());
UI.renderingStack.pop();
return children;
}
redraw() {
if (!this.node) {
console.error("Element not yet mounted. Redraw aborted!", this);
return false;
}
let newChildren = this.getChildrenForRedraw();
if (newChildren === this.children) {
for (let i = 0; i < newChildren.length; i += 1) {
newChildren[i].redraw();
}
this.applyNodeAttributes();
this.applyRef();
return true;
}
let domNode = this.node;
let childrenKeyMap = this.getElementKeyMap(this.children);
for (let i = 0; i < newChildren.length; i++) {
let newChild = newChildren[i];
let prevChildNode = (i > 0) ? newChildren[i - 1].node : null;
let currentChildNode = (prevChildNode) ? prevChildNode.nextSibling : domNode.firstChild;
// Not a UIElement, to be converted to a TextElement
if (!newChild.getNodeType) {
newChild = newChildren[i] = new UI.TextElement(newChild);
}
let newChildKey = (newChild.options && newChild.options.key) || ("autokey" + i);
let existingChild = childrenKeyMap && childrenKeyMap.get(newChildKey);
if (existingChild && newChildren[i].canOverwrite(existingChild)) {
// We're replacing an existing child element, it might be the very same object
if (existingChild !== newChildren[i]) {
newChildren[i] = this.overwriteChild(existingChild, newChildren[i]);
}
newChildren[i].redraw();
if (newChildren[i].node !== currentChildNode) {
domNode.insertBefore(newChildren[i].node, currentChildNode);
}
} else {
// Getting here means we are not replacing anything, should just render
newChild.mount(this, currentChildNode);
}
}
if (this.children.length) {
// Remove children that don't need to be here
let newChildrenSet = new Set(newChildren);
for (let i = 0; i < this.children.length; i += 1) {
if (!newChildrenSet.has(this.children[i])) {
this.children[i].destroyNode();
}
}
}
this.children = newChildren;
this.applyNodeAttributes();
this.applyRef();
return true;
}
getOptionsAsNodeAttributes() {
return setObjectPrototype(this.options, NodeAttributes);
}
getNodeAttributes(returnCopy=true) {
if (returnCopy) {
return new NodeAttributes(this.options);
} else {
return this.getOptionsAsNodeAttributes();
}
}
// Don't make changes here, unless you're also removing the optimization with NOOP_FUNCTION
extraNodeAttributes(attr) {}
applyNodeAttributes() {
let attr;
if (this.extraNodeAttributes != NOOP_FUNCTION) {
// Create a copy of options, that is modifiable
attr = this.getNodeAttributes(true);
this.extraNodeAttributes(attr);
} else {
attr = this.getNodeAttributes(false);
}
attr.apply(this.node, this.constructor.domAttributesMap);
// TODO: this.styleSheet.container should be added to this.addClass
}
setAttribute(key, value) {
this.getOptionsAsNodeAttributes().setAttribute(key, value, this.node, this.constructor.domAttributesMap);
}
setStyle(key, value) {
if (typeof key === "object") {
for (const [styleKey, styleValue] of Array.from(Object.entries(key))) {
this.setStyle(styleKey, styleValue);
}
return;
}
this.getOptionsAsNodeAttributes().setStyle(key, value, this.node);
}
removeStyle(key) {
this.getOptionsAsNodeAttributes().removeStyle(key, this.node);
}
addClass(className) {
this.getOptionsAsNodeAttributes().addClass(className, this.node);
}
removeClass(className) {
this.getOptionsAsNodeAttributes().removeClass(className, this.node);
}
hasClass(className) {
return this.getOptionsAsNodeAttributes().hasClass(className);
}
toggleClass(className) {
if (!this.hasClass(className)) {
this.addClass(className);
} else {
this.removeClass(className);
}
}
get styleSheet() {
return this.getStyleSheet();
}
addListenersFromOptions() {
for (const key in this.options) {
if (typeof key === "string" && key.startsWith("on") && key.length > 2) {
const eventType = key.substring(2);
const addListenerMethodName = "add" + eventType + "Listener";
const handlerMethodName = "on" + eventType + "Handler";
// The handlerMethod might have been previously added
// by a previous call to this function or manually by the user
if (typeof this[addListenerMethodName] === "function" && !this.hasOwnProperty(handlerMethodName)) {
this[handlerMethodName] = (...args) => {
if (this.options[key]) {
this.options[key](...args, this);
}
};
// Actually add the listener
this[addListenerMethodName](this[handlerMethodName]);
}
}
}
}
refLink(name) {
return {parent: this, name: name};
}
refLinkArray(arrayName, index) {
if (!this.hasOwnProperty(arrayName)) {
this[arrayName] = [];
}
return {parent: this[arrayName], name: index};
}
bindToNode(node, doRedraw) {
this.node = node;
if (doRedraw) {
this.clearNode();
this.redraw();
}
return this;
}
mount(parent, nextSiblingNode) {
if (!parent.node) {
parent = new UI.Element().bindToNode(parent);
}
this.parent = parent;
if (this.node) {
parent.insertChildNodeBefore(this, nextSiblingNode);
this.dispatch("changeParent", this.parent);
return;
}
this.createNode();
this.redraw();
parent.insertChildNodeBefore(this, nextSiblingNode);
this.addListenersFromOptions();
this.onMount();
}
// You need to overwrite the next child manipulation rutines if this.options.children !== this.children
appendChild(child) {
// TODO: the next check should be done with a decorator
if (this.children !== this.options.children) {
throw "Can't properly handle appendChild, you need to implement it for " + this.constructor;
}
this.options.children.push(child);
child.mount(this, null);
return child;
}
insertChild(child, position) {
if (this.children !== this.options.children) {
throw "Can't properly handle insertChild, you need to implement it for " + this.constructor;
}
position = position || 0;
this.options.children.splice(position, 0, child);
const nextChildNode = position + 1 < this.options.children.length ? this.children[position + 1].node : null;
child.mount(this, nextChildNode);
return child;
}
eraseChild(child, destroy = true) {
let index = this.options.children.indexOf(child);
if (index < 0) {
// child not found
return null;
}
return this.eraseChildAtIndex(index, destroy);
}
eraseChildAtIndex(index, destroy=true) {
if (index < 0 || index >= this.options.children.length) {
console.error("Erasing child at invalid index ", index, this.options.children.length);
return;
}
if (this.children !== this.options.children) {
throw "Can't properly handle eraseChild, you need to implement it for " + this.constructor;
}
let erasedChild = this.options.children.splice(index, 1)[0];
if (destroy) {
erasedChild.destroyNode();
} else {
this.node.removeChild(erasedChild.node);
}
return erasedChild;
}
show() {
this.removeClass("hidden");
}
hide() {
this.addClass("hidden");
}
insertChildNodeBefore(childElement, nextSiblingNode) {
this.node.insertBefore(childElement.node, nextSiblingNode);
}
// TODO: should be renamed emptyNode()
clearNode() {
while (this.node && this.node.lastChild) {
this.node.removeChild(this.node.lastChild);
}
}
isInDocument() {
return document.body.contains(this.node);
}
// TODO: this method also doesn't belong here
getWidthOrHeight(parameter) {
let node = this.node;
if (!node) {
return 0;
}
let value = parseFloat(parameter === "width" ? node.offsetWidth : node.offsetHeight);
return value || 0;
}
getHeight() {
return this.getWidthOrHeight("height");
};
getWidth() {
return this.getWidthOrHeight("width");
}
setHeight(value) {
this.setStyle("height", suffixNumber(value, "px"));
this.dispatch("resize");
};
setWidth(value) {
this.setStyle("width", suffixNumber(value, "px"));
this.dispatch("resize");
}
addNodeListener(name, callback, ...args) {
this.node.addEventListener(name, callback, ...args);
const handler = {
remove: () => {
this.removeNodeListener(name, callback, ...args);
}
};
this.addCleanupJob(handler);
return handler;
}
removeNodeListener(name, callback) {
this.node.removeEventListener(name, callback);
}
// TODO: methods can be automatically generated by addNodeListener(UI.Element, "dblclick", "DoubleClick") for instance
addClickListener(callback) {
return this.addNodeListener("click", callback);
}
removeClickListener(callback) {
this.removeNodeListener("click", callback);
}
addDoubleClickListener(callback) {
return this.addNodeListener("dblclick", callback);
}
removeDoubleClickListener(callback) {
this.removeNodeListener("dblclick", callback);
}
} |
JavaScript | class Admin extends Component {
render() {
const {routes} = this.props.route;
const {classes, location} = this.props;
const routePathName = location.pathname.split('/').pop();
return (
<div className={classes.root}>
<SideBar/>
<main className={classes.content}>
<NavBar title={routePathName}/>
{renderRoutes(routes)}
</main>
</div>
)
}
} |
JavaScript | class VelocityComponent extends Component {
//////////////////////////////////////////////////////////////////////////////
// Private Properties
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Public Properties
//////////////////////////////////////////////////////////////////////////////
/**
* @public
* @readonly
* @return {number}
*/
get x() {
return this.state.x;
}
/**
* @public
* @readonly
* @return {number}
*/
get y() {
return this.state.y;
}
/**
* VelocityComponent
* @constructor
* @param {number} type - The type of component.
* @param {number} entityId - The id of the parent entity.
* @param {object} state - The state of the component.
*/
constructor(type, entityId, state) {
super(type, entityId, state);
}
//////////////////////////////////////////////////////////////////////////////
// Public Methods
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Private Methods
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Static Methods
//////////////////////////////////////////////////////////////////////////////
/**
* Static factory method.
* @static
* @param {number} type - The type of component.
* @param {number} entityId - The id of the parent entity.
* @param {object} state - The state of the component.
*
* @return {VelocityComponent} A new velocity component instance.
*/
static createInstance(type, entityId, state) {
return new VelocityComponent(type, entityId, state);
}
} |
JavaScript | class OverlayTopology {
constructor(config, options) {
this.features = config
this.options = options
this.layer = []
this.createLayers()
}
createLayers() {
for (const feature of this.features) {
switch (feature.type) {
case 'earthquake': {
let layer = this.createEarthquakeLayer(feature)
if (layer) this.layer.push(layer)
break;
}
case 'quarry blast': {
let layer = this.createQuarryBlastLayer(feature)
if (layer) this.layer.push(layer)
break;
}
default: {
break;
}
}
}
}
createQuarryBlastLayer(data) {
if(!this.options['quarry blast']) return
let size = Math.ceil(data.mag)
return L.circleMarker([data.lat, data.lng], {
...this.options['quarry blast'].style,
radius: size * 2
}).bindPopup(`${data.title}`)
}
createEarthquakeLayer(data) {
if(!this.options['earthquake']) return
let size = Math.ceil(data.mag)
return L.circleMarker([data.lat, data.lng], {
...this.options['earthquake'].style,
radius: size * 2
}).bindPopup(`${data.title}`)
}
drawOverlayTopology(map) {
for (const l of this.layer) {
l.addTo(map)
}
}
hideOverlayTopology(map) {
for (const l of this.layer) {
l.removeFrom(map)
}
}
} |
JavaScript | class StackedSetMap {
/**
* @param {Map<K, V>[]=} parentStack an optional parent
*/
constructor(parentStack) {
/** @type {Map<K, InternalCell<V>>} */
this.map = new Map();
/** @type {Map<K, InternalCell<V>>[]} */
this.stack = parentStack === undefined ? [] : parentStack.slice();
this.stack.push(this.map);
}
/**
* @param {K} item the item to add
* @returns {void}
*/
add(item) {
this.map.set(item, true);
}
/**
* @param {K} item the key of the element to add
* @param {V} value the value of the element to add
* @returns {void}
*/
set(item, value) {
this.map.set(item, value === undefined ? UNDEFINED_MARKER : value);
}
/**
* @param {K} item the item to delete
* @returns {void}
*/
delete(item) {
if (this.stack.length > 1) {
this.map.set(item, TOMBSTONE);
} else {
this.map.delete(item);
}
}
/**
* @param {K} item the item to test
* @returns {boolean} true if the item exists in this set
*/
has(item) {
const topValue = this.map.get(item);
if (topValue !== undefined) {
return topValue !== TOMBSTONE;
}
if (this.stack.length > 1) {
for (let i = this.stack.length - 2; i >= 0; i--) {
const value = this.stack[i].get(item);
if (value !== undefined) {
this.map.set(item, value);
return value !== TOMBSTONE;
}
}
this.map.set(item, TOMBSTONE);
}
return false;
}
/**
* @param {K} item the key of the element to return
* @returns {Cell<V>} the value of the element
*/
get(item) {
const topValue = this.map.get(item);
if (topValue !== undefined) {
return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER
? undefined
: topValue;
}
if (this.stack.length > 1) {
for (let i = this.stack.length - 2; i >= 0; i--) {
const value = this.stack[i].get(item);
if (value !== undefined) {
this.map.set(item, value);
return value === TOMBSTONE || value === UNDEFINED_MARKER
? undefined
: value;
}
}
this.map.set(item, TOMBSTONE);
}
return undefined;
}
_compress() {
if (this.stack.length === 1) return;
this.map = new Map();
for (const data of this.stack) {
for (const pair of data) {
if (pair[1] === TOMBSTONE) {
this.map.delete(pair[0]);
} else {
this.map.set(pair[0], pair[1]);
}
}
}
this.stack = [this.map];
}
asArray() {
this._compress();
return Array.from(this.map.keys());
}
asSet() {
this._compress();
return new Set(this.map.keys());
}
asPairArray() {
this._compress();
return Array.from(this.map.entries(), extractPair);
}
asMap() {
return new Map(this.asPairArray());
}
get size() {
this._compress();
return this.map.size;
}
createChild() {
return new StackedSetMap(this.stack);
}
} |
JavaScript | class EncryptedSocket extends EventEmitter {
constructor(socket, publicKey, secretKey) {
super()
this.socket = socket
this.publicKey = publicKey
this.secretKey = secretKey
this._error = this._error.bind(this)
this._onReceive = this._onReceive.bind(this)
this._authTimeout = this._authTimeout.bind(this)
this.destroy = this.destroy.bind(this)
this.socket.once('close', this.destroy)
}
/**
* Connect to peer
* @param {*} hostKey If present, authenticate with the host
* @param {*} initiator Whether this connection is initiating
*/
connect(hostKey) {
if (hostKey) {
this._authHost(hostKey)
} else {
this._authPeer()
}
this._authTimeoutId = setTimeout(this._authTimeout, AUTH_TIMEOUT)
}
_authTimeout() {
this._authTimeoutId = null
this._error(`Auth timed out`)
}
_setupSocket() {
this._encode = lpstream.encode()
this._decode = lpstream.decode()
this._decode.on('data', this._onReceive)
this._decode.once('error', this._error)
this._encode.pipe(this.socket)
this.socket.pipe(this._decode)
}
_setupEncryptionKey(peerKey) {
if (!this.sharedKey) {
this.peerKey = peerKey
this.sharedKey = enc.scalarMultiplication(this.secretKey, this.peerKey)
this._setupSocket()
}
}
/** Auth connection to host */
_authHost(hostKey) {
const self = this
/** 1. Send auth request with encrypted identity */
function sendAuthRequest() {
const box = crypto.seal(self.publicKey, self.peerKey)
// Send without shared key encryption until peer can derive it
self.socket.write(box)
self.once('data', receiveChallenge)
}
/** 2. Receive challenge to decrypt, send back decrypted */
function receiveChallenge(challenge) {
self.write(challenge)
self.once('data', receiveAuthSuccess)
}
/** 3. Receive auth success */
function receiveAuthSuccess(data) {
if (data.equals(SUCCESS)) {
self._onAuthed()
}
}
this._setupEncryptionKey(hostKey)
sendAuthRequest()
}
/** Auth connection to peer */
_authPeer(socket, publicKey, secretKey) {
const self = this
let challenge
/** 1. Learn peer identity */
function receiveAuthRequest(data) {
const buf = Buffer.from(data)
const peerPublicKey = crypto.unseal(buf, self.publicKey, self.secretKey)
if (!peerPublicKey) {
self._error('Failed to unseal peer box')
return
}
if (self.publicKey.equals(peerPublicKey)) {
// debug('Auth request key is the same as the host')
// return
}
self._setupEncryptionKey(peerPublicKey)
sendChallenge()
}
/** 2. Respond with challenge to decrypt */
function sendChallenge() {
challenge = enc.nonce()
self.write(challenge)
self.once('data', receiveChallengeVerification)
}
/** 3. Verify decrypted challenge */
function receiveChallengeVerification(decryptedChallenge) {
if (challenge.equals(decryptedChallenge)) {
self.write(SUCCESS)
self._onAuthed()
} else {
self._error('Failed to authenticate peer')
}
}
this.socket.once('data', receiveAuthRequest)
}
_onAuthed() {
if (this._authTimeoutId) {
clearTimeout(this._authTimeoutId)
this._authTimeoutId = null
}
this.emit('connection')
}
write(data) {
if (!this.socket) {
return
}
if (!this.sharedKey) {
this._error(`EncryptedSocket failed to write. Missing 'sharedKey'`)
return
}
const nonce = enc.nonce()
const box = enc.encrypt(data, nonce, this.sharedKey)
const msg = Buffer.alloc(nonce.length + box.length)
nonce.copy(msg)
box.copy(msg, nonce.length)
this._encode.write(msg)
debug(`Write ${msg.length} to ${this.peerKey.toString('hex')}`)
}
_onReceive(data) {
if (!this.socket) {
// Received chunk after socket destroyed
return
}
if (!this.sharedKey) {
this._error(`EncryptedSocket failed to receive. Missing 'sharedKey'`)
return
}
debug(`Received ${data.length} from ${this.peerKey.toString('hex')}`)
const nonce = data.slice(0, sodium.crypto_box_NONCEBYTES)
const box = data.slice(sodium.crypto_box_NONCEBYTES, data.length)
const msg = enc.decrypt(box, nonce, this.sharedKey)
if (!msg) {
this._error('EncryptedSocket failed to decrypt received data.')
return
}
this.emit('data', msg)
}
destroy(destroySocket = true) {
if (this._authTimeoutId) {
clearTimeout(this._authTimeoutId)
this._authTimeoutId = null
}
if (this._decode) {
if (this.socket) {
this.socket.unpipe(this._decode)
}
this._decode.unpipe()
this._decode.destroy()
this._decode = null
this._encode.unpipe()
this._encode.destroy()
this._encode = null
}
if (this.socket) {
this.socket.removeListener('close', this.destroy)
if (destroySocket) {
this.socket.destroy()
}
this.socket = null
}
this.emit('close')
}
_error(err) {
debug(`[EncryptedSocket]`, err)
this.emit('error', err)
this.destroy()
}
} |
JavaScript | class Simple extends AbstractModel {
constructor(){
super();
/**
* HTML code after base64 encoding. To ensure correct display, this parameter should include all code information and cannot contain external CSS.
* @type {string || null}
*/
this.Html = null;
/**
* Plain text content after base64 encoding. If HTML is not involved, the plain text will be displayed in the email. Otherwise, this parameter represents the plain text style of the email.
* @type {string || null}
*/
this.Text = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Html = 'Html' in params ? params.Html : null;
this.Text = 'Text' in params ? params.Text : null;
}
} |
JavaScript | class Attachment extends AbstractModel {
constructor(){
super();
/**
* Attachment name, which cannot exceed 255 characters. Some attachment types are not supported. For details, see [Attachment Types](https://intl.cloud.tencent.com/document/product/1288/51951?from_cn_redirect=1).
* @type {string || null}
*/
this.FileName = null;
/**
* Attachment content after base64 encoding. A single attachment cannot exceed 5 MB. Note: Tencent Cloud APIs require that a request packet should not exceed 10 MB. If you are sending multiple attachments, the total size of these attachments cannot exceed 10 MB.
* @type {string || null}
*/
this.Content = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.FileName = 'FileName' in params ? params.FileName : null;
this.Content = 'Content' in params ? params.Content : null;
}
} |
JavaScript | class Template extends AbstractModel {
constructor(){
super();
/**
* Template ID. If you don’t have any template, please create one.
* @type {number || null}
*/
this.TemplateID = null;
/**
* Variable parameters in the template. Please use `json.dump` to format the JSON object into a string type. The object is a set of key-value pairs. Each key denotes a variable, which is represented by {{key}}. The key will be replaced with the corresponding value (represented by {{value}}) when sending the email.
* @type {string || null}
*/
this.TemplateData = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TemplateID = 'TemplateID' in params ? params.TemplateID : null;
this.TemplateData = 'TemplateData' in params ? params.TemplateData : null;
}
} |
JavaScript | class EmailSender extends AbstractModel {
constructor(){
super();
/**
* Sender address.
* @type {string || null}
*/
this.EmailAddress = null;
/**
* Sender name.
Note: this field may return `null`, indicating that no valid values can be obtained.
* @type {string || null}
*/
this.EmailSenderName = null;
/**
* Creation time.
Note: this field may return `null`, indicating that no valid values can be obtained.
* @type {number || null}
*/
this.CreatedTimestamp = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.EmailAddress = 'EmailAddress' in params ? params.EmailAddress : null;
this.EmailSenderName = 'EmailSenderName' in params ? params.EmailSenderName : null;
this.CreatedTimestamp = 'CreatedTimestamp' in params ? params.CreatedTimestamp : null;
}
} |
JavaScript | class Volume extends AbstractModel {
constructor(){
super();
/**
* Date
Note: this field may return `null`, indicating that no valid values can be obtained.
* @type {string || null}
*/
this.SendDate = null;
/**
* Number of email requests.
* @type {number || null}
*/
this.RequestCount = null;
/**
* Number of email requests accepted by Tencent Cloud.
* @type {number || null}
*/
this.AcceptedCount = null;
/**
* Number of delivered emails.
* @type {number || null}
*/
this.DeliveredCount = null;
/**
* Number of users (deduplicated) who opened emails.
* @type {number || null}
*/
this.OpenedCount = null;
/**
* Number of recipients who clicked on links in emails.
* @type {number || null}
*/
this.ClickedCount = null;
/**
* Number of bounced emails.
* @type {number || null}
*/
this.BounceCount = null;
/**
* Number of users who canceled subscriptions.
Note: this field may return `null`, indicating that no valid values can be obtained.
* @type {number || null}
*/
this.UnsubscribeCount = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.SendDate = 'SendDate' in params ? params.SendDate : null;
this.RequestCount = 'RequestCount' in params ? params.RequestCount : null;
this.AcceptedCount = 'AcceptedCount' in params ? params.AcceptedCount : null;
this.DeliveredCount = 'DeliveredCount' in params ? params.DeliveredCount : null;
this.OpenedCount = 'OpenedCount' in params ? params.OpenedCount : null;
this.ClickedCount = 'ClickedCount' in params ? params.ClickedCount : null;
this.BounceCount = 'BounceCount' in params ? params.BounceCount : null;
this.UnsubscribeCount = 'UnsubscribeCount' in params ? params.UnsubscribeCount : null;
}
} |
JavaScript | class SendEmailStatus extends AbstractModel {
constructor(){
super();
/**
* `MessageId` field returned by the `SendEmail` API
* @type {string || null}
*/
this.MessageId = null;
/**
* Recipient email address
* @type {string || null}
*/
this.ToEmailAddress = null;
/**
* Sender email address
* @type {string || null}
*/
this.FromEmailAddress = null;
/**
* Tencent Cloud processing status:
0: successful.
1001: internal system exception.
1002: internal system exception.
1003: internal system exception.
1003: internal system exception.
1004: email sending timeout.
1005: internal system exception.
1006: you have sent too many emails to the same address in a short period.
1007: the email address is in the blocklist.
1009: internal system exception.
1010: daily email sending limit exceeded.
1011: no permission to send custom content. Use a template.
2001: no results found.
3007: invalid template ID or unavailable template.
3008: template status exception.
3009: no permission to use this template.
3010: the format of the `TemplateData` field is incorrect.
3014: unable to send the email because the sender domain is not verified.
3020: the recipient email address is in the blocklist.
3024: failed to pre-check the email address format.
3030: email sending is restricted temporarily due to high bounce rate.
3033: the account has insufficient balance or overdue payment.
* @type {number || null}
*/
this.SendStatus = null;
/**
* Recipient processing status:
0: Tencent Cloud has accepted the request and added it to the send queue.
1: the email is delivered successfully, `DeliverTime` indicates the time when the email is delivered successfully.
2: the email is discarded. `DeliverMessage` indicates the reason for discarding.
3: the recipient's ESP rejects the email, probably because the email address does not exist or due to other reasons.
8: the email is delayed by the ESP. `DeliverMessage` indicates the reason for delay.
* @type {number || null}
*/
this.DeliverStatus = null;
/**
* Description of the recipient processing status
* @type {string || null}
*/
this.DeliverMessage = null;
/**
* Timestamp when the request arrives at Tencent Cloud
* @type {number || null}
*/
this.RequestTime = null;
/**
* Timestamp when Tencent Cloud delivers the email
* @type {number || null}
*/
this.DeliverTime = null;
/**
* Whether the recipient has opened the email
* @type {boolean || null}
*/
this.UserOpened = null;
/**
* Whether the recipient has clicked the links in the email
* @type {boolean || null}
*/
this.UserClicked = null;
/**
* Whether the recipient has unsubscribed from emails sent by the sender
* @type {boolean || null}
*/
this.UserUnsubscribed = null;
/**
* Whether the recipient has reported the sender
* @type {boolean || null}
*/
this.UserComplainted = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.MessageId = 'MessageId' in params ? params.MessageId : null;
this.ToEmailAddress = 'ToEmailAddress' in params ? params.ToEmailAddress : null;
this.FromEmailAddress = 'FromEmailAddress' in params ? params.FromEmailAddress : null;
this.SendStatus = 'SendStatus' in params ? params.SendStatus : null;
this.DeliverStatus = 'DeliverStatus' in params ? params.DeliverStatus : null;
this.DeliverMessage = 'DeliverMessage' in params ? params.DeliverMessage : null;
this.RequestTime = 'RequestTime' in params ? params.RequestTime : null;
this.DeliverTime = 'DeliverTime' in params ? params.DeliverTime : null;
this.UserOpened = 'UserOpened' in params ? params.UserOpened : null;
this.UserClicked = 'UserClicked' in params ? params.UserClicked : null;
this.UserUnsubscribed = 'UserUnsubscribed' in params ? params.UserUnsubscribed : null;
this.UserComplainted = 'UserComplainted' in params ? params.UserComplainted : null;
}
} |
JavaScript | class TemplatesMetadata extends AbstractModel {
constructor(){
super();
/**
* Creation time.
* @type {number || null}
*/
this.CreatedTimestamp = null;
/**
* Template name.
* @type {string || null}
*/
this.TemplateName = null;
/**
* Template status. 1: under review; 0: approved; 2: rejected; other values: unavailable.
* @type {number || null}
*/
this.TemplateStatus = null;
/**
* Template ID.
* @type {number || null}
*/
this.TemplateID = null;
/**
* Review reply
* @type {string || null}
*/
this.ReviewReason = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.CreatedTimestamp = 'CreatedTimestamp' in params ? params.CreatedTimestamp : null;
this.TemplateName = 'TemplateName' in params ? params.TemplateName : null;
this.TemplateStatus = 'TemplateStatus' in params ? params.TemplateStatus : null;
this.TemplateID = 'TemplateID' in params ? params.TemplateID : null;
this.ReviewReason = 'ReviewReason' in params ? params.ReviewReason : null;
}
} |
JavaScript | class TemplateContent extends AbstractModel {
constructor(){
super();
/**
* HTML code after base64 encoding.
* @type {string || null}
*/
this.Html = null;
/**
* Text content after base64 encoding.
* @type {string || null}
*/
this.Text = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Html = 'Html' in params ? params.Html : null;
this.Text = 'Text' in params ? params.Text : null;
}
} |
JavaScript | class EmailIdentity extends AbstractModel {
constructor(){
super();
/**
* Sender domain.
* @type {string || null}
*/
this.IdentityName = null;
/**
* Verification type. The value is fixed to `DOMAIN`.
* @type {string || null}
*/
this.IdentityType = null;
/**
* Verification passed or not.
* @type {boolean || null}
*/
this.SendingEnabled = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.IdentityName = 'IdentityName' in params ? params.IdentityName : null;
this.IdentityType = 'IdentityType' in params ? params.IdentityType : null;
this.SendingEnabled = 'SendingEnabled' in params ? params.SendingEnabled : null;
}
} |
JavaScript | class BlackEmailAddress extends AbstractModel {
constructor(){
super();
/**
* Time when the email address is blocklisted.
* @type {string || null}
*/
this.BounceTime = null;
/**
* Blocklisted email address.
* @type {string || null}
*/
this.EmailAddress = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.BounceTime = 'BounceTime' in params ? params.BounceTime : null;
this.EmailAddress = 'EmailAddress' in params ? params.EmailAddress : null;
}
} |
JavaScript | class DNSAttributes extends AbstractModel {
constructor(){
super();
/**
* Record types: CNAME, A, TXT, and MX.
* @type {string || null}
*/
this.Type = null;
/**
* Domain name.
* @type {string || null}
*/
this.SendDomain = null;
/**
* Expected value.
* @type {string || null}
*/
this.ExpectedValue = null;
/**
* Currently configured value.
* @type {string || null}
*/
this.CurrentValue = null;
/**
* Approved or not. The default value is `false`.
* @type {boolean || null}
*/
this.Status = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Type = 'Type' in params ? params.Type : null;
this.SendDomain = 'SendDomain' in params ? params.SendDomain : null;
this.ExpectedValue = 'ExpectedValue' in params ? params.ExpectedValue : null;
this.CurrentValue = 'CurrentValue' in params ? params.CurrentValue : null;
this.Status = 'Status' in params ? params.Status : null;
}
} |
JavaScript | class ExpressError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
} |
JavaScript | class NotFoundError extends ExpressError {
constructor(message = 'Not Found') {
super(message, 404);
}
} |
JavaScript | class UnauthorizedError extends ExpressError {
constructor(message = 'Unauthorized') {
super(message, 401);
}
} |
JavaScript | class BadRequestError extends ExpressError {
constructor(message = 'Bad Request') {
super(message, 400);
}
} |
JavaScript | class ForbiddenError extends ExpressError {
constructor(message = 'Bad Request') {
super(message, 403);
}
} |
JavaScript | class Variables {
constructor(sqz) {
this.sqz = sqz;
}
/**
* Returns all available variables
*
* @Return {String} variables - all variables
* @name this.sqz.variables.get
*/
get() {
return this.sqz.vars;
}
/**
* Returns current selected stage
*
* @Return {String} stage - stage value
* @name this.sqz.variables.getStage
*/
getStage() {
return this.sqz.vars.stage;
}
/**
* Returns current selected region
*
* @Return {String} region - region value
* @name this.sqz.variables.getRegion
*/
getRegion() {
return this.sqz.vars.region;
}
/**
* Returns project config variables
*
* @Return {Object} project - project data
* @name this.sqz.variables.getProject
*/
getProject() {
return this.sqz.vars.project;
}
/**
* Returns project's hooks
*
* @Return {Object} hooks - hooks data
* @name this.sqz.variables.getHooks
*/
getHooks() {
return this.sqz.vars.hooks;
}
} |
JavaScript | class Device extends EventEmitter {
constructor () {
super();
this.hid = null;
this._index = 0;
}
/**
* Connect to the toypad
*/
connect () {
debug('Connecting to toypad...');
if (this.hid) {
debug('Connection was already established, closing existing connection and re-connecting...');
this.disconnect();
}
this.hid = new HID.HID(VENDOR_ID, PRODUCT_ID);
this.hid.on('data', this._onHidData.bind(this));
this.hid.on('error', this._onHidError.bind(this));
// Initialize handshake
this.hid.write([
0x00, 0x55, 0x0f, 0xb0, 0x01, 0x28, 0x63, 0x29, 0x20, 0x4c, 0x45, 0x47, 0x4f, 0x20, 0x32, 0x30, 0x31,
0x34, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]);
}
/**
* Disconnect from the toypad
*/
disconnect () {
debug('Disconnecting from toypad...');
if (!this.hid) {
debug('No connection to close...');
return;
}
this.hid.close();
this.hid = null;
}
/**
* Send data packet to the toypad.
* @param {Buffer} command 3 byte prefix like [0x55, 0x06, 0xc0]
* @param {Buffer} data Binary data to send
* @return {number} the command index used for sending the packet
*/
sendPacket(command, data) {
var index = this._commandIndex();
this._write(command.concat(index, data));
return index;
}
/**
* Get the next index value to use for the next command to send.
* @return {number}
*/
_commandIndex() {
var index = this._index & 0xff;
this._index++;
return index;
}
/**
* Request to read memory from the tag. This is async request so will need to request then listen for the response.
* This is still a work in progress so the signature will probably change when we get it fully working.
* @param {number} tagIndex Tag index
* @param {number} pageNum
* @todo Finish up this method including emitting a parsed response, move it to the main toypad class
* @private
*/
_readTag(tagIndex, pageNum) {
debug('readTag: Sending command to read the %d page for tag with index %d', pageNum, tagIndex);
debug('Note: This is still experimental, responses are not yet emitted (still figuring out how to parse)');
debug(
'Index used for request: %d (will need this when getting results. Probably. It is experimental, remember?)',
this._index
);
this._write([0x55, 0x04, 0xd2, this._commandIndex(), tagIndex & 0xff, pageNum & 0xff]);
this._commandIndex++;
// todo: return command index as it appears to be needed to tell what results go to what request...
// Maybe this should be done for all commands?
}
/**
* Internal handler when data is emitted from HID. Handles emitting an appropriate event depending on the data.
* @param {string} data
* @private
*/
_onHidData (data) {
debugHidRaw('read: %o', data);
var out = {
command: commands[data[1]] || null,
commandRaw: data[1],
// include raw data for figuring out new commands
dataRaw: data
};
// parse command specific data:
switch(out.command) {
case 'minifig-scan':
out.panel = data[2];
out.minifigIndex = data[4];
out.action = data[5];
out.uid = data.slice(7, 13);
break;
case 'connected':
// todo: any interesting / useful info to extract?
case 'tag-not-found':
// todo
case 'tag-read':
// todo
case 'led-change':
// todo
}
debug('Parsed data for emit: %o', out);
this.emit('data', out);
}
/**
* Handler used internally when error is emitted by HID
* @param {object} error
* @private
*/
_onHidError (error) {
debugHid('error: %O', error);
this.emit('error', error);
}
/**
* Internal method to write data to the HID device, adding padding and checksum automatically.
* @param {string} data Data to write
* @private
*/
_write (data) {
if (!this.hid) {
error('Cannot send, not connected to toypad.');
return;
}
debugHidRaw('write: %o', data);
this.hid.write(
[0x00].concat(
this._pad(
this._checksum(data)
)
)
);
}
/**
* Used internally to add checksum to the data.
* @param {string} data
* @return {string} Data with checksum added
* @private
*/
_checksum (data) {
var checksum = 0;
for (var i = 0; i < data.length; i++) {
checksum += data[i];
}
data.push(checksum & 0xFF);
return data;
}
/**
* Used internally to pad the data with 0 up to 32 bytes
* @param {string} data
* @return {string} Data with padding added
* @private
*/
_pad (data) {
while(data.length < 32) {
data.push(0x00);
}
return data;
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
meals: []
};
}
componentDidMount() {
console.log("calling api");
fetch("http://localhost:3000/api/meals/")
.then(res => res.json())
.then(
result => {
console.log("got meals: ", result);
this.setState({
isLoaded: true,
meals: result.meals
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
return (
<ul className="list flex flex-wrap">
{this.state.meals.map(function(meal, i) {
return (
<li key={i} className="w6 pa3 mr2">
<MealChart mealData={meal} />
</li>
);
})}
</ul>
);
}
} |
JavaScript | class IoTHubEventSourceResource extends models['EventSourceResource'] {
/**
* Create a IoTHubEventSourceResource.
* @member {string} [provisioningState] Provisioning state of the resource.
* Possible values include: 'Accepted', 'Creating', 'Updating', 'Succeeded',
* 'Failed', 'Deleting'
* @member {date} [creationTime] The time the resource was created.
* @member {string} [timestampPropertyName] The event property that will be
* used as the event source's timestamp. If a value isn't specified for
* timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
* @member {string} eventSourceResourceId The resource id of the event source
* in Azure Resource Manager.
* @member {string} iotHubName The name of the iot hub.
* @member {string} consumerGroupName The name of the iot hub's consumer
* group that holds the partitions from which events will be read.
* @member {string} keyName The name of the Shared Access Policy key that
* grants the Time Series Insights service access to the iot hub. This shared
* access policy key must grant 'service connect' permissions to the iot hub.
*/
constructor() {
super();
}
/**
* Defines the metadata of IoTHubEventSourceResource
*
* @returns {object} metadata of IoTHubEventSourceResource
*
*/
mapper() {
return {
required: false,
serializedName: 'Microsoft.IotHub',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'kind',
clientName: 'kind'
},
uberParent: 'BaseResource',
className: 'IoTHubEventSourceResource',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
kind: {
required: true,
serializedName: 'kind',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'Enum',
allowedValues: [ 'Accepted', 'Creating', 'Updating', 'Succeeded', 'Failed', 'Deleting' ]
}
},
creationTime: {
required: false,
readOnly: true,
serializedName: 'properties.creationTime',
type: {
name: 'DateTime'
}
},
timestampPropertyName: {
required: false,
serializedName: 'properties.timestampPropertyName',
type: {
name: 'String'
}
},
eventSourceResourceId: {
required: true,
serializedName: 'properties.eventSourceResourceId',
type: {
name: 'String'
}
},
iotHubName: {
required: true,
serializedName: 'properties.iotHubName',
type: {
name: 'String'
}
},
consumerGroupName: {
required: true,
serializedName: 'properties.consumerGroupName',
type: {
name: 'String'
}
},
keyName: {
required: true,
serializedName: 'properties.keyName',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class ImageResize {
/**
* constructor - make image maps responsive
* @param {Object} config - setting for responsive image map
*/
constructor(config) {
const { width, height, element } = config;
this.imageW = width;
this.imageH = height;
this.imageMap = document.querySelector(element);
const mapId = this.imageMap.getAttribute('usemap');
const mapElem = `map[name="${mapId.substring(1, mapId.length)}"]`;
const area = document.querySelector(mapElem).children;
this.areaArray = Array.from(area);
window.addEventListener('resize', this.resizeEvent);
setTimeout(this.imgMap, 500);
}
/**
* getCoords - get image map coordinates
* @param {Node} elem - area tag
* @return {String} - area map coordinates
*/
getCoordinates = (elem) => {
let areaCords = elem.dataset.coords;
if (!areaCords) {
areaCords = elem.getAttribute('coords');
elem.dataset.coords = areaCords;
}
return areaCords;
};
imgMap = () => {
this.wPercent = this.imageMap.offsetWidth / 100;
this.hPercent = this.imageMap.offsetHeight / 100;
this.areaArray.forEach(this.areaLoop);
};
/**
* areaLoop - Loop through area tags for image map
* @param {Node} area - Area tag
*/
areaLoop = (area) => {
const coordinates = this.getCoordinates(area).split(',');
const coordsPercent = coordinates.map(this.mapCoords).join();
area.setAttribute('coords', coordsPercent);
};
/**
* mapCoords - Set new image map coordinates based on new image width and height
* @param {String} coordinate - coordinates from image map array
* @param {Num} index - Loop index
* @return {Num} - New image map coordinates
*/
mapCoords = (coordinate, index) => {
const parseCord = parseInt(coordinate, 10);
return index % 2 === 0
? this.coordinatesMath(parseCord, this.imageW, this.wPercent)
: this.coordinatesMath(parseCord, this.imageH, this.hPercent);
};
/**
* coordinatesMath Set new coordinates from original image map coordinates
* @param {number} coordinates - original image map coordinate
* @param {number} imgVal - Image width or height value
* @param {number} percentVal - New image width or height divided by 100
* @return {number} - New image map coordinates
*/
coordinatesMath = (coordinates, imgVal, percentVal) =>
(coordinates / imgVal) * 100 * percentVal;
/**
* resizeEvent - Resize Event
*/
resizeEvent = () => {
this.imgMap();
};
} |
JavaScript | @connect(({ organStructure }) => ({
organStructure,
}))
@Form.create()
class OrganStructureCard extends PureComponent {
onOKClick = () => {
const { form, onSubmit } = this.props;
form.validateFieldsAndScroll((err, values) => {
if (!err) {
const formData = { ...values };
formData.sequence = parseInt(formData.sequence, 10);
formData.org_type = parseInt(formData.org_type, 10);
onSubmit(formData);
}
});
};
dispatch = action => {
const { dispatch } = this.props;
dispatch(action);
};
toTreeSelect = data => {
if (!data) {
return [];
}
const newData = [];
for (let i = 0; i < data.length; i += 1) {
const item = { ...data[i], title: data[i].name, value: data[i].record_id };
if (item.children && item.children.length > 0) {
item.children = this.toTreeSelect(item.children);
}
newData.push(item);
}
return newData;
};
render() {
const {
organStructure: { formVisible, formTitle, formData, submitting, treeData },
form: { getFieldDecorator },
onCancel,
} = this.props;
const formItemLayout = {
labelCol: {
span: 6,
},
wrapperCol: {
span: 18,
},
};
const formItemLayouttwo = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const formItemLayoutmome = {
labelCol: {
span: 3,
},
wrapperCol: {
span: 21,
},
};
return (
<Modal
title={formTitle}
width={850}
visible={formVisible}
maskClosable={false}
confirmLoading={submitting}
destroyOnClose
onOk={this.onOKClick}
onCancel={onCancel}
style={{ top: 20 }}
bodyStyle={{ maxHeight: 'calc( 100vh - 158px )', overflowY: 'auto' }}
>
<Card bordered={false}>
<Form>
<Row>
<Col span={12}>
<Form.Item {...formItemLayout} label="机构名称">
{getFieldDecorator('name', {
initialValue: formData.name,
rules: [
{
required: true,
message: '请输入机构名称',
},
],
})(<Input placeholder="请输入" />)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item {...formItemLayout} label="机构类型">
{getFieldDecorator('org_type', {
initialValue: formData.org_type,
rules: [
{
required: true,
message: '请输入类型',
},
],
})(
// <DictionaryCascader code="pa$#organtype" />
<DicSelect
vmode="int"
pcode="pa$#organtype"
selectProps={{ placeholder: '请选择' }}
/>
)
}
</Form.Item>
</Col>
</Row>
<Row>
<Col span={12}>
<Form.Item {...formItemLayout} label="机构上级上级">
{getFieldDecorator('parent_id', {
initialValue: formData.parent_id,
})(
<TreeSelect
showSearch
treeNodeFilterProp="title"
style={{ width: '100%' }}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={this.toTreeSelect(treeData)}
placeholder="请选择"
/>
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item {...formItemLayouttwo} label="排序值(降序)">
{getFieldDecorator('sequence', {
initialValue: formData.sequence ? formData.sequence.toString() : '1000000',
rules: [
{
required: true,
message: '请输入排序值',
},
],
})(<InputNumber min={1} style={{ width: '100%' }} />)}
</Form.Item>
</Col>
</Row>
<Row>
<Col span={24}>
<Form.Item {...formItemLayoutmome} label="备注">
{getFieldDecorator('memo', {
initialValue: formData.memo,
rules: [
{
required: false,
message: '请输入',
},
],
})(<Input.TextArea placeholder="请输入" />)}
</Form.Item>
</Col>
</Row>
</Form>
</Card>
</Modal>
);
}
} |
JavaScript | class ServerError extends Error {
static SERVER_ERROR = 'server.error';
static NOT_FOUND = 'request.notFound';
static INVALID_RESPONSE = 'response.invalid';
static NETWORK_ERROR = 'request.networkError';
static UNKNOWN_ERROR = 'unknown';
static NOT_AUTHENTICATED = 'auth.notAuthenticated';
static INVALID_TOKEN = 'auth.invalidToken';
static AUTH_FAILED = 'auth.failed';
static AUTH_DENIED = 'auth.denied';
static RESTORE_FAILED = 'restore.failed';
static RESTORE_LIMIT_REACHED = 'restore.limitReached';
/**
* @param {string|null} code
* @param {string|null} message
*/
constructor(code = null, message = null) {
super(message || code);
this.code = code;
}
/**
* Returns true if this error is the same error code.
* @param {string} code
*/
is(code) {
return this.code === code;
}
} |
JavaScript | class Socket extends EventEmitter {
constructor(id, socket, adaptor) {
super();
this.id = id;
this.socket = socket;
this.remoteAddress = {
ip: socket.stream.remoteAddress,
port: socket.stream.remotePort
};
this.adaptor = adaptor;
socket.on('close', this.emit.bind(this, 'disconnect'));
socket.on('error', this.emit.bind(this, 'disconnect'));
socket.on('disconnect', this.emit.bind(this, 'disconnect'));
socket.on('pingreq', () => {
socket.pingresp();
});
socket.on('subscribe', this.adaptor.onSubscribe.bind(this.adaptor, this));
socket.on('publish', this.adaptor.onPublish.bind(this.adaptor, this));
this.state = ST_INITED;
// TODO: any other events?
}
send(msg) {
if (this.state !== ST_INITED) {
return;
}
if (msg instanceof Buffer) {
// if encoded, send directly
this.socket.stream.write(msg);
} else {
this.adaptor.publish(this, msg);
}
}
sendBatch(msgs) {
for (let i = 0, l = msgs.length; i < l; i++) {
this.send(msgs[i]);
}
}
disconnect() {
if (this.state === ST_CLOSED) {
return;
}
this.state = ST_CLOSED;
this.socket.stream.destroy();
}
} |
JavaScript | class App extends Component {
render() {
return (
<div>
<MainNav/>
<Hero/>
<ContentArea/>
<Footer/>
</div>
);
}
} |
JavaScript | class S8100B extends AnalogTemperatureSensor {
calc(voltage) {
return 30 + (1.508 - voltage) / -0.08; //Temp(Celsius) =
}
static info() {
return {
name: 'S8100B',
};
}
} |
JavaScript | class VegaEmbed extends React.Component {
constructor(props) {
super(props);
this.anchorRef = React.createRef();
}
render() {
return (React.createElement("div", null,
React.createElement(presentational_components_1.Error, { error: this.embedError }),
React.createElement("div", { ref: this.anchorRef })));
}
async callEmbedder() {
var _a, _b, _c, _d;
if (this.anchorRef.current === null) {
return;
}
try {
this.embedResult = await external_1.embed(this.anchorRef.current, this.props.mediaType, this.props.spec, this.props.options);
(_b = (_a = this.props).resultHandler) === null || _b === void 0 ? void 0 : _b.call(_a, this.embedResult);
}
catch (error) {
(_d = (_c = this.props).errorHandler) === null || _d === void 0 ? void 0 : _d.call(_c, error);
this.embedError = error;
this.forceUpdate();
}
}
shouldComponentUpdate(nextProps) {
if (this.props.spec !== nextProps.spec) {
this.embedError = undefined;
return true;
}
else {
return false;
}
}
componentDidMount() {
this.callEmbedder().then();
}
componentDidUpdate() {
if (!this.embedError) {
this.callEmbedder().then();
}
}
componentWillUnmount() {
var _a;
if (this.embedResult) {
if (this.embedResult.finalize) {
this.embedResult.finalize();
}
else if ((_a = this.embedResult.view) === null || _a === void 0 ? void 0 : _a.finalize) {
this.embedResult.view.finalize();
}
this.embedResult = undefined;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.