language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class favorites extends Component {
constructor(props) {
super(props);
this.state = {
name:'',
documents:[],
num:''
};
this.deleteFile=this.deleteFile.bind(this);
userService.getCurrentUser().then((response)=>{
CurrentUser.next(response.data)
this.setState({name:response.data.UTCTNOM})
favoriteService.getFavoris(response.data.UTCTNOM).then((response)=>{
this.setState({ documents: response.data})
})
})
}
selectedFileToDelete(document) {
let id=document.id;
this.setState({
num:id
})
}
async deleteFile(){
await favoriteService.deleteFavorites(this.state.num);
userService.getCurrentUser().then((response)=>{
CurrentUser.next(response.data)
this.setState({name:response.data.UTCTNOM})
favoriteService.getFavoris(response.data.UTCTNOM).then((response)=>{
this.setState({ documents: response.data})
})
})
}
render() {
return(
<div className="component-favorites">
<HeaderFavorites></HeaderFavorites>
<div id="myModal" className="modal fade" tabindex="-1">
<div className="modal-dialog modal-confirm">
<div className="modal-content">
<div className="modal-header flex-column">
<button type="button" className="close" data-dismiss="modal" aria-hidden="true">×</button>
<div className="pos4">
<img src="https://img.icons8.com/flat-round/128/000000/delete-sign.png"/>
</div>
</div>
<div className="modal-body">
<p>Do you really want to delete this document? This process cannot be undone.</p>
<div className="bouton0">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" onClick={this.deleteFile}>Delete</button>
</div>
</div>
</div>
</div>
</div>
<Container className="mt--9" fluid>
<Row className="mt-5">
<Col >
<Card className="shadow">
<Table className="align-items-center table-flush" responsive>
<thead >
<tr>
<th>name</th>
<th>description</th>
<th>creation date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.documents.map(
document =>
<tr key ={this.identifier}>
<td><DescriptionIcon/> {document.name}</td>
<td>{document.description}</td>
<td>{document.creationDate}</td>
<td className="but">
<div class="btn-group">
<button type="button" className="btn btn-danger delete" data-toggle="modal" href="#myModal" onClick={this.selectedFileToDelete.bind(this, document)}>Delete</button>
</div>
</td>
</tr>
)
}
</tbody>
</Table>
</Card>
</Col>
</Row>
</Container>
</div>)
}
} |
JavaScript | class Serverinfo extends Command {
/**
* Creates an instance of Serverinfo
*
* @param {string} file
*/
constructor(file) {
super(file);
}
/**
* Show server's information
*
* @param {Message} message
*/
async run(message) {
let { serverInformation: info } = bot.lang,
guild = message.guild;
let embed = new MessageEmbed()
.setColor(bot.consts.COLOR.SERVER_EMBED)
.setThumbnail(guild.iconURL())
.addFields(
{
name: info.serverName.name,
value: guild.name,
inline: true
},
{
name: info.createdAt.name,
value: moment.utc(guild.createdAt).format(bot.consts.FORMAT.SERVER_CREATEDAT),
inline: true
},
{
name: info.master.name,
value: guild.owner.user.tag,
inline: true
},
{
name: info.region.name,
value: guild.region,
inline: true
},
{
name: info.members.name,
value: guild.memberCount,
inline: true
},
{
name: info.bots.name,
value: guild.members.cache.filter(member => member.user.bot).size,
inline: true
},
{
name: info.textChannels.name,
value: guild.channels.cache.filter(channel => channel.type === 'text').size,
inline: true
},
{
name: info.voiceChannels.name,
value: guild.channels.cache.filter(channel => channel.type === 'voice').size,
inline: true
},
{
name: info.roles.name,
value: guild.roles.cache
.map(role => role.name)
.filter(roleName => !roleName.startsWith('@'))
.join(', ')
}
);
message.channel.send(embed);
}
} |
JavaScript | class StaffMember {
/**
*
* @param {Object} node - result of NodeStaffFields
*/
constructor(node) {
const _img = get(node, `image`);
const contact = get(node, `contactInfo`, null);
this.name = get(node, `name`);
this.jobTitle = get(node, `jobTitle`, get(node, `job.title`));
this.image = _img ? new Img(_img) : null;
this.contact = contact ? new ContactInfo(contact) : null;
}
} |
JavaScript | class TransactionFilter extends PolymerElement {
/**
* Template
* @return {HTMLTemplateElement | !HTMLTemplateElement}
*/
static get template() {
return html`
<!--suppress CssInvalidPseudoSelector -->
<!--suppress CssUnresolvedCustomProperty -->
<!--suppress CssUnresolvedCustomPropertySet -->
<style is="custom-style">
:host {
display: block;
}
.date {
background-color: var(--paper-grey-100);
height: 5rem;
margin: 20px 0px;
}
.date paper-tab {
--paper-tab-ink: var(--paper-blue-a400);
--paper-tab-content-unselected: {
height: 60%;
@apply --shadow-elevation-2dp;
font-size: 20px;
};
--paper-tab: {
margin: 0px 5px;
padding: 0 2px;
};
--paper-tab-content: {
background-color: white;
padding: 0 0.5rem;
@apply --shadow-elevation-3dp;
height: 80%;
min-width: 50px;
border-radius: 8px;
font-size: 24px;
transition: all 100ms ease-in-out;
};
}
.period paper-tab {
--paper-tab-ink: var(--paper-blue-a400);
--paper-tab-content-unselected: {
color: var(--paper-grey-500);
};
--paper-tab: {
font-size: 20px;
};
}
.period {
--paper-tabs-selection-bar-color: var(--transaction-filter-period-selection-bar, var(--paper-blue-a400));
margin: 1rem 0 0.5rem 0;
}
</style>
<paper-tabs class="period"
selected="{{period}}"
scrollable
fit-container
attr-for-selected="name"
fallback-selection$="[[periods.0.name]]"
hide-scroll-buttons>
<template is="dom-repeat" items="[[periods]]">
<paper-tab name="[[item.name]]">[[item.text]]</paper-tab>
</template>
</paper-tabs>
<paper-tabs class="date"
selected="{{date}}"
scrollable
attr-for-selected="name"
fallback-selection$="[[days.0]]"
no-bar
noink>
<template is="dom-repeat" items="[[days]]">
<paper-tab name="[[item]]">[[item]]</paper-tab>
</template>
</paper-tabs>
`;
}
/**
* Properties
* @return {object}
*/
static get properties() {
return {
/**
* Gets or sets the selected period.
*/
period: {
type: String,
value: 'daily',
reflectToAttribute: true,
notify: true,
},
/**
* Gets or sets the selected date.
*/
date: {
type: Number,
value: 1,
reflectToAttribute: true,
notify: true,
},
/**
* List of options for 'date'.
*/
days: {
type: Array,
value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
},
/**
* List of options for 'period'.
*/
periods: {
type: Array,
value: [
{
text: 'Daily',
name: 'daily',
},
{
text: 'Weekly',
name: 'weekly',
},
{
text: 'Monthly',
name: 'monthly',
},
{
text: 'Yearly',
name: 'yearly',
},
{
text: 'All',
name: 'all',
},
],
},
};
}
} |
JavaScript | class InvalidRuleResultException extends core_1.BaseException {
constructor(value) {
super(`Invalid rule result: ${_getTypeOfResult(value)}.`);
}
} |
JavaScript | class CacheRepository extends Repository {
/**
* Registers a cache instance allowing to share it across the project.
*
* @param {string} name A string containing the instance name, it must be unique.
* @param {Cache} cache The instance of the class "Cache" that will be registered.
* @param {boolean} [overwrite=false] If set to "true" it means that if the instance has already been registered, it will be overwritten by current one, otherwise an exception will be thrown.
*
* @throws {InvalidArgumentException} If an invalid instance name is given.
* @throws {InvalidArgumentException} If another instance with the same name has already been registered and the "overwrite" option wasn't set to "true".
* @throws {InvalidArgumentException} If an invalid cache instance is given.
*/
static register(name, cache, overwrite = false){
if ( cache === null || typeof cache !== 'object' || cache.constructor.name !== 'Cache' ){
throw new InvalidArgumentException('Invalid cache instance.', 4);
}
super.register(name, cache, 'com.lala.cache', overwrite);
}
/**
* Removes a cache instance that has been registered.
*
* @param {string} name A string containing the instance name.
*
* @throws {InvalidArgumentException} If an invalid instance name is given.
*/
static remove(name){
super.remove(name, 'com.lala.cache');
}
/**
* Checks if a cache instance matching a given name has been registered or not.
*
* @param {string} name A string containing the instance name.
*
* @returns {boolean} If the cache instance exists will be returned "true", otherwise "false".
*
* @throws {InvalidArgumentException} If an invalid instance name is given.
*/
static has(name){
return super.has(name, 'com.lala.cache');
}
/**
* Returns the cache instance matching a given name.
*
* @param {string} name A string containing the instance name.
*
* @returns {(Cache|null)} An instance of the class "Cache", if no instance is found, null will be returned instead.
*
* @throws {InvalidArgumentException} If an invalid instance name is given.
*/
static get(name){
return super.get(name, 'com.lala.cache');
}
/**
* Returns all the cache instances that have been registered.
*
* @returns {{string: Cache}} An object having as key the instance name and as value the cache instance itself.
*/
static getAll(){
return super.getAll('com.lala.cache');
}
} |
JavaScript | class Library extends bibsync.Library {
constructor(config) {
// this calls the init() method implicitly
super(config);
const options = {};
options.key = this.apiKey;
let [,type,id] = this.prefix.match(pathRegExp);
if ( ! type || ! id || isNaN(parseInt(id)) ){
throw new Error(`Invalid 'prefix' config "${this.prefix}"`);
}
options[type.substr(0,type.length-1)] = parseInt(id); // strip off "s"
this._library = new zotero.Library(options);
}
init(){
/**
* The path prefix to the library in the Zotero web API.
* Is either "groups/<number>" or "users/<number>"
* @type {String}
*/
this.prefix = "";
/**
* The zotero.org API key needed for access to this library
*/
this.apiKey = "";
// call parent method and merge validators
return Object.assign(super.init(),{
prefix: {
validate: v => v.match(pathRegExp).length ? true : `'${v}' is not a valid zotero path prefix`,
required: true
},
apiKey: {
validate: v => v && typeof v === "string",
required: true
}
});
}
} |
JavaScript | class HangulShaper extends DefaultShaper {
static zeroMarkWidths = 'NONE';
static planFeatures(plan) {
plan.add(['ljmo', 'vjmo', 'tjmo'], false);
}
static assignFeatures(plan, glyphs) {
let state = 0;
let i = 0;
while (i < glyphs.length) {
let action;
let glyph = glyphs[i];
let code = glyph.codePoints[0];
let type = getType(code);
[action, state] = STATE_TABLE[state][type];
switch (action) {
case DECOMPOSE:
// Decompose the composed syllable if it is not supported by the font.
if (!plan.font.hasGlyphForCodePoint(code)) {
i = decompose(glyphs, i, plan.font);
}
break;
case COMPOSE:
// Found a decomposed syllable. Try to compose if supported by the font.
i = compose(glyphs, i, plan.font);
break;
case TONE_MARK:
// Got a valid syllable, followed by a tone mark. Move the tone mark to the beginning of the syllable.
reorderToneMark(glyphs, i, plan.font);
break;
case INVALID:
// Tone mark has no valid syllable to attach to, so insert a dotted circle
i = insertDottedCircle(glyphs, i, plan.font);
break;
}
i++;
}
}
} |
JavaScript | class SelectableCollection extends Collection {
constructor(options) {
super(options);
if (this._filter) {
commons._log('warn', 'Coral.SelectableCollection does not support the options.filter');
}
// disabled items will not be a selection candicate although hidden items might
this._selectableItemSelector = this._allItemsSelector.split(',').map(selector => `${selector}:not([disabled])`).join(',');
this._selectedItemSelector = this._allItemsSelector.split(',').map(selector => `${selector}[selected]`).join(',');
this._deselectAllExceptSelector = this._selectedItemSelector;
}
/**
Returns the selectable items. Items that are disabled quality for selection. On the other hand, hidden items
can be selected as this is the default behavior in HTML. Please note that an already selected item could be
returned, since the selection could be toggled.
@returns {Array.<HTMLElement>}
an array of items whose selection could be toggled.
@protected
*/
_getSelectableItems() {
return listToArray(this._container.querySelectorAll(this._selectableItemSelector));
}
/**
Returns the first selectable item. Items that are disabled quality for selection. On the other hand, hidden items
can be selected as this is the default behavior in HTML. Please note that an already selected item could be
returned, since the selection could be toggled.
@returns {HTMLElement}
an item whose selection could be toggled.
@protected
*/
_getFirstSelectable() {
return this._container.querySelector(this._selectableItemSelector) || null;
}
/**
Returns the last selectable item. Items that are disabled quality for selection. On the other hand, hidden items
can be selected as this is the default behavior in HTML. Please note that an already selected item could be
returned, since the selection could be toggled.
@returns {HTMLElement}
an item whose selection could be toggled.
@protected
*/
_getLastSelectable() {
const items = this._container.querySelectorAll(this._selectableItemSelector);
return items[items.length - 1] || null;
}
/**
Returns the previous selectable item.
@param {HTMLElement} item
The reference item.
@returns {HTMLElement}
an item whose selection could be toggled.
@protected
*/
_getPreviousSelectable(item) {
const items = this.getAll();
let index = items.indexOf(item);
let sibling = index > 0 ? items[index - 1] : null;
while (sibling) {
if (sibling.matches(this._selectableItemSelector)) {
break;
} else {
index--;
sibling = index > 0 ? items[index - 1] : null;
}
}
// in case the item is not specified, or it is not inside the collection, we need to return the first selectable
return sibling || (item.matches(this._selectableItemSelector) ? item : this._getFirstSelectable());
}
/**
Returns the next selectable item.
@param {HTMLElement} item
The reference item.
@returns {HTMLElement}
an item whose selection could be toggled.
@protected
*/
_getNextSelectable(item) {
const items = this.getAll();
let index = items.indexOf(item);
let sibling = index < items.length - 1 ? items[index + 1] : null;
while (sibling) {
if (sibling.matches(this._selectableItemSelector)) {
break;
} else {
index++;
sibling = index < items.length - 1 ? items[index + 1] : null;
}
}
return sibling || item;
}
/**
Returns the first item that is selected in the Collection. It allows to configure the attribute used for selection
so that components that use 'selected' and 'active' can share the same implementation.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection.
@returns HTMLElement the first selected item.
@protected
*/
_getFirstSelected(selectedAttribute) {
let selector = this._selectedItemSelector;
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${selectedAttribute}]`);
}
return this._container.querySelector(selector) || null;
}
/**
Returns the last item that is selected in the Collection. It allows to configure the attribute used for selection
so that components that use 'selected' and 'active' can share the same implementation.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection.
@returns HTMLElment the last selected item.
@protected
*/
_getLastSelected(selectedAttribute) {
let selector = this._selectedItemSelector;
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${selectedAttribute}]`);
}
// last-of-type did not work so we need to query all
const items = this._container.querySelectorAll(selector);
return items[items.length - 1] || null;
}
/**
Returns an array that contains all the items that are selected.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection.
@protected
@returns Array.<HTMLElement> an array with all the selected items.
*/
_getAllSelected(selectedAttribute) {
let selector = this._selectedItemSelector;
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${selectedAttribute}]`);
}
return listToArray(this._container.querySelectorAll(selector));
}
/**
Deselects all the items except the first selected item in the Collection. By default the <code>selected</code>
attribute will be removed. The attribute to remove is configurable via the <code>selectedAttribute</code> parameter.
The selected attribute will be removed no matter if the item is <code>disabled</code> or <code>hidden</code>.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection. This attribute will be removed from the matching elements.
@protected
*/
_deselectAllExceptFirst(selectedAttribute) {
let selector = this._deselectAllExceptSelector;
const attributeToRemove = selectedAttribute || 'selected';
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${selectedAttribute}]`);
}
// we select all the selected attributes except the last one
const items = this._container.querySelectorAll(selector);
const itemsCount = items.length;
// ignores the first item of the list, everything else is deselected
for (let i = 1 ; i < itemsCount ; i++) {
// we use remoteAttribute since we do not know if the element is upgraded
items[i].removeAttribute(attributeToRemove);
}
}
/**
Deselects all the items except the last selected item in the Collecton. By default the <code>selected</code>
attribute will be removed. The attribute to remove is configurable via the <code>selectedAttribute</code> parameter.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection. This attribute will be removed from the matching elements.
@protected
*/
_deselectAllExceptLast(selectedAttribute) {
let selector = this._deselectAllExceptSelector;
const attributeToRemove = selectedAttribute || 'selected';
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${selectedAttribute}]`);
}
// we query for all matching items with the given attribute
const items = this._container.querySelectorAll(selector);
// we ignore the last item
const itemsCount = items.length - 1;
for (let i = 0 ; i < itemsCount ; i++) {
// we use remoteAttribute since we do not know if the element is upgraded
items[i].removeAttribute(attributeToRemove);
}
}
/**
Deselects all the items except the given item. The provided attribute will be remove from all matching items. By
default the <code>selected</code> attribute will be removed. The attribute to remove is configurable via the
<code>selectedAttribute</code> parameter.
@name Coral.SelectableCollection#_deselectAllExcept
@function
@param {HTMLElement} [itemOrSelectedAttribute]
The item to keep selected. If the item is not provided, all elements will be deselected.
@param {String} [selectedAttribute=selected]
the attribute that will be used to check for selection. This attribute will be removed from the matching elements.
@protected
*/
_deselectAllExcept(itemOrSelectedAttribute, selectedAttribute) {
// if no selectedAttribute we use the unmodified selector as default
let selector = this._deselectAllExceptSelector;
let item;
let attributeToRemove;
// an item was not provided so we use it as 'selectedAttribute'
if (typeof itemOrSelectedAttribute === 'string') {
item = null;
attributeToRemove = itemOrSelectedAttribute || 'selected';
selector = selector.replace('[selected]', `[${attributeToRemove}]`);
} else {
item = itemOrSelectedAttribute;
attributeToRemove = selectedAttribute || 'selected';
if (typeof selectedAttribute === 'string') {
selector = selector.replace('[selected]', `[${attributeToRemove}]`);
}
}
// we query for all matching items with the given attribute
const items = this._container.querySelectorAll(selector);
const itemsCount = items.length;
for (let i = 0 ; i < itemsCount ; i++) {
// we use remoteAttribute since we do not know if the element is upgraded
if (item !== items[i]) {
items[i].removeAttribute(attributeToRemove);
}
}
}
} |
JavaScript | class Point extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
});
this.previousPositionX = 0;
this.totalWidth = this.props.totalWidth || width;
}
/**
* @description render
*/
render() {
this.pointPosition = this.props.pointPosition;
let styles = defaultStyles;
styles.pointWrapper = {
...defaultStyles.pointWrapper,
...this.props.style,
...{
marginLeft: (this.props.pointPosition || 0.04) * 100 + '%'
}
};
return <View
ref={(point) => {
this.point = point;
}}
style={styles.pointWrapper}
{...this._panResponder.panHandlers}
>
<View style={styles.point} />
</View>;
}
componentDidMount() {
this._calculateTotalWidth();
}
/**
* @description Calculated total length
*/
_calculateTotalWidth() {
if (!isWeex) {
var progressBar = document.getElementById('progress-bar');
// console.log(progressBar.clientWidth);
this.totalWidth = progressBar.clientWidth || this.totalWidth;
}
}
_handleStartShouldSetPanResponder(e, gestureState) {
// Should we become active when the user presses down on the circle?
return true;
}
_handleMoveShouldSetPanResponder(e, gestureState) {
// Should we become active when the user moves a touch over the circle?
return true;
}
/**
* @description pan start
* @param e {Event}
* @param gestureState {Object}
* @returns {boolean} true
*/
_handlePanResponderGrant = (e, gestureState) => {
this._calculateTotalWidth();
return true;
}
/**
* @description pan move
* @param e {Event}
* @param gestureState {Object}
*/
_handlePanResponderMove = (e, gestureState) => {
if (!this.updating) {
this.updating = true;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
this.previousPositionX = this.previousPositionX || 0;
let absDelta = gestureState.dx - this.previousPositionX;
if (absDelta == 0) {
this.updating = false;
return;
}
this.pointPosition = Math.min(Math.max(0, (this.pointPosition - 0.04) / 0.92 + (gestureState.dx - this.previousPositionX) / this.totalWidth), 1) * 0.92 + 0.04;
setTimeout(() => {
this.previousPositionX = gestureState.dx;
this.props.onJustify && this.props.onJustify((this.pointPosition - 0.04) / 0.92, 'move', absDelta > 0 ? 'toward' : 'backward');
this.updating = false;
}, 0);
}
};
/**
* @description pan end
* @param e {Event}
* @param gestureState {Object}
*/
_handlePanResponderEnd = (e, gestureState) => {
this.pointPosition = Math.min(Math.max(0, (this.pointPosition - 0.04) / 0.92 + (gestureState.dx - this.previousPositionX) / this.totalWidth), 1) * 0.92 + 0.04;
this.props.onJustify && this.props.onJustify((this.pointPosition - 0.04) / 0.92, 'end');
this.previousPositionX = 0;
};
} |
JavaScript | class Group extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
filter: '',
}
}
onChange = (e) => {
var target = e.target;
var name = target.name;
var value = target.value;
var filter = name === 'filter' ? value : this.state.filter;
this.props.onFilter(filter);
this.setState({
[name]: value
});
}
handleClick = () => {
var action = "New";
this.props.getAction(action);
}
render() {
return (
<div className="input-group filter col-sm-8 d-flex float-left">
<div className="search-form d-flex align-items-center border rounded mr-2">
<span className="position-absolute pl-1">GROUP BY</span>
<select
name="filter"
className="form-control width2 select_text2 border-0 height1"
onChange={this.onChange}
>
<option value={1} >Date</option>
<option value={2} >Week</option>
<option value={3} >Month</option>
<option value={4} >Advertiser</option>
<option value={5} >Campaign</option>
</select>
</div>
<div className="filter_style_value">
<label className="close text-dark">x</label>
<label htmlFor="">Advertiser</label>
<span>Carrefour,Adias</span>
</div>
<button type="button" className="add-filter btn btn-danger btn-radius2" data-toggle="modal" data-target="#add_filter" onClick={this.handleClick}>+</button>
</div>
);
}
} |
JavaScript | class Notes extends Component {
constructor(props) {
super(props);
this.state = {
note: "",
files: null,
urls: []
};
}
UNSAFE_componentWillMount() {
this.setState({ note: this.props.todoNote });
Axios.get("http://15.206.140.31:3030/getFiles/" + this.props.todoId)
.then(result => {
this.setState({ urls: result.data });
console.log(result.data);
})
.catch(err => {
console.log(err);
});
}
noteHandler = () => {
this.props.closeNote();
Axios.post("http://15.206.140.31:3030/note/" + this.props.todoId, {
note: this.state.note,
project_id: this.props.project_id,
token: reactLocalStorage.get("token")
})
.then(result => {
console.log(result.data);
this.props.Todos("GET_TODO", result.data);
})
.catch(err => {
console.log("err in sending note to backend", err);
});
};
handleChange(files) {
console.log(files[0]);
this.setState({
files: files[0]
});
}
fileSubmit = () => {
console.log("file................");
const filedata = new FormData();
filedata.append("image", this.state.files);
Axios.post(
"http://15.206.140.31:3030/file-upload/" + this.props.todoId,
filedata
)
.then(data => {
this.setState({ urls: data.data });
console.log("file sent to backend", data.data);
})
.catch(err => {
console.log("err in sending file to backend-", err);
});
};
urlFile = () => {
if (this.state.urls.length > 0) {
return (
<div>
{this.state.urls.map((url, i) => {
console.log(url.file);
return (
<ListItem
key={i}
style={{ background: "skyblue", margin: "5px" }}
>
<a
style={{ textDecoration: "none", color: "black" }}
href={url.file}
>
File {i + 1}
</a>
</ListItem>
);
})}
</div>
);
} else {
return "";
}
};
render() {
if (this.props.editNote) {
return (
<div>
<TextField
autoFocus
id="outlined-multiline-flexible"
placeholder="Add a Description here..."
multiline
fullWidth
value={this.state.note}
onChange={e => {
this.setState({ note: e.target.value });
}}
margin="normal"
variant="outlined"
/>
<div onClick={this.noteHandler}>
<Button
style={{
background: "red",
color: "white"
}}
>
Submit
</Button>
</div>
<div style={{ marginLeft: "-40px", display: "flex" }}>
<div>
<AttachFileIcon />
</div>
<div style={{ fontWeight: "bold" }}>Attatchment</div>
</div>
<div>{this.urlFile()}</div>
<div
style={{ marginTop: "20px", marginBottom: "10px" }}
title="Click here to add a file"
>
<DropzoneArea onChange={this.handleChange.bind(this)} />
<div onClick={this.fileSubmit}>
<Button
style={{
background: "red",
color: "white",
marginTop: "25px"
}}
>
Submit
</Button>
</div>
</div>
</div>
);
} else {
return (
<div>
<div
onClick={() => {
this.props.openNote();
}}
>
<Typography
title="Click here to add a Description..."
style={{ cursor: "pointer", minHeight: "100px" }}
>
{this.state.note || "Click here to add a Description..."}
</Typography>
</div>
<div style={{ marginLeft: "-40px", display: "flex" }}>
<div>
<AttachFileIcon />
</div>
<div style={{ fontWeight: "bold" }}>Attatchment</div>
</div>
<div
style={{ marginTop: "20px", marginBottom: "10px" }}
title="Click here to add a file"
>
<DropzoneArea onChange={this.handleChange.bind(this)} />
<div onClick={this.fileSubmit}>
<Button
style={{
background: "red",
color: "white",
marginTop: "25px"
}}
>
Submit
</Button>
</div>
</div>
<div>{this.urlFile()}</div>
</div>
);
}
}
} |
JavaScript | class AriaLive extends AriaTypeToken
{
/**
* @param {DomElem} element
* @param {*} value
* @returns {boolean}
*/
static removeOnValue(element, value) {
return value === TOKEN_OFF?
!this.remove(element) :
super.removeOnValue(element, value)
}
} |
JavaScript | class MaxKey {
/** @internal */
toExtendedJSON() {
return { $maxKey: 1 };
}
/** @internal */
static fromExtendedJSON() {
return new MaxKey();
}
} |
JavaScript | class WorkflowCommonStepEditorCard extends React.Component {
get contentExpanded() {
return this.getStepEditor().contentExpanded;
}
getStepEditor() {
return this.props.stepEditor;
}
getStep() {
return this.getStepEditor().step;
}
get canDelete() {
return this.props.canDelete === undefined ? true : this.props.canDelete;
}
get canMove() {
return this.props.canMove === undefined ? true : this.props.canMove;
}
handleExpandContent = event => {
event.stopPropagation();
event.preventDefault();
const editor = this.getStepEditor();
editor.setContentExpanded(!this.contentExpanded);
};
handleDelete = event => {
event.stopPropagation(); // this was needed, otherwise, the handleClick was called after
// which resulted in mobx state tree warning about instance being accessed after being deleted
const onDelete = this.props.onDelete || _.noop;
onDelete(this.getStep());
};
render() {
const className = this.props.className || 'p0 pl1';
const step = this.getStep();
return (
<Segment size="small" className={className} clearing>
{this.renderContent(step)}
</Segment>
);
}
renderContent(step) {
const opened = this.contentExpanded;
const canDelete = this.canDelete;
const canMove = this.canMove;
return (
<Accordion className="overflow-hidden pr1">
<Accordion.Title active={opened} index={0} onClick={this.handleExpandContent}>
<div className="flex">
{canMove && (
<div className="ml1 mr1 mt1 cursor-grab">
<Icon name="align justify" color="grey" />
</div>
)}
{!canMove && <div className="ml1 mr1 mt1" />}
<Icon name="dropdown" className="mt75" />
<div className="ellipsis flex-auto mt1">
<div className="ellipsis">{step.derivedTitle || step.title}</div>
<div className="ellipsis pr1 breakout fs-9 color-grey">
{step.templateId} v{step.templateVer}
</div>
</div>
{canDelete && (
<div className="pl1 pr1 pt1" onClick={this.handleDelete}>
<Icon name="trash alternate outline" className="cursor-pointer" />
</div>
)}
</div>
</Accordion.Title>
<Accordion.Content active={opened} className="p2 pt3 mb1 cursor-default">
{this.props.children}
</Accordion.Content>
</Accordion>
);
}
} |
JavaScript | class API {
constructor (mqtt, options = {}) {
/* determine options */
this.options = Object.assign({
encoding: "json",
timeout: 10 * 1000
}, options)
/* remember the underlying MQTT Client instance */
this.mqtt = mqtt
/* make an encoder */
this.encodr = new Encodr(this.options.encoding)
/* generate unique client identifier */
this.cid = (new UUID(1)).format("std")
/* internal states */
this.registry = {}
this.requests = {}
this.subscriptions = {}
/* hook into the MQTT message processing */
this.mqtt.on("message", (topic, message) => {
this._onServer(topic, message)
this._onClient(topic, message)
})
}
/* just pass-through the entire MQTT Client API */
on (...args) { return this.mqtt.on(...args) }
addListener (...args) { return this.mqtt.addListener(...args) }
removeListener (...args) { return this.mqtt.removeListener(...args) }
publish (...args) { return this.mqtt.publish(...args) }
subscribe (...args) { return this.mqtt.subscribe(...args) }
unsubscribe (...args) { return this.mqtt.unsubscribe(...args) }
end (...args) { return this.mqtt.end(...args) }
removeOutgoingMessage (...args) { return this.mqtt.removeOutgoingMessage(...args) }
reconnect (...args) { return this.mqtt.reconnect(...args) }
handleMessage (...args) { return this.mqtt.handleMessage(...args) }
get connected () { return this.mqtt.connected }
set connected (value) { this.mqtt.connected = value }
getLastMessageId (...args) { return this.mqtt.getLastMessageId(...args) }
get reconnecting () { return this.mqtt.reconnecting }
set reconnecting (value) { this.mqtt.reconnecting = value }
/*
* RPC server/response side
*/
/* check for the registration of an RPC method */
registered (method) {
return (this.registry[method] !== undefined)
}
/* register an RPC method */
register (method, callback) {
if (this.registry[method] !== undefined)
throw new Error(`register: method "${method}" already registered`)
this.registry[method] = callback
return new Promise((resolve, reject) => {
this.mqtt.subscribe(`${method}/request`, { qos: 2 }, (err, granted) => {
if (err)
reject(err)
else
resolve(granted)
})
})
}
/* unregister an RPC method */
unregister (method) {
if (this.registry[method] === undefined)
throw new Error(`unregister: method "${method}" not registered`)
delete this.registry[method]
return new Promise((resolve, reject) => {
this.mqtt.unsubscribe(`${method}/request`, (err, packet) => {
if (err)
reject(err)
else
resolve(packet)
})
})
}
/* handle incoming RPC method request */
_onServer (topic, message) {
/* ensure we handle only MQTT RPC requests */
let m
if ((m = topic.match(/^(.+)\/request$/)) === null)
return
const method = m[1]
/* ensure we handle only JSON-RPC payloads */
const parsed = JSONRPC.parseObject(this.encodr.decode(message))
if (!(typeof parsed === "object" && typeof parsed.type === "string"))
return
/* ensure we handle a consistent JSON-RPC method request */
if (parsed.payload.method !== method)
return
/* dispatch according to JSON-RPC type */
if (parsed.type === "notification") {
/* just deliver notification */
if (typeof this.registry[method] === "function")
this.registry[method](...parsed.payload.params)
}
else if (parsed.type === "request") {
/* deliver request and send response */
let response
if (typeof this.registry[method] === "function")
response = Promise.resolve().then(() => this.registry[method](...parsed.payload.params))
else
response = Promise.reject(JSONRPC.JsonRpcError.methodNotFound({ method, id: parsed.payload.id }))
response.then((response) => {
/* create JSON-RPC success response */
return JSONRPC.success(parsed.payload.id, response)
}, (error) => {
/* create JSON-RPC error response */
return this._buildError(parsed.payload, error)
}).then((response) => {
/* send MQTT response message */
response = this.encodr.encode(response)
const m = parsed.payload.id.match(/^(.+):.+$/)
const cid = m[1]
this.mqtt.publish(`${method}/response/${cid}`, response, { qos: 0 })
})
}
}
/*
* RPC client/request side
*/
/* notify peer ("fire and forget") */
notify (method, ...params) {
let request = JSONRPC.notification(method, params)
request = this.encodr.encode(request)
this.mqtt.publish(`${method}/request`, request, { qos: 0 })
}
/* call peer ("request and response") */
call (method, ...params) {
/* remember callback and create JSON-RPC request */
const rid = `${this.cid}:${(new UUID(1)).format("std")}`
const promise = new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject(new Error("communication timeout"))
timer = null
}, this.options.timeout)
this.requests[rid] = (err, result) => {
if (timer !== null) {
clearTimeout(timer)
timer = null
}
if (err) reject(err)
else resolve(result)
}
})
let request = JSONRPC.request(rid, method, params)
/* subscribe for response */
this._responseSubscribe(method)
/* send MQTT request message */
request = this.encodr.encode(request)
this.mqtt.publish(`${method}/request`, request, { qos: 2 }, (err) => {
if (err) {
/* handle request failure */
this._responseUnsubscribe(method)
this.requests[rid](err, undefined)
}
})
return promise
}
/* handle incoming RPC method response */
_onClient (topic, message) {
/* ensure we handle only MQTT RPC responses */
let m
if ((m = topic.match(/^(.+)\/response\/(.+)$/)) === null)
return
const [ , method, cid ] = m
/* ensure we really handle only MQTT RPC responses for us */
if (cid !== this.cid)
return
/* ensure we handle only JSON-RPC payloads */
const parsed = JSONRPC.parseObject(this.encodr.decode(message))
if (!(typeof parsed === "object" && typeof parsed.type === "string"))
return
/* dispatch according to JSON-RPC type */
if (parsed.type === "success" || parsed.type === "error") {
const rid = parsed.payload.id
if (typeof this.requests[rid] === "function") {
/* call callback function */
if (parsed.type === "success")
this.requests[rid](undefined, parsed.payload.result)
else
this.requests[rid](parsed.payload.error, undefined)
/* unsubscribe from response */
delete this.requests[rid]
this._responseUnsubscribe(method)
}
}
}
/* subscribe to RPC response */
_responseSubscribe (method) {
const topic = `${method}/response/${this.cid}`
if (this.subscriptions[topic] === undefined) {
this.subscriptions[topic] = 0
this.mqtt.subscribe(topic, { qos: 2 })
}
this.subscriptions[topic]++
}
/* unsubscribe from RPC response */
_responseUnsubscribe (method) {
const topic = `${method}/response/${this.cid}`
this.subscriptions[topic]--
if (this.subscriptions[topic] === 0) {
delete this.subscriptions[topic]
this.mqtt.unsubscribe(topic)
}
}
/* determine RPC error */
_buildError (payload, error) {
let rpcError
switch (typeof error) {
case "undefined":
rpcError = new JSONRPC.JsonRpcError("undefined error", 0)
break
case "string":
rpcError = new JSONRPC.JsonRpcError(error, -1)
break
case "number":
case "bigint":
rpcError = new JSONRPC.JsonRpcError("application error", error)
break
case "object":
if (error === null)
rpcError = new JSONRPC.JsonRpcError("undefined error", 0)
else {
if (error instanceof JSONRPC.JsonRpcError)
rpcError = error
else if (error instanceof Error)
rpcError = new JSONRPC.JsonRpcError(error.toString(), -100, error)
else
rpcError = new JSONRPC.JsonRpcError("application error", -100, error)
}
break
default:
rpcError = new JSONRPC.JsonRpcError("unspecified error", 0, { data: error })
break
}
return JSONRPC.error(payload.id, rpcError)
}
} |
JavaScript | class BotLongpollController {
constructor(api, store, { key, server, ts }) {
this.api = api;
this.store = store;
this.key = key;
this.server = server;
this.ts = ts;
this.subscribes = [];
}
start() {
this.started = true;
this._call();
}
stop() {
this.started = false;
}
/**
*
* @param {String} type Type of update to recieve
* @param {Function} callback Function to recieve data
*/
subscribe(type, callback) {
this.subscribes.push({ type, callback });
}
/**
* Call Bot LongPoll server for recieve new updates
*/
async _call() {
if (this.started) {
const { server, key, ts } = this;
const { data } = await axios.get(server, {
params: {
key,
ts,
wait: 25,
act: "a_check"
}
});
const { updates } = data;
this.ts = data.ts;
updates.map(update => {
const callback = this.subscribes.find(callback => {
if (callback.type === update.type) {
return true
}
});
if (callback) {
this.store.process(update.object, callback);
} else {
error({
error_msg: `Can't find handler for "${update.type}" callback type`
}, { type: "Longpoll"})
}
});
this._call();
}
}
} |
JavaScript | class DesktopContainer extends Component {
render() {
const {children} = this.props
return (
<Responsive getWidth={getWidth} minWidth={Responsive.onlyTablet.minWidth}>
<Visibility
once={false}
onBottomPassed={this.showFixedMenu}
onBottomPassedReverse={this.hideFixedMenu}
>
{/* Colored Block for Header Starts Here */}
<Segment
inverted
color="teal"
textAlign="center"
style={{minHeight: 650, padding: '1em 0em'}}
vertical
>
{/* Navbar Goes Here */}
<Navbar />
{/* Header For My Into Goes Here */}
<HomepageHead />
</Segment>
</Visibility>
{children}
</Responsive>
)
}
} |
JavaScript | class LocalDate extends ChronoLocalDate{
/**
* Obtains the current date from the system clock in the default time-zone or
* if specified, the current date from the specified clock or
* if argument is a ZoneId this will query a clock with the specified ZoneId.
*
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
*
* @param {Clock|ZoneId} [clockOrZone=Clock.systemDefaultZone()] - the clock or zone to use,
* if null, the system clock and default time-zone is used.
* @return {LocalDate} the current date, not null
*/
static now(clockOrZone) {
let clock;
if(clockOrZone == null){
clock = Clock.systemDefaultZone();
} else if(clockOrZone instanceof ZoneId){
clock = Clock.system(clockOrZone);
} else {
clock = clockOrZone;
}
return LocalDate.ofInstant(clock.instant(), clock.zone());
}
/**
* obtain a LocalDate from an Instant in the specified time-zone or, if null
* in the system default time-zone
*
* @param {!Instant} instant
* @param {ZoneId} [zone=ZoneId.systemDefault()], defaults to ZoneId.systemDefault()
* @returns {LocalDate} the current date, not null
*/
static ofInstant(instant, zone=ZoneId.systemDefault()){
requireNonNull(instant, 'instant');
const offset = zone.rules().offset(instant);
const epochSec = instant.epochSecond() + offset.totalSeconds();
const epochDay = MathUtil.floorDiv(epochSec, LocalTime.SECONDS_PER_DAY);
return LocalDate.ofEpochDay(epochDay);
}
/**
* Obtains an instance of {@link LocalDate} from a year, month and day.
*
* This returns a {@link LocalDate} with the specified year, month and day-of-month.
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param {!number} year - the year to represent, from {@link Year.MIN_VALUE} to {@link Year.MAX_VALUE}
* @param {!(Month|Number)} month - the month-of-year to represent, from 1 (January) to 12 (December)
* @param {!number} dayOfMonth - the day-of-month to represent, from 1 to 31
* @return {LocalDate} the local date, not null
* @throws {DateTimeException} if the value of any field is out of range,
* or if the day-of-month is invalid for the month-year
*/
static of(year, month, dayOfMonth) {
return new LocalDate(year, month, dayOfMonth);
}
/**
* Obtains an instance of {@link LocalDate} from a year and day-of-year.
*
* This returns a {@link LocalDate} with the specified year and day-of-year.
* The day-of-year must be valid for the year, otherwise an exception will be thrown.
*
* @param {!number} year - the year to represent, from {@link Year.MIN_VALUE} to {@link Year.MAX_VALUE}
* @param {!number} dayOfYear - the day-of-year to represent, from 1 to 366
* @return {LocalDate} the local date, not null
* @throws {DateTimeException} if the value of any field is out of range,
* or if the day-of-year is invalid for the year
*/
static ofYearDay(year, dayOfYear) {
ChronoField.YEAR.checkValidValue(year);
//TODO: ChronoField.DAY_OF_YEAR.checkValidValue(dayOfYear);
const leap = IsoChronology.isLeapYear(year);
if (dayOfYear === 366 && leap === false) {
assert(false, 'Invalid date \'DayOfYear 366\' as \'' + year + '\' is not a leap year', DateTimeException);
}
let moy = Month.of(Math.floor((dayOfYear - 1) / 31 + 1));
const monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
if (dayOfYear > monthEnd) {
moy = moy.plus(1);
}
const dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
return new LocalDate(year, moy.value(), dom);
}
/**
* Obtains an instance of LocalDate from the epoch day count.
*
* This returns a LocalDate with the specified epoch-day.
* The {@link ChronoField.EPOCH_DAY} is a simple incrementing count
* of days where day 0 is 1970-01-01. Negative numbers represent earlier days.
*
* @param {number} [epochDay=0] - the Epoch Day to convert, based on the epoch 1970-01-01
* @return {LocalDate} the local date, not null
* @throws {AssertionError} if the epoch days exceeds the supported date range
*/
static ofEpochDay(epochDay=0) {
let adjust, adjustCycles, doyEst, yearEst, zeroDay;
zeroDay = epochDay + DAYS_0000_TO_1970;
zeroDay -= 60;
adjust = 0;
if (zeroDay < 0) {
adjustCycles = MathUtil.intDiv(zeroDay + 1, DAYS_PER_CYCLE) - 1;
adjust = adjustCycles * 400;
zeroDay += -adjustCycles * DAYS_PER_CYCLE;
}
yearEst = MathUtil.intDiv(400 * zeroDay + 591, DAYS_PER_CYCLE);
doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400));
if (doyEst < 0) {
yearEst--;
doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400));
}
yearEst += adjust;
const marchDoy0 = doyEst;
const marchMonth0 = MathUtil.intDiv(marchDoy0 * 5 + 2, 153);
const month = (marchMonth0 + 2) % 12 + 1;
const dom = marchDoy0 - MathUtil.intDiv(marchMonth0 * 306 + 5, 10) + 1;
yearEst += MathUtil.intDiv(marchMonth0, 10);
const year = yearEst;
return new LocalDate(year, month, dom);
}
/**
* Obtains an instance of {@link LocalDate} from a temporal object.
*
* A {@link TemporalAccessor} represents some form of date and time information.
* This factory converts the arbitrary temporal object to an instance of {@link LocalDate}.
*
* The conversion uses the {@link TemporalQueries.localDate} query, which relies
* on extracting the {@link ChronoField.EPOCH_DAY} field.
*
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used as a query via method reference, {@link LocalDate::from}.
*
* @param {!TemporalAccessor} temporal - the temporal object to convert, not null
* @return {LocalDate} the local date, not null
* @throws {DateTimeException} if unable to convert to a {@link LocalDate}
*/
static from(temporal) {
requireNonNull(temporal, 'temporal');
const date = temporal.query(TemporalQueries.localDate());
if (date == null) {
throw new DateTimeException(
`Unable to obtain LocalDate from TemporalAccessor: ${temporal}, type ${temporal.constructor != null ? temporal.constructor.name : ''}`);
}
return date;
}
/**
* Obtains an instance of {@link LocalDate} from a text string using a specific formatter.
*
* The text is parsed using the formatter, returning a date.
*
* @param {!string} text - the text to parse, not null
* @param {DateTimeFormatter} [formatter=DateTimeFormatter.ISO_LOCAL_DATE] - the formatter to use, default is
* {@link DateTimeFormatter.ISO_LOCAL_DATE}
* @return {LocalDate} the parsed local date, not null
* @throws {DateTimeParseException} if the text cannot be parsed
*/
static parse(text, formatter = DateTimeFormatter.ISO_LOCAL_DATE){
assert(formatter != null, 'formatter', NullPointerException);
return formatter.parse(text, LocalDate.FROM);
}
/**
* Resolves the date, resolving days past the end of month.
*
* @param {!number} year - the year to represent, validated from {@link Year.MIN_VALUE} to {@link Year.MAX_VALUE}
* @param {!number} month - the month-of-year to represent, validated from 1 to 12
* @param {!number} day - the day-of-month to represent, validated from 1 to 31
* @return {LocalDate} resolved date, not null
*/
static _resolvePreviousValid(year, month, day) {
switch (month) {
case 2:
day = Math.min(day, IsoChronology.isLeapYear(year) ? 29 : 28);
break;
case 4:
case 6:
case 9:
case 11:
day = Math.min(day, 30);
break;
}
return LocalDate.of(year, month, day);
}
/**
* Do not call the constructor directly, use the of*() factories instead like {@link LocalDate.of}
*
* @param {!number} year
* @param {!(Month|number)} month
* @param {!number} dayOfMonth
* @private
*/
constructor(year, month, dayOfMonth){
super();
requireNonNull(year, 'year');
requireNonNull(month, 'month');
requireNonNull(dayOfMonth, 'dayOfMonth');
if (month instanceof Month) {
month = month.value();
}
this._year = MathUtil.safeToInt(year);
this._month = MathUtil.safeToInt(month);
this._day = MathUtil.safeToInt(dayOfMonth);
LocalDate._validate(this._year, this._month, this._day);
}
/**
*
* @param {!number} year
* @param {!number} month
* @param {!number} dayOfMonth
* @throws {DateTimeException} if date values are invalid
* @private
*/
static _validate(year, month, dayOfMonth) {
let dom;
ChronoField.YEAR.checkValidValue(year);
ChronoField.MONTH_OF_YEAR.checkValidValue(month);
ChronoField.DAY_OF_MONTH.checkValidValue(dayOfMonth);
if (dayOfMonth > 28) {
dom = 31;
switch (month) {
case 2:
dom = IsoChronology.isLeapYear(year) ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
dom = 30;
}
if (dayOfMonth > dom) {
if (dayOfMonth === 29) {
assert(false, 'Invalid date \'February 29\' as \'' + year + '\' is not a leap year', DateTimeException);
} else {
assert(false, 'Invalid date \'' + year + '\' \'' + month + '\' \'' + dayOfMonth + '\'', DateTimeException);
}
}
}
}
/**
* Checks if the specified field is supported.
*
* This checks if this date can be queried for the specified field.
* If false, then calling the {@link LocalDate.range} range and
* {@link LocalDate.get} get methods will throw an exception.
*
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link LocalDate.isSupported} supported fields will return valid
* values based on this date-time.
* The supported fields are:
*
* * {@link ChronoField.DAY_OF_WEEK}
* * {@link ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH}
* * {@link ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR}
* * {@link ChronoField.DAY_OF_MONTH}
* * {@link ChronoField.DAY_OF_YEAR}
* * {@link ChronoField.EPOCH_DAY}
* * {@link ChronoField.ALIGNED_WEEK_OF_MONTH}
* * {@link ChronoField.ALIGNED_WEEK_OF_YEAR}
* * {@link ChronoField.MONTH_OF_YEAR}
* * {@link ChronoField.EPOCH_MONTH}
* * {@link ChronoField.YEAR_OF_ERA}
* * {@link ChronoField.YEAR}
* * {@link ChronoField.ERA}
*
* All other {@link ChronoField} instances will return false.
*
* If the field is not a {@link ChronoField}, then the result of this method
* is obtained by invoking {@link TemporalField.isSupportedBy}
* passing this as the argument.
* Whether the field is supported is determined by the field.
*
* @param {TemporalField} field the field to check, null returns false
* @return {boolean} true if the field is supported on this date, false if not
*/
isSupported(field) {
return super.isSupported(field);
}
/**
* Gets the range of valid values for the specified field.
*
* The range object expresses the minimum and maximum valid values for a field.
* This date is used to enhance the accuracy of the returned range.
* If it is not possible to return the range, because the field is not supported
* or for some other reason, an exception is thrown.
*
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link LocalDate.isSupported} supported fields will return
* appropriate range instances.
* All other {@link ChronoField} instances will throw a {@link DateTimeException}.
*
* If the field is not a {@link ChronoField}, then the result of this method
* is obtained by invoking {@link TemporalField.rangeRefinedBy}
* passing this as the argument.
* Whether the range can be obtained is determined by the field.
*
* @param {TemporalField} field the field to query the range for, not null
* @return {ValueRange} the range of valid values for the field, not null
* @throws {DateTimeException} if the range for the field cannot be obtained
*/
range(field) {
if (field instanceof ChronoField) {
if (field.isDateBased()) {
switch (field) {
case ChronoField.DAY_OF_MONTH: return ValueRange.of(1, this.lengthOfMonth());
case ChronoField.DAY_OF_YEAR: return ValueRange.of(1, this.lengthOfYear());
case ChronoField.ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, this.month() === Month.FEBRUARY && this.isLeapYear() === false ? 4 : 5);
case ChronoField.YEAR_OF_ERA:
return (this._year <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
}
return field.range();
}
throw new UnsupportedTemporalTypeException('Unsupported field: ' + field);
}
return field.rangeRefinedBy(this);
}
/**
* Gets the value of the specified field from this date as an `int`.
*
* This queries this date for the value for the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
*
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link LocalDate.isSupported} supported fields will return valid
* values based on this date, except {@link ChronoField.EPOCH_DAY} and {@link ChronoField.EPOCH_MONTH}
* which are too large to fit in an `int` and throw a {@link DateTimeException}.
* All other {@link ChronoField} instances will throw a {@link DateTimeException}.
*
* If the field is not a {@link ChronoField}, then the result of this method
* is obtained by invoking {@link TemporalField.getFrom}
* passing this as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param {!TemporalField} field the field to get, not null
* @return the value for the field
* @throws {DateTimeException} if a value for the field cannot be obtained
* @throws {ArithmeticException} if numeric overflow occurs
*/
get(field) {
return this.getLong(field);
}
/**
* see {LocalDate.get}, get and getLong are identical in javascript, because we are only limited by
* {@link MathUtil.MIN_SAFE_INTEGER}/ {@link MathUtil.MAX_SAFE_INTEGER}
*
* @param {!TemporalField} field
* @returns {*}
*/
getLong(field) {
assert(field != null, '', NullPointerException);
if (field instanceof ChronoField) {
return this._get0(field);
}
return field.getFrom(this);
}
/**
* TODO tests are missing for the ALIGNED_* ChronoFields
*
* @param {!TemporalField} field
* @returns {*}
* @private
*/
_get0(field) {
switch (field) {
case ChronoField.DAY_OF_WEEK: return this.dayOfWeek().value();
case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: return MathUtil.intMod((this._day - 1), 7) + 1;
case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: return MathUtil.intMod((this.dayOfYear() - 1), 7) + 1;
case ChronoField.DAY_OF_MONTH: return this._day;
case ChronoField.DAY_OF_YEAR: return this.dayOfYear();
case ChronoField.EPOCH_DAY: return this.toEpochDay();
case ChronoField.ALIGNED_WEEK_OF_MONTH: return MathUtil.intDiv((this._day - 1), 7) + 1;
case ChronoField.ALIGNED_WEEK_OF_YEAR: return MathUtil.intDiv((this.dayOfYear() - 1), 7) + 1;
case ChronoField.MONTH_OF_YEAR: return this._month;
case ChronoField.PROLEPTIC_MONTH: return this._prolepticMonth();
case ChronoField.YEAR_OF_ERA: return (this._year >= 1 ? this._year : 1 - this._year);
case ChronoField.YEAR: return this._year;
case ChronoField.ERA: return (this._year >= 1 ? 1 : 0);
}
throw new UnsupportedTemporalTypeException('Unsupported field: ' + field);
}
/**
*
* @return {number}
* @private
*/
_prolepticMonth() {
return (this._year * 12) + (this._month - 1);
}
/**
* Gets the chronology of this date, which is the ISO calendar system.
*
* The {@link Chronology} represents the calendar system in use.
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which today's rules for leap years are applied for all time.
*
* @return {Chronology} the ISO chronology, not null
*/
chronology() {
return IsoChronology.INSTANCE;
}
/**
*
* @return {number} gets the year
*/
year() {
return this._year;
}
/**
*
* @return {number} gets the month value
*/
monthValue() {
return this._month;
}
/**
*
* @returns {Month} month
*/
month() {
return Month.of(this._month);
}
/**
*
* @return {number} gets the day of month
*/
dayOfMonth() {
return this._day;
}
/**
* Gets the day-of-year field.
*
* This method returns the primitive int value for the day-of-year.
*
* @return {number} the day-of-year, from 1 to 365, or 366 in a leap year
*/
dayOfYear() {
return this.month().firstDayOfYear(this.isLeapYear()) + this._day - 1;
}
/**
* Gets the day-of-week field, which is an enum {@link DayOfWeek}.
*
* This method returns the enum {@link DayOfWeek} for the day-of-week.
* This avoids confusion as to what `int` values mean.
* If you need access to the primitive `int` value then the enum
* provides the {@link DayOfWeek.value} int value.
*
* Additional information can be obtained from the {@link DayOfWeek}.
* This includes textual names of the values.
*
* @return {DayOfWeek} the day-of-week, not null
*/
dayOfWeek() {
const dow0 = MathUtil.floorMod(this.toEpochDay() + 3, 7);
return DayOfWeek.of(dow0 + 1);
}
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
*
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
*
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
*
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @return {boolean} true if the year is leap, false otherwise
*/
isLeapYear() {
return IsoChronology.isLeapYear(this._year);
}
/**
* Returns the length of the month represented by this date.
*
* This returns the length of the month in days.
* For example, a date in January would return 31.
*
* @return {number} the length of the month in days
*/
lengthOfMonth() {
switch (this._month) {
case 2:
return (this.isLeapYear() ? 29 : 28);
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
/**
* Returns the length of the year represented by this date.
*
* This returns the length of the year in days, either 365 or 366.
*
* @return {number} 366 if the year is leap, 365 otherwise
*/
lengthOfYear() {
return (this.isLeapYear() ? 366 : 365);
}
/**
* Returns an adjusted copy of this date.
*
* This returns a new {@link LocalDate}, based on this one, with the date adjusted.
* The adjustment takes place using the specified adjuster strategy object.
* Read the documentation of the adjuster to understand what adjustment will be made.
*
* A simple adjuster might simply set the one of the fields, such as the year field.
* A more complex adjuster might set the date to the last day of the month.
* A selection of common adjustments is provided in {@link TemporalAdjusters}.
* These include finding the "last day of the month" and "next Wednesday".
* Key date-time classes also implement the {@link TemporalAdjuster} interface,
* such as {@link Month} and {@link MonthDay}.
* The adjuster is responsible for handling special cases, such as the varying
* lengths of month and leap years.
*
* For example this code returns a date on the last day of July:
* <pre>
* import static org.threeten.bp.Month.*;
* import static org.threeten.bp.temporal.Adjusters.*;
*
* result = localDate.with(JULY).with(lastDayOfMonth());
* </pre>
*
* The result of this method is obtained by invoking the
* {@link TemporalAdjuster.adjustInto} method on the
* specified adjuster passing `this` as the argument.
*
* @param {!TemporalAdjuster} adjuster - the adjuster to use, not null
* @return {LocalDate} a {@link LocalDate} based on `this` with the adjustment made, not null
* @throws {DateTimeException} if the adjustment cannot be made
* @throws {ArithmeticException} if numeric overflow occurs
*/
withAdjuster(adjuster) {
requireNonNull(adjuster, 'adjuster');
// optimizations
if (adjuster instanceof LocalDate) {
return adjuster;
}
assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException);
return adjuster.adjustInto(this);
}
/**
* Returns a copy of this date with the specified field set to a new value.
*
* This returns a new {@link LocalDate}, based on this one, with the value
* for the specified field changed.
* This can be used to change any supported field, such as the year, month or day-of-month.
* If it is not possible to set the value, because the field is not supported or for
* some other reason, an exception is thrown.
*
* In some cases, changing the specified field can cause the resulting date to become invalid,
* such as changing the month from 31st January to February would make the day-of-month invalid.
* In cases like this, the field is responsible for resolving the date. Typically it will choose
* the previous valid date, which would be the last valid day of February in this example.
*
* If the field is a {@link ChronoField} then the adjustment is implemented here.
* The supported fields behave as follows:
*
* * {@link DAY_OF_WEEK} -
* Returns a {@link LocalDate} with the specified day-of-week.
* The date is adjusted up to 6 days forward or backward within the boundary
* of a Monday to Sunday week.
* * {@link ALIGNED_DAY_OF_WEEK_IN_MONTH} -
* Returns a {@link LocalDate} with the specified aligned-day-of-week.
* The date is adjusted to the specified month-based aligned-day-of-week.
* Aligned weeks are counted such that the first week of a given month starts
* on the first day of that month.
* This may cause the date to be moved up to 6 days into the following month.
* * {@link ALIGNED_DAY_OF_WEEK_IN_YEAR} -
* Returns a {@link LocalDate} with the specified aligned-day-of-week.
* The date is adjusted to the specified year-based aligned-day-of-week.
* Aligned weeks are counted such that the first week of a given year starts
* on the first day of that year.
* This may cause the date to be moved up to 6 days into the following year.
* * {@link DAY_OF_MONTH} -
* Returns a {@link LocalDate} with the specified day-of-month.
* The month and year will be unchanged. If the day-of-month is invalid for the
* year and month, then a {@link DateTimeException} is thrown.
* * {@link DAY_OF_YEAR} -
* Returns a {@link LocalDate} with the specified day-of-year.
* The year will be unchanged. If the day-of-year is invalid for the
* year, then a {@link DateTimeException} is thrown.
* * {@link EPOCH_DAY} -
* Returns a {@link LocalDate} with the specified epoch-day.
* This completely replaces the date and is equivalent to {@link ofEpochDay}.
* * {@link ALIGNED_WEEK_OF_MONTH} -
* Returns a {@link LocalDate} with the specified aligned-week-of-month.
* Aligned weeks are counted such that the first week of a given month starts
* on the first day of that month.
* This adjustment moves the date in whole week chunks to match the specified week.
* The result will have the same day-of-week as this date.
* This may cause the date to be moved into the following month.
* * {@link ALIGNED_WEEK_OF_YEAR} -
* Returns a {@link LocalDate} with the specified aligned-week-of-year.
* Aligned weeks are counted such that the first week of a given year starts
* on the first day of that year.
* This adjustment moves the date in whole week chunks to match the specified week.
* The result will have the same day-of-week as this date.
* This may cause the date to be moved into the following year.
* * {@link MONTH_OF_YEAR} -
* Returns a {@link LocalDate} with the specified month-of-year.
* The year will be unchanged. The day-of-month will also be unchanged,
* unless it would be invalid for the new month and year. In that case, the
* day-of-month is adjusted to the maximum valid value for the new month and year.
* * {@link PROLEPTIC_MONTH} -
* Returns a {@link LocalDate} with the specified proleptic-month.
* The day-of-month will be unchanged, unless it would be invalid for the new month
* and year. In that case, the day-of-month is adjusted to the maximum valid value
* for the new month and year.
* * {@link YEAR_OF_ERA} -
* Returns a {@link LocalDate} with the specified year-of-era.
* The era and month will be unchanged. The day-of-month will also be unchanged,
* unless it would be invalid for the new month and year. In that case, the
* day-of-month is adjusted to the maximum valid value for the new month and year.
* * {@link YEAR} -
* Returns a {@link LocalDate} with the specified year.
* The month will be unchanged. The day-of-month will also be unchanged,
* unless it would be invalid for the new month and year. In that case, the
* day-of-month is adjusted to the maximum valid value for the new month and year.
* * {@link ERA} -
* Returns a {@link LocalDate} with the specified era.
* The year-of-era and month will be unchanged. The day-of-month will also be unchanged,
* unless it would be invalid for the new month and year. In that case, the
* day-of-month is adjusted to the maximum valid value for the new month and year.
*
* In all cases, if the new value is outside the valid range of values for the field
* then a {@link DateTimeException} will be thrown.
*
* All other {@link ChronoField} instances will throw a {@link DateTimeException}.
*
* If the field is not a {@link ChronoField}, then the result of this method
* is obtained by invoking {@link TemporalField.adjustInto}
* passing `this` as the argument. In this case, the field determines
* whether and how to adjust the instant.
*
* @param {TemporalField} field - the field to set in the result, not null
* @param {number} newValue - the new value of the field in the result
* @return {LocalDate} a {@link LocalDate} based on `this` with the specified field set, not null
* @throws {DateTimeException} if the field cannot be set
* @throws {ArithmeticException} if numeric overflow occurs
*/
withFieldValue(field, newValue) {
assert(field != null, 'field', NullPointerException);
if (field instanceof ChronoField) {
const f = field;
f.checkValidValue(newValue);
switch (f) {
case ChronoField.DAY_OF_WEEK: return this.plusDays(newValue - this.dayOfWeek().value());
case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH));
case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR));
case ChronoField.DAY_OF_MONTH: return this.withDayOfMonth(newValue);
case ChronoField.DAY_OF_YEAR: return this.withDayOfYear(newValue);
case ChronoField.EPOCH_DAY: return LocalDate.ofEpochDay(newValue);
case ChronoField.ALIGNED_WEEK_OF_MONTH: return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_MONTH));
case ChronoField.ALIGNED_WEEK_OF_YEAR: return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_YEAR));
case ChronoField.MONTH_OF_YEAR: return this.withMonth(newValue);
case ChronoField.PROLEPTIC_MONTH: return this.plusMonths(newValue - this.getLong(ChronoField.PROLEPTIC_MONTH));
case ChronoField.YEAR_OF_ERA: return this.withYear((this._year >= 1 ? newValue : 1 - newValue));
case ChronoField.YEAR: return this.withYear(newValue);
case ChronoField.ERA: return (this.getLong(ChronoField.ERA) === newValue ? this : this.withYear(1 - this._year));
}
throw new UnsupportedTemporalTypeException('Unsupported field: ' + field);
}
return field.adjustInto(this, newValue);
}
/**
* Returns a copy of this date with the year altered.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
*
* @param {!number} year the year to set in the result, from {@link Year.MIN_VALUE} to {@link Year.MAX_VALUE}
* @return {LocalDate} a {@link LocalDate} based on this date with the requested year, not null
* @throws {DateTimeException} if the year value is invalid
*/
withYear(year) {
if (this._year === year) {
return this;
}
ChronoField.YEAR.checkValidValue(year);
return LocalDate._resolvePreviousValid(year, this._month, this._day);
}
/**
* Returns a copy of this date with the month-of-year altered.
* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
*
* @param {!(Month|number)} month - the month-of-year to set in the result, from 1 (January) to 12 (December)
* @return {LocalDate} a {@link LocalDate} based on this date with the requested month, not null
* @throws {DateTimeException} if the month-of-year value is invalid
*/
withMonth(month) {
const m = (month instanceof Month) ? month.value() : month;
if (this._month === m) {
return this;
}
ChronoField.MONTH_OF_YEAR.checkValidValue(m);
return LocalDate._resolvePreviousValid(this._year, m, this._day);
}
/**
* Returns a copy of this {@link LocalDate} with the day-of-month altered.
*
* If the resulting date is invalid, an exception is thrown.
*
* @param {!number} dayOfMonth - the day-of-month to set in the result, from 1 to 28-31
* @return {LocalDate} based on this date with the requested day, not null
* @throws {DateTimeException} if the day-of-month value is invalid,
* or if the day-of-month is invalid for the month-year
*/
withDayOfMonth(dayOfMonth) {
if (this._day === dayOfMonth) {
return this;
}
return LocalDate.of(this._year, this._month, dayOfMonth);
}
/**
* Returns a copy of this date with the day-of-year altered.
* If the resulting date is invalid, an exception is thrown.
*
* @param dayOfYear the day-of-year to set in the result, from 1 to 365-366
* @return {LocalDate} a {@link LocalDate} based on this date with the requested day, not null
* @throws {DateTimeException} if the day-of-year value is invalid
* @throws {DateTimeException} if the day-of-year is invalid for the year
*/
withDayOfYear(dayOfYear) {
if (this.dayOfYear() === dayOfYear) {
return this;
}
return LocalDate.ofYearDay(this._year, dayOfYear);
}
/**
* Returns a copy of this date with the specified period added.
*
* This method returns a new date based on this date with the specified period added.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* The calculation is delegated to the specified adjuster, which typically calls
* back to {@link LocalDate.plusAmountUnit}.
*
* @param {!TemporalAmount} amount - the amount to add, not null
* @return {LocalDate} a {@link LocalDate} based on this date with the addition made, not null
* @throws {DateTimeException} if the addition cannot be made
* @throws {ArithmeticException} if numeric overflow occurs
*/
plusAmount(amount) {
requireNonNull(amount, 'amount');
return amount.addTo(this);
}
/**
* Returns a copy of this date with the specified period added.
*
* This method returns a new date based on this date with the specified period added.
* This can be used to add any period that is defined by a unit, for example to add years, months or days.
* The unit is responsible for the details of the calculation, including the resolution
* of any edge cases in the calculation.
*
* @param {!number} amountToAdd - the amount of the unit to add to the result, may be negative
* @param {!TemporalUnit} unit - the unit of the period to add, not null
* @return {LocalDate} a {@link LocalDate} based on this date with the specified period added, not null
* @throws {DateTimeException} if the unit cannot be added to this type
*/
plusAmountUnit(amountToAdd, unit) {
requireNonNull(amountToAdd, 'amountToAdd');
requireNonNull(unit, 'unit');
if (unit instanceof ChronoUnit) {
switch (unit) {
case ChronoUnit.DAYS: return this.plusDays(amountToAdd);
case ChronoUnit.WEEKS: return this.plusWeeks(amountToAdd);
case ChronoUnit.MONTHS: return this.plusMonths(amountToAdd);
case ChronoUnit.YEARS: return this.plusYears(amountToAdd);
case ChronoUnit.DECADES: return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10));
case ChronoUnit.CENTURIES: return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100));
case ChronoUnit.MILLENNIA: return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000));
case ChronoUnit.ERAS: return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit);
}
return unit.addTo(this, amountToAdd);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in years added.
*
* This method adds the specified amount to the years field in three steps:
*
* 1. Add the input years to the year field
* 2. Check if the resulting date would be invalid
* 3. Adjust the day-of-month to the last valid day if necessary
*
* For example, 2008-02-29 (leap year) plus one year would result in the
* invalid date 2009-02-29 (standard year). Instead of returning an invalid
* result, the last valid day of the month, 2009-02-28, is selected instead.
*
* @param {!number} yearsToAdd - the years to add, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the years added, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
plusYears(yearsToAdd) {
if (yearsToAdd === 0) {
return this;
}
const newYear = ChronoField.YEAR.checkValidIntValue(this._year + yearsToAdd); // safe overflow
return LocalDate._resolvePreviousValid(newYear, this._month, this._day);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in months added.
*
* This method adds the specified amount to the months field in three steps:
*
* 1. Add the input months to the month-of-year field
* 2. Check if the resulting date would be invalid
* 3. Adjust the day-of-month to the last valid day if necessary
*
* For example, 2007-03-31 plus one month would result in the invalid date
* 2007-04-31. Instead of returning an invalid result, the last valid day
* of the month, 2007-04-30, is selected instead.
*
* @param {number} monthsToAdd - the months to add, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the months added, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
plusMonths(monthsToAdd) {
if (monthsToAdd === 0) {
return this;
}
const monthCount = this._year * 12 + (this._month - 1);
const calcMonths = monthCount + monthsToAdd; // safe overflow
const newYear = ChronoField.YEAR.checkValidIntValue(MathUtil.floorDiv(calcMonths, 12));
const newMonth = MathUtil.floorMod(calcMonths, 12) + 1;
return LocalDate._resolvePreviousValid(newYear, newMonth, this._day);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in weeks added.
*
* This method adds the specified amount in weeks to the days field incrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
*
* For example, 2008-12-31 plus one week would result in 2009-01-07.
*
* @param {!number} weeksToAdd - the weeks to add, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the weeks added, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
plusWeeks(weeksToAdd) {
return this.plusDays(MathUtil.safeMultiply(weeksToAdd, 7));
}
/**
* Returns a copy of this LocalDate with the specified number of days added.
*
* This method adds the specified amount to the days field incrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
*
* For example, 2008-12-31 plus one day would result in 2009-01-01.
*
* @param {number} daysToAdd - the days to add, may be negative
* @return {LocalDate} a LocalDate based on this date with the days added, not null
* @throws AssertionError if the result exceeds the supported date range
*/
plusDays(daysToAdd) {
if (daysToAdd === 0) {
return this;
}
const mjDay = MathUtil.safeAdd(this.toEpochDay(), daysToAdd);
return LocalDate.ofEpochDay(mjDay);
}
/**
* Returns a copy of this date with the specified period subtracted.
*
* This method returns a new date based on this date with the specified period subtracted.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* The calculation is delegated to the specified adjuster, which typically calls
* back to {@link minus}.
*
* @param {!TemporalAmount} amount - the amount to subtract, not null
* @return {LocalDate} a {@link LocalDate} based on this date with the subtraction made, not null
* @throws {DateTimeException} if the subtraction cannot be made
* @throws {ArithmeticException} if numeric overflow occurs
*/
minusAmount(amount) {
requireNonNull(amount, 'amount');
return amount.subtractFrom(this);
}
/**
* Returns a copy of this date with the specified period subtracted.
*
* This method returns a new date based on this date with the specified period subtracted.
* This can be used to subtract any period that is defined by a unit, for example to subtract years, months or days.
* The unit is responsible for the details of the calculation, including the resolution
* of any edge cases in the calculation.
*
* @param {!number} amountToSubtract - the amount of the unit to subtract from the result, may be negative
* @param {!TemporalUnit} unit the unit of the period to subtract, not null
* @return {LocalDate} a {@link LocalDate} based on this date with the specified period subtracted, not null
* @throws {DateTimeException} if the unit cannot be added to this type
*/
minusAmountUnit(amountToSubtract, unit) {
requireNonNull(amountToSubtract, 'amountToSubtract');
requireNonNull(unit, 'unit');
return this.plusAmountUnit(-1 * amountToSubtract, unit);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in years subtracted.
*
* This method subtracts the specified amount from the years field in three steps:
*
* 1. Subtract the input years to the year field
* 2. Check if the resulting date would be invalid
* 3. Adjust the day-of-month to the last valid day if necessary
*
* For example, 2008-02-29 (leap year) minus one year would result in the
* invalid date 2007-02-29 (standard year). Instead of returning an invalid
* result, the last valid day of the month, 2007-02-28, is selected instead.
*
* @param {!number} yearsToSubtract - the years to subtract, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the years subtracted, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
minusYears(yearsToSubtract) {
return this.plusYears(yearsToSubtract * -1);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in months subtracted.
*
* This method subtracts the specified amount from the months field in three steps:
*
* 1. Subtract the input months to the month-of-year field
* 2. Check if the resulting date would be invalid
* 3. Adjust the day-of-month to the last valid day if necessary
*
* For example, 2007-03-31 minus one month would result in the invalid date
* 2007-02-31. Instead of returning an invalid result, the last valid day
* of the month, 2007-02-28, is selected instead.
*
* @param {!number} monthsToSubtract - the months to subtract, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the months subtracted, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
minusMonths(monthsToSubtract) {
return this.plusMonths(monthsToSubtract * -1);
}
/**
* Returns a copy of this {@link LocalDate} with the specified period in weeks subtracted.
*
* This method subtracts the specified amount in weeks from the days field decrementing
* the month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
*
* For example, 2009-01-07 minus one week would result in 2008-12-31.
*
* @param {!number} weeksToSubtract - the weeks to subtract, may be negative
* @return {LocalDate} a {@link LocalDate} based on this date with the weeks subtracted, not null
* @throws {DateTimeException} if the result exceeds the supported date range
*/
minusWeeks(weeksToSubtract) {
return this.plusWeeks(weeksToSubtract * -1);
}
/*
* Returns a copy of this LocalDate with the specified number of days subtracted.
*
* This method subtracts the specified amount from the days field decrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
*
* For example, 2009-01-01 minus one day would result in 2008-12-31.
*
* @param {number} daysToSubtract - the days to subtract, may be negative
* @return {LocalDate} a LocalDate based on this date with the days subtracted, not null
* @throws AssertionError if the result exceeds the supported date range
*/
minusDays(daysToSubtract) {
return this.plusDays(daysToSubtract * -1);
}
/**
* Queries this date using the specified query.
*
* This queries this date using the specified query strategy object.
* The {@link TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
*
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom} method on the
* specified query passing `this` as the argument.
*
* @param {TemporalQuery} query - the query to invoke, not null
* @return the query result, null may be returned (defined by the query)
* @throws {DateTimeException} if unable to query (defined by the query)
* @throws {ArithmeticException} if numeric overflow occurs (defined by the query)
*/
query(query) {
requireNonNull(query, 'query');
if (query === TemporalQueries.localDate()) {
return this;
}
return super.query(query);
}
/**
* Adjusts the specified temporal object to have the same date as this object.
*
* This returns a temporal object of the same observable type as the input
* with the date changed to be the same as this.
*
* The adjustment is equivalent to using {@link Temporal#with}
* passing {@link ChronoField.EPOCH_DAY} as the field.
*
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisLocalDate.adjustInto(temporal);
* temporal = temporal.with(thisLocalDate);
* </pre>
*
* @param {!TemporalAdjuster} temporal - the target object to be adjusted, not null
* @return the adjusted object, not null
* @throws {DateTimeException} if unable to make the adjustment
* @throws {ArithmeticException} if numeric overflow occurs
*/
adjustInto(temporal) {
return super.adjustInto(temporal);
}
/**
* function overloading for {@link LocalDate.until}
*
* called with 1 (or less) arguments {{@link LocalDate.until1}} is called
* otherwise {@link LocalDate.until2}
*
* @param {!TemporalAccessor} p1
* @param {TemporalUnit} p2 - not null if called with 2 arguments
* @return {number|Period}
*/
until(p1, p2){
if(arguments.length < 2){
return this.until1(p1);
} else {
return this.until2(p1, p2);
}
}
/**
* Calculates the period between this date and another date in
* terms of the specified unit.
*
* This calculates the period between two dates in terms of a single unit.
* The start and end points are `this` and the specified date.
* The result will be negative if the end is before the start.
* The {@link Temporal} passed to this method must be a {@link LocalDate}.
* For example, the period in days between two dates can be calculated
* using {@link startDate.until}.
*
* The calculation returns a whole number, representing the number of
* complete units between the two dates.
* For example, the period in months between 2012-06-15 and 2012-08-14
* will only be one month as it is one day short of two months.
*
* This method operates in association with {@link TemporalUnit#between}.
* The result of this method is a `long` representing the amount of
* the specified unit. By contrast, the result of {@link between} is an
* object that can be used directly in addition/subtraction:
* <pre>
* long period = start.until(end, MONTHS); // this method
* dateTime.plus(MONTHS.between(start, end)); // use in plus/minus
* </pre>
*
* The calculation is implemented in this method for {@link ChronoUnit}.
* The units {@link DAYS}, {@link WEEKS}, {@link MONTHS}, {@link YEARS},
* {@link DECADES}, {@link CENTURIES}, {@link MILLENNIA} and {@link ERAS}
* are supported. Other {@link ChronoUnit} values will throw an exception.
*
* If the unit is not a {@link ChronoUnit}, then the result of this method
* is obtained by invoking {@link TemporalUnit.between}
* passing `this` as the first argument and the input temporal as
* the second argument.
*
* @param {!TemporalAccessor} endExclusive - the end date, which is converted to a {@link LocalDate}, not null
* @param {!TemporalUnit} unit - the unit to measure the period in, not null
* @return {number} the amount of the period between this date and the end date
* @throws {DateTimeException} if the period cannot be calculated
* @throws {ArithmeticException} if numeric overflow occurs
*/
until2(endExclusive, unit) {
const end = LocalDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch (unit) {
case ChronoUnit.DAYS: return this.daysUntil(end);
case ChronoUnit.WEEKS: return MathUtil.intDiv(this.daysUntil(end), 7);
case ChronoUnit.MONTHS: return this._monthsUntil(end);
case ChronoUnit.YEARS: return MathUtil.intDiv(this._monthsUntil(end), 12);
case ChronoUnit.DECADES: return MathUtil.intDiv(this._monthsUntil(end), 120);
case ChronoUnit.CENTURIES: return MathUtil.intDiv(this._monthsUntil(end), 1200);
case ChronoUnit.MILLENNIA: return MathUtil.intDiv(this._monthsUntil(end), 12000);
case ChronoUnit.ERAS: return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA);
}
throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit);
}
return unit.between(this, end);
}
/**
*
* @param {!LocalDate} end
* @returns {number}
* @protected
*/
daysUntil(end) {
return end.toEpochDay() - this.toEpochDay(); // no overflow
}
/**
*
* @param {!LocalDate} end
* @returns {number}
* @private
*/
_monthsUntil(end) {
const packed1 = this._prolepticMonth() * 32 + this.dayOfMonth(); // no overflow
const packed2 = end._prolepticMonth() * 32 + end.dayOfMonth(); // no overflow
return MathUtil.intDiv((packed2 - packed1), 32);
}
/**
* Calculates the period between this date and another date as a {@link Period}.
*
* This calculates the period between two dates in terms of years, months and days.
* The start and end points are `this` and the specified date.
* The result will be negative if the end is before the start.
*
* The calculation is performed using the ISO calendar system.
* If necessary, the input date will be converted to ISO.
*
* The start date is included, but the end date is not.
* The period is calculated by removing complete months, then calculating
* the remaining number of days, adjusting to ensure that both have the same sign.
* The number of months is then normalized into years and months based on a 12 month year.
* A month is considered to be complete if the end day-of-month is greater
* than or equal to the start day-of-month.
* For example, from `2010-01-15` to `2011-03-18` is "1 year, 2 months and 3 days".
*
* The result of this method can be a negative period if the end is before the start.
* The negative sign will be the same in each of year, month and day.
*
* There are two equivalent ways of using this method.
* The first is to invoke this method.
* The second is to use {@link Period#between}:
* <pre>
* // these two lines are equivalent
* period = start.until(end);
* period = Period.between(start, end);
* </pre>
* The choice should be made based on which makes the code more readable.
*
* @param {!TemporalAccessor} endDate - the end date, exclusive, which may be in any chronology, not null
* @return {Period} the period between this date and the end date, not null
*/
until1(endDate) {
const end = LocalDate.from(endDate);
let totalMonths = end._prolepticMonth() - this._prolepticMonth(); // safe
let days = end._day - this._day;
if (totalMonths > 0 && days < 0) {
totalMonths--;
const calcDate = this.plusMonths(totalMonths);
days = (end.toEpochDay() - calcDate.toEpochDay()); // safe
} else if (totalMonths < 0 && days > 0) {
totalMonths++;
days -= end.lengthOfMonth();
}
const years = MathUtil.intDiv(totalMonths, 12); // safe
const months = MathUtil.intMod(totalMonths, 12); // safe
return Period.of(years, months, days);
}
//-----------------------------------------------------------------------
/**
* function overloading for {@link LocalDate.atTime}
*
* if called with 1 argument {@link LocalDate.atTime1} is called
* otherwise {@link LocalDate.atTime4}
*
* @return {LocalDateTime} the local date-time formed from this date and the specified params
*/
atTime(){
if(arguments.length===1){
return this.atTime1.apply(this, arguments);
} else {
return this.atTime4.apply(this, arguments);
}
}
/**
* Combines this date with a time to create a {@link LocalDateTime}.
*
* This returns a {@link LocalDateTime} formed from this date at the specified time.
* All possible combinations of date and time are valid.
*
* @param {LocalTime} time - the time to combine with, not null
* @return {LocalDateTime} the local date-time formed from this date and the specified time, not null
*/
atTime1(time) {
return LocalDateTime.of(this, time);
}
/**
* Combines this date with a time to create a {@link LocalDateTime}.
*
* This returns a {@link LocalDateTime} formed from this date at the
* specified hour, minute, second and nanosecond.
* The individual time fields must be within their valid range.
* All possible combinations of date and time are valid.
*
* @param {!number} hour - the hour-of-day to use, from 0 to 23
* @param {!number} minute - the minute-of-hour to use, from 0 to 59
* @param {number} [second=0] - the second-of-minute to represent, from 0 to 59
* @param {number} [nanoOfSecond=0] - the nano-of-second to represent, from 0 to 999,999,999
* @return {LocalDateTime} the local date-time formed from this date and the specified time, not null
* @throws {DateTimeException} if the value of any field is out of range
*/
atTime4(hour, minute, second=0, nanoOfSecond=0) {
return this.atTime1(LocalTime.of(hour, minute, second, nanoOfSecond));
}
/**
* Combines this date with an offset time to create an {@link OffsetDateTime}.
*
* This returns an {@link OffsetDateTime} formed from this date at the specified time.
* All possible combinations of date and time are valid.
*
* @param {OffsetTime} time - the time to combine with, not null
* @return {OffsetDateTime} the offset date-time formed from this date and the specified time, not null
*/
/*
_atTimeOffsetTime(time) { // atTime(offsetTime)
return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.getOffset());
}
*/
/**
* Combines this date with the time of midnight to create a {@link LocalDateTime}
* at the start of this date.
*
* This returns a {@link LocalDateTime} formed from this date at the time of
* midnight, 00:00, at the start of this date.
*
* @param {ZoneId} zone - if zone is not null @see {@link LocalDate.atStartOfDayWithZone}
* @return {LocalDateTime|ZonedDateTime} the local date-time of midnight at the start of this date, not null
*/
atStartOfDay(zone) {
if(zone != null){
return this.atStartOfDayWithZone(zone);
} else {
return LocalDateTime.of(this, LocalTime.MIDNIGHT);
}
}
/**
* Combines this date with a time-zone to create a {@link ZonedDateTime}
* at the start of the day
*
* This returns a {@link ZonedDateTime} formed from this date at the
* specified zone, with the time set to be the earliest valid time according
* to the rules in the time-zone.
*
* Time-zone rules, such as daylight savings, mean that not every local date-time
* is valid for the specified zone, thus the local date-time may not be midnight.
*
* In most cases, there is only one valid offset for a local date-time.
* In the case of an overlap, there are two valid offsets, and the earlier one is used,
* corresponding to the first occurrence of midnight on the date.
* In the case of a gap, the zoned date-time will represent the instant just after the gap.
*
* If the zone ID is a {@link ZoneOffset}, then the result always has a time of midnight.
*
* To convert to a specific time in a given time-zone call {@link atTime}
* followed by {@link LocalDateTime#atZone}.
*
* @param {!ZoneId} zone - the zone ID to use, not null
* @return {ZonedDateTime} the zoned date-time formed from this date and the earliest valid time for the zone, not null
*/
atStartOfDayWithZone(zone) {
requireNonNull(zone, 'zone');
let ldt = this.atTime(LocalTime.MIDNIGHT);
// need to handle case where there is a gap from 11:30 to 00:30
// standard ZDT factory would result in 01:00 rather than 00:30
if (zone instanceof ZoneOffset === false) {
const trans = zone.rules().transition(ldt);
if (trans != null && trans.isGap()) {
ldt = trans.dateTimeAfter();
}
}
return ZonedDateTime.of(ldt, zone);
}
/**
* Converts this date to the Epoch Day.
*
* The Epoch Day count is a simple incrementing count of days where day 0 is 1970-01-01 (ISO).
* This definition is the same for all chronologies, enabling conversion.
*
* @return {number} the Epoch Day equivalent to this date
*/
toEpochDay() {
const y = this._year;
const m = this._month;
let total = 0;
total += 365 * y;
if (y >= 0) {
total += MathUtil.intDiv(y + 3, 4) - MathUtil.intDiv(y + 99, 100) + MathUtil.intDiv(y + 399, 400);
} else {
total -= MathUtil.intDiv(y, -4) - MathUtil.intDiv(y, -100) + MathUtil.intDiv(y, -400);
}
total += MathUtil.intDiv(367 * m - 362, 12);
total += this.dayOfMonth() - 1;
if (m > 2) {
total--;
if (!IsoChronology.isLeapYear(y)) {
total--;
}
}
return total - DAYS_0000_TO_1970;
}
/**
* Compares this date to another date.
*
* The comparison is primarily based on the date, from earliest to latest.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* If all the dates being compared are instances of {@link LocalDate},
* then the comparison will be entirely based on the date.
* If some dates being compared are in different chronologies, then the
* chronology is also considered, see {@link ChronoLocalDate.compareTo}.
*
* @param {!LocalDate} other - the other date to compare to, not null
* @return {number} the comparator value, negative if less, positive if greater
*/
compareTo(other) {
requireNonNull(other, 'other');
requireInstance(other, LocalDate, 'other');
return this._compareTo0(other);
// return super.compareTo(other); if not instanceof LocalDate
}
/**
*
* @param {!LocalDate} otherDate
* @returns {number}
* @private
*/
_compareTo0(otherDate) {
let cmp = (this._year - otherDate._year);
if (cmp === 0) {
cmp = (this._month - otherDate._month);
if (cmp === 0) {
cmp = (this._day - otherDate._day);
}
}
return cmp;
}
/**
* Checks if this date is after the specified date.
*
* This checks to see if this date represents a point on the
* local time-line after the other date.
* <pre>
* LocalDate a = LocalDate.of(2012, 6, 30);
* LocalDate b = LocalDate.of(2012, 7, 1);
* a.isAfter(b) == false
* a.isAfter(a) == false
* b.isAfter(a) == true
* </pre>
*
* This method only considers the position of the two dates on the local time-line.
* It does not take into account the chronology, or calendar system.
* This is different from the comparison in {@link compareTo},
* but is the same approach as {@link DATE_COMPARATOR}.
*
* @param {!LocalDate} other - the other date to compare to, not null
* @return {boolean} true if this date is after the specified date
*/
isAfter(other) {
return this.compareTo(other) > 0;
// return super.isAfter(other) if not instanceof LocalDate
}
/**
* Checks if this date is before the specified date.
*
* This checks to see if this date represents a point on the
* local time-line before the other date.
* <pre>
* LocalDate a = LocalDate.of(2012, 6, 30);
* LocalDate b = LocalDate.of(2012, 7, 1);
* a.isBefore(b) == true
* a.isBefore(a) == false
* b.isBefore(a) == false
* </pre>
*
* This method only considers the position of the two dates on the local time-line.
* It does not take into account the chronology, or calendar system.
* This is different from the comparison in {@link compareTo},
* but is the same approach as {@link DATE_COMPARATOR}.
*
* @param {!LocalDate} other - the other date to compare to, not null
* @return {boolean} true if this date is before the specified date
*/
isBefore(other) {
return this.compareTo(other) < 0;
// return super.isBefore(other) if not instanceof LocalDate
}
/**
* Checks if this date is equal to the specified date.
*
* This checks to see if this date represents the same point on the
* local time-line as the other date.
* <pre>
* LocalDate a = LocalDate.of(2012, 6, 30);
* LocalDate b = LocalDate.of(2012, 7, 1);
* a.isEqual(b) == false
* a.isEqual(a) == true
* b.isEqual(a) == false
* </pre>
*
* This method only considers the position of the two dates on the local time-line.
* It does not take into account the chronology, or calendar system.
* This is different from the comparison in {@link compareTo}
* but is the same approach as {@link DATE_COMPARATOR}.
*
* @param {!LocalDate} other - the other date to compare to, not null
* @return {boolean} true if this date is equal to the specified date
*/
isEqual(other) {
return this.compareTo(other) === 0;
// return super.isEqual(other) if not instanceof LocalDate
}
/**
* Checks if this date is equal to another date.
*
* Compares this LocalDate with another ensuring that the date is the same.
*
* Only objects of type LocalDate are compared, other types return false.
*
* @param {*} other - the object to check, null returns false
* @return {boolean} true if this is equal to the other date
*/
equals(other) {
if (this === other) {
return true;
}
if (other instanceof LocalDate) {
return this._compareTo0(other) === 0;
}
return false;
}
/**
* A hash code for this date.
*
* @return {number} a suitable hash code
*/
hashCode() {
const yearValue = this._year;
const monthValue = this._month;
const dayValue = this._day;
return MathUtil.hash((yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue)));
}
/**
* Outputs this date as a String, such as 2007-12-03.
* The output will be in the ISO-8601 format uuuu-MM-dd.
*
* @return {string} a string representation of this date, not null
*/
toString() {
let dayString, monthString, yearString;
const yearValue = this._year;
const monthValue = this._month;
const dayValue = this._day;
const absYear = Math.abs(yearValue);
if (absYear < 1000) {
if (yearValue < 0) {
yearString = '-' + ('' + (yearValue - 10000)).slice(-4);
} else {
yearString = ('' + (yearValue + 10000)).slice(-4);
}
} else {
if (yearValue > 9999) {
yearString = '+' + yearValue;
} else {
yearString = '' + yearValue;
}
}
if (monthValue < 10) {
monthString = '-0' + monthValue;
} else {
monthString = '-' + monthValue;
}
if (dayValue < 10) {
dayString = '-0' + dayValue;
} else {
dayString = '-' + dayValue;
}
return yearString + monthString + dayString;
}
/**
*
* @return {string} same as {@link LocalDate.toString}
*/
toJSON() {
return this.toString();
}
/**
* Outputs this date as a string using the formatter.
*
* @param {DateTimeFormatter} formatter the formatter to use, not null
* @return {String} the formatted date string, not null
* @throws DateTimeException if an error occurs during printing
*/
format(formatter) {
requireNonNull(formatter, 'formatter');
requireInstance(formatter, DateTimeFormatter, 'formatter');
return super.format(formatter);
}
} |
JavaScript | class EnumMemberElement {
/**
*
* @param {string} value - value of an enum element
* @param {string} description
* @param {string} type
*/
constructor(value, description, type) {
this.value = value;
this.description = description;
this.type = type;
this.sourceMap = null;
}
/**
* @param {boolean} sourceMapsEnabled
*/
toRefract(sourceMapsEnabled) {
const sourceMapEl = sourceMapsEnabled && this.sourceMap ? new SourceMapElement(this.sourceMap.byteBlocks) : null;
const result = {
element: Refract.elements[this.type || 'string'],
attributes: {
typeAttributes: {
element: Refract.elements.array,
content: [{
element: Refract.elements.string,
content: 'fixed',
}],
},
...(sourceMapEl ? { sourceMap: sourceMapEl.toRefract() } : {}),
},
};
result.content = this.value;
if (this.description) {
result.meta = {
description: {
element: Refract.elements.string,
content: this.description,
...(sourceMapEl ? {
attributes: { sourceMap: sourceMapEl.toRefract() },
} : {}),
},
};
}
return result;
}
getBody() {
return this.value;
}
getSchema() {
return [this.value];
}
} |
JavaScript | class Hud extends Container {
constructor() {
super();
}
/**
* createTextBox
* This method defines a property key on the Hud object that when modified
* ensures the text box is visually updated. This is accomplished using ES6 getters
* and setters.
* @param name string - This name becomes a property key on the Hud object,
* modifying it will update the textBox automatically.
* @param opts object - Object to convey style, location, anchor point, etc of the text box
*/
createTextBox(name, opts) {
// set defaults, and allow them to be overwritten
const options = _extend({
style: {
fontFamily: 'Arial',
fontSize: '18px',
align: 'left',
fill: 'white'
},
location: new Point(0, 0),
anchor: {
x: 0.5,
y: 0.5
}
}, opts);
this[name + 'TextBox'] = new Text('', options.style);
const textBox = this[name + 'TextBox'];
textBox.position.set(options.location.x, options.location.y);
textBox.anchor.set(options.anchor.x, options.anchor.y);
this.addChild(textBox);
Object.defineProperty(this, name, {
set: (val) => {
textBox.text = val;
},
get: () => {
return textBox.text;
}
});
}
createTextureBasedCounter(name, opts) {
const options = _extend({
texture: '',
spritesheet: '',
location: new Point(0, 0)
}, opts);
this[name + 'Container'] = new Container();
const container = this[name + 'Container'];
container.position.set(options.location.x, options.location.y);
this.addChild(container);
Object.defineProperty(this, name, {
set: (val) => {
const gameTextures = loader.resources[options.spritesheet].textures;
const texture = gameTextures[options.texture];
const childCount = container.children.length;
if (childCount < val) {
for (let i = childCount; i < val; i++) {
const item = new extras.AnimatedSprite([texture]);
item.position.set(item.width * i, 0);
container.addChild(item);
}
} else if (val != childCount) {
container.removeChildren(val, childCount);
}
}
});
}
} |
JavaScript | class captureNetwork extends Gatherer {
constructor(){
super()
this._networkRequests=[]
this.__networkRequestsAdded = this.onNetworkRequest.bind(this);
this.client = undefined
}
/**
* @param {LH.Crdp.Log.EntryAddedEvent} entry
*/
onNetworkRequest(entry) {
this._networkRequests.push(entry);
}
/** *
* @param {*} options
*/
async beforePass(options) {
const driver = options.driver;
const cdp_options = {
host: driver._connection.hostname,
port: driver._connection.port
};
this.client = await CDP(cdp_options);
const {Network, Page} = this.client;
Network.requestWillBeSent(this.__networkRequestsAdded);
await Network.enable();
await Page.enable();
}
/** *
* @param {*} passContext
*/
async afterPass(passContext) {
console.log("=========== You reached in after pass ================");
const driver = passContext.driver
const cdp_options = {
host: driver._connection.hostname,
port: driver._connection.port
};
this.client = await CDP(cdp_options);
this.client.close()
return this._networkRequests
}
} |
JavaScript | class MyRoof extends CGFobject {
constructor(scene, material) {
super(scene);
this.initBuffers();
this.material = material;
}
initBuffers() {
this.indices = [
1,2,0,
3,5,4,
5,6,4,
7,9,8,
10,11,12,
10,12,13,
];
this.normals = [
-1/1.118, 0.5/1.118, 0,
-1/1.118, 0.5/1.118, 0,
-1/1.118, 0.5/1.118, 0,
0,1/2.236,2/2.236,
0,1/2.236,2/2.236,
0,1/2.236,2/2.236,
0,1/2.236,2/2.236,
2/2.236,1/2.236,0,
2/2.236,1/2.236,0,
2/2.236,1/2.236,0,
0,1/2.236,-2/2.236,
0,1/2.236,-2/2.236,
0,1/2.236,-2/2.236,
0,1/2.236,-2/2.236,
];
this.vertices = [
-1, 0, -0.5, //0
-1, 0, 0.5, //1
-0.5, 1, 0, //2
-1, 0, 0.5, //3
-0.5, 1, 0, //4
1, 0, 0.5, //5
0.5, 1, 0, //6
1, 0, 0.5, //7
0.5, 1, 0, //8
1, 0, -0.5, //9
1, 0, -0.5, //10
-1, 0, -0.5, //11
-0.5, 1, 0, //12
0.5, 1, 0, //13
];
this.texCoords = [
0, 1, //0
1, 1, //1
0.5, 0.1, //2
-0.5, 1, //3
0, 0, //4
1.5, 1, //5
1, 0, //6
0, 1, //7
0.5, 0.1, //8
1, 1, //9
-0.5, 1, //10
1.5, 1, //11
1, 0, //12
0, 0, //13
];
this.primitiveType = this.scene.gl.TRIANGLES;
this.initGLBuffers();
this.updateTexCoordsGLBuffers();
//this.enableNormalViz();
}
display() {
this.material.apply();
super.display();
}
} |
JavaScript | class ToolRunner extends events.EventEmitter {
constructor(toolPath, args, options) {
super();
if (!toolPath) {
throw new Error("Parameter 'toolPath' cannot be null or empty.");
}
this.toolPath = toolPath;
this.args = args || [];
this.options = options || {};
}
_debug(message) {
if (this.options.listeners && this.options.listeners.debug) {
this.options.listeners.debug(message);
}
}
_getCommandString(options, noPrefix) {
const toolPath = this._getSpawnFileName();
const args = this._getSpawnArgs(options);
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
if (IS_WINDOWS) {
// Windows + cmd file
if (this._isCmdFile()) {
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows + verbatim
else if (options.windowsVerbatimArguments) {
cmd += `"${toolPath}"`;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows (regular)
else {
cmd += this._windowsQuoteCmdArg(toolPath);
for (const a of args) {
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
}
}
}
else {
// OSX/Linux - this can likely be improved with some form of quoting.
// creating processes on Unix is fundamentally different than Windows.
// on Unix, execvp() takes an arg array.
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
return cmd;
}
_processLineBuffer(data, strBuffer, onLine) {
try {
let s = strBuffer + data.toString();
let n = s.indexOf(os.EOL);
while (n > -1) {
const line = s.substring(0, n);
onLine(line);
// the rest of the string ...
s = s.substring(n + os.EOL.length);
n = s.indexOf(os.EOL);
}
strBuffer = s;
}
catch (err) {
// streaming lines to console is best effort. Don't fail a build.
this._debug(`error processing line. Failed with error ${err}`);
}
}
_getSpawnFileName() {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
return process.env['COMSPEC'] || 'cmd.exe';
}
}
return this.toolPath;
}
_getSpawnArgs(options) {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
for (const a of this.args) {
argline += ' ';
argline += options.windowsVerbatimArguments
? a
: this._windowsQuoteCmdArg(a);
}
argline += '"';
return [argline];
}
}
return this.args;
}
_endsWith(str, end) {
return str.endsWith(end);
}
_isCmdFile() {
const upperToolPath = this.toolPath.toUpperCase();
return (this._endsWith(upperToolPath, '.CMD') ||
this._endsWith(upperToolPath, '.BAT'));
}
_windowsQuoteCmdArg(arg) {
// for .exe, apply the normal quoting rules that libuv applies
if (!this._isCmdFile()) {
return this._uvQuoteCmdArg(arg);
}
// otherwise apply quoting rules specific to the cmd.exe command line parser.
// the libuv rules are generic and are not designed specifically for cmd.exe
// command line parser.
//
// for a detailed description of the cmd.exe command line parser, refer to
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
// need quotes for empty arg
if (!arg) {
return '""';
}
// determine whether the arg needs to be quoted
const cmdSpecialChars = [
' ',
'\t',
'&',
'(',
')',
'[',
']',
'{',
'}',
'^',
'=',
';',
'!',
"'",
'+',
',',
'`',
'~',
'|',
'<',
'>',
'"'
];
let needsQuotes = false;
for (const char of arg) {
if (cmdSpecialChars.some(x => x === char)) {
needsQuotes = true;
break;
}
}
// short-circuit if quotes not needed
if (!needsQuotes) {
return arg;
}
// the following quoting rules are very similar to the rules that by libuv applies.
//
// 1) wrap the string in quotes
//
// 2) double-up quotes - i.e. " => ""
//
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
// doesn't work well with a cmd.exe command line.
//
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
// for example, the command line:
// foo.exe "myarg:""my val"""
// is parsed by a .NET console app into an arg array:
// [ "myarg:\"my val\"" ]
// which is the same end result when applying libuv quoting rules. although the actual
// command line from libuv quoting rules would look like:
// foo.exe "myarg:\"my val\""
//
// 3) double-up slashes that precede a quote,
// e.g. hello \world => "hello \world"
// hello\"world => "hello\\""world"
// hello\\"world => "hello\\\\""world"
// hello world\ => "hello world\\"
//
// technically this is not required for a cmd.exe command line, or the batch argument parser.
// the reasons for including this as a .cmd quoting rule are:
//
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
//
// b) it's what we've been doing previously (by deferring to node default behavior) and we
// haven't heard any complaints about that aspect.
//
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
// by using %%.
//
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
//
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
// to an external program.
//
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
// % can be escaped within a .cmd file.
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\'; // double the slash
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '"'; // double the quote
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_uvQuoteCmdArg(arg) {
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
// is used.
//
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
// pasting copyright notice from Node within this function:
//
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
if (!arg) {
// Need double quotation for empty argument
return '""';
}
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
// No quotation needed
return arg;
}
if (!arg.includes('"') && !arg.includes('\\')) {
// No embedded double quotes or backslashes, so I can just wrap
// quote marks around the whole thing.
return `"${arg}"`;
}
// Expected input/output:
// input : hello"world
// output: "hello\"world"
// input : hello""world
// output: "hello\"\"world"
// input : hello\world
// output: hello\world
// input : hello\\world
// output: hello\\world
// input : hello\"world
// output: "hello\\\"world"
// input : hello\\"world
// output: "hello\\\\\"world"
// input : hello world\
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
// but it appears the comment is wrong, it should be "hello world\\"
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\';
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '\\';
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_cloneExecOptions(options) {
options = options || {};
const result = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: options.silent || false,
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
failOnStdErr: options.failOnStdErr || false,
ignoreReturnCode: options.ignoreReturnCode || false,
delay: options.delay || 10000
};
result.outStream = options.outStream || process.stdout;
result.errStream = options.errStream || process.stderr;
return result;
}
_getSpawnOptions(options, toolPath) {
options = options || {};
const result = {};
result.cwd = options.cwd;
result.env = options.env;
result['windowsVerbatimArguments'] =
options.windowsVerbatimArguments || this._isCmdFile();
if (options.windowsVerbatimArguments) {
result.argv0 = `"${toolPath}"`;
}
return result;
}
/**
* Exec a tool.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param tool path to tool to exec
* @param options optional exec options. See ExecOptions
* @returns number
*/
exec() {
return __awaiter(this, void 0, void 0, function* () {
// root the tool path if it is unrooted and contains relative pathing
if (!ioUtil.isRooted(this.toolPath) &&
(this.toolPath.includes('/') ||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
}
// if the tool is only a file name, then resolve it from the PATH
// otherwise verify it exists (add extension on Windows if necessary)
this.toolPath = yield io.which(this.toolPath, true);
return new Promise((resolve, reject) => {
this._debug(`exec tool: ${this.toolPath}`);
this._debug('arguments:');
for (const arg of this.args) {
this._debug(` ${arg}`);
}
const optionsNonNull = this._cloneExecOptions(this.options);
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
}
const state = new ExecState(optionsNonNull, this.toolPath);
state.on('debug', (message) => {
this._debug(message);
});
const fileName = this._getSpawnFileName();
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
const stdbuffer = '';
if (cp.stdout) {
cp.stdout.on('data', (data) => {
if (this.options.listeners && this.options.listeners.stdout) {
this.options.listeners.stdout(data);
}
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(data);
}
this._processLineBuffer(data, stdbuffer, (line) => {
if (this.options.listeners && this.options.listeners.stdline) {
this.options.listeners.stdline(line);
}
});
});
}
const errbuffer = '';
if (cp.stderr) {
cp.stderr.on('data', (data) => {
state.processStderr = true;
if (this.options.listeners && this.options.listeners.stderr) {
this.options.listeners.stderr(data);
}
if (!optionsNonNull.silent &&
optionsNonNull.errStream &&
optionsNonNull.outStream) {
const s = optionsNonNull.failOnStdErr
? optionsNonNull.errStream
: optionsNonNull.outStream;
s.write(data);
}
this._processLineBuffer(data, errbuffer, (line) => {
if (this.options.listeners && this.options.listeners.errline) {
this.options.listeners.errline(line);
}
});
});
}
cp.on('error', (err) => {
state.processError = err.message;
state.processExited = true;
state.processClosed = true;
state.CheckComplete();
});
cp.on('exit', (code) => {
state.processExitCode = code;
state.processExited = true;
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
state.CheckComplete();
});
cp.on('close', (code) => {
state.processExitCode = code;
state.processExited = true;
state.processClosed = true;
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
state.CheckComplete();
});
state.on('done', (error, exitCode) => {
if (stdbuffer.length > 0) {
this.emit('stdline', stdbuffer);
}
if (errbuffer.length > 0) {
this.emit('errline', errbuffer);
}
cp.removeAllListeners();
if (error) {
reject(error);
}
else {
resolve(exitCode);
}
});
if (this.options.input) {
if (!cp.stdin) {
throw new Error('child process missing stdin');
}
cp.stdin.end(this.options.input);
}
});
});
}
} |
JavaScript | class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {}; // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
} |
JavaScript | class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
} |
JavaScript | class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parse_url(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parse_url(`${input}`);
}
input = {};
} else {
parsedURL = parse_url(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has('Content-Type')) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
} |
JavaScript | class CalendarDay extends Day {
constructor() {
super(...arguments);
/**
* Whether this day is the current day (ex: today).
*/
this.currentDay = false;
/**
* Whether this day is on the same week as the current day (ex: today).
*/
this.currentWeek = false;
/**
* Whether this day is on the same month as the current day (ex: today).
*/
this.currentMonth = false;
/**
* Whether this day is on the same year as the current day (ex: today).
*/
this.currentYear = false;
/**
* How many days away this day is from the current day (ex: today). If this
* day is the current day the offset is 0. If this day is before the current
* day it will be the negative number of days away. Otherwise this will be
* positive meaning this day is after the current day by the given days.
*/
this.currentOffset = 0;
/**
* Whether this day is part of a selection on the calendar.
*/
this.selectedDay = false;
/**
* Whether this day is on the same week that the calendar selection is.
*/
this.selectedWeek = false;
/**
* Whether this day is on the same month that the calendar selection is.
*/
this.selectedMonth = false;
/**
* Whether this day is on the same year that the calendar selection is.
*/
this.selectedYear = false;
/**
* Whether this day is in the current calendar or not. Some days are outside
* the calendar span and used to fill in weeks. Month calendars will fill in
* days so the list of days in the calendar start on Sunday and end on Saturday.
*/
this.inCalendar = false;
/**
* The list of events on this day based on the settings and schedules in the
* calendar.
*/
this.events = [];
}
/**
* Creates an iterator for the events on this day.
*
* @returns The new iterator for the events on this day.
*/
iterateEvents() {
return Iterator.forArray(this.events);
}
/**
* Updates the current flags on this day given the current day (ex: today).
*
* @param current The current day of the calendar.
*/
updateCurrent(current) {
this.currentDay = this.sameDay(current);
this.currentWeek = this.sameWeek(current);
this.currentMonth = this.sameMonth(current);
this.currentYear = this.sameYear(current);
this.currentOffset = this.daysBetween(current, Op.DOWN, false);
return this;
}
/**
* Updates the selection flags on this day given the selection range on the
* calendar.
*
* @param selected The span of days selected on the calendar.
*/
updateSelected(selected) {
this.selectedDay = selected.matchesDay(this);
this.selectedWeek = selected.matchesWeek(this);
this.selectedMonth = selected.matchesMonth(this);
this.selectedYear = selected.matchesYear(this);
return this;
}
/**
* Clears the selection flags on this day. This is done when the selection on
* the calendar is cleared.
*/
clearSelected() {
this.selectedDay = this.selectedWeek = this.selectedMonth = this.selectedYear = false;
return this;
}
} |
JavaScript | class Model extends events.EventEmitter {
/**
* Model manager constructor
*/
constructor () {
// We must call super() in child class to have access to 'this' in a constructor
super();
/**
* Requiring system logger
*
* @type {Logger|exports|module.exports}
* @private
*/
this._logger = require('./logger.js');
this._logger.log('## Initializing Model Manager');
/**
* Base path for models
*
* @type {string}
*/
this.modelsPath = path.dirname(process.mainModule.filename) + '/app/models/';
/**
* Collections Map
*
* @type {{}}
* @private
*/
this._collections = {};
}
/**
* Loading models for some path
*
* @param modelsPath
*/
loadModels (modelsPath) {
var applicationFacade = require('./facade.js').ApplicationFacade.instance;
var normalizedPath = modelsPath;
if (!fs.existsSync(normalizedPath)) {
this._logger.info('## Models Dir is not exists [%s]. Trying another one.', normalizedPath);
if (fs.existsSync(applicationFacade.basePath + '/' + normalizedPath)) {
normalizedPath = applicationFacade.basePath + '/' + normalizedPath;
}
}
normalizedPath = fs.realpathSync(normalizedPath);
this._logger.info('## Get realpath of models directory: [%s]', normalizedPath);
this._logger.debug('---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------');
// Loading models
fs.readdirSync(normalizedPath).forEach((file) => {
var fileInfo = path.parse(file);
if (fileInfo.ext == '.js') {
this._logger.info('Loading model: %s', modelsPath + '/' + file);
this.registerModel(fileInfo.name, normalizedPath + '/' + file);
} else {
this._logger.debug(' @@@@ File %s is not js file. Ignoring.', file);
}
});
}
/**
* Registering model by its definition and name
*
* @param collectionName
* modelDefinition
*/
registerModel(collectionName, modelDefinition) {
if (typeof modelDefinition == "function") {
var collectionInstance = new modelDefinition(collectionName);
collectionInstance.init();
// Set instance of the model
this._collections[collectionName] = collectionInstance;
} else {
this.collection(collectionName, modelDefinition);
}
}
/**
* Returns collection instance
*
* @param collectionName
*/
collection (collectionName, collectionFile) {
// Check collection
if (this._collections[collectionName] == null) {
var CollectionClass = this.getModelClassDefinition(collectionName, collectionFile);
/**
* Initializing model instance
*/
var collectionInstance = new CollectionClass(collectionName);
collectionInstance.init();
// Set instance of the model
this._collections[collectionName] = collectionInstance;
}
return this._collections[collectionName];
}
/**
* Returns definition for specified model
*
* @param collectionName
* @param collectionFile
*/
getModelClassDefinition (collectionName, collectionFile) {
// Check collection
var fileName = collectionFile != null ? collectionFile : collectionName + '.js';
// Trying to find in parent models dir
var modelPath = fileName;
if (!fs.existsSync(modelPath)) {
modelPath = path.normalize(this.modelsPath + fileName);
}
this._logger.log('## Trying to initialize model: %s', modelPath);
if (!fs.existsSync(modelPath)) {
// Trying local models dir
if (!fs.existsSync(modelPath)) {
modelPath = path.normalize(path.dirname(__dirname) + '/app/models/' + fileName)
this._logger.log('## Model file not found, trying another one: %s', modelPath);
}
}
var CollectionClass = require(modelPath);
return CollectionClass;
}
/**
* Returns list of all models from default locations
*/
getModelsList () {
var result = [];
var modelsList = [];
modelsList = modelsList.concat(this.getModelsForPath(this.modelsPath));
var resultsMap = {};
for (var i = 0; i < modelsList.length; i++) {
if (resultsMap[modelsList[i]] == null) {
result.push(modelsList[i]);
}
resultsMap[modelsList[i]] = true;
}
return result;
}
/**
* Loading models for some path
*
* @param modelsPath
*/
getModelsForPath (modelsPath) {
var result = [];
var normalizedPath = path.normalize(modelsPath);
this._logger.info('## Checking models in the dir: %s', normalizedPath);
if (!fs.existsSync(normalizedPath)) {
this._logger.info('## Models Dir is not exists %s. Trying another one.', normalizedPath);
return []
}
normalizedPath = fs.realpathSync(normalizedPath);
fs.readdirSync(normalizedPath).forEach((file) => {
var fileInfo = path.parse(file);
if (fileInfo.ext == '.js') {
result.push(fileInfo.name)
}
});
return result;
}
/**
* Initialize models manager
*/
init () {
// Initializing model mogic
}
} |
JavaScript | class ViberAllOf {
/**
* Constructs a new <code>ViberAllOf</code>.
* @alias module:sunshine-conversations-client/sunshine-conversations-client.model/ViberAllOf
* @param token {String} Viber Public Account token.
*/
constructor(token) {
ViberAllOf.initialize(this, token);
}
/**
* 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, token) {
obj['token'] = token;
}
/**
* Constructs a <code>ViberAllOf</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:sunshine-conversations-client/sunshine-conversations-client.model/ViberAllOf} obj Optional instance to populate.
* @return {module:sunshine-conversations-client/sunshine-conversations-client.model/ViberAllOf} The populated <code>ViberAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ViberAllOf();
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
}
if (data.hasOwnProperty('token')) {
obj['token'] = ApiClient.convertToType(data['token'], 'String');
}
if (data.hasOwnProperty('uri')) {
obj['uri'] = ApiClient.convertToType(data['uri'], 'String');
}
if (data.hasOwnProperty('accountId')) {
obj['accountId'] = ApiClient.convertToType(data['accountId'], 'String');
}
}
return obj;
}
/**
* Returns To configure a Viber integration, acquire the Viber Public Account token from the user and call the Create Integration endpoint.
* @return {String}
*/
getType() {
return this.type;
}
/**
* Sets To configure a Viber integration, acquire the Viber Public Account token from the user and call the Create Integration endpoint.
* @param {String} type To configure a Viber integration, acquire the Viber Public Account token from the user and call the Create Integration endpoint.
*/
setType(type) {
this['type'] = type;
}
/**
* Returns Viber Public Account token.
* @return {String}
*/
getToken() {
return this.token;
}
/**
* Sets Viber Public Account token.
* @param {String} token Viber Public Account token.
*/
setToken(token) {
this['token'] = token;
}
/**
* Returns Unique URI of the Viber account.
* @return {String}
*/
getUri() {
return this.uri;
}
/**
* Sets Unique URI of the Viber account.
* @param {String} uri Unique URI of the Viber account.
*/
setUri(uri) {
this['uri'] = uri;
}
/**
* Returns Unique ID of the Viber account.
* @return {String}
*/
getAccountId() {
return this.accountId;
}
/**
* Sets Unique ID of the Viber account.
* @param {String} accountId Unique ID of the Viber account.
*/
setAccountId(accountId) {
this['accountId'] = accountId;
}
} |
JavaScript | class OrderCancelCommandBuilder {
static build() {
const orderCancelCommandValidator = new OrderCancelCommandValidator(logger)
const orderCancelCommand = new OrderCancelCommand(logger, orderService, orderCancelCommandValidator,
privateKeyService, privateKeyValidator)
return orderCancelCommand
}
} |
JavaScript | class App extends Component {
state={
showTerminal: false
}
toggleTerminal = (e, sta) =>{
const {showTerminal} = this.state;
this.setState({showTerminal: sta || !showTerminal});
}
render(){
const {showTerminal} = this.state;
return (
<BrowserRouter>
<Route path="*" render={(props)=><NavBar toggleTerminal={this.toggleTerminal} {...props} />} />
{showTerminal &&
<>
<Route path="*" render={(props)=><Terminal toggleTerminal={this.toggleTerminal} {...props} />} />
<div className="close-terminal-btn m-halfr p-halfr fade-appear-01 b-1r pointer" onClick={this.toggleTerminal}>×</div>
</>}
<Switch>
<Route path="/projects" exact component={Projects} />
<Route path="/blogs" exact component={Blogs} />
<Route path="/" exact component={Home} />
</Switch>
</BrowserRouter>
);
}
} |
JavaScript | class TestAudit extends ManualAudit {
static get meta() {
return Object.assign({
name: 'manual-audit',
helpText: 'Some help text.',
}, super.partialMeta);
}
} |
JavaScript | class WaveFileTagEditor extends WaveFileCreator {
/**
* Return the value of a RIFF tag in the INFO chunk.
* @param {string} tag The tag name.
* @return {?string} The value if the tag is found, null otherwise.
*/
getTag(tag) {
/** @type {!Object} */
let index = this.getTagIndex_(tag);
if (index.TAG !== null) {
return this.LIST[index.LIST].subChunks[index.TAG].value;
}
return null;
}
/**
* Write a RIFF tag in the INFO chunk. If the tag do not exist,
* then it is created. It if exists, it is overwritten.
* @param {string} tag The tag name.
* @param {string} value The tag value.
* @throws {Error} If the tag name is not valid.
*/
setTag(tag, value) {
tag = fixRIFFTag_(tag);
/** @type {!Object} */
let index = this.getTagIndex_(tag);
if (index.TAG !== null) {
this.LIST[index.LIST].subChunks[index.TAG].chunkSize =
value.length + 1;
this.LIST[index.LIST].subChunks[index.TAG].value = value;
} else if (index.LIST !== null) {
this.LIST[index.LIST].subChunks.push({
chunkId: tag,
chunkSize: value.length + 1,
value: value});
} else {
this.LIST.push({
chunkId: 'LIST',
chunkSize: 8 + value.length + 1,
format: 'INFO',
subChunks: []});
this.LIST[this.LIST.length - 1].subChunks.push({
chunkId: tag,
chunkSize: value.length + 1,
value: value});
}
}
/**
* Remove a RIFF tag from the INFO chunk.
* @param {string} tag The tag name.
* @return {boolean} True if a tag was deleted.
*/
deleteTag(tag) {
/** @type {!Object} */
let index = this.getTagIndex_(tag);
if (index.TAG !== null) {
this.LIST[index.LIST].subChunks.splice(index.TAG, 1);
return true;
}
return false;
}
/**
* Return a Object<tag, value> with the RIFF tags in the file.
* @return {!Object<string, string>} The file tags.
*/
listTags() {
/** @type {?number} */
let index = this.getLISTIndex('INFO');
/** @type {!Object} */
let tags = {};
if (index !== null) {
for (let i = 0, len = this.LIST[index].subChunks.length; i < len; i++) {
tags[this.LIST[index].subChunks[i].chunkId] =
this.LIST[index].subChunks[i].value;
}
}
return tags;
}
/**
* Return the index of a list by its type.
* @param {string} listType The list type ('adtl', 'INFO')
* @return {?number}
* @protected
*/
getLISTIndex(listType) {
for (let i = 0, len = this.LIST.length; i < len; i++) {
if (this.LIST[i].format == listType) {
return i;
}
}
return null;
}
/**
* Return the index of a tag in a FILE chunk.
* @param {string} tag The tag name.
* @return {!Object<string, ?number>}
* Object.LIST is the INFO index in LIST
* Object.TAG is the tag index in the INFO
* @private
*/
getTagIndex_(tag) {
/** @type {!Object<string, ?number>} */
let index = {LIST: null, TAG: null};
for (let i = 0, len = this.LIST.length; i < len; i++) {
if (this.LIST[i].format == 'INFO') {
index.LIST = i;
for (let j=0, subLen = this.LIST[i].subChunks.length; j < subLen; j++) {
if (this.LIST[i].subChunks[j].chunkId == tag) {
index.TAG = j;
break;
}
}
break;
}
}
return index;
}
} |
JavaScript | class Backdrop extends LitElement {
static get properties() {
return {
/**
* REQUIRED: id of the target element to display backdrop behind
* @type {string}
*/
forTarget: { type: String, attribute: 'for-target' },
/**
* Disables the fade-out transition while the backdrop is being hidden
* @type {boolean}
*/
noAnimateHide: { type: Boolean, attribute: 'no-animate-hide' },
/**
* Used to control whether the backdrop is shown
* @type {boolean}
*/
shown: { type: Boolean },
_state: { type: String, reflect: true }
};
}
static get styles() {
return [ css`
:host {
background-color: var(--d2l-color-regolith);
height: 0;
left: 0;
opacity: 0;
position: fixed;
top: 0;
transition: opacity 200ms ease-in;
width: 0;
z-index: 999;
}
:host([slow-transition]) {
transition: opacity 1200ms ease-in;
}
:host([_state="showing"]) {
opacity: 0.7;
}
:host([_state="showing"]),
:host([_state="hiding"]) {
height: 100%;
width: 100%;
}
:host([_state=null][no-animate-hide]) {
transition: none;
}
@media (prefers-reduced-motion: reduce) {
:host {
transition: none;
}
}
`];
}
constructor() {
super();
this.shown = false;
this.noAnimateHide = false;
this._state = null;
}
disconnectedCallback() {
// allow body scrolling, show hidden elements, if backdrop is removed from the DOM
if (this._bodyScrollKey) {
allowBodyScroll(this._bodyScrollKey);
this._bodyScrollKey = null;
}
if (this._hiddenElements) {
showAccessible(this._hiddenElements);
this._hiddenElements = null;
}
this._state = null;
super.disconnectedCallback();
}
render() {
return html`<div></div>`;
}
updated(changedProperties) {
super.updated(changedProperties);
if (!changedProperties.has('shown')) return;
if (this.shown) {
if (this._state === null) {
this._bodyScrollKey = preventBodyScroll();
this._hiddenElements = hideAccessible(this.parentNode.querySelector(`#${cssEscape(this.forTarget)}`));
}
this._state = 'showing';
} else if (this._state === 'showing') {
const hide = () => {
if (!this.shown) {
allowBodyScroll(this._bodyScrollKey);
this._bodyScrollKey = null;
showAccessible(this._hiddenElements);
this._hiddenElements = null;
this._state = null;
}
};
if (!reduceMotion && !this.noAnimateHide && isVisible(this)) {
this.addEventListener('transitionend', hide, { once: true });
this._state = 'hiding';
} else {
hide();
}
}
}
} |
JavaScript | class ExtendedKey {
constructor(version, key, chainCode, parentFP, depth, childNum, isPrivate) {
this._version = version;
this._key = key;
this._chainCode = chainCode;
this._parentFP = parentFP;
this._depth = depth;
this._childNum = childNum;
this._isPrivate = isPrivate;
}
/**
* Derive child key is a derivation schedule for extended public
* and private keys. It allows you to derive multiple child public
* and private keys. They can be Hardened or normal as indicated by
* the index passed
* The keys between 0 (inclusive) and 0x80000000 (exclusive) are normal
* and those between 2^31 and 2^32 - 1 are Hardened
* @link https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
*
* @param {*} index - child index, must be a valid unsigned integer
*
* @throws Error if you try to derive Hardened child key from extended public key
*/
deriveChild(index) {
if (index < 0 || index > ((0x80000000 * 2) - 1)) {
throw new Error("Index out of range. The index should be between 0 and int.MaxValue");
}
if (this._depth > MaxDerivationDepth) {
throw new Error("Max derivation depth was exceeded");
}
//Check if the derivation is from public extended
//to HARDENED child public key
var isHardened = index >= HardenedKeyStart;
if (isHardened && !this._isPrivate) {
throw new Error("Cannot derive public hardened key from extended parent public key.");
}
var keyLen = 33;
var data;
//ser256(k) is the BigEndian 32byte sequence of the current parent key
//ser(i) are the Hex Encoded BigEndian 4 bytes of the index
if (isHardened) {
//This is possible only if the current extended key is private
//The format for this type of child key specified by BIP32
//is 0x00 + ser256(k) + ser(i) ~ 1 byte + 32 bytes + 4 bytes ~ 37 bytes
data = Buffer.concat([new Buffer(1), new Buffer(this._key, 'hex')]);
} else {
//The current parent key is eihter private or public extended
//The format for this type of child key
//is serP(k) + ser(i) ~ 33 bytes + 4 bytes ~ 37 bytes
var secp256CompressedPublicKey = this.pubKeyBytes();
data = Buffer.from(secp256CompressedPublicKey, 'hex');
}
// Ser32(i) is the index turned into hex encoded
// BigEndian bytes buffer
// It must be appended to the childKeyDataBuffer
var ser32 = new Buffer(4);
ser32.fill(0);
ser32.writeUInt32BE(index);
data = Buffer.concat([data, ser32]).toString('hex');
// Derive Hmac from the chaincode and the child
var hmac = Crypto.HmacSHA512(this._chainCode, data);
var l = hmac.toString();
// Left side is the newly derived childkey part
var lL = l.slice(0, 64);
// Right side is the newly derived chain code
var lR = l.slice(64, 128);
//if it doesn't throw error just continue
this.isOutOfCurveOrder(lL);
var childIsPrivate;
var childKey;
if (this._isPrivate) {
//Format is ser256(lL) + k
//Order of the curve
var n = new BigNumber(secp256k1.n, 16, 'be');
var intermediateKey = new BigNumber(lL, 16, 'be');
var parentKey = new BigNumber(this._key, 16, 'be');
var result = intermediateKey.add(parentKey);
childKey = result.mod(n).toString('hex');
childIsPrivate = true;
} else {
//Scalar multiplication ~ deriving new point on the curve
var G = secp256k1.g;
var childPoint = G.mul(lL);
//Turning the parent public key into a point (uncompress)
var parentPoint = this.parseKey(this._key);
childKey = childPoint.add(parentPoint);
childKey = this.compressKey(childKey);
}
//Creating the parent fingerprint ~ the first 4 bytes from RIPEMD160(SHA256(pubKey))
var shaPublicKeyBytes = Crypto.SHA256(this.pubKeyBytes()).toString(Crypto.enc.Hex);
var ripeShaPublicKeyBytes = Crypto.RIPEMD160(this.pubKeyBytes()).toString(Crypto.enc.Hex);
//Parent fingerprint for the child ~ ensures that this child was derived from this parent
var parentFP = '0x' + ripeShaPublicKeyBytes.slice(0, 8);
return new ExtendedKey(this._version, childKey, lR, parentFP,
this._depth + 1, index, childIsPrivate);
}
/**
* Transforms the extended key into Base58 format
*/
toBase58() {
//Padding with null nibble if necessary
var depth = this._depth < 15 ? '0' + this._depth : this._depth.toString(16);
//childNum 4 bytes buffer
var childNum = new Buffer(4);
childNum.fill(0);
childNum.writeUInt32BE(childNum);
var serializedBytes =
Buffer.concat([Buffer.from(this._version.slice(2, ), 'hex'),
Buffer.from(depth, 'hex'),
Buffer.from(this._parentFP.slice(2, ), 'hex'),
Buffer.from(childNum, 'hex'),
Buffer.from(this._chainCode, 'hex')
]);
if (this._isPrivate) {
serializedBytes = Buffer.concat([serializedBytes,
new Buffer(1).fill(0),
Buffer.from(this._key, 'hex')
]);
} else {
serializedBytes = this.paddedAppend(32, serializedBytes,
Buffer.from(this.pubKeyBytes(), 'hex'));
}
// Double sha256 to generate a 4byte checksum
var checksum = Crypto.SHA256(serializedBytes).toString(Crypto.enc.Hex);
checksum = Crypto.SHA256(checksum).toString(Crypto.enc.Hex).slice(0, 8);
serializedBytes = Buffer.concat([serializedBytes, Buffer.from(checksum, 'hex')]);
return Base58.encode(serializedBytes);
}
/**
* Multiplies the private key by G (point on the curve) and returns
* new public key point.
* @returns compressed public key bytes
*/
pubKeyBytes(key) {
if (!this._isPrivate) return this._key;
var G = secp256k1.g;
var pubKeyPoint = G.mul(this._key);
//Compressing the key
return this.compressKey(pubKeyPoint);
}
/**
* Parse public key determines whether the passed in key object
* is valid point on the curve (x: x, y: y)
* It supports compressed and uncompressed public keys
*
* @param {*} key - The public key you are trying to validate
*/
parsePublicKey(key) {
if (key.length === 0) {
throw new Error(`Key length should not be 0.`)
}
//The key format -> isOdd of the y point i think
let format = key.slice(0, 1).toString('hex');
//Is y bit odd
let yBit = (format & 0x1) == 0x1;
//Return the format to the default 0x2
format = format & (~0x1);
let pubX;
let pubY;
switch (key.length) {
//Key is compressed (not implemented so i will leave it empty)
case PublicKeyCompressedLength:
if (format !== publicKeyCompressedFormat) {
throw new Error("The format of the key is incorrect!");
}
//X point of the public key
let pubX = key.slice(1, 33);
//WHERE ARE THE EXTENSION METHODS WHEN YOU NEED THEM :(
let point = this.decompressPoint(pubX, yBit);
return point;
//Key is uncompressed
case PublicKeyUncompressedLength:
break;
default:
throw new Error(`KeyLength should be eihter
${PublicKeyUncompressedLength} or ${PublicKeyUncompressedLength}`)
}
if (pubX === undefined || pubY === undefined) {
throw new Error("The key couldn't be parsed.");
}
// P represents the {Zp} finite field over which secp256k1 is mapped
let primeField = parseInt(Secp256k1PointP, 16);
if (pubX >= primeField || pubY >= primeField) {
throw new Error("Invalid curve coordinates " +
"~they exceed the curve order, which is impossible for normal key.");
}
return {
x: pubX,
y: pubY
};
}
/**
* paddedAppend appends src to dest and adds padding of "size"
* to the source if its size is smaller
* @param {*} size - padding size
* @param {*} src - source to append
* @param {*} dest - destination to append to
*/
paddedAppend(size, dest, src) {
var source = src;
var delta = size - source.length;
if (delta > 0) source = Buffer.concat([new Buffer(delta), source]);
var buffer = Buffer.concat([dest, source]);
return buffer;
}
/**
* Decompress point expands a 33byte compressed key into
* 65 byte point on the curve
* It uses sqrtModPrime(x^3 + secp256k1.B, secp256k1.P)
* @param {*} x - Public key x coordinate
* @param {*} yBit - Is the y point parity odd @type number
*/
decompressPoint(x, yBit) {
return ecp.curve.pointFromX(x, yBit);
}
/**
* Utility method which checks whether the passed in key is valid
* and on the elliptic curve. If its zero,less or bigger,equal to curve order
* it is not valid. There is extremely low chance but there is still chance
* that the generated key is not valid. ~~@damn probablistic algorithms
* @param {*} key - The key you want to check for curve validity
* @returns true
*
* @throws Error, if
*/
isOutOfCurveOrder(key) {
var curveOrder = secp256k1.n.toString('hex');
curveOrder = parseInt(curveOrder, 16);
var parsedKey = parseInt(key, 16);
if (parsedKey <= 0 || parsedKey >= curveOrder) {
throw new Error("Key generation failed. " +
"Please, try again (the failure chance is extremely low)");
}
return true;
}
/**
* Compresses the passed publci key point
* From Point{x, y} it becomes a compressed 33 byte public key
* It can be later decompressed with the following equation
* Y^2 = X^3 + B mod n
* Y = Sqrt(x^3 + b) mod n
* Where n is the order of the curve
* @see elliptic - Elliptic provides nefty way for decompressing
* @example
*
* const EC = require('elliptic').ec;
* var secp256k1 = new EC('secp256k1');
*
* decompressedPoint = secp256k1.curve.pointFromX(x, parity);
*
* @param {*} point
*/
compressKey(point) {
const pubKeyCompressed = 0x2;
var isOddPointY = point.y % 2 != 0
var format = pubKeyCompressed;
if (isOddPointY) format |= 0x1;
var formatBuffer = Buffer.from('0' + format, 'hex');
var buffer = Buffer.from(point.x.toString('hex'), 'hex');
return this.paddedAppend(32, formatBuffer, buffer).toString('hex');
}
/**
* This function derives a new public
* ExtendedKey from the current private extended key
* which you can use for generating new public extended keys
*
* @returns ExtendedKey / public if this is a private extended key
* / else returns this instance
*
*/
deriveExtendedPublicKey() {
// Already an extended public key.
if (!this._isPrivate) {
return this;
}
// Convert it to an extended public key. The key for the new extended
// key will simply be the pubkey of the current extended private key.
//
// This is the function N((k,c)) -> (K, c) from [BIP32].
return new ExtendedKey(HDPublicKeyID, this.pubKeyBytes(), this._chainCode, this._parentFP,
this._depth, this._childNum, false);
}
/**
* Static method which provides way to convert a public extended key
* into payment address.
* @param {*} key - the public key which you want to convert to standard address
*/
static toAddress(key){
if(key === undefined || !(key instanceof ExtendedKey)){
throw new Error("The key argument should be of type ExtendedKey");
}
let keyHash = Crypto.SHA256(key.pubKeyBytes()).toString();
keyHash = Crypto.RIPEMD160(keyHash).toString();
return {
netId: HDPublicKeyHashAddressID,
hash: keyHash
};
}
} |
JavaScript | class CSSDirective {
/**
* Creates a CSS fragment to interpolate into the CSS document.
* @returns - the string to interpolate into CSS
*/
createCSS() {
return '';
}
/**
* Creates a behavior to bind to the host element.
* @returns - the behavior to bind to the host element, or undefined.
*/
createBehavior() {
return void 0;
}
} |
JavaScript | class Settings extends React.Component {
/**
* confirmData {Object} data for the notification confirm modal (title, body and handleYes)
* isNotificationOne {boolean} state to update if notification is turned on or off
* now {Date} state to store the date which is updated every second
* showTimestamp {boolean} If should show timestamp or full date in date and time
*/
state = {
confirmData: {},
isNotificationOn: null,
now: new Date(),
showTimestamp: false,
}
// Stores the setTimeout interval of the date update
dateSetTimeoutInterval = null
componentDidMount() {
this.setState({ isNotificationOn: wallet.isNotificationOn() });
this.dateSetTimeoutInterval = setInterval(() => {
this.setState({ now: new Date() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.dateSetTimeoutInterval);
}
/**
* Method called when user confirmed the reset, then we reset all data and redirect to Welcome screen
*/
handleReset = () => {
$('#confirmResetModal').modal('hide');
wallet.resetWalletData();
this.props.history.push('/welcome/');
}
/**
* When user clicks Reset button we open a modal to confirm it
*/
resetClicked = () => {
$('#confirmResetModal').modal('show');
}
/**
* When user clicks Add Passphrase button we redirect to Passphrase screen
*/
addPassphrase = () => {
if (hathorLib.wallet.isHardwareWallet()) {
$('#notSupported').modal('show');
} else {
this.props.history.push('/wallet/passphrase/');
}
}
/**
* When user clicks Change Server button we redirect to Change Server screen
*/
changeServer = () => {
this.props.history.push('/server/');
}
/**
* Called when user clicks to change notification settings
* Sets modal state, depending on the current settings and open it
*
* @param {Object} e Event emitted on link click
*/
toggleNotificationSettings = (e) => {
e.preventDefault();
if (wallet.isNotificationOn()) {
this.setState({
confirmData: {
title: t`Turn notifications off`,
body: t`Are you sure you don't want to receive wallet notifications?`,
handleYes: this.handleToggleNotificationSettings
}
});
} else {
this.setState({
confirmData: {
title: t`Turn notifications on`,
body: t`Are you sure you want to receive wallet notifications?`,
handleYes: this.handleToggleNotificationSettings
}
});
}
$('#confirmModal').modal('show');
}
/**
* Called after user confirms the notification toggle action
* Toggle user notification settings, update screen state and close the confirm modal
*/
handleToggleNotificationSettings = () => {
if (wallet.isNotificationOn()) {
wallet.turnNotificationOff();
} else {
wallet.turnNotificationOn();
}
this.setState({ isNotificationOn: wallet.isNotificationOn() });
$('#confirmModal').modal('hide');
}
/**
* Method called to open external Ledger page.
*
* @param {Object} e Event for the click
*/
openLedgerLink = (e) => {
e.preventDefault();
const url = 'https://support.ledger.com/hc/en-us/articles/115005214529-Advanced-passphrase-security';
helpers.openExternalURL(url);
}
render() {
const serverURL = hathorLib.helpers.getServerURL();
return (
<div className="content-wrapper settings">
<BackButton {...this.props} />
<div>
<p onDoubleClick={() => this.setState({ showTimestamp: !this.state.showTimestamp })}><strong>{t`Date and time:`}</strong> {this.state.showTimestamp ? hathorLib.dateFormatter.dateToTimestamp(this.state.now) : this.state.now.toString()}</p>
</div>
<div>
<p><SpanFmt>{t`**Server:** You are connected to ${serverURL}`}</SpanFmt></p>
<button className="btn btn-hathor" onClick={this.changeServer}>{t`Change server`}</button>
</div>
<hr />
<div>
<h4>{t`Advanced Settings`}</h4>
<div className="d-flex flex-column align-items-start mt-4">
<p><strong>{t`Allow notifications:`}</strong> {this.state.isNotificationOn ? <span>{t`Yes`}</span> : <span>{t`No`}</span>} <a className='ml-3' href="true" onClick={this.toggleNotificationSettings}> {t`Change`} </a></p>
<p><strong>{t`Automatically report bugs to Hathor:`}</strong> {wallet.isSentryAllowed() ? <span>{t`Yes`}</span> : <span>{t`No`}</span>} <Link className='ml-3' to='/permission/'> {t`Change`} </Link></p>
<button className="btn btn-hathor" onClick={this.addPassphrase}>{t`Set a passphrase`}</button>
<button className="btn btn-hathor mt-4" onClick={this.resetClicked}>{t`Reset all data`}</button>
</div>
</div>
<ModalResetAllData success={this.handleReset} />
<ModalConfirm title={this.state.confirmData.title} body={this.state.confirmData.body} handleYes={this.state.confirmData.handleYes} />
<ModalAlertNotSupported title={t`Complete action on your hardware wallet`}>
<div>
<p>{t`You can set your passphrase directly on your hardware wallet.`}</p>
<p>
{str2jsx(t`|fn:More info| about this on Ledger.`,
{fn: (x, i) => <a key={i} onClick={this.openLedgerLink} href="true">{x}</a>})}
</p>
</div>
</ModalAlertNotSupported>
</div>
);
}
} |
JavaScript | class ProfilePref1 extends React.Component {
render(){
return (
<PreferenceForm
header={'Hi!'}
subHeader={"Let's start by setting up appointment preferences"}
sectionHeader={'You want'}
btnOption1={'Hair Dresser'}
btnOption2={'Barber'}
resultSectionHeader={'Where do you prefer to book ?'}
onContiune={'Pref2'}
onRemoveSkipBtn={false}
onSkip={'Pref2'}
/>
)
}
} |
JavaScript | class SMEntity {
constructor(parent, name, preferences) {
this.parent = parent;
this.name = name;
this.partner = null;
this.preferences = [];
this._preferences = preferences;
this.rejects = [];
// Instead of the names stored into the preference list,
// their indices will be stored instead.
for (name of preferences) {
this.preferences.push(this.parent.getIndexByName(name) );
}
}
/*
* Returns a boolean indicating if another entity has takes on higher
* preference compared to the current partner.
*/
changePartnerFor(entity) {
if (this.partner == null) return true;
let partnerIndex = this.parent.getIndexByName(this.partner.name);
let otherIndex = this.parent.getIndexByName(entity.name);
if (this.preferences.indexOf(partnerIndex) > this.preferences.indexOf(otherIndex)) {
return true;
}
return false;
}
/*
* Adds an entity to the rejection list.
* In the algorithm, this prevents the same entity from
* retrying on an engagement with this given entity.
*/
addRejection(entity) {
entity.rejects.push(this.parent.getIndexByName(this.name));
this.rejects.push(this.parent.getIndexByName(entity.name));
}
/*
* Returns an index (relative to parent's array) of the currently highest preferred entity that has not
* rejected this entity.
*/
getNonRejectedPreferenceIndex() {
for (let index = 0; index < this.preferences.length; ++index) {
if (this.rejects.indexOf(this.preferences[index]) == -1) return this.preferences[index];
}
return -1;
}
} |
JavaScript | class StableMarriage {
constructor(configuration, nameIndexMap) {
this.log = new ProcessLogger();
this.nameIndex = nameIndexMap ? nameIndexMap : {};
this.male = [];
this.female = [];
this.single = [];
this.nosolution = [];
// This iteration prepares a dictionary for
// O(1) time complexity on later lookups.
if(Object.keys(this.nameIndex).length == 0) for (let group in configuration) {
for (let index = 0; index < configuration[group].length; ++index) {
let { name } = configuration[group][index];
this.nameIndex[name] = index;
}
}
// Instantiate all males and also put them on the single array.
for (let entity of configuration.male) {
let { name, preferences } = entity;
this.male.push(new SMEntity(this, name, preferences));
this.single.push(this.male[this.male.length-1]);
}
// Instantiate all females.
for (let entity of configuration.female) {
let { name, preferences } = entity;
this.female.push(new SMEntity(this, name, preferences));
}
}
/*
* Returns the index of any entity regardless of what group it belongs to
* in O(1) time referring to either male or female array of this object.
*/
getIndexByName(name) {
return this.nameIndex[name];
}
/*
* This sets two entities
* as the partner of one
* another.
*/
engage(male, female) {
male.partner = female;
female.partner = male;
}
/*
* Runs the algorithm by one iteration.
* Use the method isDone() to see whether the algorithm
* is finished or not.
*/
iterate() {
if ( this.isDone() ) return;
// Mark the beginning of the current log.
this.log.beginProcess();
// Get a male who still has a female to propose to.
// Get a female who is on the top of the list of the male
// and has not rejected the male as well.
let male = this.single[0];
let female = this.female[male.getNonRejectedPreferenceIndex()];
// In case a male has proposed to all possible females
// and have been rejected by all (somehow), then add him
// to the nosolution array.
if (male.rejects.length == this.female.length) {
this.nosolution.push( this.single.shift() );
return;
}
this.log.addProcess('prepare', { male, female });
// If the male and female are both free,
if (female.partner == null) {
// engage them. This will remove the male from
// the single list.
this.engage(male, female);
this.single.shift();
this.log.addProcess('engage', { male, female });
// Otherwise if the female has a partner,
} else if (female.partner) {
let currentPartner = female.partner;
// check if the female prefers the new male over her
// current partner.
if (female.changePartnerFor(male)) {
// If this male is preferred,
// then the current partner will
// be dumped
currentPartner.addRejection(currentPartner.partner);
currentPartner.partner = null;
this.single.push(this.male[this.getIndexByName(currentPartner.name)]);
// and the new male will become
// the new partner.
this.engage(male, female);
this.single.shift();
// Male in break refers to the new partner of this female.
this.log.addProcess('break', { male, female, dumped: currentPartner });
} else {
// Otherwise the new male is rejected completely by the female.
male.addRejection(female);
// male in reject refers to the rejected male of the female.
this.log.addProcess('reject', { male, female });
}
}
this.log.addProcess('done', { male, female });
// Mark the end of the log
this.log.endProcess();
}
/*
* Returns a boolean indicating
* if the stable marriage algorithm
* is finished.
*/
isDone() {
return this.single.length == 0 ? true : false
}
} |
JavaScript | class EventSystem extends EventEmitter {
constructor(self) {
super();
this.ready = false;
// for schedules that are fired before conditions are fully loaded.
this.queue = [];
process.nextTick(() => {
this.shard = self.shard;
this.particle = self.particle;
this.action = self.action;
this.domain = self.domain;
});
setImmediate(() => {
// { nodes: Array, edges: Array, createdAt: Date }
this.shape = index(sublevel(this.particle.abstract, 'event.node'), { primaryIndex: null });
this.schedule = cache(sublevel(this.particle.abstract, 'event.schedule'));
this.log = sublevel(this.particle.abstract, 'event.log');
// eval-able scripts.
this.script = sublevel(this.particle.abstract, 'event.script');
// condition: Function input: type: String, data: Buffer output: shapeId to trigger
this.condition = [];
// load all when the system starts.
(async () => {
const scripts = await concat(this.script);
scripts.forEach(s => this.condition.push(eval(s)));
this.ready = true;
this.queue.forEach(([type, ]) => {
process()
})
})();
});
}
// type: String, indicates whether it is for action or domain
// name: String, name for the condition function
// script: String, eval-able js script
async createCondition(type, name, script) {
let func;
try {
func = eval(script);
} catch (e) {
throw new Error('Invalid script was given.');
}
await this.script.put(name, script);
this.condition[name] = func;
return name;
}
async removeCondition(name) {
if (this.condition[name]) {
delete this.condition[name];
}
await this.script.del(name);
}
/**
* Creates a shape. It connects nodes (action and domain) with edges.
* @param nodes {Array< Object
* { id: Number, (starting: true), condition: { action, domain } or Function(script) }
* >}
* @param edges {Array< Object { from: nodeId, to: nodeId, required: boolean } >}
* @return shapeId {Number}
*/
async createShape(nodes, edges) {
(function validate() {
// no mulitple starting nodes
let startings = 0;
nodes.forEach(n => { if (n.starting) startings += 1; });
if (startings !== 1) throw new Error('No multiple starting nodes are allowed.');
// no multiple same nodes
nodes.forEach(n => {
let count = 0;
nodes.forEach(n2 => {
if (n2.id === n.id) count += 1;
});
if (count > 1) throw new Error('No multiple same nodes are allowed.');
});
// no wrong-pointing edges
const nodeids = [];
edges.forEach(e => {
if (!nodeids.includes(e.from)) nodeids.push(e.from);
if (!nodeids.includes(e.to)) nodeids.push(e.from);
});
nodeids.forEach(p => {
if (!nodes.find(p)) throw new Error('No node is found that edge is pointing.');
});
// no multiple same edges
edges.forEach(e => {
let found = 0;
edges.forEach(e2 => {
if (e2.from === e.from && e2.to === e.to) {
found += 1;
}
});
if (found > 1) throw new Error('No multiple same edges are allowed.');
})
})();
const shape = { nodes, edges }.toString();
return await this.shape.putIndexedObject(shape);
}
async removeShape(id) {
return await this.shape.delByPrimaryValue(id);
}
/**
* createSchedule(start, end, interval)(event)
* @param start - Date time when schedule starts
* @param end - optional, Date time when schedule forcefully stops
*/
async setScheduleAtDate(start, end) {
if (start < Date.now()) throw new Error();
await this.schedule.put({ type: 'date', start: start, end: end });
}
/**
* @param delay - milliseconds from when system started
* @return {Promise<void>}
*/
async setScheduleWithDelay(delay, condition) {
return await this.schedule.put({ type: 'delay', delay: delay });
}
// trigger new schedule by conditioning data that is passed to process
async setScheduleByProcess(scriptName) {
return await this.schedule.put();
}
async removeScheduleByProcess(scriptName){
await this.schedule.del(scriptName);
}
async removeSchedule(id) {
await this.schedule.del(id);
}
emit(eventName, ...args) {
if (!this.ready) {
this.queue.push([eventName, ...args]);
return;
}
// todo
this.shard.process();
this.particle.process();
}
// type: String 'action' or 'domain', data: function or object
process(type, data) {
// todo
this.emit('process', type, data);
}
} |
JavaScript | class Player {
constructor(name, tank) {
this.name = name;
this.tank = tank;
this.moved = false;
}
//gets replicated to client
json() {
return {
"name": this.name,
"tank": this.tank.json()
};
}
} |
JavaScript | class NativeElementInjectorDirective {
constructor(controlDir, host) {
this.controlDir = controlDir;
this.host = host;
}
ngOnInit() {
if (this.controlDir.control) {
this.controlDir.control['nativeElement'] = this.host.nativeElement;
}
}
} |
JavaScript | class ContractService extends BaseService {
constructor() {
super();
}
static detailedContractResultsQuery = `select *
from ${ContractResult.tableName} ${ContractResult.tableAlias}`;
static contractResultsQuery = `select
${ContractResult.AMOUNT},
${ContractResult.BLOOM},
${ContractResult.CALL_RESULT},
${ContractResult.CONSENSUS_TIMESTAMP},
${ContractResult.CONTRACT_ID},
${ContractResult.CREATED_CONTRACT_IDS},
${ContractResult.ERROR_MESSAGE},
${ContractResult.FUNCTION_PARAMETERS},
${ContractResult.GAS_LIMIT},
${ContractResult.GAS_USED},
${ContractResult.PAYER_ACCOUNT_ID}
from ${ContractResult.tableName}`;
static contractStateChangesQuery = `select
${ContractStateChange.CONSENSUS_TIMESTAMP},
${ContractStateChange.CONTRACT_ID},
${ContractStateChange.PAYER_ACCOUNT_ID},
${ContractStateChange.SLOT},
${ContractStateChange.VALUE_READ},
${ContractStateChange.VALUE_WRITTEN}
from ${ContractStateChange.tableName}`;
static contractLogsQuery = `select
${ContractLog.BLOOM},
${ContractLog.CONTRACT_ID},
${ContractLog.CONSENSUS_TIMESTAMP},
${ContractLog.DATA},
${ContractLog.INDEX},
${ContractLog.ROOT_CONTRACT_ID},
${ContractLog.TOPIC0},
${ContractLog.TOPIC1},
${ContractLog.TOPIC2},
${ContractLog.TOPIC3}
from ${ContractLog.tableName} ${ContractLog.tableAlias}`;
getContractResultsByIdAndFiltersQuery(whereConditions, whereParams, order, limit) {
const params = whereParams;
const query = [
ContractService.detailedContractResultsQuery,
whereConditions.length > 0 ? `where ${whereConditions.join(' and ')}` : '',
super.getOrderByQuery(ContractResult.getFullName(ContractResult.CONSENSUS_TIMESTAMP), order),
super.getLimitQuery(whereParams.length + 1), // get limit param located at end of array
].join('\n');
params.push(limit);
return [query, params];
}
async getContractResultsByIdAndFilters(
whereConditions = [],
whereParams = [],
order = orderFilterValues.DESC,
limit = defaultLimit
) {
const [query, params] = this.getContractResultsByIdAndFiltersQuery(whereConditions, whereParams, order, limit);
const rows = await super.getRows(query, params, 'getContractResultsByIdAndFilters');
return rows.map((cr) => new ContractResult(cr));
}
/**
* Retrieves contract results based on the timestamps
*
* @param {string|string[]} timestamps consensus timestamps
* @return {Promise<{ContractResult}[]>}
*/
async getContractResultsByTimestamps(timestamps) {
let params = [timestamps];
let timestampsOpAndValue = '= $1';
if (Array.isArray(timestamps)) {
params = timestamps;
const positions = _.range(1, timestamps.length + 1).map((i) => `$${i}`);
timestampsOpAndValue = `in (${positions})`;
}
const whereClause = `where ${ContractResult.CONSENSUS_TIMESTAMP} ${timestampsOpAndValue}`;
const query = [ContractService.contractResultsQuery, whereClause].join('\n');
const rows = await super.getRows(query, params, 'getContractResultsByTimestamps');
return rows.map((row) => new ContractResult(row));
}
/**
* Builds a query for retrieving contract logs based on contract id and various filters
*
* @param whereConditions the conditions to build a where clause out of
* @param whereParams the parameters for the where clause
* @param timestampOrder the sorting order for field consensus_timestamp
* @param indexOrder the sorting order for field index
* @param limit the limit parameter for the query
* @returns {(string|*)[]} the build query and the parameters for the query
*/
getContractLogsByIdAndFiltersQuery(whereConditions, whereParams, timestampOrder, indexOrder, limit) {
const params = whereParams;
const orderClause = [
super.getOrderByQuery(ContractLog.getFullName(ContractLog.CONSENSUS_TIMESTAMP), timestampOrder),
`${ContractLog.getFullName(ContractLog.INDEX)} ${indexOrder}`,
].join(', ');
const query = [
ContractService.contractLogsQuery,
whereConditions.length > 0 ? `where ${whereConditions.join(' and ')}` : '',
orderClause,
super.getLimitQuery(params.length + 1),
].join('\n');
params.push(limit);
return [query, params];
}
/**
* Retrieves contract logs based on contract id and various filters
*
* @param whereConditions the conditions to build a where clause out of
* @param whereParams the parameters for the where clause
* @param timestampOrder the sorting order for field consensus_timestamp
* @param indexOrder the sorting order for field index
* @param limit the limit parameter for the query
* @returns {Promise<*[]|*>} the result of the getContractLogsByIdAndFilters query
*/
async getContractLogsByIdAndFilters(
whereConditions = [],
whereParams = [],
timestampOrder = orderFilterValues.DESC,
indexOrder = orderFilterValues.DESC,
limit = defaultLimit
) {
const [query, params] = this.getContractLogsByIdAndFiltersQuery(
whereConditions,
whereParams,
timestampOrder,
indexOrder,
limit
);
const rows = await super.getRows(query, params, 'getContractLogsByIdAndFilters');
return rows.map((cr) => new ContractLog(cr));
}
async getContractLogsByTimestamps(timestamps) {
let params = [timestamps];
let timestampsOpAndValue = '= $1';
if (Array.isArray(timestamps)) {
params = timestamps;
const positions = _.range(1, timestamps.length + 1).map((i) => `$${i}`);
timestampsOpAndValue = `in (${positions})`;
}
const whereClause = `where ${ContractLog.CONSENSUS_TIMESTAMP} ${timestampsOpAndValue}`;
const orderClause = `order by ${ContractLog.CONSENSUS_TIMESTAMP}, ${ContractLog.INDEX}`;
const query = [ContractService.contractLogsQuery, whereClause, orderClause].join('\n');
const rows = await super.getRows(query, params, 'getContractLogsByTimestamps');
return rows.map((row) => new ContractLog(row));
}
async getContractStateChangesByTimestamps(timestamps) {
let params = [timestamps];
let timestampsOpAndValue = '= $1';
if (Array.isArray(timestamps)) {
params = timestamps;
const positions = _.range(1, timestamps.length + 1).map((i) => `$${i}`);
timestampsOpAndValue = `in (${positions})`;
}
const whereClause = `where ${ContractStateChange.CONSENSUS_TIMESTAMP} ${timestampsOpAndValue}`;
const orderClause = `order by ${ContractStateChange.CONSENSUS_TIMESTAMP}, ${ContractStateChange.CONTRACT_ID}, ${ContractStateChange.SLOT}`;
const query = [ContractService.contractStateChangesQuery, whereClause, orderClause].join('\n');
const rows = await super.getRows(query, params, 'getContractStateChangesByTimestamps');
return rows.map((row) => new ContractStateChange(row));
}
} |
JavaScript | class SolidityError extends Error {
constructor(message, stackTrace) {
super(message);
this.stackTrace = stackTrace;
}
[inspect]() {
return this.inspect();
}
inspect() {
return this.stack !== undefined
? this.stack
: "Internal error when encoding SolidityError";
}
} |
JavaScript | class Database {
/**
* Database constructor
* @param {object} options {config, logging}
*/
constructor({config, logger}) {
this.config=config;
this.logger=logger('DB');
this.logger.trace('constructor');
}
/**
* returns the status of the db connection
*/
get status() {
return {
status: this._status,
readyState: this.db.readyState,
lastError: this.lastError,
};
}
/**
* connect the model to the db connection
*/
createModels() {
this.Question = this.db.model('Question', require('../../schemas/question').default);
this.QuestionSet = this.db.model('QuestionSet', require('../../schemas/questionset').default);
this.Response = this.db.model('Response', require('../../schemas/response').default);
this.User = this.db.model('User', require('../../schemas/user').default);
this.Company = this.db.model('Company', require('../../schemas/company').default);
this.Node = this.db.model('Node', require('../../schemas/node').default);
this.Token = this.db.model('Token', require('../../schemas/token').default);
this.Options = this.db.model('Options', require('../../schemas/options').default);
}
/**
* listen to mongo db events
*/
_setupDBEvents() {
this.db.on('connected', ()=>{
this._status='connected';
this.logger.info(`DB connected.`);
});
this.db.on('error', (err)=>{
this.lastError=err;
this.logger.error('DB error', err);
});
this.db.on('reconnected', ()=>{
this._status='connected';
this.logger.warn('DB reconnected');
});
this.db.on('disconnected', ()=>{
this._status='disconnected';
this.logger.error('DB disconnected');
});
}
/**
* Connect to the mongo db
* @return {Promise} that gets resolved when the db is connected.
*/
async connect() {
this.logger.trace('connect');
const uri = `mongodb://${process.env['DB_SERVER']}:${process.env['DB_PORT']}/pulsedb`;
this.db = mongoose.createConnection();
this._setupDBEvents();
try {
this.logger.debug('MONGODB connecting to ' + uri);
await this.db.openUri(uri, {
user: process.env['DB_USERNAME'],
pass: process.env['DB_PASSWORD'],
useNewUrlParser: true,
useMongoClient: true,
autoIndex: false, // Don't build indexes
});
this.createModels();
} catch (err) {
this.logger.error(`DB unable to connect to ${uri}`, err);
throw err;
}
}
} |
JavaScript | class AssemblerDriver {
/**
* @constructor
* @param {string} text - The code written by the user
*/
constructor(text) {
this._text = text;
this._lexer = new Lexer();
this._parser = new Parser({});
}
} |
JavaScript | class LineEvent {
constructor(repo, line, parts) {
this.offset = 0; // To be calculated later
this.parts = parts;
this.decEvent = parseInt(this.parts[0]);
this.hexEvent = EmulatorCommon.zeroPad(this.decEvent.toString(16).toUpperCase());
this.timestamp = +new Date(this.parts[1]);
this.networkLine = line;
repo.updateTimestamp(this.timestamp);
}
convert() {
this.convertedLine = this.prefix() + (this.parts.join(':')).replace('|', ':');
}
prefix() {
return '[' + EmulatorCommon.timeToTimeString(this.timestamp, true) + '] ' + this.hexEvent + ':';
}
static isDamageHallowed(damage) {
return parseInt(damage, 16) & parseInt('1000', 16);
}
static isDamageBig(damage) {
return parseInt(damage, 16) & parseInt('4000', 16);
}
static calculateDamage(damage) {
if (LineEvent.isDamageHallowed(damage))
return 0;
damage = EmulatorCommon.zeroPad(damage, 8);
let parts = [
damage.substr(0, 2),
damage.substr(2, 2),
damage.substr(4, 2),
damage.substr(6, 2),
];
if (!LineEvent.isDamageBig(damage))
return parseInt(parts.slice(0, 2).reverse().join(''), 16);
return parseInt(
parts[3] +
parts[0] +
(parseInt(parts[1], 16) - parseInt(parts[3], 16)
).toString(16), 16);
}
} |
JavaScript | class VigenereCipheringMachine {
constructor(type = true) {
this.type = type ? 'direct' : 'reverse';
}
encrypt(message, key) {
if (message === undefined || key === undefined) {
throw new Error('Incorrect arguments!');
}
// a 97 in UNICODE
// z 122 in UNICODE
// 25 symbols in alphabet
const lowerMessage = message.toLowerCase();
let encryptedStr = '';
let countSpace = 0;
const lowerKey = key.toLowerCase();
const filledKey = this.fillKey(lowerMessage.length, lowerKey);
for (let i = 0; i < lowerMessage.length; i++) {
if (/[a-z]/.test(lowerMessage[i])) {
let diff = lowerMessage.charCodeAt(i) - 97 // 97 - 'a' in unicode
const charCodeWidthDiff = filledKey.charCodeAt(i - countSpace) + diff;
let currentCode = charCodeWidthDiff > 122 ? charCodeWidthDiff - 26: charCodeWidthDiff;
encryptedStr += String.fromCharCode(currentCode)
} else {
countSpace += 1;
encryptedStr += lowerMessage[i];
}
}
if (this.type === 'direct') {
return encryptedStr.toUpperCase();
} else {
return encryptedStr.toUpperCase().split('').reverse().join('');
}
}
decrypt(message, key) {
if (message === undefined || key === undefined) {
throw new Error('Incorrect arguments!');
}
let decriptedStr = '';
let countSpace = 0;
const lowerMessage = message.toLowerCase();
const lowerKey = key.toLowerCase();
const filledKey = this.fillKey(lowerMessage.length, lowerKey);
for (let i = 0; i < lowerMessage.length; i++) {
if (/[a-z]/.test(lowerMessage[i])) {
let diff = filledKey.charCodeAt(i - countSpace) - 97 // 97 - 'a' in unicode
const charCodeWidthDiff = lowerMessage.charCodeAt(i) - diff;
let currentCode = charCodeWidthDiff < 97 ? 122 - (96 - charCodeWidthDiff) : charCodeWidthDiff;
decriptedStr += String.fromCharCode(currentCode)
} else {
countSpace += 1;
decriptedStr += lowerMessage[i];
}
}
if (this.type === 'direct') {
return decriptedStr.toUpperCase();
} else {
return decriptedStr.toUpperCase().split('').reverse().join('');
}
}
fillKey(length, key) {
let filledKey = key;
while (length > filledKey.length) {
filledKey += key;
}
return filledKey;
}
} |
JavaScript | class EzsigndocumentCreateObjectV1Request {
/**
* Constructs a new <code>EzsigndocumentCreateObjectV1Request</code>.
* Request for POST /1/object/ezsigndocument
* @alias module:eZmaxAPI/model/EzsigndocumentCreateObjectV1Request
*/
constructor() {
EzsigndocumentCreateObjectV1Request.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>EzsigndocumentCreateObjectV1Request</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:eZmaxAPI/model/EzsigndocumentCreateObjectV1Request} obj Optional instance to populate.
* @return {module:eZmaxAPI/model/EzsigndocumentCreateObjectV1Request} The populated <code>EzsigndocumentCreateObjectV1Request</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EzsigndocumentCreateObjectV1Request();
if (data.hasOwnProperty('objEzsigndocument')) {
obj['objEzsigndocument'] = EzsigndocumentRequest.constructFromObject(data['objEzsigndocument']);
}
if (data.hasOwnProperty('objEzsigndocumentCompound')) {
obj['objEzsigndocumentCompound'] = EzsigndocumentRequestCompound.constructFromObject(data['objEzsigndocumentCompound']);
}
}
return obj;
}
/**
* @return {module:eZmaxAPI/model/EzsigndocumentRequest}
*/
getObjEzsigndocument() {
return this.objEzsigndocument;
}
/**
* @param {module:eZmaxAPI/model/EzsigndocumentRequest} objEzsigndocument
*/
setObjEzsigndocument(objEzsigndocument) {
this['objEzsigndocument'] = objEzsigndocument;
}
/**
* @return {module:eZmaxAPI/model/EzsigndocumentRequestCompound}
*/
getObjEzsigndocumentCompound() {
return this.objEzsigndocumentCompound;
}
/**
* @param {module:eZmaxAPI/model/EzsigndocumentRequestCompound} objEzsigndocumentCompound
*/
setObjEzsigndocumentCompound(objEzsigndocumentCompound) {
this['objEzsigndocumentCompound'] = objEzsigndocumentCompound;
}
} |
JavaScript | class InputChoose extends _react.default.Component {
constructor(props) {
super(props);
_defineProperty(this, "labelGenerate", option => {
let label = [];
if ((0, _lodash.isArray)(this.props.optionLabel)) {
let separator = this.props.separator ? this.props.separator : ' | ';
for (let i = 0; i <= this.props.optionLabel.length - 1; i++) {
let isi = option[this.props.optionLabel[i]];
label.push(isi);
}
} else {
label.push(option[this.props.optionLabel]);
}
return label;
});
_defineProperty(this, "onChange", selectedOption => {
if (!this.props.isReadonly && this.props.name) {
try {
if (this.props.isMultiple) {
let current_val = this.state.defaultValue || [];
let removed = false;
let new_val = [];
for (let i = 0; i < current_val.length; i++) {
let isi = current_val[i];
if (isi == selectedOption[this.props.optionValue]) {
removed = true;
} else {
new_val.push(isi);
}
}
if (!removed) {
new_val.push(selectedOption[this.props.optionValue]);
}
this.props.setInput(this.props.name, new_val);
} else {
if (this.props.value) {
val = this.props.value;
} else {
val = (0, _tcomponent.findArrayName)(this.props.name, this.props.input) || null;
}
if (val == selectedOption[this.props.optionValue]) {
this.props.setInput(this.props.name, null);
} else {
this.props.setInput(this.props.name, selectedOption[this.props.optionValue]);
}
}
} catch (e) {
this.props.setInput(this.props.name, null);
}
}
this.onRefresh();
});
this.state = {
defaultValue: null
}; // this.onRefresh = debounce(this.onRefresh.bind(this), 200);
}
onRefresh() {
let val = null;
let defaultValue = null;
if (this.props.value) {
val = this.props.value;
} else {
val = (0, _tcomponent.findArrayName)(this.props.name, this.props.input) || null;
}
if (val) {
if (this.props.isMultiple) {
defaultValue = [];
for (let i = 0; i < this.props.options.length; i++) {
for (let y = 0; y < val.length; y++) {
let opt = this.props.options[i];
let cur = val[y];
if (String(opt[this.props.optionValue]) == String(cur)) {
defaultValue.push(opt[this.props.optionValue]);
}
}
}
} else {
defaultValue = (0, _lodash.find)(this.props.options, function (o) {
return String(o[this.props.optionValue]) == String(val);
}.bind(this));
}
}
defaultValue = !(0, _lodash.isUndefined)(defaultValue) && !(0, _lodash.isNull)(defaultValue) ? defaultValue : null;
this.setState({
defaultValue
});
}
componentDidUpdate(prevProps, prevState) {
if (!(0, _lodash.isEqual)((0, _tcomponent.findArrayName)(this.props.name, prevProps.input), (0, _tcomponent.findArrayName)(this.props.name, this.props.input)) && !(0, _lodash.isEqual)(this.state.defaultValue, (0, _tcomponent.findArrayName)(this.props.name, this.props.input))) {
this.onRefresh();
}
}
componentDidMount() {
this.onRefresh();
}
render() {
let options = [];
try {
options = this.props.options.length > 0 ? this.props.options : [];
} catch (e) {}
const isReadonly = this.props.disabled || this.props.isReadonly;
return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
style: {
justifyContent: 'space-between',
flexDirection: 'row',
padding: 10
}
}, options.map(value => {
let isChecked = false;
try {
if (this.props.isMultiple) {
isChecked = (0, _lodash.includes)(this.state.defaultValue, value[this.props.optionValue]);
} else {
isChecked = (0, _lodash.isEqual)(value[this.props.optionValue], this.state.defaultValue[this.props.optionValue]);
}
} catch (e) {}
return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
style: {
paddingLeft: 8,
paddingRight: 8
},
key: value[this.props.optionValue]
}, /*#__PURE__*/_react.default.createElement(_reactNative.Switch, {
disabled: isReadonly,
trackColor: {
false: '#767577',
true: '#81b0ff'
},
thumbColor: isReadonly ? '#767577' : '#f4f3f4',
ios_backgroundColor: "#3e3e3e",
onValueChange: this.onChange.bind(this, value),
value: isChecked
}), /*#__PURE__*/_react.default.createElement(_reactNative.View, null, this.labelGenerate(value).map((val, i) => {
if ((0, _lodash.isEqual)(String(val).substring(0, 3), 'AT-')) {
return /*#__PURE__*/_react.default.createElement(_InputFile.default, {
value: val,
isReadonly: true,
preview: true
});
} else {
return /*#__PURE__*/_react.default.createElement(_reactNative.Text, null, val);
}
})));
}));
}
} |
JavaScript | class Auth {
/**
* @description - Verify JWT token
*
* @param {object} req - HTTP Request
*
* @param {object} res - HTTP Response
*
* @param {function} next - HTTP Next() function
*
* @returns {object} this - Class instance
*
* @memberof Auth
*/
static verify(req, res, next) {
const token = req.body.token
|| req.query.token
|| req.headers.authorization;
if (token) {
const jwtSecret = process.env.JWT_SECRET;
jasonwebtoken.verify(token, jwtSecret, (err, decoded) => {
if (err) {
return res.status(401).json({
success: false,
message: 'Invalid token, please sign in again.'
});
}
if (decoded.exp < new Date().getTime() / 1000) {
return res.status(401).json({
success: false,
message: 'Your session has expired, please sign in again'
});
}
req.user = decoded;
next();
});
} else {
return res.status(403).json({
success: false,
message: 'No token provided.'
});
}
}
} |
JavaScript | class MixinBuilder {
/**
* @constructor
* @param {Class} Superclass the parent class to have the mixins applied too
* @private
*/
constructor(Superclass) {
this.superclass = Superclass;
}
/**
* @method MixinBuilder~with
* @description specifies whch mixins to apply to the super class
* @param {...Function} mixins
* @returns {Class} returns the superclass with the mixins applied
* @private
*/
with(...mixins) {
return mixins.reduce((c, mixin) => { return mixin(c); }, this.superclass);
}
} |
JavaScript | class Row extends Component {
render() {
return <div className="row">{this.props.children}</div>;
}
} |
JavaScript | class ImmersHUD extends window.HTMLElement {
#queryCache = {}
#container
/**
* @prop {FriendStatus[]} - Live-updated friends list with current status
*/
friends = []
/**
* @prop {ImmersClient} - Immers client instance
*/
immersClient
constructor () {
super()
this.attachShadow({ mode: 'open' })
const styleTag = document.createElement('style')
styleTag.innerHTML = styles
const template = document.createElement('template')
template.innerHTML = htmlTemplate.trim()
this.shadowRoot.append(styleTag, template.content.cloneNode(true))
this.#container = this.shadowRoot.lastElementChild
}
connectedCallback () {
if (this.immersClient) {
// already initialized
return
}
// Immers client setup
if (this.getAttribute('local-immer')) {
/* todo: fetch local place object and initialize client in full immer mode */
} else {
this.immersClient = new ImmersClient({
id: window.location.href,
name: this.getAttribute('destination-name'),
url: this.getAttribute('destination-url')
}, {
allowStorage: this.hasAttribute('allow-storage')
})
this.immersClient.addEventListener(
'immers-client-friends-update',
({ detail: { friends } }) => this.onFriendsUpdate(friends)
)
this.immersClient.addEventListener(
'immers-client-connected',
({ detail: { profile } }) => this.onClientConnected(profile)
)
this.immersClient.addEventListener(
'immers-client-disconnected',
() => this.onClientDisconnected()
)
}
this.#container.addEventListener('click', evt => {
switch (evt.target.id) {
case 'login':
evt.preventDefault()
this.login()
break
case 'logo':
this.setAttribute('open', this.getAttribute('open') !== 'true')
break
case 'exit-button':
// TODO: add confirmation modal
this.remove()
break
case 'logout':
this.immersClient.logout()
break
}
})
if (this.immersClient.handle) {
this.#el('handle-input').value = this.immersClient.handle
this.immersClient.reconnect().then(connected => {
if (!connected) {
// user has logged in before, but action required to reconnect
// prompt with open, pre-filled login
this.setAttribute('open', true)
}
})
}
}
attributeChangedCallback (name, oldValue, newValue) {
switch (name) {
case 'position':
if (newValue && !ImmersHUD.POSITION_OPTIONS.includes(newValue)) {
console.warn(`immers-hud: unknown position ${newValue}. Valid options are ${ImmersHUD.POSITION_OPTIONS.join(', ')}`)
}
break
case 'open':
this.#el('notification').classList.add('hidden')
break
}
}
login () {
return this.immersClient.connect(
this.getAttribute('token-catcher'),
this.getAttribute('access-role'),
this.#el('handle-input').value
)
}
onClientConnected (profile) {
this.#el('login-container').classList.add('removed')
this.#el('status-container').classList.remove('removed')
// show profile info
if (profile.avatarImage) {
this.#el('logo').style.backgroundImage = `url(${profile.avatarImage})`
}
this.#el('username').textContent = profile.displayName
this.#el('profile-link').setAttribute('href', profile.url)
this.#emit('immers-hud-connected', { profile })
}
onClientDisconnected () {
this.#el('login-container').classList.remove('removed')
this.#el('status-container').classList.add('removed')
this.#el('handle-input').value = ''
this.#el('logo').style.backgroundImage = ''
this.#el('username').textContent = ''
this.#el('profile-link').setAttribute('href', '#')
}
onFriendsUpdate (friends) {
this.friends = friends
if (this.getAttribute('open') !== 'true') {
this.#el('notification').classList.remove('hidden')
}
this.#el('status-message').textContent = `${friends.filter(f => f.isOnline).length}/${friends.length} friends online`
}
#el (id) {
return this.#queryCache[id] ?? (this.#queryCache[id] = this.#container.querySelector(`#${id}`))
}
#emit (type, data) {
this.dispatchEvent(new window.CustomEvent(type, {
detail: data
}))
}
static get observedAttributes () {
return ['position', 'open']
}
static get POSITION_OPTIONS () {
return ['top-left', 'bottom-left', 'top-right', 'bottom-right']
}
static Register () {
window.customElements.define('immers-hud', ImmersHUD)
}
} |
JavaScript | class InlineResponse2001Trigger {
/**
* Constructs a new <code>InlineResponse2001Trigger</code>.
* Trigger data at the time of alert creation.
* @alias module:model/InlineResponse2001Trigger
*/
constructor() {
InlineResponse2001Trigger.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>InlineResponse2001Trigger</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/InlineResponse2001Trigger} obj Optional instance to populate.
* @return {module:model/InlineResponse2001Trigger} The populated <code>InlineResponse2001Trigger</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse2001Trigger();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('creation')) {
obj['creation'] = ApiClient.convertToType(data['creation'], 'String');
}
if (data.hasOwnProperty('notation')) {
obj['notation'] = InlineResponse200DataTriggerNotation.constructFromObject(data['notation']);
}
if (data.hasOwnProperty('price')) {
obj['price'] = InlineResponse2001TriggerPrice.constructFromObject(data['price']);
}
if (data.hasOwnProperty('range')) {
obj['range'] = InlineResponse200DataTriggerRange.constructFromObject(data['range']);
}
if (data.hasOwnProperty('comment')) {
obj['comment'] = ApiClient.convertToType(data['comment'], 'String');
}
if (data.hasOwnProperty('status')) {
obj['status'] = InlineResponse2001TriggerStatus.constructFromObject(data['status']);
}
}
return obj;
}
} |
JavaScript | class TSQLServerController extends TAbstractDataController {
constructor ( parameters = {} ) {
const _parameters = {
...{
driver: null,
tableName: '',
columns: []
}, ...parameters
};
super( _parameters );
this.tableName = _parameters.tableName;
this.columns = _parameters.columns;
}
get tableName () {
return this._tableName
}
set tableName ( value ) {
const valueName = 'Table name';
const expect = 'Expect an instance of String.';
if ( isNull( value ) ) { throw new TypeError( `${valueName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${valueName} cannot be undefined ! ${expect}` ) }
if ( isNotString( value ) ) { throw new TypeError( `${valueName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._tableName = value;
}
get columns () {
return this._columns
}
set columns ( value ) {
const valueName = 'Columns';
const expect = 'Expect an array of strings.';
if ( isNull( value ) ) { throw new TypeError( `${valueName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${valueName} cannot be undefined ! ${expect}` ) }
if ( isNotArrayOfString( value ) ) { throw new TypeError( `${valueName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._columns = value;
}
setTableName ( value ) {
this.tableName = value;
return this
}
setColumns ( value ) {
this.columns = value;
return this
}
_createMany ( datas, response ) {
super._createMany( datas, response );
const columns = this.columns;
const formatedColumns = columns.toString();
let data = null;
let formatedValues = '';
let value = null;
for ( let index = 0, numberOfDatas = datas.length ; index < numberOfDatas ; index++ ) {
data = datas[ index ];
formatedValues += `(`;
for ( let key in data ) {
if ( !columns.includes( key ) ) { continue }
value = data[ key ];
if ( isString( value ) ) {
formatedValues += `'${value}', `;
} else {
formatedValues += `${value}, `;
}
}
formatedValues = formatedValues.slice( 0, -2 );
formatedValues += `), `;
}
formatedValues = formatedValues.slice( 0, -2 );
const query = `INSERT INTO ${this._tableName} (${formatedColumns}) VALUES ${formatedValues}`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_createOne ( data, response ) {
super._createOne( data, response );
const columns = this.columns;
let formatedColumns = '';
let column = null;
let formatedValues = '';
let value = null;
for ( let index = 0, numberOfColumns = columns.length ; index < numberOfColumns ; index++ ) {
column = columns[ index ];
value = data[ column ];
if ( value ) {
formatedColumns += `${column}, `;
if ( isString( value ) ) {
formatedValues += `'${value}', `;
} else {
formatedValues += `${value}, `;
}
}
}
formatedColumns = formatedColumns.slice( 0, -2 );
formatedValues = formatedValues.slice( 0, -2 );
const query = `INSERT INTO ${this._tableName} (${formatedColumns}) VALUES (${formatedValues})`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_deleteAll ( response ) {
super._deleteAll( response );
const query = `TRUNCATE TABLE ${this._tableName}`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_deleteMany ( ids, response ) {
super._deleteMany( ids, response );
const query = `DELETE FROM ${this._tableName} WHERE id IN (${ids})`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_deleteOne ( id, response ) {
super._deleteOne( id, response );
const query = `DELETE FROM ${this._tableName} WHERE id=${id}`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_deleteWhere ( query, response ) {
super._deleteWhere( query, response );
TAbstractDataController.returnError( 'Unimplemented methods (DELETE WHERE)', response );
}
_readAll ( projection, response ) {
super._readAll( projection, response );
const query = `SELECT * FROM ${this.tableName}`;
const request = new this._driver.Request( query, ( requestError, rowCount, results ) => {
if ( requestError ) {
TAbstractDataController.returnError( requestError, response );
} else if ( results.length === 0 ) {
TAbstractDataController.returnNotFound( response );
} else {
TAbstractDataController.returnData( results, response );
}
} );
request.on( 'row', columns => {
let result = {};
columns.forEach( column => {
result[ column.metadata.colName ] = column.value;
} );
} );
this._driver.Connection.execSql( request );
}
_readMany ( ids, projection, response ) {
super._readMany( ids, projection, response );
const idsFormated = ids.toString();
const query = `SELECT * FROM ${this.tableName} WHERE id IN (${idsFormated})`;
const request = new this._driver.Request( query, ( requestError, rowCount, results ) => {
if ( requestError ) {
TAbstractDataController.returnError( requestError, response );
} else if ( results.length === 0 ) {
TAbstractDataController.returnNotFound( response );
} else {
TAbstractDataController.returnData( results, response );
}
} );
request.on( 'row', columns => {
let result = {};
columns.forEach( column => {
result[ column.metadata.colName ] = column.value;
} );
} );
this._driver.Connection.execSql( request );
}
_readOne ( id, projection, response ) {
super._readOne( id, projection, response );
const query = `SELECT * FROM ${this.tableName} WHERE id=${id}`;
const request = new this._driver.Request( query, ( requestError, rowCount, results ) => {
if ( requestError ) {
TAbstractDataController.returnError( requestError, response );
} else if ( results.length === 0 ) {
TAbstractDataController.returnNotFound( response );
} else {
TAbstractDataController.returnData( results, response );
}
} );
request.on( 'row', columns => {
let result = {};
columns.forEach( column => {
result[ column.metadata.colName ] = column.value;
} );
} );
this._driver.Connection.execSql( request );
}
_readWhere ( query, projection, response ) {
super._readWhere( query, projection, response );
TAbstractDataController.returnError( 'Unimplemented methods (READ WHERE)', response );
}
_updateAll ( update, response ) {
super._updateAll( update, response );
let formatedUpdates = '';
for ( let key in update ) {
const formatedUpdate = update[ key ];
if ( isString( formatedUpdate ) ) {
formatedUpdates += `${key} = '${formatedUpdate}', `;
} else {
formatedUpdates += `${key} = ${formatedUpdate}, `;
}
}
formatedUpdates = formatedUpdates.slice( 0, -2 );
const query = `UPDATE ${this._tableName} SET ${formatedUpdates}`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_updateMany ( ids, updates, response ) {
super._updateMany( ids, updates, response );
let formatedUpdates = '';
let formatedUpdate = null;
for ( let key in updates ) {
formatedUpdate = updates[ key ];
if ( isString( formatedUpdate ) ) {
formatedUpdates += `${key} = '${formatedUpdate}', `;
} else {
formatedUpdates += `${key} = ${formatedUpdate}, `;
}
}
formatedUpdates = formatedUpdates.slice( 0, -2 );
const query = `UPDATE ${this._tableName} SET ${formatedUpdates} WHERE id IN (${ids})`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_updateOne ( id, update, response ) {
super._updateOne( id, update, response );
let formatedUpdates = '';
let formatedUpdate = null;
for ( let key in update ) {
formatedUpdate = update[ key ];
if ( isString( formatedUpdate ) ) {
formatedUpdates += `${key} = '${formatedUpdate}', `;
} else {
formatedUpdates += `${key} = ${formatedUpdate}, `;
}
}
formatedUpdates = formatedUpdates.slice( 0, -2 );
const query = `UPDATE ${this._tableName} SET ${formatedUpdates} WHERE id=${id}`;
const request = new this._driver.Request( query, this.return( response ) );
this._driver.Connection.execSql( request );
}
_updateWhere ( query, update, response ) {
super._updateWhere( query, update, response );
TAbstractDataController.returnError( 'Unimplemented methods (UPDATE WHERE)', response );
}
} |
JavaScript | class MainScene extends Phaser.Scene{
constructor() {
super('MainScene');
var sidebar;
var rgb;
var username;
var volume_text;
}
init(data){
this.userID = data.name;
}
// Cargar assets y otros elementos para usarlos más adelante
preload() {
this.load.image('tint', '../../assets/images/tintable.png');
this.load.image('GH', '../../assets/images/GitHubLogo.png');
this.load.image('UFV', '../../assets/images/LogoUFV.jpg');
this.load.image('Pf', '../../assets/images/Pfp.png');
this.load.html('RGB', '../../assets/html/RGB.html');
this.load.html('Vol', '../../assets/html/Volumen.html');
this.load.html('Join', '../../assets/html/CodigoPartida.html');
this.load.html('Create', '../../assets/html/NumeroRounds.html');
this.load.html('Error', '../../assets/html/ErrorCode.html');
this.load.html('Full', '../../assets/html/FullRoom.html');
}
// Código que se ejecuta al iniciar el juego por primera vez
create(){
const gamescene = this;
var name = this.userID.value;
var socket = io();
socket.on("connect", () => {
console.log(`A socket connection has been made: ${socket.id}`);
});
var bg = gamescene.add.image(this.game.canvas.width*0, this.game.canvas.height*0, 'tint').setScale(20,20).setTint('0xD7FAFE');
// ----------------------- Color ---------------------------
this.sidebar = this.add.image(this.game.canvas.width*0.35, this.game.canvas.height*0, 'tint').setOrigin(1,0).setScale(10,10).setTint(rgb2Hex(255, 255, 255));
this.rgb = this.add.dom(this.game.canvas.width*0.18, this.game.canvas.height*0.4).createFromCache('RGB').setScale(1.25,1.25);
this.username = this.add.text(this.game.canvas.width*0.18, this.game.canvas.height*0.23, name, { color: 'black', align: 'center', fontFamily: 'Arial', fontSize: '32px'}).setOrigin(0.5,0);
var profile = this.add.image(this.game.canvas.width*0.18, this.game.canvas.height*0.15, 'Pf').setScale(0.1,0.1);
// --------------------- Fin de Color -------------------------
// ----------------------- Volumen ---------------------------
this.volume_text = this.add.text(this.game.canvas.width*0.18, this.game.canvas.height*0.63, 'Volumen', { color: 'black', align: 'center', fontFamily: 'Arial', fontSize: '32px'}).setOrigin(0.5,0);
var volume = this.add.dom(this.game.canvas.width*0.18, this.game.canvas.height*0.7).createFromCache('Vol').setScale(1.5,1.5);
// --------------------- Fin de Volumen -------------------------
// -------------------------- Unirse a Partida -----------------------------
var error_cod = this.add.dom(this.game.canvas.width*0.5, this.game.canvas.height*0.5).createFromCache('Error').setOrigin(0.5,0.5).setScale(1,1).setActive(false).setVisible(false);
error_cod.addListener('click');
error_cod.on('click', function(event){
if(event.target.name === 'Code_Error'){
error_cod = error_cod.setActive(false).setVisible(false);
}
});
var full_r = this.add.dom(this.game.canvas.width*0.5, this.game.canvas.height*0.5).createFromCache('Full').setOrigin(0.5,0.5).setScale(1,1).setActive(false).setVisible(false);
full_r.addListener('click');
full_r.on('click', function(event){
if(event.target.name === 'Room_Full'){
full_r = full_r.setActive(false).setVisible(false);
}
});
var join_G = this.add.dom(this.game.canvas.width*0.67, this.game.canvas.height*0.2).createFromCache('Join');
join_G.addListener('click');
join_G.on('click', function(event){
if(event.target.name === 'Unirse'){
const codigo = this.getChildByName('codigopartida');
if(codigo.value.length == 6){
socket.emit('isKeyValid', codigo.value.toUpperCase());
}
}
});
socket.on('keyNotValid', function(){
error_cod = error_cod.setActive(false).setVisible(false);
error_cod = error_cod.setActive(true).setVisible(true);
});
socket.on('keyIsValid', function(code){
gamescene.scene.start('Gameplay', {name: name, socket: socket, key: code});
});
// --------------------- Fin de Unirse a Partida -------------------------
// -------------------------- Crear Partida -----------------------------
var create_G = this.add.dom(this.game.canvas.width*0.67, this.game.canvas.height*0.6).createFromCache('Create');
create_G.addListener('click');
create_G.on('click', function(event){
if(event.target.name === 'Iniciar'){
var noRondas = this.getChildByName('rondas');
if(noRondas.value>3){
noRondas.value = 3;
}
else if (noRondas.value<1){
noRondas.value = 1;
}
socket.emit('createRoom', noRondas.value);
}
});
socket.on('roomCreated', function(gameRoomInfo){
gamescene.scene.start('Gameplay', {name: name, socket: socket, key: gameRoomInfo.roomKey});
})
// --------------------- Fin de Crear Partida -------------------------
// -------------------------- Footer -----------------------------
var footbar = this.add.image(this.game.canvas.width*0, this.game.canvas.height*0.80, 'tint').setOrigin(0,0).setScale(20,3).setTint('0x333333');
var GitHub = this.add.image(this.game.canvas.width*0.30, this.game.canvas.height*0.9, 'GH').setScale(0.05,0.05).setInteractive({cursor: 'pointer'});
var uniFV = this.add.image(this.game.canvas.width*0.70, this.game.canvas.height*0.9, 'UFV').setOrigin(0.75,0.5).setScale(0.08,0.08).setInteractive({cursor: 'pointer'});
GitHub.on('pointerup', linkGH , this);
uniFV.on('pointerup', linkUFV, this);
// ---------------------- Fin de Footer --------------------------
}
// Código que se ejecutara cada frame (gameplay loop del juego)
update(){
this.sidebar = this.sidebar.setTint(rgb2Hex(this.rgb.getChildByName('R').valueAsNumber, this.rgb.getChildByName('G').valueAsNumber, this.rgb.getChildByName('B').valueAsNumber));
if (this.rgb.getChildByName('R').value < 100 && this.rgb.getChildByName('G').value < 100 && this.rgb.getChildByName('B').value < 100){
this.username.setColor('#FFFFFF');
this.volume_text.setColor('#FFFFFF');
this.rgb.color = '#FFFFFF';
}
else {
this.username.setColor('#000000');
this.volume_text.setColor('#000000');
this.rgb.color = '#FFFFFF';
}
// actualizar valores bdd con el resultado de this.rgb.getChildByName('R').value para r g y b
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
//Update the address field:
var sqlr = "UPDATE colores SET rojo = " + this.rgb.getChildByName('R').value;
var sqlv = "UPDATE colores SET verde = " + this.rgb.getChildByName('G').value;
var sqla = "UPDATE colores SET azul = " + this.rgb.getChildByName('B').value;
con.query(sqlr, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
con.query(sqlv, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
con.query(sqla, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
} |
JavaScript | class Command {
/**
* @param {string} trigger Command trigger
* @param {SpreadsheetService} sheet Spreadsheet for this command
* @param {Object} definition A definition object containing information
* for the functionality of the command
*/
constructor(trigger, sheet, definition) {
this.triggerName = trigger;
this.sheet = sheet;
this.random = !!definition.random;
this.lookup_column = definition.lookup_column;
this.slackToken = definition.slack_token;
this.caseSensitive = definition.case_sensitive !== undefined ?
!!definition.case_sensitive : false;
}
/**
* Trigger the command with the given text parameters
*
* @param {string} [text] Parameters for the command
* @return {Array[]} An array of rows that contains arrays of columns
* represnting the results of the triggered command
*/
trigger(text) {
return this.sheet.getResultObjectByColumn(
this.lookup_column, text, this.random, this.caseSensitive
);
}
/**
* Check whether the incoming token is valid.
*
* @param {string} incomingToken Incoming token to compare
* @return {boolean} Token is valid
*/
isTokenValid(incomingToken) {
return this.slackToken === incomingToken;
}
/**
* Check whether this command is random
*
* @return {boolean} Command is random
*/
isRandom() {
return this.random;
}
/**
* Check whether this command relies on case sensitivity when requesting lookup
*
* @return {boolean} Command lookup is case sensitive
*/
isCaseSensitive() {
return this.caseSensitive;
}
/**
* Get the SpreadsheetService that is connected to this command
*
* @return {SpreadsheetService} SpreadsheetService connected to this command
*/
getSheet() {
return this.sheet;
}
} |
JavaScript | class Serializable {
/**
* Generates a JSON representation of the object.
*
* @return {object} a JSON representation of the object
*/
toObject() {
let attrs = this.attributes_();
let obj = {};
for (var name in attrs) {
if (this.hasOwnProperty(name)) {
obj[attrs[name]] = _recurse(this[name]);
}
}
return obj;
}
/**
* Generates a string representation of the Serializable object.
*
* @return {string} a string representation of the object
*/
toString() {
return JSONToStr(this.toObject());
}
/**
* Writes the object to disk in JSON format.
*
* @param {string} path - the output JSON file path. The base output
* directory is created, if necessary
*/
toJSON(path) {
writeJSON(this.toObject(), path);
}
/**
* Constructs a Serializable object from a JSON representation of it.
* Subclasses must implement this method.
*
* @abstract
* @param {object} obj - a JSON representation of a Serializable subclss
* @return {Serializable} an instance of the Serializable subclass
*/
static fromObject(obj) {
throw new NotImplementedError('subclass must implement fromObject()');
}
/**
* Constructs a Serializable object from a string representation of it.
*
* @param {string} str - a string representation of a Serializable subclass
* @return {Serializable} an instance of the Serializable subclass
*/
static fromString(str) {
return this.fromObject(JSON.parse(str));
}
/**
* Constructs a Serializable object from a JSON file.
*
* @param {string} path - the path to a JSON file
* @return {Serializable} an instance of the Serializable subclass
*/
static fromJSON(path) {
return this.fromObject(readJSON(path));
}
/**
* Returns an object describing the class attributes to be serialized.
*
* Subclasses may override this method, but, by default, all attributes in
* Object.keys(this) are returned, minus private attributes (those ending
* with '_')
*
* @private
* @method attributes_
* @return {object} an object mapping attribute names to field names (as
* they should appear in the JSON file)
*/
attributes_() {
return Object.keys(this).reduce(
function(attrs, name) {
if (!name.endsWith('_')) {
attrs[name] = name;
}
return attrs;
}, {});
}
} |
JavaScript | class ExtendableError extends Error {
/**
* Creates a new ExtendableError instance.
*
* @param {string} message - a human-readable message
* @param {*} args - additional arguments to pass to the `Error` constructor
*/
constructor(message, ...args) {
super(message, ...args);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
} |
JavaScript | class IntervalScheduler {
constructor(intervalMs) {
this.intervalMs = intervalMs;
}
start(callback) {
this.stop();
this.timer = setInterval(callback, this.intervalMs);
}
stop() {
if (this.timer === undefined) {
return;
}
clearInterval(this.timer);
this.timer = undefined;
}
running() {
return this.timer !== undefined;
}
} |
JavaScript | class Node {
constructor() {
this.previous = null;
this.next = null;
this.value = {};
}
} |
JavaScript | class RateLimitQueue extends Array {
constructor(bucket) {
super();
this.bucket = bucket;
}
/**
* Adds a new API request to the queue and waits until it executes
* @param {string} endpoint The endpoint for the added API request
* @param {Params} params The params / body for the added API request
* @param {RequestFile[]} files The files sent in the API request
* @returns {Promise<ReturnedData>}
*/
add(endpoint, params, files) {
return new Promise(resolve => {
this.push({
endpoint,
params,
files,
callback: (data) => {
resolve(data);
},
});
});
}
/**
* Frees the queue for the remaining capacity of the bucket
* @returns {Promise<void>}
*/
async free() {
// Runs until either the queue's or the bucket's capacity empties
while (this.length && this.bucket.remaining && this.bucket.remaining > 0) {
const nextRequest = this.shift();
if (!nextRequest)
break;
const { endpoint, params, files, callback } = nextRequest;
// Sends the request
const data = await this.bucket.send(endpoint, params, files);
// Executes the callback function
callback(data);
}
}
} |
JavaScript | class Coinchart extends React.Component {
componentDidMount() {
/*const chart = new CryptowatchEmbed('bittrex', 'xvgbtc', {
height: 500,
timePeriod: '4h',
});
chart.mount('#chart-container');*/
}
render() {
return (
<div id="chart-container" className="pb" />
);
}
} |
JavaScript | class Certificate extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'tbscertobj': obj, 'prvkeyobj': key})
*/
constructor(params) {
super();
/** @type {TBSCertificate | null} */ this.asn1TBSCert = null;
/** @type {AlgorithmIdentifier | null} */ this.asn1SignatureAlg = null;
/** @type {DERBitString | null} */ this.asn1Sig = null;
/** @type {string | null} */ this.hexSig = null;
/** @type {KeyObject | null} */ this.prvKey = null;
if (params !== undefined) {
if (params['tbscertobj'] instanceof TBSCertificate) {
this.asn1TBSCert = /** @type {TBSCertificate} */ ( params['tbscertobj'] );
}
let key = params['prvkeyobj'];
if ((key !== undefined) && (key instanceof RSAKeyEx || key instanceof DSA || key instanceof ECDSA)) {
this.prvKey = /** @type {KeyObject} */ ( params['prvkeyobj'] );
}
}
}
/**
* sign TBSCertificate and set signature value internally
* @description
* @example
* let cert = new Certificate({tbscertobj: tbs, prvkeyobj: prvKey});
* cert.sign();
*/
sign() {
this.asn1SignatureAlg = this.asn1TBSCert.asn1SignatureAlg;
let sig = new Signature(/** @type {Dictionary} */ ( { 'alg': this.asn1SignatureAlg.nameAlg } ));
sig.init(this.prvKey);
sig.updateHex(this.asn1TBSCert.getEncodedHex());
this.hexSig = sig.sign();
this.asn1Sig = new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + this.hexSig } ));
let seq = new DERSequence(/** @type {Dictionary} */ ( { 'array': [this.asn1TBSCert, this.asn1SignatureAlg, this.asn1Sig] } ));
this.hTLV = seq.getEncodedHex();
this.isModified = false;
}
/**
* set signature value internally by hex string
* @param {string} sigHex
* @description
* @example
* let cert = new Certificate({'tbscertobj': tbs});
* cert.setSignatureHex('01020304');
*/
setSignatureHex(sigHex) {
this.asn1SignatureAlg = this.asn1TBSCert.asn1SignatureAlg;
this.hexSig = sigHex;
this.asn1Sig = new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + this.hexSig } ));
let seq = new DERSequence(/** @type {Dictionary} */ ( {
'array': [this.asn1TBSCert,
this.asn1SignatureAlg,
this.asn1Sig]
} ));
this.hTLV = seq.getEncodedHex();
this.isModified = false;
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
if (this.isModified == false && this.hTLV != null) return /** @type {string} */ ( this.hTLV );
throw "not signed yet";
}
/**
* get PEM formatted certificate string after signed
* @return PEM formatted string of certificate
* @description
* @example
* let cert = new Certificate({'tbscertobj': tbs, 'prvkeyobj': prvKey});
* cert.sign();
* let sPEM = cert.getPEMString();
*/
getPEMString() {
let pemBody = hextob64nl(this.getEncodedHex());
return "-----BEGIN CERTIFICATE-----\r\n" +
pemBody +
"\r\n-----END CERTIFICATE-----\r\n";
}
} |
JavaScript | class KeyUsage extends X500Extension {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'bin': '11', 'critical': true})
*/
constructor(params) {
super(params);
this.oid = "2.5.29.15";
/** @type {DERBitString | null} */ this.asn1ExtnValue;
if (params !== undefined) {
if (params['bin'] !== undefined) {
this.asn1ExtnValue = new DERBitString(params);
}
if (params['names'] !== undefined && params['names'].length !== undefined) {
let names = /** @type {Array} */ ( params['names'] );
let s = "000000000";
for (let i = 0; i < names.length; i++) {
for (let j = 0; j < KEYUSAGE_NAME.length; j++) {
if (names[i] === KEYUSAGE_NAME[j]) {
s = s.substring(0, j) + '1' +
s.substring(j + 1, s.length);
}
}
}
this.asn1ExtnValue = new DERBitString(/** @type {Dictionary} */ ( { 'bin': s } ));
}
}
}
/**
* @returns {string}
*/
getExtnValueHex() {
return this.asn1ExtnValue.getEncodedHex();
}
} |
JavaScript | class BasicConstraints extends X500Extension {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'cA': true, 'critical': true})
*/
constructor(params) {
super(params);
/** @type {DERSequence | null} */ this.asn1ExtnValue;
this.oid = "2.5.29.19";
/** @type {boolean} */ this.cA = false;
/** @type {number} */ this.pathLen = -1;
if (params !== undefined) {
if (isBoolean(params['cA'])) {
this.cA = /** @type {boolean} */ ( params['cA'] );
}
if (isNumber(params['pathLen'])) {
this.pathLen = /** @type {number} */ ( params['pathLen'] );
}
}
}
/**
* @returns {string}
*/
getExtnValueHex() {
/** @type {Array<ASN1Object>} */ let asn1Array = new Array();
if (this.cA) asn1Array.push(new DERBoolean());
if (this.pathLen > -1)
asn1Array.push(new DERInteger(/** @type {Dictionary} */ ( { 'int': this.pathLen }) ));
let asn1Seq = new DERSequence(/** @type {Dictionary} */ ( { 'array': asn1Array } ));
this.asn1ExtnValue = asn1Seq;
return this.asn1ExtnValue.getEncodedHex();
}
} |
JavaScript | class CRLDistributionPoints extends X500Extension {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'uri': 'http://a.com/', 'critical': true})
*/
constructor(params) {
super(params);
this.oid = "2.5.29.31";
if (params !== undefined) {
if (params['array'] !== undefined) {
this.setByDPArray(params['array']);
} else if (params['uri'] !== undefined) {
this.setByOneURI(params['uri']);
}
}
}
/**
* @returns {string}
*/
getExtnValueHex() {
return this.asn1ExtnValue.getEncodedHex();
}
setByDPArray(dpArray) {
this.asn1ExtnValue = new DERSequence(/** @type {Dictionary} */ ( { 'array': dpArray } ));
}
setByOneURI(uri) {
let gn1 = new GeneralNames([{ 'uri': uri }]);
let dpn1 = new DistributionPointName(gn1);
let dp1 = new DistributionPoint(/** @type {Dictionary} */ ( { 'dpobj': dpn1 } ));
this.setByDPArray([dp1]);
}
} |
JavaScript | class SubjectAltName extends X500Extension {
/**
* @param {Dictionary=} params dictionary of parameters
*/
constructor(params) {
super(params);
/** @type {GeneralNames | null} */ this.asn1ExtnValue;
this.oid = "2.5.29.17";
if (params !== undefined) {
if (isListOfDictionaries(params['array'])) {
this.setNameArray(/** @type {Array<Dictionary>} */ ( params['array'] ));
}
}
}
/**
* @param {Array<Dictionary>} paramsArray
*/
setNameArray(paramsArray) {
this.asn1ExtnValue = new GeneralNames(paramsArray);
}
/**
* @returns {string}
*/
getExtnValueHex() {
return this.asn1ExtnValue.getEncodedHex();
}
} |
JavaScript | class IssuerAltName extends X500Extension {
/**
* @param {Dictionary=} params dictionary of parameters
*/
constructor(params) {
super(params);
/** @type {GeneralNames | null} */ this.asn1ExtnValue;
this.oid = "2.5.29.18";
if (params !== undefined) {
if (isListOfDictionaries(params['array'])) {
this.setNameArray(/** @type {Array<Dictionary>} */ ( params['array'] ));
}
}
}
/**
* @param {Array<Dictionary>} paramsArray
*/
setNameArray(paramsArray) {
this.asn1ExtnValue = new GeneralNames(paramsArray);
}
/**
* @returns {string}
*/
getExtnValueHex() {
return this.asn1ExtnValue.getEncodedHex();
}
} |
JavaScript | class CRL extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'tbsobj': obj, 'rsaprvkey': key})
*/
constructor(params) {
super();
/** @type {TBSCertList | null} */ this.asn1TBSCertList = null;
/** @type {AlgorithmIdentifier | null} */ this.asn1SignatureAlg = null;
/** @type {DERBitString | null} */ this.asn1Sig = null;
/** @type {string | null} */ this.hexSig = null;
/** @type {string | KeyObject | null} */ this.prvKey = null;
if (params !== undefined) {
if (params['tbsobj'] instanceof TBSCertList) {
this.asn1TBSCertList = /** @type {TBSCertList} */ ( params['tbsobj'] );
}
let prvkeyobj = params['prvkeyobj'];
if (isString(prvkeyobj) || prvkeyobj instanceof RSAKeyEx || prvkeyobj instanceof DSA || prvkeyobj instanceof ECDSA) {
this.prvKey = /** @type {string | KeyObject} */ ( params['prvkeyobj'] );
}
}
}
/**
* sign TBSCertList and set signature value internally
* @description
* @example
* let cert = new CRL({'tbsobj': tbs, 'prvkeyobj': prvKey});
* cert.sign();
*/
sign() {
this.asn1SignatureAlg = this.asn1TBSCertList.asn1SignatureAlg;
let sig = new Signature(/** @type {Dictionary} */ ( { 'alg': 'SHA1withRSA', 'prov': 'cryptojs/jsrsa' } ));
sig.init(this.prvKey);
sig.updateHex(this.asn1TBSCertList.getEncodedHex());
this.hexSig = sig.sign();
this.asn1Sig = new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + this.hexSig } ));
let seq = new DERSequence(/** @type {Dictionary} */ ( {
'array': [this.asn1TBSCertList,
this.asn1SignatureAlg,
this.asn1Sig]
} ));
this.hTLV = seq.getEncodedHex();
this.isModified = false;
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
if (this.isModified == false && this.hTLV != null) return /** @type {string} */ ( this.hTLV );
throw "not signed yet";
}
/**
* get PEM formatted CRL string after signed
* @return {string} PEM formatted string of certificate
* @description
* @example
* let cert = new CRL({'tbsobj': tbs, 'rsaprvkey': prvKey});
* cert.sign();
* let sPEM = cert.getPEMString();
*/
getPEMString() {
let pemBody = hextob64nl(this.getEncodedHex());
return "-----BEGIN X509 CRL-----\r\n" +
pemBody +
"\r\n-----END X509 CRL-----\r\n";
}
} |
JavaScript | class TBSCertList extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {})
*/
constructor(params) {
super();
/** @type {Array<ASN1Object>} */ this.asn1Array;
/** @type {DERTaggedObject | null} */ this.asn1Version = null;
/** @type {AlgorithmIdentifier | null} */ this.asn1SignatureAlg = null;
/** @type {X500Name | null} */ this.asn1Issuer = null;
/** @type {Time | null} */ this.asn1ThisUpdate = null;
/** @type {Time | null} */ this.asn1NextUpdate = null;
/** @type {Array<CRLEntry>} */ this.aRevokedCert = new Array();
}
/**
* set signature algorithm field by parameter
* @param {Dictionary} algIdParam AlgorithmIdentifier parameter
* @description
* @example
* tbsc.setSignatureAlgByParam({'name': 'SHA1withRSA'});
*/
setSignatureAlgByParam(algIdParam) {
this.asn1SignatureAlg = new AlgorithmIdentifier(algIdParam);
}
/**
* set issuer name field by parameter
* @param {Dictionary} x500NameParam X500Name parameter
* @description
* @example
* tbsc.setIssuerParam({'str': '/C=US/CN=b'});
*/
setIssuerByParam(x500NameParam) {
this.asn1Issuer = new X500Name(x500NameParam);
}
/**
* set thisUpdate field by parameter
* @param {Dictionary} timeParam Time parameter
* @description
* @example
* tbsc.setThisUpdateByParam({'str': '130508235959Z'});
*/
setThisUpdateByParam(timeParam) {
this.asn1ThisUpdate = new Time(timeParam);
}
/**
* set nextUpdate field by parameter
* @param {Dictionary} timeParam Time parameter
* @description
* @example
* tbsc.setNextUpdateByParam({'str': '130508235959Z'});
*/
setNextUpdateByParam(timeParam) {
this.asn1NextUpdate = new Time(timeParam);
}
/**
* add revoked certificate by parameter
* @param {Dictionary} snParam DERInteger parameter for certificate serial number
* @param {Dictionary} timeParam Time parameter for revocation date
* @description
* @example
* tbsc.addRevokedCert({'int': 3}, {'str': '130508235959Z'});
*/
addRevokedCert(snParam, timeParam) {
let param = /** @type {Dictionary} */ ( {} );
if (snParam != undefined && snParam != null)
param['sn'] = snParam;
if (timeParam != undefined && timeParam != null)
param['time'] = timeParam;
let o = new CRLEntry(param);
this.aRevokedCert.push(o);
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
this.asn1Array = new Array();
if (this.asn1Version != null) this.asn1Array.push(this.asn1Version);
this.asn1Array.push(this.asn1SignatureAlg);
this.asn1Array.push(this.asn1Issuer);
this.asn1Array.push(this.asn1ThisUpdate);
if (this.asn1NextUpdate != null) this.asn1Array.push(this.asn1NextUpdate);
if (this.aRevokedCert.length > 0) {
let seq = new DERSequence(/** @type {Dictionary} */ ( { 'array': this.aRevokedCert } ));
this.asn1Array.push(seq);
}
let o = new DERSequence(/** @type {Dictionary} */ ( { "array": this.asn1Array } ));
this.hTLV = o.getEncodedHex();
this.isModified = false;
return /** @type {string} */ ( this.hTLV );
}
} |
JavaScript | class CRLEntry extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {})
*/
constructor(params) {
super();
/** @type {DERInteger | null} */ this.sn = null;
/** @type {Time | null} */ this.time = null;
/** @type {string | null} */ this.TLV = null;
if (params !== undefined) {
if (isDictionary(params['time'])) {
this.setRevocationDate(/** @type {Dictionary} */ ( params['time'] ));
}
if (isNumber(params['sn']) || isDictionary(params['sn'])) {
this.setCertSerial(/** @type {number | Dictionary} */ ( params['sn'] ));
}
}
}
/**
* set DERInteger parameter for serial number of revoked certificate
* @param {number | Dictionary} intParam DERInteger parameter for certificate serial number
* @description
* @example
* entry.setCertSerial({'int': 3});
*/
setCertSerial(intParam) {
this.sn = new DERInteger(intParam);
}
/**
* set Time parameter for revocation date
* @param {Dictionary} timeParam Time parameter for revocation date
* @description
* @example
* entry.setRevocationDate({'str': '130508235959Z'});
*/
setRevocationDate(timeParam) {
this.time = new Time(timeParam);
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let o = new DERSequence(/** @type {Dictionary} */ ( { "array": [this.sn, this.time] } ));
this.TLV = o.getEncodedHex();
return this.TLV;
}
} |
JavaScript | class X500Name extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'str': '/C=US/O=a'})
*/
constructor(params) {
super();
/** @type {Array<RDN>} */ this.asn1Array = new Array();
if (params !== undefined) {
if (isString(params['str'])) {
this.setByString(/** @type {string} */ ( params['str'] ));
} else if (isString(params['ldapstr'])) {
this.setByLdapString(/** @type {string} */ ( params['ldapstr'] ));
// If params is an object, then set the ASN1 array just using the object
// attributes. This is nice for fields that have lots of special
// characters (i.e. CN: 'https://www.github.com/SergioRando/').
} else if (typeof params === "object") {
this.setByObject(params);
}
if (isString(params['certissuer'])) {
let x = new X509();
x.hex = pemtohex(/** @type {string} */ ( params['certissuer'] ));
this.hTLV = x.getIssuerHex();
}
if (isString(params['certsubject'])) {
let x = new X509();
x.hex = pemtohex(/** @type {string} */ ( params['certsubject'] ));
this.hTLV = x.getSubjectHex();
}
}
}
/**
* set DN by OpenSSL oneline distinguished name string<br/>
* @param {string} dnStr distinguished name by string (ex. /C=US/O=aaa)
* @description
* Sets distinguished name by string.
* dnStr must be formatted as
* "/type0=value0/type1=value1/type2=value2...".
* No need to escape a slash in an attribute value.
* @example
* name = new X500Name();
* name.setByString("/C=US/O=aaa/OU=bbb/[email protected]");
* // no need to escape slash in an attribute value
* name.setByString("/C=US/O=aaa/CN=1980/12/31");
*/
setByString(dnStr) {
let a = dnStr.split('/');
a.shift();
let a1 = [];
for (let i = 0; i < a.length; i++) {
if (a[i].match(/^[^=]+=.+$/)) {
a1.push(a[i]);
} else {
let lastidx = a1.length - 1;
a1[lastidx] = a1[lastidx] + "/" + a[i];
}
}
for (let i = 0; i < a1.length; i++) {
this.asn1Array.push(new RDN(/** @type {Dictionary} */ ( { 'str': a1[i] } )));
}
}
/**
* set DN by LDAP(RFC 2253) distinguished name string<br/>
* @param {string} dnStr distinguished name by LDAP string (ex. O=aaa,C=US)
* @description
* @example
* name = new X500Name();
* name.setByLdapString("[email protected],OU=bbb,O=aaa,C=US");
*/
setByLdapString(dnStr) {
let oneline = X500Name.ldapToOneline(dnStr);
this.setByString(oneline);
}
/**
* set DN by associative array<br/>
* @param {Dictionary} dnObj associative array of DN (ex. {'C': "US", 'O': "aaa"})
* @description
* @example
* name = new X500Name();
* name.setByObject({'C': "US", 'O': "aaa", CN="http://example.com/"1});
*/
setByObject(dnObj) {
// Get all the dnObject attributes and stuff them in the ASN.1 array.
for (let x in dnObj) {
if (/** @type {Object} */ ( dnObj ).hasOwnProperty(x)) {
let newRDN = new RDN(/** @type {Dictionary} */ ( { 'str': x + '=' + dnObj[x] } ));
// Initialize or push into the ANS1 array.
this.asn1Array ? this.asn1Array.push(newRDN)
: this.asn1Array = [newRDN];
}
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
if (typeof this.hTLV == "string") return /** @type {string} */ ( this.hTLV );
let o = new DERSequence(/** @type {Dictionary} */ ( { "array": this.asn1Array } ));
this.hTLV = o.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
/**
* convert OpenSSL oneline distinguished name format string to LDAP(RFC 2253) format<br/>
* @param {string} s distinguished name string in OpenSSL oneline format (ex. /C=US/O=test)
* @return {string} distinguished name string in LDAP(RFC 2253) format (ex. O=test,C=US)
* @description
* This static method converts a distinguished name string in OpenSSL oneline
* format to LDAP(RFC 2253) format.
* @example
* X500Name.onelineToLDAP("/C=US/O=test") → 'O=test,C=US'
* X500Name.onelineToLDAP("/C=US/O=a,a") → 'O=a\,a,C=US'
*/
static onelineToLDAP(s) {
if (s.substr(0, 1) !== "/") throw "malformed input";
s = s.substr(1);
let a = s.split("/");
a.reverse();
a = a.map(function (s) { return s.replace(/,/, "\\,") });
return a.join(",");
}
/**
* convert LDAP(RFC 2253) distinguished name format string to OpenSSL oneline format<br/>
* @param {string} s distinguished name string in LDAP(RFC 2253) format (ex. O=test,C=US)
* @return {string} distinguished name string in OpenSSL oneline format (ex. /C=US/O=test)
* @description
* This static method converts a distinguished name string in
* LDAP(RFC 2253) format to OpenSSL oneline format.
* @example
* X500Name.ldapToOneline('O=test,C=US') → '/C=US/O=test'
* X500Name.ldapToOneline('O=a\,a,C=US') → '/C=US/O=a,a'
* X500Name.ldapToOneline('O=a/a,C=US') → '/C=US/O=a\/a'
*/
static ldapToOneline(s) {
let a = s.split(",");
// join \,
let isBSbefore = false;
let a2 = [];
for (let i = 0; a.length > 0; i++) {
let item = a.shift();
//console.log("item=" + item);
if (isBSbefore === true) {
let a2last = a2.pop();
let newitem = (a2last + "," + item).replace(/\\,/g, ",");
a2.push(newitem);
isBSbefore = false;
} else {
a2.push(item);
}
if (item.substr(-1, 1) === "\\") isBSbefore = true;
}
a2 = a2.map(function (s) { return s.replace("/", "\\/") });
a2.reverse();
return "/" + a2.join("/");
}
} |
JavaScript | class RDN extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'str': 'C=US'})
*/
constructor(params) {
super();
/** @type {Array<AttributeTypeAndValue>} */ this.asn1Array = new Array();
/** @type {string | null} */ this.hTLV = null;
if (params !== undefined) {
if (isString(params['str'])) {
this.addByMultiValuedString(/** @type {string} */ ( params['str'] ));
}
}
}
/**
* add one AttributeTypeAndValue by string<br/>
* @param {string} s string of AttributeTypeAndValue
* @description
* This method add one AttributeTypeAndValue to RDN object.
* @example
* rdn = new RDN();
* rdn.addByString("CN=john");
* rdn.addByString("serialNumber=1234"); // for multi-valued RDN
*/
addByString(s) {
this.asn1Array.push(new AttributeTypeAndValue(/** @type {Dictionary} */ ( { 'str': s } )));
}
/**
* add one AttributeTypeAndValue by multi-valued string<br/>
* @param {string} s string of multi-valued RDN
* @description
* This method add multi-valued RDN to RDN object.
* @example
* rdn = new RDN();
* rdn.addByMultiValuedString("CN=john+O=test");
* rdn.addByMultiValuedString("O=a+O=b\+b\+b+O=c"); // multi-valued RDN with quoted plus
* rdn.addByMultiValuedString("O=a+O=\"b+b+b\"+O=c"); // multi-valued RDN with quoted quotation
*/
addByMultiValuedString(s) {
let a = RDN.parseString(s);
for (let i = 0; i < a.length; i++) {
this.addByString(a[i]);
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let o = new DERSet(/** @type {Dictionary} */ ( { "array": this.asn1Array } ));
this.hTLV = o.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
/**
* parse multi-valued RDN string and split into array of 'AttributeTypeAndValue'<br/>
* @param {string} s multi-valued string of RDN
* @return {Array<string>} array of string of AttributeTypeAndValue
* @description
* This static method parses multi-valued RDN string and split into
* array of AttributeTypeAndValue.
* @example
* RDN.parseString("CN=john") → ["CN=john"]
* RDN.parseString("CN=john+OU=test") → ["CN=john", "OU=test"]
* RDN.parseString('CN="jo+hn"+OU=test') → ["CN=jo+hn", "OU=test"]
* RDN.parseString('CN=jo\+hn+OU=test') → ["CN=jo+hn", "OU=test"]
* RDN.parseString("CN=john+OU=test+OU=t1") → ["CN=john", "OU=test", "OU=t1"]
*/
static parseString(s) {
let a = s.split(/\+/);
// join \+
let isBSbefore = false;
/** @type {Array<string>} */ let a2 = [];
for (let i = 0; a.length > 0; i++) {
let item = a.shift();
//console.log("item=" + item);
if (isBSbefore === true) {
let a2last = a2.pop();
let newitem = (a2last + "+" + item).replace(/\\\+/g, "+");
a2.push(newitem);
isBSbefore = false;
} else {
a2.push(item);
}
if (item.substr(-1, 1) === "\\") isBSbefore = true;
}
// join quote
let beginQuote = false;
/** @type {Array<string>} */ let a3 = [];
for (let i = 0; a2.length > 0; i++) {
let item = a2.shift();
if (beginQuote === true) {
let a3last = a3.pop();
if (item.match(/"$/)) {
let newitem = (a3last + "+" + item).replace(/^([^=]+)="(.*)"$/, "$1=$2");
a3.push(newitem);
beginQuote = false;
} else {
a3.push(a3last + "+" + item);
}
} else {
a3.push(item);
}
if (item.match(/^[^=]+="/)) {
//console.log(i + "=" + item);
beginQuote = true;
}
}
return a3;
}
} |
JavaScript | class AttributeTypeAndValue extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'str': 'C=US'})
*/
constructor(params) {
super();
/** @type {DERObjectIdentifier | null} */ this.typeObj = null;
/** @type {DERAbstractString | null} */ this.valueObj = null;
/** @type {string | null} */ this.hTLV = null;
if (params !== undefined) {
if (isString(params['str'])) {
this.setByString(/** @type {string} */ ( params['str'] ));
}
}
}
/**
* @param {string} attrTypeAndValueStr
*/
setByString(attrTypeAndValueStr) {
let matchResult = attrTypeAndValueStr.match(/^([^=]+)=(.+)$/);
if (matchResult) {
this.setByAttrTypeAndValueStr(matchResult[1], matchResult[2]);
} else {
throw "malformed attrTypeAndValueStr: " + attrTypeAndValueStr;
}
}
/**
* @param {string} shortAttrType
* @param {string} valueStr
*/
setByAttrTypeAndValueStr(shortAttrType, valueStr) {
this.typeObj = atype2obj(shortAttrType);
let dsType = defaultDSType;
if (shortAttrType == "C") dsType = "prn";
this.valueObj = this.getValueObj(dsType, valueStr);
}
/**
* @param {string} dsType
* @param {string} valueStr
* @returns {DERAbstractString}
*/
getValueObj(dsType, valueStr) {
if (dsType == "utf8") return new DERUTF8String(/** @type {Dictionary} */ ( { "str": valueStr } ));
if (dsType == "prn") return new DERPrintableString(/** @type {Dictionary} */ ( { "str": valueStr } ));
if (dsType == "tel") return new DERTeletexString(/** @type {Dictionary} */ ( { "str": valueStr } ));
if (dsType == "ia5") return new DERIA5String(/** @type {Dictionary} */ ( { "str": valueStr } ));
throw "unsupported directory string type: type=" + dsType + " value=" + valueStr;
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let o = new DERSequence(/** @type {Dictionary} */ ( { "array": [this.typeObj, this.valueObj] } ));
this.hTLV = o.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
} |
JavaScript | class SubjectPublicKeyInfo extends ASN1Object {
/**
* @param {KeyObject=} params parameter for subject public key
*/
constructor(params) {
super();
/** @type {AlgorithmIdentifier | null} */ this.asn1AlgId = null;
/** @type {DERBitString | null} */ this.asn1SubjPKey = null;
/** @type {string | null} */ this.hTLV = null;
if (params !== undefined) {
this.setPubKey(params);
}
}
/*
*/
getASN1Object() {
if (this.asn1AlgId == null || this.asn1SubjPKey == null)
throw "algId and/or subjPubKey not set";
let o = new DERSequence(/** @type {Dictionary} */ ( {
'array':
[this.asn1AlgId, this.asn1SubjPKey]
} ));
return o;
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let o = this.getASN1Object();
this.hTLV = o.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
/**
* @param {KeyObject} key {@link RSAKeyEx}, {@link ECDSA} or {@link DSA} object
* @description
* @example
* spki = new SubjectPublicKeyInfo();
* pubKey = getKey(PKCS8PUBKEYPEM);
* spki.setPubKey(pubKey);
*/
setPubKey(key) {
try {
if (key instanceof RSAKeyEx) {
let asn1RsaPub = newObject(/** @type {Dictionary} */ ( {
'seq': [{ 'int': { 'bigint': key.n } }, { 'int': { 'int': key.e } }]
} ));
let rsaKeyHex = asn1RsaPub.getEncodedHex();
this.asn1AlgId = new AlgorithmIdentifier(/** @type {Dictionary} */ ( { 'name': 'rsaEncryption' } ));
this.asn1SubjPKey = new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + rsaKeyHex } ));
}
} catch (ex) { };
try {
if (key instanceof ECDSA) {
let asn1Params = new DERObjectIdentifier(/** @type {Dictionary} */ ( { 'name': key.curveName } ));
this.asn1AlgId =
new AlgorithmIdentifier(/** @type {Dictionary} */ ( {
'name': 'ecPublicKey',
'asn1params': asn1Params
} ));
this.asn1SubjPKey = new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + key.pubKeyHex } ));
}
} catch (ex) { };
try {
if (key instanceof DSA) {
let asn1Params = newObject(/** @type {Dictionary} */ ( {
'seq': [{ 'int': { 'bigint': key.p } },
{ 'int': { 'bigint': key.q } },
{ 'int': { 'bigint': key.g } }]
} ));
this.asn1AlgId =
new AlgorithmIdentifier(/** @type {Dictionary} */ ( {
'name': 'dsa',
'asn1params': asn1Params
} ));
let pubInt = new DERInteger(/** @type {Dictionary} */ ( { 'bigint': key.y } ));
this.asn1SubjPKey =
new DERBitString(/** @type {Dictionary} */ ( { 'hex': '00' + pubInt.getEncodedHex() } ));
}
} catch (ex) { };
}
} |
JavaScript | class AlgorithmIdentifier extends ASN1Object {
/**
* @param {Dictionary=} params dictionary of parameters (ex. {'name': 'SHA1withRSA'})
*/
constructor(params) {
super();
/** @type {string | null} */ this.nameAlg = null;
/** @type {DERObjectIdentifier | null} */ this.asn1Alg = null;
/** @type {ASN1Object | null} */ this.asn1Params = null;
/** @type {boolean} */ this.paramEmpty = false;
if (params !== undefined) {
if (params['name'] !== undefined) {
this.nameAlg = String(params['name']);
}
if (params['asn1params'] instanceof ASN1Object) {
this.asn1Params = /** @type {ASN1Object} */ ( params['asn1params'] );
}
if (isBoolean(params['paramempty'])) {
this.paramEmpty = /** @type {boolean} */ ( params['paramempty'] );
}
}
// set algorithm parameters will be ommitted for
// "*withDSA" or "*withECDSA" otherwise will be NULL.
if (this.asn1Params === null &&
this.paramEmpty === false &&
this.nameAlg !== null) {
let lcNameAlg = this.nameAlg.toLowerCase();
if (lcNameAlg.substr(-7, 7) !== "withdsa" &&
lcNameAlg.substr(-9, 9) !== "withecdsa") {
this.asn1Params = new DERNull();
}
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
if (this.nameAlg === null && this.asn1Alg === null) {
throw "algorithm not specified";
}
if (this.nameAlg !== null && this.asn1Alg === null) {
this.asn1Alg = name2obj(this.nameAlg);
}
let a = [this.asn1Alg];
if (this.asn1Params !== null) a.push(this.asn1Params);
let o = new DERSequence(/** @type {Dictionary} */ ( { 'array': a } ));
this.hTLV = o.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
} |
JavaScript | class GeneralName extends ASN1Object {
/**
* @param {Dictionary=} params
*/
constructor(params) {
super();
this.asn1Obj = null;
/** @type {string | null} */ this.type = null;
this.explicit = false;
if (params !== undefined) {
this.setByParam(params);
}
}
/**
* @param {Dictionary} params
*/
setByParam(params) {
/** @type {ASN1Object | null} */ let v = null;
if (params === undefined) return;
if (params['rfc822'] !== undefined) {
this.type = 'rfc822';
v = new DERIA5String(/** @type {Dictionary} */ ( { 'str': params[this.type] } ));
}
if (params['dns'] !== undefined) {
this.type = 'dns';
v = new DERIA5String(/** @type {Dictionary} */ ( { 'str': params[this.type] } ));
}
if (params['uri'] !== undefined) {
this.type = 'uri';
v = new DERIA5String(/** @type {Dictionary} */ ( { 'str': params[this.type] } ));
}
if (params['dn'] !== undefined) {
this.type = 'dn';
this.explicit = true;
v = new X500Name(/** @type {Dictionary} */ ( { 'str': params['dn'] } ));
}
if (params['ldapdn'] !== undefined) {
this.type = 'dn';
this.explicit = true;
v = new X500Name(/** @type {Dictionary} */ ( { 'ldapstr': params['ldapdn'] } ));
}
if (isString(params['certissuer'])) {
this.type = 'dn';
this.explicit = true;
let certStr = /** @type {string} */ ( params['certissuer'] );
/** @type {string | null} */ let certHex = null;
if (certStr.match(/^[0-9A-Fa-f]+$/)) {
certHex = certStr;
}
if (certStr.indexOf("-----BEGIN ") != -1) {
certHex = pemtohex(certStr);
}
if (certHex == null) throw "certissuer param not cert";
let x = new X509();
x.hex = certHex;
let dnHex = x.getIssuerHex();
v = new ASN1Object();
v.hTLV = dnHex;
}
if (isString(params['certsubj'])) {
this.type = 'dn';
this.explicit = true;
let certStr = /** @type {string} */ ( params['certsubj'] );
/** @type {string | null} */ let certHex = null;
if (certStr.match(/^[0-9A-Fa-f]+$/)) {
certHex = certStr;
}
if (certStr.indexOf("-----BEGIN ") != -1) {
certHex = pemtohex(certStr);
}
if (certHex == null) throw "certsubj param not cert";
let x = new X509();
x.hex = certHex;
let dnHex = x.getSubjectHex();
v = new ASN1Object();
v.hTLV = dnHex;
}
if (isString(params['ip'])) {
this.type = 'ip';
this.explicit = false;
let ip = /** @type {string} */ ( params['ip'] );
let hIP;
let malformedIPMsg = "malformed IP address";
if (ip.match(/^[0-9.]+[.][0-9.]+$/)) { // ipv4
hIP = intarystrtohex("[" + ip.split(".").join(",") + "]");
if (hIP.length !== 8) throw malformedIPMsg;
} else if (ip.match(/^[0-9A-Fa-f:]+:[0-9A-Fa-f:]+$/)) { // ipv6
hIP = ipv6tohex(ip);
} else if (ip.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/)) { // hex
hIP = ip;
} else {
throw malformedIPMsg;
}
v = new DEROctetString(/** @type {Dictionary} */ ( { 'hex': hIP } ));
}
if (this.type == null)
throw "unsupported type in params=" + params;
this.asn1Obj = new DERTaggedObject(/** @type {Dictionary} */ ( {
'explicit': this.explicit,
'tag': pTag[this.type],
'obj': v
} ));
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
return this.asn1Obj.getEncodedHex();
}
} |
JavaScript | class GeneralNames extends ASN1Object {
/**
* @param {Array<Dictionary>=} paramsArray
*/
constructor(paramsArray) {
super();
/** @type {Array<GeneralName>} */ this.asn1Array = new Array();
if (typeof paramsArray != "undefined") {
this.setByParamArray(paramsArray);
}
}
/**
* set a array of {@link GeneralName} parameters<br/>
* @param {Array<Dictionary>} paramsArray Array of {@link GeneralNames}
* @description
* <br/>
* <h4>EXAMPLES</h4>
* @example
* gns = new GeneralNames();
* gns.setByParamArray([{uri: 'http://aaa.com/'}, {uri: 'http://bbb.com/'}]);
*/
setByParamArray(paramsArray) {
for (let i = 0; i < paramsArray.length; i++) {
let o = new GeneralName(paramsArray[i]);
this.asn1Array.push(o);
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let o = new DERSequence(/** @type {Dictionary} */ ( { 'array': this.asn1Array } ));
return o.getEncodedHex();
}
} |
JavaScript | class DistributionPointName extends ASN1Object {
/**
* @param {GeneralNames=} gnOrRdn
*/
constructor(gnOrRdn) {
super();
/** @type {DERTaggedObject | null} */ this.asn1Obj = null;
/** @type {string | null} */ this.type = null;
/** @type {string | null} */ this.tag = null;
/** @type {GeneralNames | null} */ this.asn1V = null;
if (gnOrRdn !== undefined) {
if (gnOrRdn instanceof GeneralNames) {
this.type = "full";
this.tag = "a0";
this.asn1V = gnOrRdn;
} else {
throw "This class supports GeneralNames only as argument";
}
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
if (this.type != "full")
throw "currently type shall be 'full': " + this.type;
this.asn1Obj = new DERTaggedObject(/** @type {Dictionary} */ ( {
'explicit': false,
'tag': this.tag,
'obj': this.asn1V
} ));
this.hTLV = this.asn1Obj.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
} |
JavaScript | class DistributionPoint extends ASN1Object {
/**
* @param {Dictionary=} params
*/
constructor(params) {
super();
/** @type {ASN1Object | null} */ this.asn1DP = null;
if (params !== undefined) {
if (params['dpobj'] instanceof ASN1Object) {
this.asn1DP = /** @type {ASN1Object} */ ( params['dpobj'] );
}
}
}
/**
* @override
* @returns {string}
*/
getEncodedHex() {
let seq = new DERSequence();
if (this.asn1DP != null) {
let o1 = new DERTaggedObject(/** @type {Dictionary} */ ( {
'explicit': true,
'tag': 'a0',
'obj': this.asn1DP
} ));
seq.appendASN1Object(o1);
}
this.hTLV = seq.getEncodedHex();
return /** @type {string} */ ( this.hTLV );
}
} |
JavaScript | class BotsSDKMessage {
constructor() {
this._logger = new Logger('BotsSDKMessage');
}
/**
* Convert bots sdk message to common model message
* @return {IMessage}
*/
toCommonMessage() {
let payload;
switch (this.type) {
case BOTS_SDK_PAYLOAD_TYPE.TEXT:
payload = {
type: PAYLOAD_TYPE.TEXT,
text: this.text,
actions: this.convertSDKBotActionsToCommon(this.actions)
};
break;
case BOTS_SDK_PAYLOAD_TYPE.LIST:
case BOTS_SDK_PAYLOAD_TYPE.CAROUSEL:
let cards = [];
for (let item of this.items) {
cards.push({
title: item.title,
description: item.description,
imageUrl: item.mediaUrl,
actions: this.convertSDKBotActionsToCommon(item.actions)
});
}
payload = {
type: PAYLOAD_TYPE.CARD,
layout: (this.type === BOTS_SDK_PAYLOAD_TYPE.LIST ? LAYOUT.VERTICAL : LAYOUT.HORIZONTAL),
cards: cards,
globalActions: this.convertSDKBotActionsToCommon(this.actions)
};
break;
case BOTS_SDK_PAYLOAD_TYPE.LOCATION:
payload = {
type: PAYLOAD_TYPE.LOCATION,
location: {
title: this.text,
longitude: this.coordinates.long,
latitude: this.coordinates.lat
},
actions: this.convertSDKBotActionsToCommon(this.actions)
};
break;
case BOTS_SDK_PAYLOAD_TYPE.IMAGE:
payload = {
type: PAYLOAD_TYPE.ATTACHMENT,
attachment: {
type: ATTACHMENT_TYPE.IMAGE,
url: this.mediaUrl
// TODO: add this.text as caption
},
actions: this.convertSDKBotActionsToCommon(this.actions)
};
break;
case BOTS_SDK_PAYLOAD_TYPE.FILE:
let attachmentType = ATTACHMENT_TYPE.FILE;
if (['video/quicktime'].indexOf(this.mediaType) > -1) {
attachmentType = ATTACHMENT_TYPE.VIDEO;
}
else if (['audio/mpeg'].indexOf(this.mediaType) > -1) {
attachmentType = ATTACHMENT_TYPE.AUDIO;
}
payload = {
type: PAYLOAD_TYPE.ATTACHMENT,
attachment: {
type: attachmentType,
url: this.mediaUrl
// TODO: add this.text as caption
},
actions: this.convertSDKBotActionsToCommon(this.actions)
};
break;
default:
this._logger.error('This Bots SDK message type is not implemented. ', this);
break;
}
this._logger.debug('toCommonMessage', this, payload);
if (this.role === BOTS_SDK_MESSAGE_ROLE.APP_USER) {
return {
to: {
type: USER_MESSAGE_TYPE.USER,
id: ''
},
messagePayload: payload,
};
}
else {
return {
from: {
type: BOT_MESSAGE_TYPE.BOT
},
body: {
messagePayload: payload,
}
};
}
}
/**
* Convert the common model message to bots sdk message
* @param {IUserMessage} message
* @return {BotsSDKMessage}
*/
static fromCommonMessage(message) {
let botsSDKMessage;
let payload = message.messagePayload;
switch (payload.type) {
case PAYLOAD_TYPE.TEXT:
let txtPayload = payload;
botsSDKMessage = {
type: BOTS_SDK_PAYLOAD_TYPE.TEXT,
text: txtPayload.text
};
break;
case PAYLOAD_TYPE.LOCATION:
let locationPayload = payload;
botsSDKMessage = {
type: BOTS_SDK_PAYLOAD_TYPE.LOCATION,
coordinates: {
long: locationPayload.location.longitude,
lat: locationPayload.location.latitude
}
};
break;
}
return Object.assign(new BotsSDKMessage(), botsSDKMessage);
}
/**
* Converts the bots sdk action to common message action
* @param {IBotsSDKMessageAction[]} sdkActions
* @return {IActionPayload[]}
*/
convertSDKBotActionsToCommon(sdkActions) {
let actions = [];
if (sdkActions) {
for (let sdkAction of sdkActions) {
let action;
switch (sdkAction.type) {
case BOTS_SDK_ACTION_TYPE.POSTBACK:
let postbackAction = sdkAction;
action = {
type: ACTION_TYPE.POST_BACK,
label: postbackAction.text,
postback: { payload: postbackAction.payload, id: postbackAction._id }
};
break;
case BOTS_SDK_ACTION_TYPE.LINK:
let linkAction = sdkAction;
action = {
type: ACTION_TYPE.URL,
label: linkAction.text,
url: linkAction.uri
};
break;
case BOTS_SDK_ACTION_TYPE.LOCATION_REQUEST:
action = {
type: ACTION_TYPE.LOCATION,
label: sdkAction.text,
};
break;
case BOTS_SDK_ACTION_TYPE.REPLY:
let replyAction = sdkAction;
action = {
type: ACTION_TYPE.POST_BACK,
label: replyAction.text,
postback: { payload: replyAction.payload, id: replyAction._id }
};
break;
default:
this._logger.error('Not supported BOTS SDK action. ', sdkAction);
break;
}
if (action) {
actions.push(action);
}
}
}
return actions;
}
} |
JavaScript | class ParticleEffect {
/**
* Creates a particle effect.
*
* @param asset Particle effect asset.
* @param effectName Name of effect.
*/
constructor(asset, effectName) {
this.asset = asset;
this.effectName = effectName;
this.offset = new utils_1.Vector3();
this.rotation = new utils_1.Vector3();
this.color = new utils_1.Color(255, 255, 255, 255);
this.scale = 0;
this.range = 0;
this.invertAxis = { flags: enums_1.InvertAxisFlags.None };
this.handle = -1;
}
/**
* Get the particle effect handle.
*/
get Handle() {
return this.handle;
}
/**
* Get whether particle effect is currently active.
*/
get IsActive() {
return this.Handle !== -1 && !!DoesParticleFxLoopedExist(this.Handle);
}
/**
* Stop a particle effect.
*/
stop() {
if (this.IsActive) {
RemoveParticleFx(this.Handle, false);
}
this.handle = -1;
}
/**
* Get the rotation of the particle effect.
*/
get Rotation() {
return this.rotation;
}
/**
* Set the rotation of the particle effect.
*/
set Rotation(rotation) {
this.rotation = rotation;
if (this.IsActive) {
const off = this.offset; // TODO Matrix stuff to access from memory
SetParticleFxLoopedOffsets(this.Handle, off.x, off.y, off.z, rotation.x, rotation.y, rotation.z);
}
}
/**
* Get the range of the particle effect.
*/
get Range() {
return this.range;
}
/**
* Set the range of the particle effect.
*/
set Range(range) {
this.range = range;
SetParticleFxLoopedRange(this.Handle, range);
}
/**
* Get the invert axis flag of the particle effect.
*/
get InvertAxis() {
return this.invertAxis;
}
/**
* Set the inverted axis of the particle effect.
*/
set InvertAxis(invertAxis) {
this.invertAxis = invertAxis;
if (this.IsActive) {
this.stop();
this.start();
}
}
/**
* Set a paramaeter of a particle effect.
*
* @param parameterName Name of parameter.
* @param value Value of parameter.
*/
setParameter(parameterName, value) {
if (this.IsActive) {
SetParticleFxLoopedEvolution(this.Handle, parameterName, value, false);
}
}
/**
* Get the name of the particle effect asset. Same as ParticleEffect.AssetName.
*/
get AssetName() {
return this.asset.AssetName;
}
/**
* Get the name of the particle effect.
*/
get EffectName() {
return this.effectName;
}
/**
* Return the particle effect as string. `AssetName`\\`EffectName`.
*/
toString() {
return `${this.AssetName}\\${this.EffectName}`;
}
} |
JavaScript | class Database extends Base {
/**
* Creates quickmongo instance
* @param {string} mongodbURL Mongodb database url
* @param {string} name Schema name
* @param {object} connectionOptions Mongoose connection options
* @example const { Database } = require("quickmongo");
* const db = new Database("mongodb://localhost/quickmongo");
*/
constructor(mongodbURL, name, connectionOptions={}) {
super(mongodbURL, connectionOptions);
/**
* Current Schema
* @type {Schema}
*/
this.schema = Schema(name);
}
/**
* Sets the value to the database
* @param {string} key Key
* @param value Data
* @example db.set("foo", "bar").then(() => console.log("Saved data"));
*/
async set(key, value) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
if (!Util.isValue(value)) throw new Error("Invalid value specified!", "ValueError");
if(!key.includes('.')) {
let raw = await this.schema.findOne({
ID: key
});
if (!raw) {
let data = new this.schema({
ID: key,
data: value
});
await data.save()
.catch(e => {
return this.emit("error", e);
});
return data.data;
} else {
raw.data = value;
await raw.save()
.catch(e => {
return this.emit("error", e);
});
return raw.data;
}
} else {
const subkey = key.split('.').shift();
let raw = await this.schema.findOne({
ID: subkey
});
if(!raw) {
const setValue = _.set({}, key.split('.').slice(1).join('.'), value);
let data = new this.schema({
ID: subkey,
data: setValue
});
await data.save()
.catch(e => {
return this.emit("error", e);
});
return data.data;
} else {
const setValue = _.set(raw, key.split('.').slice(1).join('.'), value);
raw.data = setValue;
await raw.save()
.catch(e => {
return this.emit("error", e);
});
return raw.data;
}
}
}
/**
* Deletes a data from the database
* @param {string} key Key
* @example db.delete("foo").then(() => console.log("Deleted data"));
*/
async delete(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
let data = await this.schema.findOneAndDelete({ ID: key })
.catch(e => {
return this.emit("error", e);
});
return data;
}
/**
* Checks if there is a data stored with the given key
* @param {string} key Key
* @example db.exists("foo").then(console.log);
*/
async exists(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
let get = await this.get(key);
return !!get;
}
/**
* Checks if there is a data stored with the given key
* @param {string} key Key
* @example db.has("foo").then(console.log);
*/
async has(key) {
return await this.exists(key);
}
/**
* Fetches the data from database
* @param {string} key Key
* @example db.get("foo").then(console.log);
*/
async get(key) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
if(!key.includes('.')) {
let get = await this.schema.findOne({ ID: key })
.catch(e => {
return this.emit("error", e);
});
if (!get) return null;
return get.data;
} else {
const subkey = key.split('.').shift();
let get = await this.schema.findOne({ ID: subkey })
.catch(e => {
return this.emit("error", e);
});
if (!get) return null;
const data = key.split('.').slice(1).reduce((a, b) => a[b], get.data)
if(!data) return null;
return data;
}
}
/**
* Fetches the data from database
* @param {string} key Key
* @example db.fetch("foo").then(console.log);
*/
async fetch(key) {
return this.get(key);
}
/**
* Returns everything from the database
* @returns {Promise<Array>}
* @example let data = await db.all();
* console.log(`There are total ${data.length} entries.`);
*/
async all() {
let data = await this.schema.find().catch(e => {});
let comp = [];
data.forEach(c => {
comp.push({
ID: c.ID,
data: c.data
});
});
return comp;
}
/**
* Deletes the entire schema
* @example db.deleteAll().then(() => console.log("Deleted everything"));
*/
async deleteAll() {
this.emit("debug", "Deleting everything from the database...");
await this.schema.deleteMany().catch(e => {});
return true;
}
/**
* Math calculation
* @param {string} key Key of the data
* @param {string} operator One of +, -, * or /
* @param {number} value Value
* @example db.math("items", "+", 200).then(() => console.log("Added 200 items"));
*/
async math(key, operator, value) {
if (!Util.isKey(key)) throw new Error("Invalid key specified!", "KeyError");
if (!operator) throw new Error("No operator provided!");
if (!Util.isValue(value)) throw new Error("Invalid value specified!", "ValueError");
switch(operator) {
case "add":
case "+":
let add = await this.get(key);
if (!add) {
return this.set(key, value);
} else {
if (typeof add !== "number") throw new Error("Target is not a number!");
return this.set(key, add + value);
}
break;
case "subtract":
case "sub":
case "-":
let less = await this.get(key);
if (!less) {
return this.set(key, value);
} else {
if (typeof less !== "number") throw new Error("Target is not a number!");
return this.set(key, less - value);
}
break;
case "multiply":
case "mul":
case "*":
let mul = await this.get(key);
if (!mul) {
return this.set(key, value);
} else {
if (typeof mul !== "number") throw new Error("Target is not a number!");
return this.set(key, mul * value);
}
break;
case "divide":
case "div":
case "/":
let div = await this.get(key);
if (!div) {
return this.set(key, value);
} else {
if (typeof div !== "number") throw new Error("Target is not a number!");
return this.set(key, div / value);
}
break;
default:
throw new Error("Unknown operator");
}
}
/**
* Add
* @param {string} key key
* @param {number} value value
* @example db.add("items", 200).then(() => console.log("Added 200 items"));
*/
async add(key, value) {
return await this.math(key, "+", value);
}
/**
* Subtract
* @param {string} key Key
* @param {number} value Value
* @example db.subtract("items", 100).then(() => console.log("Removed 100 items"));
*/
async subtract(key, value) {
return await this.math(key, "-", value);
}
/**
* Returns database uptime
* @type {number}
* @example console.log(`Database is up for ${db.uptime} ms.`);
*/
get uptime() {
if (!this.readyAt) return 0;
const timestamp = this.readyAt.getTime();
return Date.now() - timestamp;
}
/**
* Exports the data to json file
* @param {string} fileName File name
* @param {string} path File path
* @returns {Promise<string>}
* @example db.export("database", "./").then(path => {
* console.log(`File exported to ${path}`);
* });
*/
export(fileName="database", path="./") {
if (typeof fileName !== "string") throw new Error("File name must be a string!");
if (typeof path !== "string") throw new Error("File path must be a string!");
return new Promise((resolve, reject) => {
this.emit("debug", `Exporting database entries to ${path}${fileName}.json`);
this.all().then((data) => {
fs.writeFileSync(`${path}${fileName}.json`, JSON.stringify(data));
this.emit("debug", `Exported all data!`);
resolve(`${path}${fileName}.json`);
}).catch(reject);
});
}
/**
* Imports data from other source to quickmongo.
*
* Data type should be Array containing `ID` and `data` fields.
* Example:
* ```js
* [{ ID: "foo", data: "bar" }, { ID: "hi", data: "hello" }]
* ```
* @param {Array} data Array of data
* @example const data = QuickDB.all(); // imports data from quick.db to quickmongo
* QuickMongo.import(data);
* @returns {Promise<Boolean>}
*/
async import(data=[]) {
if (!Array.isArray(data)) throw new Error("Data type must be Array.", "DataTypeError");
if (data.length < 1) return [];
let start = Date.now();
this.emit("debug", `Queued ${data.length} entries!`);
data.forEach((item, index) => {
if (!item.ID || typeof item.ID !== "string") {
this.emit("debug", `Found invalid entry at position ${index}, ignoring...`);
return;
};
if (typeof item.data === "undefined") {
this.emit("debug", `Found entry with data type "undefined", setting the value to "null"...`);
item.data = null;
};
this.set(item.ID, item.data);
this.emit("debug", `Successfully migrated ${item.ID} @${index}!`);
});
this.emit("debug", `Successfully migrated ${data.length}. Took ${Date.now() - start}ms!`);
return;
}
/**
* Disconnects the database
* @example db.disconnect();
*/
disconnect() {
this.emit("debug", "'database.disconnect()' was called, destroying the process...");
return this._destroyDatabase();
}
/**
* Creates database connection.
*
* You don't need to call this method because it is automatically called by database manager.
*
* @param {string} url Database url
*/
connect(url) {
return this._create(url);
}
/**
* Returns current schema name
* @readonly
*/
get name() {
return this.schema.modelName;
}
/**
* Read latency
* @ignore
*/
async _read() {
let start = Date.now();
await this.get("LQ==");
return Date.now() - start;
}
/**
* Write latency
* @ignore
*/
async _write() {
let start = Date.now();
await this.set("LQ==", Buffer.from(start.toString()).toString("base64"));
return Date.now() - start;
}
/**
* Fetches read and write latency of the database in ms
* @example const ping = await db.fetchLatency();
* console.log("Read: ", ping.read);
* console.log("Write: ", ping.write);
* console.log("Average: ", ping.average);
*/
async fetchLatency() {
let read = await this._read();
let write = await this._write();
let average = (read + write) / 2;
this.delete("LQ==").catch(e => {});
return { read, write, average };
}
/**
* Fetches read and write latency of the database in ms
* @example const ping = await db.ping();
* console.log("Read: ", ping.read);
* console.log("Write: ", ping.write);
* console.log("Average: ", ping.average);
*/
async ping() {
return await this.fetchLatency();
}
/**
* Fetches everything and sorts by given target
* @param {string} key Key
* @param {object} ops Options
* @example const data = await db.startsWith("money", { sort: ".data" });
*/
async startsWith(key, ops) {
if (!key || typeof key !== "string") throw new Error(`Expected key to be a string, received ${typeof key}`);
let all = await this.all();
return Util.sort(key, all, ops);
}
/**
* Resolves data type
* @param {string} key key
*/
async type(key) {
if (!Util.isKey(key)) throw new Error("Invalid Key!", "KeyError");
let fetched = await this.get(key);
if (Array.isArray(fetched)) return "array";
return typeof fetched;
}
/**
* Returns array of the keys
* @example const keys = await db.keyarray();
* console.log(keys);
*/
async keyArray() {
const data = await this.all();
return data.map(m => m.ID);
}
/**
* Returns array of the values
* @example const data = await db.valueArray();
* console.log(data);
*/
async valueArray() {
const data = await this.all();
return data.map(m => m.data);
}
/**
* Pushes an item into array
* @param {string} key key
* @param {any|Array} value Value to push
* @example db.push("users", "John"); // -> ["John"]
* db.push("users", ["Milo", "Simon", "Kyle"]); // -> ["John", "Milo", "Simon", "Kyle"]
*/
async push(key, value) {
const data = await this.get(key);
if (data == null) {
if (!Array.isArray(value)) return await this.set(key, [value]);
return await this.set(key, value);
}
if (!Array.isArray(data)) throw new Error(`Expected target type to be Array, received ${typeof data}!`);
if (Array.isArray(value)) return await this.set(key, data.concat(value));
data.push(value);
return await this.set(key, data);
}
/**
* Removes an item from array
* @param {string} key key
* @param {any|Array} value item to remove
* @example db.pull("users", "John"); // -> ["Milo", "Simon", "Kyle"]
* db.pull("users", ["Milo", "Simon"]); // -> ["Kyle"]
*/
async pull(key, value) {
let data = await this.get(key);
if (data === null) return false;
if (!Array.isArray(data)) throw new Error(`Expected target type to be Array, received ${typeof data}!`);
if (Array.isArray(value)) {
data = data.filter(i => !value.includes(i));
return await this.set(key, data);
} else {
data = data.filter(i => i !== value);
return await this.set(key, data);
}
}
/**
* String representation of the database
* @example console.log(`Current database: ${db}`);
*/
toString() {
return `${this.name}`;
}
/**
* Allows you to eval code using `this` keyword.
* @param {string} code code to eval
* @example
* db._eval("this.all().then(console.log)"); // -> [{ ID: "...", data: ... }, ...]
*/
_eval(code) {
return eval(code);
}
} |
JavaScript | class InitiateRecoveryRouter extends AuxWorkflowRouterBase {
/**
* Constructor for initiate recovery router.
*
* @augments AuxWorkflowRouterBase
*
* @constructor
*/
constructor(params) {
params.workflowKind = workflowConstants.initiateRecoveryKind; // Assign workflowKind.
super(params);
}
/**
* Fetch current step config for every router.
*
* @sets oThis.currentStepConfig
*
* @private
*/
_fetchCurrentStepConfig() {
const oThis = this;
oThis.currentStepConfig = initiateRecoveryConfig[oThis.stepKind];
}
/**
* Perform step.
*
* @return {Promise<*>}
* @private
*/
async _performStep() {
const oThis = this;
const configStrategy = await oThis.getConfigStrategy(),
ic = new InstanceComposer(configStrategy);
switch (oThis.stepKind) {
case workflowStepConstants.initiateRecoveryInit: {
logger.step('**********', workflowStepConstants.initiateRecoveryInit);
return oThis.insertInitStep();
}
// Perform transaction to initiate recovery.
case workflowStepConstants.initiateRecoveryPerformTransaction: {
logger.step('**********', workflowStepConstants.initiateRecoveryPerformTransaction);
require(rootPrefix + '/lib/deviceRecovery/byOwner/initiateRecovery/PerformTransaction');
oThis.requestParams.pendingTransactionExtraData = oThis._currentStepPayloadForPendingTrx();
oThis.requestParams.workflowId = oThis.workflowId;
const PerformInitiateRecoveryTransaction = ic.getShadowedClassFor(
coreConstants.icNameSpace,
'PerformInitiateRecoveryTransaction'
),
performInitiateRecoveryTransactionObj = new PerformInitiateRecoveryTransaction(oThis.requestParams);
return performInitiateRecoveryTransactionObj.perform();
}
// Verify initiate recovery transaction.
case workflowStepConstants.initiateRecoveryVerifyTransaction: {
logger.step('**********', workflowStepConstants.initiateRecoveryVerifyTransaction);
require(rootPrefix + '/lib/deviceRecovery/byOwner/initiateRecovery/VerifyTransaction');
const VerifyInitiateRecoveryTransaction = ic.getShadowedClassFor(
coreConstants.icNameSpace,
'VerifyInitiateRecoveryTransaction'
),
verifyInitiateRecoveryTransactionObj = new VerifyInitiateRecoveryTransaction(oThis.requestParams);
return verifyInitiateRecoveryTransactionObj.perform();
}
case workflowStepConstants.markSuccess: {
logger.step('*** Mark Initiate Recovery As Success.');
const preProcessorWebhookDetails = oThis.preProcessorWebhookDetails(true);
await oThis.sendPreprocessorWebhook(preProcessorWebhookDetails.chainId, preProcessorWebhookDetails.payload);
return await oThis.handleSuccess();
}
case workflowStepConstants.markFailure: {
logger.step('*** Mark Initiate Recovery As Failed');
return await oThis.handleFailure();
}
default: {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_w_dr_bo_ir_r_1',
api_error_identifier: 'something_went_wrong',
debug_options: { workflowId: oThis.workflowId }
})
);
}
}
}
/**
* Get next step configs.
*
* @param {string} nextStep
*
* @return {*}
*/
getNextStepConfigs(nextStep) {
return initiateRecoveryConfig[nextStep];
}
/**
* Get config strategy.
*
* @return {Promise<*>}
*/
async getConfigStrategy() {
const oThis = this;
const rsp = await chainConfigProvider.getFor([oThis.chainId]);
return rsp[oThis.chainId];
}
/**
* Get preprocessor webhook details.
*
* @param {boolean} status: true for success, false for failure.
*
* @returns {{chainId: *, payload: {webhookKind: string, clientId: string, tokenId: string, oldDeviceAddress: string,
* newDeviceAddress: string, userId: string}}}
*/
preProcessorWebhookDetails(status) {
const oThis = this;
return {
chainId: oThis.requestParams.auxChainId,
payload: {
webhookKind: status
? webhookSubscriptionsConstants.devicesRecoveryInitiateTopic
: webhookSubscriptionsConstants.devicesRecoveryInitiateTopic,
clientId: oThis.requestParams.clientId,
tokenId: oThis.requestParams.tokenId,
userId: oThis.requestParams.userId,
oldDeviceAddress: oThis.requestParams.oldDeviceAddress,
newDeviceAddress: oThis.requestParams.newDeviceAddress
}
};
}
} |
JavaScript | class SanityAPI {
constructor({ dataset, projectId, token }) {
this.client = sanityClient({
dataset,
projectId,
token,
useCdn: false
});
}
/**
* -----------------------------------------------------------------------------
* Determine whether an instantiated object can be used for API requests.
* @return {boolean} Validity of the class instance
*/
valid = () => {
return typeof this.client !== `undefined`;
};
/**
* -----------------------------------------------------------------------------
* Convert Shopify product data to a Sanity-compatible document JSON file.
* @return {Promise} The completion state of the document cache operation
*/
transform = (shopifyProducts, excludedHandles = []) => {
const sanityDocuments = [];
if (!shopifyProducts?.[0]) {
console.error(
`Shopify data did not contain a 'products' object. Aborting.`
);
}
shopifyProducts.forEach((shopifyProduct, shopifyProductIndex) => {
if (excludedHandles.includes(shopifyProduct.handle)) {
return;
}
//
const sanityDocument = {
_id: `shopify-import-${shopifyProduct.id.toString()}`,
_type: `product`,
title: shopifyProduct.title,
handle: shopifyProduct.handle,
description: shopifyProduct.body_html.replace(/<\/?[^>]+(>|$)/g, ``)
};
if (shopifyProduct?.image?.src) {
sanityDocument.image = {
_type: `altImage`,
_sanityAsset: `image@${shopifyProduct.image.src}`,
altText: shopifyProduct.title
};
} else if (shopifyProduct?.images?.[0]?.src) {
sanityDocument.image = {
_type: `altImage`,
_sanityAsset: `image@${shopifyProduct.images[0].src}`,
altText: shopifyProduct.title
};
}
sanityDocuments.push(sanityDocument);
});
//
const cacheFile = `${global.exportDirectory}/sanity-documents.json`;
const writeableData = sanityDocuments.map(JSON.stringify).join(`\n`);
return new Promise((resolve, reject) => {
(async () => {
try {
await fs.writeFile(cacheFile, writeableData, (err) => {
if (err) {
throw err;
}
});
} catch (e) {
reject(e);
}
resolve(sanityDocuments);
})();
});
};
/**
* -----------------------------------------------------------------------------
* Upload the resulting documents to Sanity via credentials provided.
* @return {null}
*/
upload = (documents) => {
if (!this.valid()) {
throw new Error(`Sanity Client has not yet been instantiated`);
}
if (!documents?.[0]) {
throw new Error(`Documents is not iterable`);
}
const processDocument = async (document) => {
return new Promise((resolve, reject) => {
console.log(`[info] Uploading ${document.title}...`);
try {
this.client.createIfNotExists(document).then((response) => {
// todo: something better than dumb timeouts
// if (response?.handle) {
// console.log(
// `[info] Created ${document.title} [${response.handle}]`
// );
// }
resolve(response);
});
} catch (e) {
reject(e);
}
});
};
//
// todo: something better than dumb timeouts
const promises = [];
documents.forEach((document, documentIndex) => {
setTimeout(() => {
promises.push(processDocument(document));
}, documentIndex * 500);
});
return Promise.all(promises);
//
// todo: queues..?
// const { default: PQueue } = require(`p-queue`);
// const queue = new PQueue({
// concurrency: 1,
// interval: 1000 / 25
// });
//
// ...
};
} |
JavaScript | class Order {
/**
* Constructs a new <code>Order</code>.
* Order information.
* @alias module:client/models/Order
* @class
* @param amazonOrderId {String} An Amazon-defined order identifier, in 3-7-7 format.
* @param purchaseDate {String} The date when the order was created.
* @param lastUpdateDate {String} The date when the order was last updated. Note: LastUpdateDate is returned with an incorrect date for orders that were last updated before 2009-04-01.
* @param orderStatus {module:client/models/Order.OrderStatusEnum} The current order status.
*/
constructor(amazonOrderId, purchaseDate, lastUpdateDate, orderStatus) {
this['AmazonOrderId'] = amazonOrderId;
this['PurchaseDate'] = purchaseDate;
this['LastUpdateDate'] = lastUpdateDate;
this['OrderStatus'] = orderStatus;
}
/**
* Constructs a <code>Order</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:client/models/Order} obj Optional instance to populate.
* @return {module:client/models/Order} The populated <code>Order</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Order();
if (data.hasOwnProperty('AmazonOrderId')) {
obj['AmazonOrderId'] = ApiClient.convertToType(data['AmazonOrderId'], 'String');
}
if (data.hasOwnProperty('SellerOrderId')) {
obj['SellerOrderId'] = ApiClient.convertToType(data['SellerOrderId'], 'String');
}
if (data.hasOwnProperty('PurchaseDate')) {
obj['PurchaseDate'] = ApiClient.convertToType(data['PurchaseDate'], 'String');
}
if (data.hasOwnProperty('LastUpdateDate')) {
obj['LastUpdateDate'] = ApiClient.convertToType(data['LastUpdateDate'], 'String');
}
if (data.hasOwnProperty('OrderStatus')) {
obj['OrderStatus'] = ApiClient.convertToType(data['OrderStatus'], 'String');
}
if (data.hasOwnProperty('FulfillmentChannel')) {
obj['FulfillmentChannel'] = ApiClient.convertToType(data['FulfillmentChannel'], 'String');
}
if (data.hasOwnProperty('SalesChannel')) {
obj['SalesChannel'] = ApiClient.convertToType(data['SalesChannel'], 'String');
}
if (data.hasOwnProperty('OrderChannel')) {
obj['OrderChannel'] = ApiClient.convertToType(data['OrderChannel'], 'String');
}
if (data.hasOwnProperty('ShipServiceLevel')) {
obj['ShipServiceLevel'] = ApiClient.convertToType(data['ShipServiceLevel'], 'String');
}
if (data.hasOwnProperty('OrderTotal')) {
obj['OrderTotal'] = Money.constructFromObject(data['OrderTotal']);
}
if (data.hasOwnProperty('NumberOfItemsShipped')) {
obj['NumberOfItemsShipped'] = ApiClient.convertToType(data['NumberOfItemsShipped'], 'Number');
}
if (data.hasOwnProperty('NumberOfItemsUnshipped')) {
obj['NumberOfItemsUnshipped'] = ApiClient.convertToType(data['NumberOfItemsUnshipped'], 'Number');
}
if (data.hasOwnProperty('PaymentExecutionDetail')) {
obj['PaymentExecutionDetail'] = PaymentExecutionDetailItemList.constructFromObject(data['PaymentExecutionDetail']);
}
if (data.hasOwnProperty('PaymentMethod')) {
obj['PaymentMethod'] = ApiClient.convertToType(data['PaymentMethod'], 'String');
}
if (data.hasOwnProperty('PaymentMethodDetails')) {
obj['PaymentMethodDetails'] = PaymentMethodDetailItemList.constructFromObject(data['PaymentMethodDetails']);
}
if (data.hasOwnProperty('MarketplaceId')) {
obj['MarketplaceId'] = ApiClient.convertToType(data['MarketplaceId'], 'String');
}
if (data.hasOwnProperty('ShipmentServiceLevelCategory')) {
obj['ShipmentServiceLevelCategory'] = ApiClient.convertToType(data['ShipmentServiceLevelCategory'], 'String');
}
if (data.hasOwnProperty('EasyShipShipmentStatus')) {
obj['EasyShipShipmentStatus'] = ApiClient.convertToType(data['EasyShipShipmentStatus'], 'String');
}
if (data.hasOwnProperty('CbaDisplayableShippingLabel')) {
obj['CbaDisplayableShippingLabel'] = ApiClient.convertToType(data['CbaDisplayableShippingLabel'], 'String');
}
if (data.hasOwnProperty('OrderType')) {
obj['OrderType'] = ApiClient.convertToType(data['OrderType'], 'String');
}
if (data.hasOwnProperty('EarliestShipDate')) {
obj['EarliestShipDate'] = ApiClient.convertToType(data['EarliestShipDate'], 'String');
}
if (data.hasOwnProperty('LatestShipDate')) {
obj['LatestShipDate'] = ApiClient.convertToType(data['LatestShipDate'], 'String');
}
if (data.hasOwnProperty('EarliestDeliveryDate')) {
obj['EarliestDeliveryDate'] = ApiClient.convertToType(data['EarliestDeliveryDate'], 'String');
}
if (data.hasOwnProperty('LatestDeliveryDate')) {
obj['LatestDeliveryDate'] = ApiClient.convertToType(data['LatestDeliveryDate'], 'String');
}
if (data.hasOwnProperty('IsBusinessOrder')) {
obj['IsBusinessOrder'] = ApiClient.convertToType(data['IsBusinessOrder'], 'Boolean');
}
if (data.hasOwnProperty('IsPrime')) {
obj['IsPrime'] = ApiClient.convertToType(data['IsPrime'], 'Boolean');
}
if (data.hasOwnProperty('IsPremiumOrder')) {
obj['IsPremiumOrder'] = ApiClient.convertToType(data['IsPremiumOrder'], 'Boolean');
}
if (data.hasOwnProperty('IsGlobalExpressEnabled')) {
obj['IsGlobalExpressEnabled'] = ApiClient.convertToType(data['IsGlobalExpressEnabled'], 'Boolean');
}
if (data.hasOwnProperty('ReplacedOrderId')) {
obj['ReplacedOrderId'] = ApiClient.convertToType(data['ReplacedOrderId'], 'String');
}
if (data.hasOwnProperty('IsReplacementOrder')) {
obj['IsReplacementOrder'] = ApiClient.convertToType(data['IsReplacementOrder'], 'Boolean');
}
if (data.hasOwnProperty('PromiseResponseDueDate')) {
obj['PromiseResponseDueDate'] = ApiClient.convertToType(data['PromiseResponseDueDate'], 'String');
}
if (data.hasOwnProperty('IsEstimatedShipDateSet')) {
obj['IsEstimatedShipDateSet'] = ApiClient.convertToType(data['IsEstimatedShipDateSet'], 'Boolean');
}
if (data.hasOwnProperty('IsSoldByAB')) {
obj['IsSoldByAB'] = ApiClient.convertToType(data['IsSoldByAB'], 'Boolean');
}
if (data.hasOwnProperty('AssignedShipFromLocationAddress')) {
obj['AssignedShipFromLocationAddress'] = Address.constructFromObject(data['AssignedShipFromLocationAddress']);
}
if (data.hasOwnProperty('FulfillmentInstruction')) {
obj['FulfillmentInstruction'] = FulfillmentInstruction.constructFromObject(data['FulfillmentInstruction']);
}
}
return obj;
}
/**
* An Amazon-defined order identifier, in 3-7-7 format.
* @member {String} AmazonOrderId
*/
'AmazonOrderId' = undefined;
/**
* A seller-defined order identifier.
* @member {String} SellerOrderId
*/
'SellerOrderId' = undefined;
/**
* The date when the order was created.
* @member {String} PurchaseDate
*/
'PurchaseDate' = undefined;
/**
* The date when the order was last updated. Note: LastUpdateDate is returned with an incorrect date for orders that were last updated before 2009-04-01.
* @member {String} LastUpdateDate
*/
'LastUpdateDate' = undefined;
/**
* The current order status.
* @member {module:client/models/Order.OrderStatusEnum} OrderStatus
*/
'OrderStatus' = undefined;
/**
* Whether the order was fulfilled by Amazon (AFN) or by the seller (MFN).
* @member {module:client/models/Order.FulfillmentChannelEnum} FulfillmentChannel
*/
'FulfillmentChannel' = undefined;
/**
* The sales channel of the first item in the order.
* @member {String} SalesChannel
*/
'SalesChannel' = undefined;
/**
* The order channel of the first item in the order.
* @member {String} OrderChannel
*/
'OrderChannel' = undefined;
/**
* The shipment service level of the order.
* @member {String} ShipServiceLevel
*/
'ShipServiceLevel' = undefined;
/**
* @member {module:client/models/Money} OrderTotal
*/
'OrderTotal' = undefined;
/**
* The number of items shipped.
* @member {Number} NumberOfItemsShipped
*/
'NumberOfItemsShipped' = undefined;
/**
* The number of items unshipped.
* @member {Number} NumberOfItemsUnshipped
*/
'NumberOfItemsUnshipped' = undefined;
/**
* @member {module:client/models/PaymentExecutionDetailItemList} PaymentExecutionDetail
*/
'PaymentExecutionDetail' = undefined;
/**
* The payment method for the order. This property is limited to Cash On Delivery (COD) and Convenience Store (CVS) payment methods. Unless you need the specific COD payment information provided by the PaymentExecutionDetailItem object, we recommend using the PaymentMethodDetails property to get payment method information.
* @member {module:client/models/Order.PaymentMethodEnum} PaymentMethod
*/
'PaymentMethod' = undefined;
/**
* @member {module:client/models/PaymentMethodDetailItemList} PaymentMethodDetails
*/
'PaymentMethodDetails' = undefined;
/**
* The identifier for the marketplace where the order was placed.
* @member {String} MarketplaceId
*/
'MarketplaceId' = undefined;
/**
* The shipment service level category of the order. Possible values: Expedited, FreeEconomy, NextDay, SameDay, SecondDay, Scheduled, Standard.
* @member {String} ShipmentServiceLevelCategory
*/
'ShipmentServiceLevelCategory' = undefined;
/**
* The status of the Amazon Easy Ship order. This property is included only for Amazon Easy Ship orders. Possible values: PendingPickUp, LabelCanceled, PickedUp, OutForDelivery, Damaged, Delivered, RejectedByBuyer, Undeliverable, ReturnedToSeller, ReturningToSeller.
* @member {String} EasyShipShipmentStatus
*/
'EasyShipShipmentStatus' = undefined;
/**
* Custom ship label for Checkout by Amazon (CBA).
* @member {String} CbaDisplayableShippingLabel
*/
'CbaDisplayableShippingLabel' = undefined;
/**
* The type of the order.
* @member {module:client/models/Order.OrderTypeEnum} OrderType
*/
'OrderType' = undefined;
/**
* The start of the time period within which you have committed to ship the order. In ISO 8601 date time format. Returned only for seller-fulfilled orders. Note: EarliestShipDate might not be returned for orders placed before February 1, 2013.
* @member {String} EarliestShipDate
*/
'EarliestShipDate' = undefined;
/**
* The end of the time period within which you have committed to ship the order. In ISO 8601 date time format. Returned only for seller-fulfilled orders. Note: LatestShipDate might not be returned for orders placed before February 1, 2013.
* @member {String} LatestShipDate
*/
'LatestShipDate' = undefined;
/**
* The start of the time period within which you have committed to fulfill the order. In ISO 8601 date time format. Returned only for seller-fulfilled orders.
* @member {String} EarliestDeliveryDate
*/
'EarliestDeliveryDate' = undefined;
/**
* The end of the time period within which you have committed to fulfill the order. In ISO 8601 date time format. Returned only for seller-fulfilled orders that do not have a PendingAvailability, Pending, or Canceled status.
* @member {String} LatestDeliveryDate
*/
'LatestDeliveryDate' = undefined;
/**
* When true, the order is an Amazon Business order. An Amazon Business order is an order where the buyer is a Verified Business Buyer.
* @member {Boolean} IsBusinessOrder
*/
'IsBusinessOrder' = undefined;
/**
* When true, the order is a seller-fulfilled Amazon Prime order.
* @member {Boolean} IsPrime
*/
'IsPrime' = undefined;
/**
* When true, the order has a Premium Shipping Service Level Agreement. For more information about Premium Shipping orders, see \"Premium Shipping Options\" in the Seller Central Help for your marketplace.
* @member {Boolean} IsPremiumOrder
*/
'IsPremiumOrder' = undefined;
/**
* When true, the order is a GlobalExpress order.
* @member {Boolean} IsGlobalExpressEnabled
*/
'IsGlobalExpressEnabled' = undefined;
/**
* The order ID value for the order that is being replaced. Returned only if IsReplacementOrder = true.
* @member {String} ReplacedOrderId
*/
'ReplacedOrderId' = undefined;
/**
* When true, this is a replacement order.
* @member {Boolean} IsReplacementOrder
*/
'IsReplacementOrder' = undefined;
/**
* Indicates the date by which the seller must respond to the buyer with an estimated ship date. Returned only for Sourcing on Demand orders.
* @member {String} PromiseResponseDueDate
*/
'PromiseResponseDueDate' = undefined;
/**
* When true, the estimated ship date is set for the order. Returned only for Sourcing on Demand orders.
* @member {Boolean} IsEstimatedShipDateSet
*/
'IsEstimatedShipDateSet' = undefined;
/**
* When true, the item within this order was bought and re-sold by Amazon Business EU SARL (ABEU). By buying and instantly re-selling your items, ABEU becomes the seller of record, making your inventory available for sale to customers who would not otherwise purchase from a third-party seller.
* @member {Boolean} IsSoldByAB
*/
'IsSoldByAB' = undefined;
/**
* @member {module:client/models/Address} AssignedShipFromLocationAddress
*/
'AssignedShipFromLocationAddress' = undefined;
/**
* @member {module:client/models/FulfillmentInstruction} FulfillmentInstruction
*/
'FulfillmentInstruction' = undefined;
/**
* Allowed values for the <code>OrderStatus</code> property.
* @enum {String}
* @readonly
*/
static OrderStatusEnum = {
/**
* value: "Pending"
* @const
*/
"Pending": "Pending",
/**
* value: "Unshipped"
* @const
*/
"Unshipped": "Unshipped",
/**
* value: "PartiallyShipped"
* @const
*/
"PartiallyShipped": "PartiallyShipped",
/**
* value: "Shipped"
* @const
*/
"Shipped": "Shipped",
/**
* value: "Canceled"
* @const
*/
"Canceled": "Canceled",
/**
* value: "Unfulfillable"
* @const
*/
"Unfulfillable": "Unfulfillable",
/**
* value: "InvoiceUnconfirmed"
* @const
*/
"InvoiceUnconfirmed": "InvoiceUnconfirmed",
/**
* value: "PendingAvailability"
* @const
*/
"PendingAvailability": "PendingAvailability" };
/**
* Allowed values for the <code>FulfillmentChannel</code> property.
* @enum {String}
* @readonly
*/
static FulfillmentChannelEnum = {
/**
* value: "MFN"
* @const
*/
"MFN": "MFN",
/**
* value: "AFN"
* @const
*/
"AFN": "AFN" };
/**
* Allowed values for the <code>PaymentMethod</code> property.
* @enum {String}
* @readonly
*/
static PaymentMethodEnum = {
/**
* value: "COD"
* @const
*/
"COD": "COD",
/**
* value: "CVS"
* @const
*/
"CVS": "CVS",
/**
* value: "Other"
* @const
*/
"Other": "Other" };
/**
* Allowed values for the <code>OrderType</code> property.
* @enum {String}
* @readonly
*/
static OrderTypeEnum = {
/**
* value: "StandardOrder"
* @const
*/
"StandardOrder": "StandardOrder",
/**
* value: "LongLeadTimeOrder"
* @const
*/
"LongLeadTimeOrder": "LongLeadTimeOrder",
/**
* value: "Preorder"
* @const
*/
"Preorder": "Preorder",
/**
* value: "BackOrder"
* @const
*/
"BackOrder": "BackOrder",
/**
* value: "SourcingOnDemandOrder"
* @const
*/
"SourcingOnDemandOrder": "SourcingOnDemandOrder" };
} |
JavaScript | class AccessPolicyEntry {
/**
* Create a AccessPolicyEntry.
* @member {uuid} tenantId The Azure Active Directory tenant ID that should
* be used for authenticating requests to the key vault.
* @member {string} objectId The object ID of a user, service principal or
* security group in the Azure Active Directory tenant for the vault. The
* object ID must be unique for the list of access policies.
* @member {uuid} [applicationId] Application ID of the client making request
* on behalf of a principal
* @member {object} permissions Permissions the identity has for keys,
* secrets and certificates.
* @member {array} [permissions.keys] Permissions to keys
* @member {array} [permissions.secrets] Permissions to secrets
* @member {array} [permissions.certificates] Permissions to certificates
* @member {array} [permissions.storage] Permissions to storage accounts
*/
constructor() {
}
/**
* Defines the metadata of AccessPolicyEntry
*
* @returns {object} metadata of AccessPolicyEntry
*
*/
mapper() {
return {
required: false,
serializedName: 'AccessPolicyEntry',
type: {
name: 'Composite',
className: 'AccessPolicyEntry',
modelProperties: {
tenantId: {
required: true,
serializedName: 'tenantId',
type: {
name: 'String'
}
},
objectId: {
required: true,
serializedName: 'objectId',
type: {
name: 'String'
}
},
applicationId: {
required: false,
serializedName: 'applicationId',
type: {
name: 'String'
}
},
permissions: {
required: true,
serializedName: 'permissions',
type: {
name: 'Composite',
className: 'Permissions'
}
}
}
}
};
}
} |
JavaScript | class SelecFieldLong extends Component {
state = {
value: 10,
};
handleChange = (event, index, value) => {
this.setState({value});
};
render() {
return (
<SelectField
value={this.state.value}
onChange={this.handleChange}
maxHeight={200}
>
{items}
</SelectField>
);
}
} |
JavaScript | class Line {
constructor(text, markedSpans, estimateHeight) {
this.text = text
attachMarkedSpans(this, markedSpans)
this.height = estimateHeight ? estimateHeight(this) : 1
}
lineNo() { return lineNo(this) }
} |
JavaScript | class TraktError extends Error {
constructor(err, resource, params = {}, status) {
super(
`${resource}(${Object.keys(params)
.map(key => `${key}: ${params[key]}`)
.join(', ')})${status ? ` [${status}]` : ''} failed: ${err}`
)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, TraktError)
}
this.name = 'TraktError'
this.status = status
}
} |
JavaScript | class DirectiveNodeHandlerInclude extends DirectiveNodeHandlerAdapter_1.DirectiveNodeHandlerAdapter {
constructor(util, settings) {
super('include', util, settings);
}
handle(directiveContext, convertContext) {
const val = this.getDirectiveConditionalValue(directiveContext.directive, convertContext);
if (val.termType === 'Literal' && val.value === 'false') {
return { ignore: true };
}
return {};
}
} |
JavaScript | class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
// If we want the sidebar to toggle on/off and on the side of the screen instead of on top, we
// can add these back into the render()
handleToggle = () => this.setState({open: !this.state.open});
render() {
return (
<MuiThemeProvider>
<div>
<a onClick={this.props.toggleDemo}><MenuItem><FlatButton>Home</FlatButton></MenuItem></a>
<MenuItem onClick={this.handleToggle}>
<DialogBox>
<FileUploader handleUploadComplete={this.props.handleUploadComplete} />
</DialogBox>
</MenuItem>
</div>
</MuiThemeProvider>
);
}
} |
JavaScript | class DealScene extends BaseScene {
/**
*Creates an instance of DealScene.
* @memberof DealScene
*/
constructor() {
super(CONSTANTS.Scenes.Keys.Deal);
}
/**
* Initializatin data.
*
* @param {*} data
* @memberof DealScene
*/
init(data) {
this.blackjack = data;
}
/**
* creates a card object.
*
* @param {*} index
* @param {boolean} [flipped=false]
* @param {*} [player=null]
* @returns
* @memberof DealScene
*/
createCardObject(index, flipped = false, player = null) {
let model = this.getCardModel(player, flipped);
let pos = this.grid.getIndexPos(7);
let cardSprite = new Card(this, model).setPosition(pos.x, pos.y);
this.cardsOnTable.add(cardSprite);
return {
card: cardSprite.setVisible(false),
position: this.grid.getIndexPos(index)
}
}
/**
* gets a card model using the dealers deck and returns it.
*
* @param {*} player
* @param {*} flipped
* @returns
* @memberof DealScene
*/
getCardModel(player, flipped) {
try {
if (player)
return this.blackjack.dealer.deal(player);
else
return this.blackjack.dealer.draw(flipped);
} catch (e) {
console.log(e);
switch (e) {
case "Empty deck":
this.reshuffleSound.play();
this.fadeReshufflingText("in", () => this.fadeReshufflingText("out"));
this.blackjack.dealer.reshuffle();
return this.getCardModel(player, flipped);
default:
throw (e);
}
}
}
/**
* Create a tween for the given card.
*
* @param {*} card
* @param {*} onComplete
* @returns
* @memberof DealScene
*/
createTween(card, onComplete) {
return {
targets: card.card,
ease: 'Cubic',
duration: 300,
x: card.position.x,
y: card.position.y,
onComplete: onComplete,
onStart: () => {
card.card.setVisible(true);
card.card.place();
},
};
}
/**
* Create components in the scene.
*
* @memberof DealScene
*/
create() {
super.create(() => {
this.clearCardsSound = this.sound.add('clear_cards');
this.reshuffleSound = this.sound.add('shuffling');
this.cardsOnTable = this.add.group('cardsOnTable');
this.createTextComponents();
this.scene.launch(CONSTANTS.Scenes.Keys.PlayerPlay, this.blackjack);
});
}
/**
* Creates all of the text components.
*
* @memberof DealScene
*/
createTextComponents() {
this.playerScore = new Text(this, "0").setVisible(false);
this.dealerScore = new Text(this, "0").setVisible(false);
this.reshufflingText = new Text(this, "Reshuffling...").setVisible(false).setAlpha(0);
this.grid.placeAtIndex(184, this.playerScore);
this.grid.placeAtIndex(79, this.dealerScore);
this.grid.placeAtIndex(22, this.reshufflingText);
}
/**
* Flips the dealer's down card and updates its score.
*
* @memberof DealScene
*/
flipDealersDownCard() {
this.blackjack.dealer.flipDownCard();
this.blackjack.dealer.setDirty(true);
this.dealersDownCard.card.flip();
this.updateDealerScore();
}
/**
* Fades's the reshuffling text.
*
* @param {*} type
* @param {*} onComplete
* @memberof DealScene
*/
fadeReshufflingText(type, onComplete) {
this.tweens.add({
targets: this.reshufflingText,
duration: 500,
alpha: type == "out" ? 0 : 1,
onStart: type == "in" ? () => this.reshufflingText.setVisible(true) : null,
yoyo: true,
repeat: 1,
})
}
/**
* Creats the first 4 cards dealt at the beginning of the round.
*
* @memberof DealScene
*/
createInitialCards() {
this.playerIndex = 186;
this.dealerIndex = 81;
this.playersFirstCard = this.createCardObject(this.playerIndex++, false, this.blackjack.player);
this.dealersUpCard = this.createCardObject(this.dealerIndex++, true);
this.playersSecondCard = this.createCardObject(this.playerIndex++, false, this.blackjack.player);
this.dealersDownCard = this.createCardObject(this.dealerIndex++, false);
}
/**
* Starts the dealing of the cards.
*
* @memberof DealScene
*/
startDeal() {
this.createInitialCards();
this.fadeScoreText("in");
this.animateCardsToTable();
}
/**
* Animates the initial cards to the table.
*
* @memberof DealScene
*/
animateCardsToTable() {
this.tweens.timeline({
tweens: [
this.createTween(this.playersFirstCard,
() => this.updatePlayerScore()),
this.createTween(this.dealersUpCard,
() => this.updateDealerScore()),
this.createTween(this.playersSecondCard,
() => this.updatePlayerScore()),
this.createTween(this.dealersDownCard,
() => this.updateDealerScore())
],
onStart: () => this.setScoreVisibility(true),
onComplete: () => this.handleCardsDealt()
});
}
/**
* Sets the player and dealer's score text visibility.
*
* @param {*} visibility
* @memberof DealScene
*/
setScoreVisibility(visibility) {
this.playerScore.setVisible(visibility);
this.dealerScore.setVisible(visibility);
}
/**
* Prepares the scene for a new round.
*
* @param {*} onComplete
* @memberof DealScene
*/
prepareForNewRound() {
let position = this.grid.getIndexPos(7);
let bettingScene = this.scene.get(CONSTANTS.Scenes.Keys.Betting);
this.tweens.add({
targets: this.cardsOnTable.getChildren(),
x: position.x,
y: position.y - this.game.config.height / 2,
duration: 500,
delay: this.tweens.stagger(50),
onStart: (_, cards) => {
cards.forEach(card => {
if (card.model.visible) card.flip();
});
this.clearCardsSound.play();
this.fadeScoreText("out");
this.blackjack.dealer.resetHand();
this.blackjack.player.resetHand();
},
onComplete: (_, cardsOnTable) => {
cardsOnTable.forEach(card => this.cardsOnTable.remove(card, true, true));
bettingScene.fadeChips("in");
this.tweens.add({
targets: bettingScene.pot.getChildren(),
duration: 500,
alpha: 0,
onComplete: () => {
if (this.blackjack.player.money > 0) {
bettingScene.prepareForBetting()
} else {
let gameScene = this.scene.get(CONSTANTS.Scenes.Keys.Game);
setTimeout(() => gameScene.goToMenuScene(), 1000);
}
}
});
}
});
}
/**
*
*
* @param {*} type
* @memberof DealScene
*/
fadeScoreText(type) {
this.tweens.add({
onStart: type == "in" ? () => this.setScoreVisibility(true) : null,
targets: [
this.playerScore, this.dealerScore
],
duration: 1000,
alpha: type == "out" ? 0 : 1,
ease: "Linear",
onComplete: type == "out" ? () => this.setScoreVisibility(false) : null
});
}
/**
* Callback function for when the cards are finished being laid down.
*
* @memberof DealScene
*/
handleCardsDealt() {
let playScene = this.scene.get(CONSTANTS.Scenes.Keys.PlayerPlay);
this.tweens.add({
targets: [
playScene.hitButton.setInteractive(true),
playScene.standButton.setInteractive(true)
],
onStart: () => playScene.play(),
alpha: 1,
ease: 'Cubic'
})
}
/**
* Updates the player's score text.
*
* @memberof DealScene
*/
updatePlayerScore() {
this.playerScore.setText(this.blackjack.player.hand.getTotal());
}
/**
* Update's the dealer's score text.
*
* @memberof DealScene
*/
updateDealerScore() {
this.dealerScore.setText(this.blackjack.dealer.hand.getTotal());
}
} |
JavaScript | class CA extends Component {
state = {
name: "",
mail: "",
col: "",
mobnum: "",
pass: "",
msg: "",
dob: "DD/MM/YYYY",
};
handleChange = ({ target }) => {
const { name, value } = target;
this.setState({ [name]: value });
};
submit = (event) => {
event.preventDefault();
axios
.post("/api/ca/register/", {
email: this.state.mail,
name: this.state.name,
phone: this.state.mobnum,
password: this.state.pass,
college: this.state.col,
dob: this.state.dob,
})
.then(() => {
console.log("Data has been sent to the server");
this.setState({ msg: "CA Registration was succesfull" });
this.resetUserInputs();
})
.catch(() => {
this.setState({ msg: "Please check your details" });
console.log("Internal server error");
});
};
resetUserInputs = () => {
this.setState({
name: "",
mail: "",
col: "",
mobnum: "",
pass: "",
dob: "",
});
};
render() {
console.log("State: ", this.state);
return (
<div>
<Navbar />
<div className="ca">
{/* home section */}
{/*<div>
<img
src={require("../../assets/img/astronaut.png")}
alt=""
className="astronaut1"
/>
</div>*/}
<div id="homeSection" className="homes">
<h1 className="display-3 main-headline">
CELESTA'20 Campus Ambassador Program
</h1>
<p className="abt-headline">
Indian Institute Of Technology Patna is bringing forward it’s very
own techno-management fest, <strong>CELESTA-20</strong>. Be the
face of the innovation in your college. Inspire your friends to
take part in the exciting events, be the leader!!
</p>
<br />
{/* <a href="#register" className="btn btn-outline-dark register-btn">
{" "}
Register Now{" "}
</a> */}
<Link to="/register-page">
<Button
className="btn-round"
color="primary"
size="lg"
>
Normal Registration
</Button>
</Link>
</div>
{/* home section ends here */}
{/* features start here */}
<div id="features" className="features-x">
<h1 className="display-3 features-headline">Why Become the CA?</h1>
<br />
<div className="container">
<div className="row">
<div className="col-md-4 benefit-cards">
<img
src={require("../../assets/img/skills.jpg")}
className="img-resp"
/>
<br />
<h4 className="display-5 ben-heading">Skill Improvement</h4>
<p className="about-tbl">
It will help you to improve your managerial as well as
communication skills.
</p>
</div>
<div className="col-md-4 benefit-cards">
<img
src={require("../../assets/img/networks.jpg")}
className="img-resp"
/>
<br />
<h4 className="display-5 ben-heading">Networking</h4>
<p className="about-tbl">
By communicating with many people it will increase your
contacts which will help you in future.
</p>
</div>
<div className="col-md-4 benefit-cards">
<img
src={require("../../assets/img/recognition.jpg")}
className="img-resp"
/>
<br />
<h4 className="display-5 ben-heading">Recognition</h4>
<p className="about-tbl">
You are getting to represent your college at a higher level.
</p>
</div>
</div>
</div>
<br />
</div>
{/* features ends here */}
{/* registration section start here */}
<div id="register" className="register-x">
<h1 className="display-3 register-headline">
{/* Hurry Up and Register Yourself! */}
</h1>
<br />
<br />
{/* <div className="form-registration">
<div className="card card-x">
<div className="card-body card-bodyx">
<form onSubmit={this.submit}>
<h1>{this.state.msg}</h1>
<div className="form-group" style={{ fontSize: "20px" }}>
<label className="form-label" htmlFor="identityName">
Name
</label>
<input
type="text"
name="name"
className="form-control"
id="identityName"
value={this.state.name}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group" style={{ fontSize: "20px" }}>
<label className="form-label" htmlFor="identityName">
Date of birth
</label>
<input
type="text"
name="dob"
className="form-control"
id="identityName"
value={this.state.dob}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label className="form-label" htmlFor="inputEmail">
Email Address
</label>
<input
type="email"
name="mail"
className="form-control"
id="inputEmail"
value={this.state.mail}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label className="form-label" htmlFor="mobileNum">
Mobile Number
</label>
<input
type="text"
name="mobnum"
className="form-control"
id="mobileNum"
pattern="^\d{10}$"
value={this.state.mobnum}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label className="form-label" htmlFor="colgName">
College/University Name
</label>
<input
type="text"
name="col"
className="form-control"
id="colgName"
value={this.state.col}
onChange={this.handleChange}
required
/>
</div>
<div className="form-group">
<label className="form-label" htmlFor="pwd">
Password
</label>
<input
type="password"
name="pass"
className="form-control"
id="pwd"
value={this.state.pass}
onChange={this.handleChange}
required
/>
</div>
<br />
<button className="btn btn-register btn-lg btn-block">
Register!
</button>
</form>
</div>
</div>
</div> */}
</div>
{/* end of registration section here */}
<Footer/>
</div>
<CustomizedSnackbars
type="info"
component={
<a>
Campus Ambassador Registrations are now closed!
</a>
}
/>
</div>
);
}
} |
JavaScript | class User {
constructor(username, friendly_name) {
this.name = friendly_name;
this.username = username;
}
} |
JavaScript | class ApplicationListenerCertificate extends core_1.Construct {
/**
* @stability stable
*/
constructor(scope, id, props) {
super(scope, id);
if (!props.certificateArns && !props.certificates) {
throw new Error('At least one of \'certificateArns\' or \'certificates\' is required');
}
const certificates = [
...(props.certificates || []).map(c => ({ certificateArn: c.certificateArn })),
...(props.certificateArns || []).map(certificateArn => ({ certificateArn })),
];
new elasticloadbalancingv2_generated_1.CfnListenerCertificate(this, 'Resource', {
listenerArn: props.listener.listenerArn,
certificates,
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.