text
stringlengths 7
3.69M
|
|---|
/*
* @file i am a file description
* @author: lao niubi
* @date: 2018-12-27
*/
import {serverWindows} from '../util/env'
import {
detectIE
} from './detect-browser'
export function offset(el) {
if (el && el.length) {
el = el[0];
}
if (el && el.getBoundingClientRect) {
let obj = el.getBoundingClientRect();
return {
left: obj.left + serverWindows.pageXOffset,
top: obj.top + serverWindows.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
} else {
return {
left: 0,
top: 0,
width: 0,
height: 0
}
}
}
export function isVisible(el, postion) {
let elOffset = offset(el);
postion = postion || {};
let section = {
left: postion.left || 0,
right: postion.right || serverWindows.innerWidth,
top: postion.top || scrollTop(document.body),
bottom: postion.bottom || scrollTop(document.body) + serverWindows.innerHeight
};
if(elOffset.left >= section.left && elOffset.left < section.right && elOffset.top >= section.top && elOffset.top < section.bottom) {
return true;
} else {
return false;
}
}
export function bindScrollEnd(callback) {
let cache = bindScrollEnd;
if (!serverWindows.addEventListener) {
return
}
serverWindows.addEventListener('scroll', function() {
const _scrollTop = scrollTop(document.body) + serverWindows.pageYOffset;
if (cache.timer) {
clearTimeout(cache.timer);
}
if (cache.scrollTop !== _scrollTop) {
cache.scrollTop = _scrollTop;
cache.timer = setTimeout(function(){
callback()
}, 0);
} else {
callback()
}
});
}
/**
* 获取相对于body的相对偏移
* @param {HTMLElement|Window} Node DOM元素
* @param {number} [value] scrollTop值
* @return {number|HTMLElement|Window}
*/
export function scrollTop(Node, value) {
const doc = document, body = doc.body, win = window, docEl = doc.documentElement;
if (value === undefined) {
if (Node === body || Node === win || Node === docEl) {
return doc.documentElement.scrollTop + body.scrollTop;
}
const hasScrollTop = 'scrollTop' in Node;
return hasScrollTop ? Node['scrollTop'] : Node['pageYOffset'];
}
let scrollElement;
if (Node === body || Node === win || Node === docEl) {
doc.documentElement.scrollTop = value;
body.scrollTop = value;
return Node;
} else if (Node === body || Node === win) {
scrollElement = body;
} else {
scrollElement = Node;
}
scrollElement['scrollTop'] = value;
return Node;
}
/**
*
* @param {HTMLElement|Window} el
* @param {string} className
* @return {boolean}
*/
export function hasClass(el, className) {
return el.className && new RegExp('(^|\\s)' + className + '(\\s|$)').test(el.className);
}
|
var fs = require('fs');
var path = require('path');
var mime = require('mime');
exports.serveStatic = serveStatic;
exports.sendFile = sendFile;
exports.send404 = send404;
function serveStatic(res, cache, absPath) {
if (cache[absPath]) {
sendFile(res, absPath, cache[absPath]);
} else {
fs.exists(absPath, function (exists) {
if (exists) {
fs.readFile(absPath, function (err, data) {
if (err) {
send404(res);
} else {
cache[absPath] = data;
sendFile(res, absPath, data);
}
});
} else {
send404(res);
}
});
}
}
function sendFile(res, filePath, fileContents) {
res.writeHead(200, { 'Content-Type': mime.lookup(path.basename(filePath)) });
res.end(fileContents);
}
function send404(res) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.write("错误404,您请求的资源无法找到!");
res.end();
}
|
/* @flow */
/* **********************************************************
* File: containers/AppContainer.js
*
* Brief: Top level container for the application
*
* Authors: Craig Cheney
*
* 2017.10.10 CC - Document created
*
********************************************************* */
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import App from '../components/App';
import { showUserSettings } from '../actions/appWideActions';
function mapStateToProps(state) {
return {
developer: state.appWide.userSettings.developer
};
}
/* Action creators to be used in the component */
const mapDispatchToProps = (dispatcher: *) => bindActionCreators({
showUserSettings
}, dispatcher);
export default connect(mapStateToProps, mapDispatchToProps)(App);
/* [] - END OF FILE */
|
// VARIABLES:
const gifsUrl = "http://localhost:3000/api/v1/gifs"
const ulTag = document.querySelector('#pandas')
const pandaDiv = document.querySelector('#gif-detail')
const likeComment = document.querySelector('#like-comment')
const commentList = document.querySelector('#comments-list')
//-----
// FUNCTIONS:
function gifsList(gif) {
return `
<li id="gif" data-id=${gif.id}>
<br>
<img src="${gif.img_url}" width="30" height="30">
</li>
`
};
function displayDancingPanda(gifObj) {
pandaDiv.dataset.id = gifObj.data.id
return `
<h2 data-id="${gifObj.data.id}">${gifObj.data.name}</h2>
<img class="featured-gif" src="${gifObj.data.img_url}">
<audio controls loop id="song" src="sounds/${gifObj.data.music}"></audio>
<button type="button">Rate my moves!</button>
`
};
function displayLikesAndComments(gifObj) {
return `
<button class='btn-like' data-id=${gifObj.data.id}><3 Likes: <span>${gifObj.data.likes}</span></button>
<button class='btn-comment' data-id=${gifObj.data.id}>Add Comment</button>
`
};
const creatingGifCommentHTML = (gif_id) => {
return `
<form data-id='${gif_id}'>First Name:<br>
<input type="text" name="firstname" placeholder="name"><br>
Comment:<br>
<input type="text" name="comment" placeholder="comment"><br><br>
<input type="submit" value="Submit">
</form>`
} // Do you mind if we change from First name to Name so the user can put in any name?
function createCommentListItem(comment) {
// return `<li ${comment.id}>`
return `
<li class='comment-list-item' data-id=${comment.id}>
<p class="mb-0">${comment.comment}</p>
<footer class="blockquote-footer">${comment.name}</footer>
</li>
`
};
function getPanda(id) {
return fetch(gifsUrl + '/' + id)
.then(resp => resp.json())
};
function updateLikes(id, currentLikes) {
// debugger
const fetchObj = {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
likes: currentLikes
})
};
return fetch(gifsUrl + '/' + id, fetchObj)
};
function playSound(e) {
const audio = document.querySelector('#song')
if(!audio) return;
audio.currentTime = 0
audio.play();
// key.classList.add('playing');
};
//-----
// EVENT LISTENERS:
ulTag.addEventListener('click', e => {
const pandaGIF = e.target
const liTag = pandaGIF.parentElement
const likeComment = pandaDiv.parentElement.parentElement.querySelector('#like-comment')
if (pandaGIF.parentElement.id === "gif") {
getPanda(liTag.dataset.id)
.then(gifObj => {
if (!!gifObj) {
pandaDiv.dataset.id = liTag.dataset.id
pandaDiv.innerHTML = displayDancingPanda(gifObj)
playSound()
likeComment.innerHTML = displayLikesAndComments(gifObj)
}
})
}
});
likeComment.addEventListener('click', e => {
if (e.target.className === 'btn-like') {
let likeButton = e.target
let likesOnTheDom = e.target.querySelector('span');
let currentLikes = parseInt(e.target.querySelector('span').innerText) + 1
updateLikes(likeButton.dataset.id, currentLikes)
.then(resp => {
if (resp.ok) {
likesOnTheDom.innerText = currentLikes
}
})
} else if(e.target.className === 'btn-comment') {
let commentButton = e.target
let likeCommentDiv = e.target.parentElement
// let gif_id = pandaDiv.dataset.id
likeCommentDiv.innerHTML += creatingGifCommentHTML(commentButton.dataset.id)
// stops playing sound so added this in the bottom need to fix
// also makes multiple forms
const gifCommentFormTag = document.querySelector('form')
gifCommentFormTag.addEventListener('submit', event => {
event.preventDefault()
let form = event.target
let name = event.target.firstname.value
let comment = event.target.comment.value
addingCommentsToBackEnd(name, comment, form.dataset.id)
.then(commentObj => {
if (!!commentObj) {
if (commentObj.gif_id) {
debugger
commentList.innerHTML += createCommentListItem(commentObj)
}
}
})
// debugger
// pandaDiv.innerHTML += `<h3>${comment} said ${name}</h3>`
// Creatig an object with a null ID and and null gif_ID need to fix.
// also when adding another comment the submit button refreshed the page.
// playSound()
})
// playSound()
}
})
// pandaDiv.addEventListener('click', event => {
// // debugger
// if(event.target.tagName === 'BUTTON') {
// let gif_id = pandaDiv.dataset.id
// pandaDiv.innerHTML += creatingGifCommentHTML(gif_id)
// // stops playing sound so added this in the bottom need to fix
// // also makes multiple forms
// const gifCommentFormTag = document.querySelector('form')
// gifCommentFormTag.addEventListener('submit', event => {
// event.preventDefault()
// let name = event.target.firstname.value
// let comment = event.target.comment.value
// addingCommentsToBackEnd(name, comment, gif_id).then(console.log)
// pandaDiv.innerHTML += `<h3>${comment} said ${name}</h3>`
// // Creatig an object with a null ID and and null gif_ID need to fix.
// // also when adding another comment the submit button refreshed the page.
// playSound()
// })
// playSound()
// }
// })
//-----
// adding comment form to button and fetching from comments
const addingCommentsToBackEnd = (name, comment, gif_id) => {
return fetch(`http://localhost:3000/api/v1/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
name: name,
comment: comment,
gif_id: gif_id
})
})
.then(res => res.json())
};
//-----
// GETs gifs:
fetch(gifsUrl)
.then(resp => resp.json())
.then(gifs => {
// console.log(gifs)
gifs.data.forEach(gif => {
ulTag.innerHTML += gifsList(gif)
})
})
//-----
|
const movPag = document.querySelector(".movPag");
const btn_adelante2 = document.querySelector(".sigPag");
const btn_atras1 = document.querySelector(".volver-pagina-1");
const btn_adelante3 = document.querySelector("adelante-pagina-3");
const btn_atras2 = document.querySelector(".volver-pagina-2");
const btn_adelante4 = document.querySelector(".adelante-pagina-4");
const btn_atras3 = document.querySelector(".volver-pagina-3");
const btn_final = document.querySelector(".fin");
btn_adelante2.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-25%;"
});
btn_adelante3.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-25%;"
});
btn_adelante4.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-25%;"
});
btn_final.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-25%;"
alert ("Aqui finaliza el registro.");
});
btn_atras1.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-0%;"
});
btn_atras2.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-25%;"
alert ("Aqui finaliza el registro.");
});
btn_atras3.addEventListener("click", function(e) {
e.preventDefault();
movPag.style.marginLeft = "-50%;"
alert ("Aqui finaliza el registro.");
});
|
import React, { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Alert from '../shared/Alert.jsx';
import CancelBuildButton from '../shared/branch-build/CancelBuildButton.jsx';
import BuildTriggerLabel from './shared/BuildTriggerLabel.jsx';
const PendingBranchBuildsAlert = ({branchBuild, onCancelBuild}) => {
const id = branchBuild.get('id');
const buildNumber = branchBuild.get('buildNumber');
return (
<Alert className="pending-branch-build-alert" type="info" key={id}>
<div className="pending-branch-build-alert__content">
<span className="pending-branch-build-alert__build-number">#{buildNumber}</span>
<BuildTriggerLabel buildTrigger={branchBuild.get('buildTrigger')} />
<span className="pending-branch-build-alert__build-state">
is pending
</span>
<CancelBuildButton
onCancel={onCancelBuild}
build={branchBuild.toJS()}
btnSize="xs"
btnStyle="link"
btnClassName="cancel-build-button-link"
/>
</div>
</Alert>
);
};
PendingBranchBuildsAlert.propTypes = {
branchBuild: ImmutablePropTypes.mapContains({
id: PropTypes.number.isRequired,
buildNumber: PropTypes.number.isRequired,
buildTrigger: ImmutablePropTypes.map.isRequired
}),
onCancelBuild: PropTypes.func.isRequired
};
export default PendingBranchBuildsAlert;
|
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
export default class daysOfWeekNav extends React.Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-light">
<ul id="navbarNavAltMarkup" className="d-flex flex-row navbar-nav mx-auto">
<li className="nav-item">
<a
className="nav-item nav-link text-dark SundayLink"
onClick={e => {this.props.handleClick("Sunday");}}
href="#"
title="Go to Sunday gyms"
>
Sun
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark MondayLink"
onClick={e => {this.props.handleClick("Monday");}}
href="#"
title="Go to Monday gyms"
>
Mon
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark TuesdayLink"
onClick={e => {this.props.handleClick("Tuesday");}}
href="#"
title="Go to Tuesday gyms"
>
Tue
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark WednesdayLink"
onClick={e => {this.props.handleClick("Wednesday");}}
href="#"
title="Go to Wednesday gyms"
>
Wed
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark ThursdayLink"
onClick={e => {this.props.handleClick("Thursday");}}
href="#"
title="Go to Thursday gyms"
>
Thu
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark FridayLink"
onClick={e => {this.props.handleClick("Friday");}}
href="#"
title="Go to Friday gyms"
>
Fri
</a>
</li>
<li className="nav-item">
<a
className="nav-item nav-link text-dark SaturdayLink"
onClick={e => {this.props.handleClick("Saturday");}}
href="#"
title="Go to Saturday gyms"
>
Sat
</a>
</li>
</ul>
</nav>
);
}
}
|
// --- Initial array of topics that will be the basis of our first buttons on the page.
var topics = ["Horror Movies", "Monkeys", "Goats", "Heavy-Metal", "Cooking"];
// --- Creating buttons for each string in the topic array above.
for(var i = 0; i < topics.length; i++) {
console.log(topics[i]);
var pageButton = $("<button>");
pageButton.addClass("topic btn btn-dark btn-lg");
pageButton.attr("data-name", topics[i]); // will spit out as <button data-name="topics[i]">
pageButton.text(topics[i]);
$("#button-container").append(pageButton);
};
// When clicked, the pageButton will grab data with AJAX.
function displayArrayInfo() {
var topic = $(this).attr("data-name");
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&api_key=dc6zaTOxFJmzC&limit=10";
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
// Clears the page of gif's so that new ones can take its place.
$("#giphy").empty();
// For-loop that allows each button-click to result
// in 10 static GIFs to be populated on the page.
var results = response.data;
for(var x = 0; x < results.length; x++) {
var displayDiv = $("<div class='display-div'>");
displayDiv.css("float", "left");
displayDiv.css("margin", "10px");
var p = $("<p>").text("Rating: " + results[x].rating);
var image = $("<img>");
image.addClass("gif");
image.attr("src", results[x].images.fixed_height_still.url);
image.attr("data-state", "still")
image.attr("data-still", results[x].images.fixed_height_still.url);
image.attr("data-animate", results[x].images.fixed_height.url);
displayDiv.append(p);
displayDiv.append(image);
$("#giphy").prepend(displayDiv);
console.log(queryURL);
console.log(response.data);
}
})
};
// Call-function that allows user to click button to display images + rating.
$(document).on("click", ".topic", displayArrayInfo);
// Function that animates on/off the GIFs when they're clicked:
$(document).on("click", ".gif", function() {
var state = $(this).attr("data-state");
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
};
});
// Function that will create new buttons from the visitor's input
$("#add-button").on("click", function(event) {
// Prevents page from refreshing.
event.preventDefault();
// Stores user input as a value to be used later
var newTopic = $("#newfav-input").val().trim();
topics.push(newTopic);
// Creating the new button
var newButton = $("<button>");
newButton.addClass("topic btn btn-dark btn-lg");
newButton.attr("data-name", newTopic);
newButton.text(newTopic);
$("#button-container").append(newButton);
})
|
/// <reference path="./santedb-model.js"/>
/*
* Copyright 2015-2018 Mohawk College of Applied Arts and Technology
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* User: justin
* Date: 2018-7-23
*/
// Interactive SHIM between host environment and browser
var __SanteDBAppService = window.SanteDBAppService || {};
// Backing of execution environment
var ExecutionEnvironment = {
Unknown: 0,
Server: 1,
Mobile: 2,
UserInterface: 3
};
if (!SanteDBWrapper)
/**
* @class
* @constructor
* @summary SanteDB Binding Class
* @description This class exists as a simple interface which is implemented by host implementations of the SanteDB hostable core. This interface remains the same even though the
* implementations of this file on each platform (Admin, BRE, Client, etc.) are different.
*/
function SanteDBWrapper() {
"use strict";
var _viewModelJsonMime = "application/json+sdb-viewModel";
/**
* @summary Re-orders the JSON object properties so that $type appears as the first property
* @param {any} object The object whose properites should be reordered
* @returns {any} The appropriately ordered object
*/
var _reorderProperties = function(object) {
// Object has $type and $type is not the first property
if(object.$type) {
var retVal = { $type: object.$type };
Object.keys(object).filter(function(d) { return d != "$type" })
.forEach(function(k) {
retVal[k] = object[k];
if(!retVal[k]) ;
else if(retVal[k].$type) // reorder k
retVal[k] = _reorderProperties(retVal[k]);
else if(Array.isArray(retVal[k]))
for(var i in retVal[k])
if(retVal[k][i].$type)
retVal[k][i] = _reorderProperties(retVal[k][i]);
})
return retVal;
}
return object;
};
/**
* @summary Global error handler
* @param {xhr} e The Errored request
* @param {*} data
* @param {*} setting
* @param {*} err
*/
var _globalErrorHandler = function (data, setting, err) {
if (data.status == 401 && data.getResponseHeader("WWW-Authenticate")) {
if (_session && _session.exp > Date.now // User has a session that is valid, but is still 401 hmm... elevation!!!
&& _elevator
&& !_elevator.getToken() ||
_session == null && _elevator) {
// Was the response a security policy exception where the back end is asking for elevation on the same user account?
if (data.responseJSON &&
data.responseJSON.type == "SecurityPolicyException" &&
data.responseJSON.message == "error.elevate")
_elevator.elevate(_session);
else
_elevator.elevate(null);
return true;
}
}
else
console.warn(new Exception("Exception", "error.general", err, null));
return false;
};
/**
* @class APIWrapper
* @constructor
* @memberof SanteDBWrapper
* @summary SanteDB HDSI implementation that uses HTTP (note, other implementations may provide alternates)
* @param {any} _config The configuration of the service
* @param {string} _config.base The base URL for the service
* @param {boolean} _config.idByQuery When true, indicates the wrapper wants to pass IDs by query
*/
function APIWrapper(_config) {
/**
* @method
* @summary Reconfigures this instance of the API wrapper
* @memberof SanteDBWrapper.APIWrapper
* @param {any} config The configuration of the service
* @param {string} config.base The base URL for the service
* @param {boolean} config.idByQuery When true, indicates the wrapper wants to pass IDs by query
*/
this.configure = function (config) {
_config = config;
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Creates a new item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be posted
* @param {any} configuration.data The data that is to be posted
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.postAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'POST',
url: _config.base + configuration.resource,
data: configuration.contentType.indexOf('application/json') == 0 ? JSON.stringify(_reorderProperties(configuration.data)) : configuration.data,
dataType: configuration.dataType || 'json',
contentType: configuration.contentType || 'application/json',
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr && response.getResponseHeader("etag"))
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules, error.data), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Updates an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be posted
* @param {any} configuration.data The data that is to be posted
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {string} configuration.id The identifier of the object on the interface to update
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.putAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'PUT',
url: _config.base + configuration.resource + (_config.idByQuery ? "?_id=" + configuration.id : "/" + configuration.id),
data: configuration.contentType.indexOf('application/json') == 0 ? JSON.stringify(_reorderProperties(configuration.data)) : configuration.data,
dataType: configuration.dataType ||'json',
contentType: configuration.contentType || 'application/json',
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr && response.getResponseHeader("etag"))
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Patches an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be posted
* @param {any} configuration.data The data that is to be posted
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {string} configuration.id The identifier of the object on the interface to update
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.patchAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'PATCH',
url: _config.base + configuration.resource + (_config.idByQuery ? "?_id=" + configuration.id : "/" + configuration.id),
data: configuration.contentType.indexOf('application/json') == 0 ? JSON.stringify(_reorderProperties(configuration.data)) : configuration.data,
dataType: configuration.dataType ||'json',
contentType: configuration.contentType || 'application/json',
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Performs a GET on an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be fetched
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {any} configuration.query The query to be applied to the get
* @returns {Promise} The promise for the operation
*/
this.getAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'GET',
url: _config.base + configuration.resource,
data: configuration.query,
dataType: configuration.dataType ||'json',
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr && response.getResponseHeader("etag"))
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = {};
if(e.responseJSON)
error = e.responseJSON;
else if(e.responseText)
try { error = JSON.parse(e.responseText); }
catch {};
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Performs a DELETE on an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be deleted
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {any} configuration.id The object that is to be deleted on the server
* @param {any} configuration.data The additional data that should be sent for the delete command
* @param {string} configuration.mode The mode in which the delete should occur. Can be NULLIFY, CANCEL or OBSOLETE (default)
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.deleteAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
var hdr = configuration.headers || {};
hdr["X-Delete-Mode"] = configuration.mode || "OBSOLETE";
$.ajax({
method: 'DELETE',
url: _config.base + configuration.resource + (configuration.id ? (_config.idByQuery ? "?_id=" + configuration.id : "/" + configuration.id) : ""),
data: configuration.contentType == 'application/json' ? JSON.stringify(_reorderProperties(configuration.data)) : configuration.data,
headers: hdr,
dataType: configuration.dataType ||'json',
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr && response.getResponseHeader("etag"))
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Performs a LOCK on an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be locked
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {any} configuration.id The object that is to be locked on the server
* @param {any} configuration.data The additional data that should be sent for the delete command
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.lockAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'LOCK',
url: _config.base + configuration.resource + (configuration.id ? (_config.idByQuery ? "?_id=" + configuration.id : "/" + configuration.id) : ""),
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr && response.getResponseHeader("etag"))
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
/**
* @method
* @memberof SanteDBWrapper.APIWrapper
* @summary Performs a UNLOCK on an existing item on the instance
* @param {any} configuration The configuration object
* @param {string} configuration.resource The resource that is to be locked
* @param {any} configuration.state A piece of state data which is passed back to the caller for state tracking
* @param {boolean} configuration.sync When true, executes the request in synchronous mode
* @param {any} configuration.id The object that is to be locked on the server
* @param {any} configuration.data The additional data that should be sent for the delete command
* @param {string} configuration.contentType Identifies the content type of the data
* @returns {Promise} The promise for the operation
*/
this.unLockAsync = function (configuration) {
return new Promise(function (fulfill, reject) {
$.ajax({
method: 'UNLOCK',
url: _config.base + configuration.resource + (configuration.id ? (_config.idByQuery ? "?_id=" + configuration.id : "/" + configuration.id) : ""),
headers: configuration.headers,
async: !configuration.sync,
success: function (xhr, status, response) {
try {
if(xhr)
xhr.etag = response.getResponseHeader("etag");
if (fulfill) fulfill(xhr, configuration.state);
}
catch (e) {
if (reject) reject(e.responseJSON || e, configuration.state);
}
},
error: function (e, data, setting) {
if (_globalErrorHandler(e, data, setting))
return;
var error = e.responseJSON;
if (reject) {
if (error && error.error !== undefined) // oauth2
reject(new Exception(error.type, error.error, error.error_description, error.caused_by), configuration.state);
else if (error && (error.$type === "Exception" || error.$type))
reject(new Exception(error.$type, error.message, error.detail, error.cause, error.stack, error.policy, error.rules), configuration.state);
else
reject(new Exception("HttpException", "error.http." + e.status, e, null), configuration.state);
}
else
console.error("UNHANDLED PROMISE REJECT: " + JSON.stringify(e));
}
});
});
};
};
/**
* @class ResourceWrapper
* @memberof SanteDBWrapper
* @constructor
* @summary Represents a wrapper for a SanteDB resource
* @param {any} _config The configuration object
* @param {string} _config.resource The resource that is being wrapped
* @param {APIWrapper} _config.api The API to use for this resource
*/
function ResourceWrapper(_config) {
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Retrieves a specific instance of the resource this wrapper wraps
* @param {string} id The unique identifier of the resource to retrieve
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.getAsync = function (id, viewModel, state) {
// Prepare query
var url = null;
if (id) {
if (id.id)
url = `${_config.resource}/${id.id}`;
else
url = `${_config.resource}/${id}`;
if(id.version)
url += `/history/${id.version}`;
}
else
url = _config.resource;
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
else if (id && id.viewModel)
headers["X-SanteDB-ViewModel"] = id.viewModel;
return _config.api.getAsync({
headers: headers,
state: state,
resource: url
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Queries for instances of the resource this wrapper wraps
* @param {any} query The HDSI query to filter on
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.findAsync = function (query, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.getAsync({
headers: headers,
query: query,
state: state,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @param {any} query The query for the object that you are looking for
* @summary Queries for instances of the resource this wrapper wraps in a synchronous fashion
* @see {SanteDBWrapper.findAsync} For asynchronous method
* @return {Promise} A promise which is blocked and not executed until the operation is complete
*/
this.find = function (query) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.getAsync({
headers: headers,
sync: true,
resource: _config.resource,
query: query
});
}
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Inserts a specific instance of the wrapped resource
* @param {any} data The data / resource which is to be created
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.insertAsync = function (data, state) {
if (data.$type !== _config.resource && data.$type !== `${_config.resource}Info`)
throw new Exception("ArgumentException", "error.invalidType", `Invalid type, resource wrapper expects ${_config.resource} however ${data.$type} specified`);
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
var resource = _config.resource;
// Does the resource have an ID? If so then do CreateOrUpdate
if(data.id)
resource += "/" + data.id;
if(data.createdBy)
delete(data.createdBy);
if(data.creationTime)
delete(data.creationTime);
// Perform post
return _config.api.postAsync({
headers: headers,
data: data,
state: state,
contentType: _config.accept,
resource: resource
});
};
/**
* @method
* @memberof SantedBWrapper.ResourceWrapper
* @summary Sends a patch to the service
* @param {string} id The identifier of the object to patch
* @param {string} etag The e-tag to assert
* @param {Patch} patch The patch to be applied
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.patchAsync = function (id, etag, patch, state) {
if (patch.$type !== "Patch")
throw new Exception("ArgumentException", "error.invalidType", `Invalid type, resource wrapper expects ${_config.resource} however ${data.$type} specified`);
var headers = {};
if(etag)
headers['If-Match'] = etag;
// Send PUT
return _config.api.patchAsync({
headers: headers,
data: patch,
id: id,
state: state,
contentType: "application/json+sdb-patch",
resource: _config.resource
});
}
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Updates the identified instance of the wrapped resource
* @param {string} id The unique identifier for the object to be updated
* @param {any} data The data / resource which is to be updated
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.updateAsync = function (id, data, state) {
if (data.$type !== _config.resource && data.$type !== `${_config.resource}Info`)
throw new Exception("ArgumentException", "error.invalidType", `Invalid type, resource wrapper expects ${_config.resource} however ${data.$type} specified`);
else if (data.id && data.id !== id)
throw new Exception("ArgumentException", "error.invalidValue", `Identifier mismatch, PUT identifier ${id} doesn't match ${data.id}`);
if(data.updatedBy)
delete(data.updatedBy);
if(data.updatedTime)
delete(data.updatedTime);
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
// Send PUT
return _config.api.putAsync({
headers: headers,
data: data,
id: id,
state: state,
contentType: _config.accept,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs an obsolete (delete) operation on the server
* @param {string} id The unique identifier for the object to be deleted
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.deleteAsync = function (id, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.deleteAsync({
headers: headers,
id: id,
state: state,
contentType: _config.accept,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs the specified LOCK operation on the server
* @param {string} id The unique identifier for the object on which the invokation is to be called
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.lockAsync = function (id, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.lockAsync({
headers: headers,
id: id,
state: state,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs the specified UNLOCK operation on the server
* @param {string} id The unique identifier for the object on which the invokation is to be called
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.unLockAsync = function (id, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.unLockAsync({
headers: headers,
id: id,
state: state,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs a nullify on the specified object
* @description A nullify differs from a delete in that a nullify marks an object as "never existed"
* @param {string} id The unique identifier for the object to be nullified
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.nullifyAsync = function (id, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.deleteAsync({
headers: headers,
id: id,
mode: "NULLIFY",
state: state,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs a cancel on the specified object
* @description A cancel differs from a delete in that a cancel triggers a state change from NORMAL>CANCELLED
* @param {string} id The unique identifier for the object to be cancelled
* @param {any} state A unique state object which is passed back to the caller
* @returns {Promise} The promise for the operation
*/
this.cancelAsync = function (id, state) {
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
return _config.api.deleteAsync({
headers: headers,
id: id,
mode: "CANCEL",
state: state,
resource: _config.resource
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Performs a find operation on an association
* @description Some resources allow you to chain queries which automatically scopes the results to the container
* @param {string} id The identifier of the object whose children you want query
* @param {string} property The property path you would like to filter on
* @param {any} query The query you want to execute
* @returns {Promise} A promise for when the request completes
*/
this.findAssociatedAsync = function(id, property, query, state) {
if(!id)
throw new Exception("ArgumentNullException", "Missing scoping identifier");
else if(!property)
throw new Exception("ArgumentNullException", "Missing scoping property");
var headers = {
Accept: _config.accept
};
if(_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
// Prepare query
var url = null;
if (id.id)
url = `${_config.resource}/${id.id}/${property}`;
else
url = `${_config.resource}/${id}/${property}`;
return _config.api.getAsync({
headers: headers,
query: query,
state: state,
resource: url
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Adds a new association to the specified parent object
* @param {string} id The identifier of the container
* @param {string} property The associative property you want to add the value to
* @param {any} data The data to be added as an associative object (note: Most resources require that this object already exist)
* @param {any} state A stateful object for callback correlation
* @returns {Promise} A promise which is fulfilled when the request is complete
*/
this.addAssociatedAsync = function(id, property, data, state) {
if(!id)
throw new Exception("ArgumentNullException", "Missing scoping identifier");
else if(!property)
throw new Exception("ArgumentNullException", "Missing scoping property");
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
// Prepare path
var url = null;
if (id.id)
url = `${_config.resource}/${id.id}/${property}`;
else
url = `${_config.resource}/${id}/${property}`;
return _config.api.postAsync({
headers: headers,
data: data,
state: state,
resource: url,
contentType: _config.accept
});
};
/**
* @method
* @memberof SanteDBWrapper.ResourceWrapper
* @summary Removes an existing associated object from the specified scoper
* @param {string} id The identifier of the container object
* @param {string} property The property path from which the object is to be removed
* @param {string} associatedId The identifier of the sub-object to be removed
* @param {any} state A state for correlating multiple requests
* @returns {Promise} A promise which is fulfilled when the request comletes
*/
this.removeAssociatedAsync = function(id, property, associatedId, state) {
if(!id)
throw new Exception("ArgumentNullException", "Missing scoping identifier");
else if(!property)
throw new Exception("ArgumentNullException", "Missing scoping property");
else if (!associatedId)
throw new Exception("ArgumentNullException", "Missing associated object id");
var headers = {
Accept: _config.accept
};
if (_config.viewModel)
headers["X-SanteDB-ViewModel"] = _config.viewModel;
// Prepare path
var url = null;
if (id.id)
url = `${_config.resource}/${id.id}/${property}`;
else
url = `${_config.resource}/${id}/${property}`;
return _config.api.deleteAsync({
headers: headers,
id: associatedId,
state: state,
resource: url,
contentType: _config.accept
});
}
};
// Public exposeing
this.APIWrapper = APIWrapper;
this.ResourceWrapper = ResourceWrapper;
// hdsi internal
var _hdsi = new APIWrapper({
idByQuery: false,
base: "/hdsi/"
});
// ami internal
var _ami = new APIWrapper({
idByQuery: false,
base: "/ami/"
});
// auth internal
var _auth = new APIWrapper({
idByQuery: false,
base: "/auth/"
});
// Backing data for app API
var _app = new APIWrapper({
base: "/app/",
idByQuery: false
});
// App controller internal
var _application = {
/**
* @summary Calculates the strength of the supplied password
* @param {*} password The password
* @returns {number} The strength of the password between 0 and 5
*/
calculatePasswordStrength: function(password) {
var strength = 0;
if (password.length >= 6) {
strength++;
if(password.length > 10)
strength++;
if (/(?=.*[a-z])(?=.*[A-Z])/.test(password))
strength++;
if (/(?:[^A-Za-z0-9]{1,})/.test(password))
strength++;
if (/(?:[0-9]{1,})/.test(password))
strength++;
}
return strength;
},
/**
* Get the specified widgets
* @param context The context to fetch widgets for
*/
getWidgetsAsync: function (context, type) {
return new Promise(function (fulfill, reject) {
_app.getAsync({
resource: "Widgets",
query: {
context: context,
type: type
}
}).then(function (widgets) {
widgets.forEach(function (w) {
w.htmlId = w.name.replace(/\./g, "_");
});
fulfill(widgets);
}).catch(function (e) { reject(e); });
});
},
/**
* @summary Gets solutions that can be installed on this appliccation
* @method
* @memberof SnateDBWrapper.app
*/
getAppSolutionsAsync: function () {
return _ami.getAsync({
resource: "AppletSolution",
query: "_upstream=true"
});
},
/**
* @summary Closes the application or restarts it in the case of the mobile
* @method
* @memberof SanteDBWrapper.app
*/
close: function () {
__SanteDBAppService.Close();
},
/**
* @summary Instructs the back end service to perform a system upgrade
* @param {string} appId The id of the applet which should be updated
* @returns {Promise} A promise representing the fulfillment or rejection of update
* @method
* @memberof SanteDBWrapper.app
*/
doUpdateAsync: function (appId) {
return _app.postAsync({
resource: "/Update"
});
},
/**
* @summary Instructs the back end service to perform a compact
* @param {boolean} takeBackup When true, instructs the back end to take a backup of data
* @returns {Promise} A promise representing the fulfillment or rejection of update
* @method
* @memberof SanteDBWrapper.app
*/
compactAsync: function (takeBackup) {
return _app.post({
resource: "Data",
data: { backup: takeBackup },
contentType: 'application/x-www-form-urlencoded'
});
},
/**
* @summary Instructs the back end service to perform a purge of all data
* @param {boolean} takeBackup True if the back-end should take a backup before purge
* @returns {Promise} The promise representing the fulfillment or rejection
* @method
* @memberof SanteDBWrapper.app
*/
purgeAsync: function (takeBackup) {
return _app.deleteAsync({
resource: "Data",
data: { backup: takeBackup },
contentType: 'application/x-www-form-urlencoded'
});
},
/**
* @summary Instructs the backend to restore the data from a backup
* @returns {Promise} The promise representing the fulfillment or rejection
* @method
* @memberof SanteDBWrapper.app
*/
restoreAsync: function () {
return _app.postAsync({
resource: "Data/Restore"
});
},
/**
* @summary Create a backup of current assets
* @returns {Promise}
* @param {boolean} makePublic Make the backup public
* @method
* @memberof SanteDBWrapper.app
*/
createBackupAsync: function (makePublic) {
return _app.postAsync({
resource: "Data/Backup",
data: { makePublic: makePublic },
contentType: 'application/x-www-form-urlencoded'
});
},
/**
* @summary Get all backups and backup information
* @method
* @memberof SanteDBWrapper.app
* @returns {Promise} The promise representing the fulfillment or rejection
*/
getBackupAsync: function () {
return _app.getAsync({
resource: "Data/Backup",
});
},
/**
* @summary Load a data asset from an applet's Data/ directory
* @method
* @memberof SanteDBWrapper.app
* @param {string} dataId The identifier of the data asset to load
* @returns {string} The data asset
*/
loadDataAsset: function (dataId) {
return atob(__SanteDBAppService.GetDataAsset(dataId));
},
/**
* @summary Submits a user entered bug report
* @method
* @memberof SanteDBWrapper.app
* @param {any} bugReport The structured bug report to be submitted
* @returns {Promise} The promise to fulfill or reject the request
*/
submitBugReportAsync: function (bugReport) {
return _ami.postAsync({
resource: "Sherlock",
data: bugReport
});
},
/**
* @summary Gets a list of all logs and their information from the server
* @method
* @memberof SanteDBWrapper.app
* @param {string} _id The id of the log file to fetch contents of
* @param {any} query The query filters to use / apply
* @returns {Promise} The promise representing the async request
*/
getLogInfoAsync: function (_id, query) {
var resource = "Log";
if (_id)
resource += "/" + _id;
return _ami.getAsync({
resource: resource,
query: query
});
},
/**
* @summary Generates a new random password
* @method
* @memberof SanteDBWrapper.app
* @returns {string} A new random password
*/
generatePassword: function() {
var specChars = [ '@','_','-','~','!','#','$'];
var secret = SanteDB.application.newGuid().replace(/-/g, function() {
return specChars[Math.trunc(Math.random() * specChars.length)];
});
var repl = "";
for(var i = 0; i < secret.length; i++)
if(secret[i] >= 'a' && secret[i] <= 'f')
repl += String.fromCharCode(97 + Math.trunc(Math.random() * 24));
else if(i % 2 == 1)
repl += String.fromCharCode(65 + Math.trunc(Math.random() * 24));
else
repl += secret[i];
return repl;
},
/**
* @summary Create a new UUID
* @method
* @memberof SanteDBWrapper.app
* @returns {string} A new unique UUID
*/
newGuid: function () {
return __SanteDBAppService.NewGuid();
},
/**
* @summary Get application version information
* @method
* @memberof SanteDBWrapper.app
* @returns {Promise} The promise from the async representation
* @param {any} settings The settings to use for the server diagnostic report
* @param {boolean} settings.updates When true check for updates
* @param {boolean} settings.remote When true check the remote server
*/
getAppInfoAsync: function (settings) {
return _ami.getAsync({
resource: "Sherlock",
query: { _includeUpdates: (settings || {}).updates, _upstream: (settings || {}).remote }
});
},
/**
* @summary Get the online status of the application
* @method
* @memberof SanteDBWrapper.app
* @returns {boolean} True if the application is online
*/
getOnlineState: function () {
return __SanteDBAppService.GetOnlineState();
},
/**
* @summary Indicates whether the server's AMI is available
* @description This command actually sends a lightweight PING function to the AMI server
* @method
* @memberof SanteDBWrapper.app
* @returns {boolean} True if the AMI is available
*/
isAdminAvailable: function () {
return __SanteDBAppService.IsAdminAvailable();
},
/**
* @summary Indicates whether the HDSI is available
* @description This command actually sends a lightweight PING function to the HDSI server
* @method
* @memberof SanteDBWrapper.app
* @returns {boolean} True if the HDSI is available
*/
isClinicalAvailable: function () {
return __SanteDBAppService.IsClinicalAvailable
},
/**
* @summary Resolves the HTML input form for the specified template
* @method
* @memberof SanteDBWrapper.app
* @returns {string} The HTML content of the input form for the specified template
* @param {string} templateId The id of the template for which HTML input should be gathered
*/
resolveTemplateForm: function (templateId) {
return __SanteDBAppService.GetTemplateForm(templateId);
},
/**
* @summary Resolves the HTML view for the specified template
* @method
* @memberof SanteDBWrapper.app
* @returns {string} The HTML content of the view for the specified template
* @param {string} templateId The id of the template for which HTML view should be gathered
*/
resolveTemplateView: function (templateId) {
return __SanteDBAppService.GetTemplateView(templateId);
},
/**
* @summary Get a list of all installed template definitions
* @method
* @memberof SanteDBWrapper.app
* @returns {Array<string>} The list of template definitions
*/
getTemplateDefinitions: function () {
return JSON.parse(__SanteDBAppService.GetTemplates());
},
/**
* @summary Get the version of the application host
* @method
* @memberof SanteDBWrapper.app
* @returns {string} The version of the host this applet is running in
*/
getVersion: function () {
return __SanteDBAppService.GetVersion();
},
/**
* @summary Get all available user interface menus for the current user
* @method
* @memberof SanteDBWrapper.app
* @param {string} contextName The name of the context to retrieve
* @returns {any} A structure of menus the user is allowed to access
*/
getMenusAsync: function (contextName) {
return _app.getAsync({
resource: "Menu",
query: { context: contextName }
});
},
/**
* @summary Indicates whether the application host can scan barcodes
* @method
* @memberof SanteDBWrapper.app
* @returns {boolean} True if the application supports a camera
*/
canScanBarcode: function () {
return __SanteDBAppService.HasCamera();
},
/**
* @summary Launches the camera on the device to take a picture of a barcode
* @method
* @memberof SanteDBWrapper.app
* @returns {string} The scanned barcode
*/
scanBarcode: function () {
try {
var value = __SanteDBAppService.ScanBarcode();
return value;
}
catch (e) {
console.error(e);
throw new Exception("Exception", "error.general", e);
}
}
}
// Resources internal
var _resources = {
/**
* @property {SanteDBWrapper.ResourceWrapper} bundle The bundle resource handler
* @memberof SanteDBWrapper.resources
* @summary Represents a resource wrapper that persists bundles
*/
bundle: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Bundle",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents an resource wrapper that interoperates with the care planner
*/
carePlan: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "CarePlan",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Patient Resource
*/
patient: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Patient",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the SubstanceAdministration Resource
*/
substanceAdministration: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SubstanceAdministration",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Act Resource
*/
act: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Act",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @summary Represents the entity resource
* @memberof SanteDBWrapper.resources
*/
entity: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Entity",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @summary A resource wrapper for Assigning Authorities
* @memberof SanteDBWrapper.resources
*/
assigningAuthority: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "AssigningAuthority",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @summary Represents the entity relationship resource
* @memberof SanteDBWrapper.resources
*/
entityRelationship: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "EntityRelationship",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Observation Resource
*/
observation: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Observation",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Place Resource
*/
place: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Place",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Provider Resource
*/
provider: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Provider",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the UserEntity Resource
*/
userEntity: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "UserEntity",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Organization Resource
*/
organization: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Organization",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the Material Resource
*/
material: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Material",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the ManufacturedMaterial Resource
*/
manufacturedMaterial: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "ManufacturedMaterial",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the ManufacturedMaterial Resource
*/
concept: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Concept",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the ConceptSet Resource
*/
conceptSet: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "ConceptSet",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the ReferenceTerm Resource
*/
referenceTerm: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "ReferenceTerm",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the CodeSystem Resource
*/
codeSystem: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "CodeSystem",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the DeviceEntity Resource
*/
deviceEntity: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "DeviceEntity",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Represents the ApplicationEntity Resource
*/
applicationEntity: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "ApplicationEntity",
api: _hdsi
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Gets the configuration resource
*/
configuration: new ResourceWrapper({
accept: "application/json",
resource: "Configuration",
api: _app
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Gets the queue control resource
*/
queue: new ResourceWrapper({
accept: "application/json",
resource: "Queue",
api: _app
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary Resource wrapper which interacts with the administrative task scheduler
*/
task: new ResourceWrapper({
accept: "application/json",
resource: "Task",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary A resource wrapper for alerts which are messages between users
*/
mail: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "MailMessage",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary A wrapper which is used for fetching user notifications
**/
tickle: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Tickle",
api: _app
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberof SanteDBWrapper.resources
* @summary A wrapper for locale information which comes from the server
*/
locale: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "Locale",
api: _app
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for Security USers
*/
securityUser: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SecurityUser",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for Security Roles
*/
securityRole: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SecurityRole",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for session information
*/
sessionInfo: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SessionInfo",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for Security Devices
*/
securityDevice: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SecurityDevice",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for Security Applications
*/
securityApplication: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SecurityApplication",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for Security Policies
*/
securityPolicy: new ResourceWrapper({
accept: _viewModelJsonMime,
resource: "SecurityPolicy",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for provenance
*/
securityProvenance: new ResourceWrapper({
resource: "SecurityProvenance",
api: _ami,
accept: _viewModelJsonMime,
viewModel: 'base'
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for audit API
*/
audit: new ResourceWrapper({
resource: "Audit",
accept: "application/json",
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for probe API
*/
probe: new ResourceWrapper({
resource: "Probe",
accept: _viewModelJsonMime,
api: _ami
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for sync log API
*/
sync: new ResourceWrapper({
resource: "Sync",
accept: _viewModelJsonMime,
api: _app
}),
/**
* @property {SanteDB.ResourceWrapper}
* @memberOf SanteDBWrapper.resources
* @summary Wrapper for subscription definition API
*/
subscriptionDefinition : new ResourceWrapper({
resource: "SubscriptionDefinition",
api: _ami
})
};
// HACK: Wrapper pointer facility = place
_resources.facility = _resources.place;
// master configuration closure
var _masterConfig = null;
var _configuration = {
/**
* @method
* @memberof SanteDBWrapper.configuration
* @return {Promise} The data providers
* @summary Gets a list of data providers available on this offline provider mode
*/
getDataProvidersAsync: function () {
return _app.getAsync({
resource: "DataProviders"
});
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Get the configuration, nb: this caches the configuration
* @returns {Promise} The configuration
*/
getAsync: function () {
return new Promise(function (fulfill, reject) {
try {
if (_masterConfig)
fulfill(_masterConfig);
else {
_resources.configuration.getAsync()
.then(function (d) {
_masterConfig = d;
if (fulfill) fulfill(_masterConfig);
})
.catch(function (e) {
if (reject) reject(e.responseJSON || e);
});
}
}
catch (e) {
if (reject) reject(e.responseJSON || e);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Get the specified configuration key
* @returns {string} The application key setting
* @param {string} key The key of the setting to find
*/
getAppSetting: function (key) {
try {
if (!_masterConfig) throw new Exception("Exception", "error.invalidOperation", "You need to call configuration.getAsync() before calling getAppSetting()");
var _setting = _masterConfig.application.setting.find((k) => k.key === key);
if (_setting)
return _setting.value;
else
return null;
}
catch (e) {
if (!e.$type)
throw new Exception("Exception", "error.unknown", e.detail, e);
else
throw e;
}
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Sets the specified application setting
* @param {string} key The key of the setting to set
* @param {string} value The value of the application setting
* @see SanteDB.configuration.save To save the updated configuration
*/
setAppSetting: function (key, value) {
try {
if (!_masterConfig) throw new Exception("Exception", "error.invalidOperation", "You need to call configuration.getAsync() before calling getAppSetting()");
var _setting = _masterConfig.application.setting.find((k) => k.key === key);
if (_setting)
_setting.value = value;
else
_masterConfig.application.setting.push({ key: key, value: value });
}
catch (e) {
if (!e.$type)
throw new Exception("Exception", "error.unknown", e.detail, e);
else
throw e;
}
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Gets the currently configured realm
* @returns {string} The name of the security realm
*/
getRealm: function () {
try {
if (!_masterConfig) throw new Exception("Exception", "error.invalidOperation", "You need to call configuration.getAsync() before calling getAppSetting()");
return _masterConfig.realmName;
}
catch (e) {
if (!e.$type)
throw new Exception("Exception", "error.unknown", e.detail, e);
else
throw e;
}
},
/**
* @method
* @summary Gets the specified section name
* @memberof SanteDBWrapper.configuration
* @param {any} name The name of the configuration section
* @returns {any} A JSON object representing the configuration setting section
*/
getSection: function (name) {
try {
if (!_masterConfig) throw new Exception("Exception", "error.invalidOperation", "You need to call configuration.getAsync() before calling getAppSetting()");
return _masterConfig[name];
}
catch (e) {
if (!e.$type)
throw new Exception("Exception", "error.unknown", e.detail, e);
else
throw e;
}
},
/**
* @method
* @summary Instructs the current system to join a realm
* @memberof SanteDBWrapper.configuration
* @returns {Promise} The configuration file after joining the realm
* @param {any} configData The configuration data for the realm
* @param {string} configData.domain The domain to which the application is to be joined
* @param {string} configData.deviceName The name of the device to join as
* @param {boolean} configData.replaceExisting When true, instructs the application to replace an existing registration
* @param {boolean} configData.enableTrace When true, enables log file tracing of requests
* @param {boolean} configData.enableSSL When true, enables HTTPS
* @param {boolean} configData.noTimeout When true, removes all timeouts from the configuration
* @param {number} configData.port The port number to connect to the realm on
* @param {boolean} overwrite Overwrites the existing configuration if needed
*/
joinRealmAsync: function (configData, overwrite) {
return new Promise(function (fulfill, reject) {
try {
_app.postAsync({
resource: "Configuration/Realm",
contentType: 'application/json',
data: {
realmUri: configData.domain,
deviceName: configData.deviceName,
enableTrace: configData.enableTrace || false,
enableSSL: configData.enableSSL || false,
port: configData.port,
noTimeout: false,
replaceExisting: overwrite || false,
client_secret: configData.client_secret,
domainSecurity: configData.domainSecurity
}
}).then(function (d) {
_masterConfig = d;
if (fulfill) fulfill(d);
}).catch(function (e) {
console.error(`Error joining realm: ${e}`);
if (reject) reject(e.responseJSON || e);
});
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Instructs the application to remove realm configuration
* @returns {Promise} A promise that is fulfilled when the leave operation succeeds
*/
leaveRealmAsync: function () {
return _app.deleteAsync({
resource: "Configuration/Realm"
});
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Save the configuration object
* @param {any} configuration The configuration object to save
* @returns {Promise} A promise object indicating whether the save was successful
*/
saveAsync: function (configuration) {
return _resources.configuration.insertAsync(configuration);
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Gets the user specific preferences
* @returns {Promise} A promise representing the retrieval of the user settings
*/
getUserPreferencesAsync: function () {
return _app.getAsync({
resource: "Configuration/User"
});
},
/**
* @method
* @memberof SanteDBWrapper.configuration
* @summary Saves the user preferences
* @param {any} preferences A dictionary of preferences to be saved
* @returns {Promise} A promise which indicates when preferences were saved
* @example Save user preference for color
* SanteDB.configuration.saveUserPreferences([
* { key: "color", value: "red" }
* ]);
*/
saveUserPreferencesAsync: function (preferences) {
return _app.postAsync({
resource: "Configuration/User",
data: preferences
});
}
};
// Session and auth data
var _session = null;
var _elevator = null;
var _authentication = {
/**
* SID for SYSTEM USER
*/
SYSTEM_USER: "fadca076-3690-4a6e-af9e-f1cd68e8c7e8",
/**
* SID for ANONYMOUS user
*/
ANONYMOUS_USER: "c96859f0-043c-4480-8dab-f69d6e86696c",
/**
* @method
* @summary Sets the elevator function
* @param {any} elevator An elevation implementation
* @param {function():String} elevator.getToken A function to get the current token
* @param {function(boolean):void} elevator.elevate A function to perform elevation
* @memberof SanteDBWrapper.authentication
*/
setElevator: function (elevator) {
_elevator = elevator;
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @returns {any} The oauth session response with an access token, etc.
* @summary Gets the current session
*/
getSession: function () {
return _session ? {
access_token: _session.access_token,
expires_in: _session.expires_in
} : null;
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @returns {Promise} A promise representing the fulfillment or rejection of the get request
* @summary Gets the extended session information
*/
getSessionInfoAsync: function () {
return new Promise(function (fulfill, reject) {
if (_session)
fulfill(_session);
else
try {
_auth.getAsync({
resource: "session"
})
.then(function (s) {
_session = s;
if (fulfill) fulfill(s);
})
.catch(function (e) {
if (e.detail.status <= 204) {
_session = null;
fulfill(null);
}
else if (reject) reject(e.responseJSON || e);
});
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Requests a two-factor authentication secret to be sent
* @param {string} mode The mode of two-factor authentication (email, sms, etc.)
* @returns {Promise} A promise representing the outcome of the TFA secret send
*/
sendTfaSecretAsync: function (mode) {
return _ami.postAsync({
resource: "Tfa",
data: { mode: mode }
})
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Retrieves information about the two-factor authentication modes supported by the server
* @returns {Promise} The promise representing the fulfillment or rejection of the get request
*/
getTfaModeAsync: function () {
return _ami.getAsync({
resource: "Tfa"
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Performs a OAUTH password login
* @param {string} userName The name of the user which is logging in
* @param {string} password The password of the user
* @param {string} tfaSecret The two-factor secret if provided
* @param {string} scope When true indicates that there should not be a persistent session (i.e. one time authentication)
* @param {boolean} uacPrompt True if the authentication is part of a UAC prompt and no perminant session is to be
* @param {String} purposeOfUse The identifier of the purpose of use for the access
* @returns {Promise} A promise representing the login request
*/
passwordLoginAsync: function (userName, password, tfaSecret, uacPrompt, purposeOfUse, scope) {
return new Promise(function (fulfill, reject) {
try {
_auth.postAsync({
resource: "session",
data: {
username: userName,
password: password,
grant_type: 'password',
scope: (scope || ["*"]).join(",")
},
headers: {
"X-SanteDB-TfaSecret": tfaSecret,
"X-SanteDBClient-UserAccessControl": uacPrompt,
"X-SanteDBClient-Claim":
`${btoa(`http://santedb.org/claims/override=${uacPrompt && (purposeOfUse || false)}`)},${btoa(`urn:oasis:names:tc:xacml:2.0:action:purpose=${purposeOfUse || null}`)}`
},
contentType: 'application/x-www-form-urlencoded'
})
.then(function (d) {
if (!uacPrompt) {
_session = d;
}
if (fulfill) fulfill(d);
})
.catch(reject);
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Performs a local pin login
* @param {string} userName The name of the user which is logging in
* @param {string} password The password of the user
* @param {string} tfaSecret The two-factor secret if provided
* @param {boolean} noSession When true indicates that there should not be a persistent session (i.e. one time authentication)
* @param {String} purposeOfUse The reason the authentication is happening
* @param {Array} scope The requested scope of the session
* @returns {Promise} A promise representing the login request
*/
pinLoginAsync: function (userName, pin, uacPrompt, purposeOfUse, tfaSecret, scope) {
return new Promise(function (fulfill, reject) {
try {
_auth.postAsync({
resource: "session",
data: {
username: userName,
pin: pin,
grant_type: 'pin',
scope: (scope || ["*"]).join(",")
},
headers: {
"X-SanteDB-TfaSecret": tfaSecret,
"X-SanteDBClient-Sessionless": uacPrompt,
"X-SanteDBClient-Claim":
`${btoa(`http://santedb.org/claims/override=${uacPrompt && (purposeOfUse || false)}`)},${btoa(`urn:oasis:names:tc:xacml:2.0:action:purpose=${purposeOfUse || null}`)}`
},
contentType: 'application/x-www-form-urlencoded'
})
.then(function (d) {
if (!uacPrompt) {
_session = d;
}
if (fulfill) fulfill(d);
})
.catch(reject);
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Performs an OAUTH client credentials login
* @description A client credentials login is a login principal which only has an application principal. This is useful for password resets, etc.
* @returns {Promise} A promise representing the login request
* @param {boolean} noSession When true, indicates that a session should not be replaced that the request is a one time use token
*/
clientCredentialLoginAsync: function (noSession) {
return new Promise(function (fulfill, reject) {
try {
_auth.postAsync({
resource: "session",
data: {
grant_type: 'client_credentials',
scope: "*"
},
contentType: 'application/x-www-form-urlencoded'
})
.then(function (d) {
if (!noSession) {
_session = d;
}
if (fulfill) fulfill(d);
})
.catch(reject);
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Performs an OAUTH authorization code grant
* @description This function should be called *after* the authorization code has been obtained from the authorization server
* @param {boolean} noSession When true, indicates that there should not be a persistent session created
* @returns {Promise} A promise representing the session request
*/
authorizationCodeLoginAsync: function (code, redirect_uri, noSession) {
return new Promise(function (fulfill, reject) {
try {
_auth.postAsync({
resource: "session",
data: {
grant_type: 'authorization_code',
code: code,
redirect_uri: redirect_uri,
scope: "*"
},
contentType: 'application/x-www-form-urlencoded'
})
.then(function (d) {
if (!noSession) {
_session = d;
}
if (fulfill) fulfill(d);
})
.catch(reject);
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Performs a refresh token grant
* @returns {Promise} A promise representing the session refresh request
*/
refreshLoginAsync: function () {
return new Promise(function (fullfill, reject) {
try {
if (_session) {
_auth.postAsync({
resource: "session",
data: {
grant_type: 'refresh_token',
refresh_token: _session.refresh_token,
scope: "*"
},
contentType: 'application/x-www-form-urlencoded'
})
.then(function (d) {
if (!noSession) {
_session = d;
_authentication.getSessionInfoAsync().then(fulfill).catch(reject);
}
if (fulfill) fulfill(d);
})
.catch(reject);
}
else {
if (reject) reject(new Exception("SecurityException", "error.security", "Cannot refresh a null session"));
}
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Sets the password of the specified user
* @param {string} sid The security identifier of the user which is being updated
* @param {string} userName The name of the user to set the password to
* @param {string} passwd The password to set the currently logged in user to
* @returns {Promise} The promise representing the fulfillment or rejection of the password change
*/
setPasswordAsync: function (sid, userName, passwd) {
if (!_session || !_session)
throw new Exception("SecurityException", "error.security", "Can only set password with active session");
return _ami.putAsync({
id: sid,
resource: "SecurityUser",
contentType: _viewModelJsonMime,
data: {
$type: "SecurityUserInfo",
passwordOnly: true,
entity: new SecurityUser({
userName: userName,
password: passwd
})
}
});
},
/**
* @method
* @memberof SanteDBWrapper.authentication
* @summary Abandons the current SanteDB session
* @returns {Promise} The promise representing the fulfillment or rejection of the logout request
*/
logoutAsync: function () {
return new Promise(function (fulfill, reject) {
if (!_session) {
if (reject) reject(new Exception("SecurityException", "error.security", "Cannot logout of non-existant session"));
}
try {
_auth.deleteAsync({
resource: "session"
})
.then(function (d) {
_session = null;
window.sessionStorage.removeItem('token');
if (fulfill) fulfill(d);
})
.catch(reject);
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("Exception", "error.general", e);
if (reject) reject(ex);
}
});
}
};
// Provides localization support functions
var _localeCache = {};
var _localization = {
/**
* @summary Gets a string from the current user interface localization
* @memberof SanteDBWrapper.localiztion
* @method
* @param {string} stringId The id of the localization string to get
* @returns {string} The localized string
*/
getString: function (stringId) {
try {
var retVal = __SanteDBAppService.GetString(stringId);
return retVal || stringId;
}
catch (e) {
console.error(e);
return stringId;
}
},
/**
* @summary Get the currently configured locale
* @memberof SanteDBWrapper.localization
* @method
* @return {string} The ISO language code and country code of the application
*/
getLocale: function () {
var retVal = __SanteDBAppService.GetLocale();
return retVal;
},
/**
* @summary Get the currently configured language
* @memberof SanteDBWrapper.localization
* @method
* @return {string} The ISO language code
*/
getLanguage: function () {
return __SanteDBAppService.GetLocale().substr(0, 2);
},
/**
* @summary Get the currently configured country code
* @memberof SanteDBWrapper.localization
* @method
* @return {string} The 2 digit ISO country code
*/
getCountry: function () {
return __SanteDBAppService.GetLocale().substr(4, 2);
},
/**
* @summary Set the current locale of the application
* @memberof SanteDBWrapper.localization
* @method
* @param {string} locale The ISO locale (i.e. en-US, en-CA, sw-TZ to set)
*/
setLocale: function (locale) {
return __SanteDBAppService.SetLocale(locale);
},
/**
* @summary Get localization format information for the specified locale
* @memberof SanteDBWrapper.localization
* @method
* @param {string} locale The locale for which the format information should be retrieved
* @returns {Promise} The promise representing the operation to fetch locale
* @description The localization information contains formatting for currency, formatting for dates, and formatting for numbers
*/
getFormatInformationAsync: function (locale) {
return new Promise(function (fulfill, reject) {
try {
if (_localeCache[locale])
fulfill(_localeCache[locale]);
else {
_resources.locale.getAsync(locale)
.then(function (d) {
_localeCache[locale] = d;
if (fulfill) fulfill(d);
})
.catch(reject);
}
}
catch (e) {
var ex = e.responseJSON || e;
if (!ex.$type)
ex = new Exception("LocalizationException", "error.general", e);
if (reject) reject(ex);
}
});
},
}
// Public bindings
this.api = {
/**
* @type {APIWrapper}
* @summary Represents a property which wraps the HDSI interface
* @memberof SanteDBWrapper
*/
hdsi: _hdsi,
/**
* @type {APIWrapper}
* @memberof SanteDBWrapper
* @summary Represents a property which communicates with the AMI
*/
ami: _ami,
/**
* @type {APIWrapper}
* @memberof SanteDBWrapper
* @summary Represents a property which communicates with the AUTH service
*/
auth: _auth
};
/**
* @property
* @memberof SanteDBWrapper
* @summary Provide access to localization data
*/
this.locale = _localization;
/**
* @property
* @memberof SanteDBWrapper
* @summary Provides access to resource handlers
*/
this.resources = _resources;
/**
* @summary Configuration routines for SanteDB
* @class
* @static
* @memberof SanteDBWrapper
*/
this.configuration = _configuration;
/**
* @summary Authentication functions for SanteDB
* @class
* @static
* @memberof SanteDBWrapper
*/
this.authentication = _authentication;
/**
* @summary Application functions for SanteDB
* @class
* @static
* @memberof SanteDBWrapper
*/
this.application = _application;
// Application magic
var _magic = null;
// Setup JQuery to send up authentication and cookies!
$.ajaxSetup({
cache: false,
beforeSend: function (data, settings) {
if (_elevator && _elevator.getToken()) {
data.setRequestHeader("Authorization", "BEARER " +
_elevator.getToken());
}
else if (window.sessionStorage.getItem('token'))
data.setRequestHeader("Authorization", "BEARER " +
window.sessionStorage.getItem("token"));
if (!_magic)
_magic = __SanteDBAppService.GetMagic();
data.setRequestHeader("X-SdbMagic", _magic);
},
converters: {
"text json": function (data) {
return $.parseJSON(data, true);
}
}
});
};
if (!SanteDB)
var SanteDB = new SanteDBWrapper();
/**
* Return the string as a camel case
* @param {String} str The String
*/
String.prototype.toCamelCase = function () {
return this
.replace(/\s(.)/g, function ($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function ($1) { return $1.toLowerCase(); });
}
/**
* Pad the specified string
* @param {String} str The String
*/
String.prototype.pad = function (len) {
var pad = "0".repeat(len);
return (pad + this).slice(-len);
}
|
export default {
primary: 'Roboto',
secondary: 'monospace',
};
|
/*
ESTRUTURA DE DADOS PILHA
- Pilha é uma lista linear de acesso restrito, que permite apenas as operações
de inserção (push) e retirada (pop), ambas ocorrendo no final da estrutura.
- Como consequência, a pilha funciona pelo princípio LIFO (Last In, First Out -
último a entrar, primeiro a sair).
- A principal aplicação das pilhas são tarefas que envolvem a inversão de uma
sequência de dados.
*/
export default class Stack {
#data // Vetor privado
constructor() {
this.#data = [] // Vetor vazio
}
// Método para inserção no vetor
push(val) {
this.#data.push(val)
}
// Método para remoção do vetor
pop() {
return this.#data.pop()
}
// Método para consultar o topo (última posição) da pilha
// sem remover o elemento
peek() {
return this.#data[this.#data.length - 1]
}
// Getter para informar se a pilha está ou não vazia
// (propriedade somente leitura)
get isEmpty() {
return this.#data.length === 0
}
// Método que imprime a pilha (para efeitos de depuração)
print() {
return JSON.stringify(this.#data)
}
}
////////////////////////////////////////////////////////////////
|
// Unlike log4js, with Bunyan we have to create a single logger instance that the
// entire app shares. We'll use a singleton pattern to do that here.
//
// Here is a relevant discussion about this topic: https://github.com/trentm/node-bunyan/issues/116
//
var bunyan = require('bunyan');
var mainLogger;
// This method will only be called once (by the top level app) to pass in the config and create the
// main/root logger.
//
exports.createMainLogger = function(config)
{
// !!! We could be more clever about pulling config to configure Bunyan logging (other than just level for default stream)
//
// !!! Manta client uses this for level: process.env.MANTA_LOG_LEVEL || 'fatal',
//
mainLogger = bunyan.createLogger({
name: "CloudStashWeb",
level: config.get('LOG_LEVEL')
});
return mainLogger;
}
exports.createTestLogger = function()
{
mainLogger = bunyan.createLogger({name: "CloudStashTest"});
return mainLogger;
}
// All modules will call this to get a logger (typically by passing at least a category). If a category
// or any options are passed, an appropriate child logger will be returned.
//
// If you need the main logger for some reason, just call this with no params.
//
exports.getLogger = function(category, options, simple)
{
if (!category && !options)
{
return mainLogger;
}
else
{
options = options || {}
options.category = category;
return mainLogger.child(options, simple);
}
}
|
demo = window.demo || (window.demo = {});
let bgm;
let bg;
demo.online = function () { };
demo.online.prototype = {
preload: function () {
game.load.image('sky', '../assets/art/onlineBG3.png');
game.load.spritesheet('rain1', '../assets/art/redb1.png', 15, 15);
game.load.spritesheet('rain2', '../assets/art/redg1.png', 15, 15);
game.load.spritesheet('rain3', '../assets/art/redp1.png', 15, 15);
game.load.spritesheet('rain4', '../assets/art/redpk1.png', 15, 15);
game.load.audio('bgm', '../assets/music/Intermission.ogg');
},
create: function () {
bgm = game.add.audio('bgm');
bgm.play();
bgm.loopFull();
bg = game.add.image(0, 0, 'sky');
bg.width = 1000;
bg.height = 800;
var emitter = game.add.emitter(game.world.centerX, 0, 400);
emitter.width = game.world.width;
emitter.makeParticles('rain1');
emitter.minParticleScale = 0.1;
emitter.maxParticleScale = 0.5;
emitter.setYSpeed(300, 500);
emitter.setXSpeed(-5, 5);
emitter.minRotation = 0;
emitter.maxRotation = 0;
emitter.start(false, 1600, 5, 0);
var emitter2 = game.add.emitter(game.world.centerX, 0, 400);
emitter2.width = game.world.width;
emitter2.makeParticles('rain2');
emitter2.minParticleScale = 0.1;
emitter2.maxParticleScale = 0.5;
emitter2.setYSpeed(300, 500);
emitter2.setXSpeed(-5, 5);
emitter2.minRotation = 0;
emitter2.maxRotation = 0;
emitter2.start(false, 1600, 5, 0);
var emitter3= game.add.emitter(game.world.centerX, 0, 400);
emitter3.width = game.world.width;
emitter3.makeParticles('rain3');
emitter3.minParticleScale = 0.1;
emitter3.maxParticleScale = 0.5;
emitter3.setYSpeed(300, 500);
emitter3.setXSpeed(-5, 5);
emitter3.minRotation = 0;
emitter3.maxRotation = 0;
emitter3.start(false, 1600, 5, 0);
var emitter4= game.add.emitter(game.world.centerX, 0, 400);
emitter4.width = game.world.width;
emitter4.makeParticles('rain4');
emitter4.minParticleScale = 0.1;
emitter4.maxParticleScale = 0.5;
emitter4.setYSpeed(300, 500);
emitter4.setXSpeed(-5, 5);
emitter4.minRotation = 0;
emitter4.maxRotation = 0;
emitter4.start(false, 1600, 5, 0);
},
update: function () {
}
}
|
$('body').on('click','.user-update',function(data){
var name=$("input[name='name']").val();
var password=$("input[name='password']").val();
var campus=$("input[name='campus']").val();
var address=$("input[name='address']").val();
var email=$("input[name='email']").val();
var sign=$("input[name='sign']").val();
var updateid=$(this).attr("updateid");
var url=$(this).attr("action");
$.post(url,{id:updateid,name:name,password:password,campus:campus,address:address,email:email,sign:sign,
},function(data){
alert(data.name+"更新成功");
});
});
|
import { StaticQuery, graphql } from "gatsby";
import React from "react";
const TitleCertifications = () => (
<StaticQuery
query={graphql`
query {
wordpressAcfPages(wordpress_id: { eq: 23 }) {
acf {
title_certifications
sub_title_certifications
}
}
}
`}
render={data => (
<div className="co-sm-12 p0 col-lg-10">
<div className="se-cert_header">
<h2 className="se_cert_title">
{data.wordpressAcfPages.acf.title_certifications}
</h2>
<div className="se_cert_excerpt">
<p>{data.wordpressAcfPages.acf.sub_title_certifications}</p>
</div>
</div>
</div>
)}
/>
);
export default TitleCertifications;
|
var fs = require("fs"),
healthcare = [],
ratesOBJ = {},
tempOBJ = {};
//constructor
function Healthgroup(name, rates){
this.type = name;
this.rates = rates;
this.console = function(){
console.log(this);
};
}
//first
function parseFromFile(filename, name){
fs.readFile(filename, 'utf8', function(err, data){
if (err) {
console.log(err);
} else {
ctrObj(data, name);
}
});
}
//second
function ctrObj(data, name){
var rows = data.split(/\r?\n/);
var keys = rows.shift().split(",");
// var ratesARR = rows.map(function(row) {
var ratesARR = createRateObj(rows)
// console.log(row);
// console.log(row.split(",").reduce(key, pair){
// }
//////NEED TO GET NAME OR PROPERTY USED IN '0' and use in '1' to assign value
// var splRow = row.split(",");
// for (var i = 0; i < splRow.length; i++) {
// if (i===0) {
// tempOBJ[splRow[i]] = splRow[1];
// }
// }
// return tempOBJ;
// return row.split(",").reduce(function(map, val, i) {
// console.log(map);
// console.log("val is: " + val);
// console.log("i is: " + i);
// if (i===0) {
// map[val] = "";
// var myKey = map[val];
// console.log("0 if - myKey below: ");
// console.log(myKey);
// } else {
// map[1] = val;
// console.log("1 if - myKey below: ");
// console.log(myKey);
// }
// console.log("Map below");
// console.log(map);
// console.log("========END OF SET========");
// return map;
// }, {});
// console.log(ratesARR);
// for (var i = 0; i < ratesARR.length; i++) {
// ratesOBJ[i] = ratesARR[i];
// }
// console.log(ratesARR);
// var name = new Healthgroup(name, ratesOBJ);
// healthcare.push(ratesOBJ);
// console.log(healthcare);
// name.console();
}
parseFromFile("./Health_insurance.csv", "medical");
// parseFromFile("./Children_insurance.csv", "children");
console.log("This is running...")
function createRateObj(rows){
// console.log(rows);
for (var i = 0; i < rows.length; i++) {
console.log(rows.length);
var splRow = rows[i].split(",");
for (var i = 0; i < splRow.length; i++) {
console.log(splRow.length)
if (i===0) {
tempOBJ[splRow[i]] = splRow[1];
}
}
// console.log(tempOBJ);
}
// console.log(tempOBJ);
return tempOBJ;
}
|
import React from "react";
import ReactEmoji from "react-emoji";
import "./Message.css";
const Message = ({ message: { text, name, icon }, user }) => {
let isSentByCurrentUser = false;
const trimmedName = name.trim().toLowerCase();
if (user.name === trimmedName) {
isSentByCurrentUser = true;
}
const populateUserIcon = () => {
return name.toUpperCase().slice(0, 2);
};
return isSentByCurrentUser ? (
<div className="messageContainer justifyEnd">
<div className="userThumb"></div>
<div className="messageBox backgroundBlue">
<p className="messageText colorWhite">
{ReactEmoji.emojify(text)}
</p>
</div>
</div>
) : (
<div className="messageContainer justifyStart">
<div className="userThumb">
<span
style={{
border: `1px solid ${icon}`,
background: `${icon}`,
}}
>
{populateUserIcon()}
</span>
</div>
<div className="messageBox backgroundLight">
<p className="messageText colorDark">
{ReactEmoji.emojify(text)}
</p>
</div>
</div>
);
};
export default Message;
|
import React from 'react';
import { GoogleMap, withScriptjs, withGoogleMap, Marker, InfoWindow } from "react-google-maps"
const Map = props => {
const { lat, lng } = props.defaultGeocode
const renderMarkers = () => (
props.markers.map(place => {
console.log(place)
const { lat, lng } = place.geometry.location
return (<Marker key={place.id} position={{lat: lat, lng: lng}} onClick={() => props.handleSelectPlace(place)}/>)
})
)
return (
<GoogleMap defaultZoom={10} center={{lat: lat, lng: lng}} >
{renderMarkers()}
{props.selected && (
<InfoWindow
position={{lat: props.selected.geometry.location.lat, lng: props.selected.geometry.location.lng}}
onCloseClick={() => props.handleSelectPlace(null)}
>
<div>
<h2>{props.selected.name}</h2>
<p>{props.selected.formatted_address}</p>
</div>
</InfoWindow>
)}
</GoogleMap>
);
}
export default withScriptjs(withGoogleMap(Map))
|
import React from "react";
import { storiesOf } from "@storybook/react";
import { withKnobs } from "@storybook/addon-knobs";
import HOCExample from "./HOCExample";
import HooksExample from "./HooksExample";
const stories = storiesOf("react-hotkeyz", module);
stories.addDecorator(withKnobs);
stories.add("HOC example", () => <HOCExample />);
stories.add("Hooks example", () => <HooksExample />);
|
utils = require("./utils");
module.exports = {
init: function(collection) {
this.collection = collection;
(this.fetchById = function(math_ids, callback) {
if (math_ids.length == 0) {
callback([]);
return
}
this.collection
.find({ math_id: { $in: math_ids } })
.toArray(function(err, items) {
if (err) {
throw err;
} else {
callback(utils.uniquify(items));
}
});
}),
(this.fetchByName = function(math_name, callback) {
this.collection
.find({ name: { $regex: math_name } })
.toArray(function(err, items) {
if (err) {
throw err;
} else {
callback(utils.uniquify(items));
}
});
})
return this;
}
};
|
myStocks = null;
function Stock(ticker){
this.name = ticker;
this.price = 0;
this.chart = null;
this.tweets = [];
this.tweetSentCount = 0;
this.ps = -1;
this.ns = -1;
this.nus = -1;
this.htmlElement = document.getElementById(ticker)
this.currenttweetsaccountedfor = false;
//refreshCard(ticker);
}
ztik123 = '';
tickerIter = null;
ttt = null;
data_g = {
labels: [],
datasets: [{
label: 'Price ($)',
data: []
}]
}
options_g = {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: false
},
gridLines: {
display: false
}
}]
}
}
$(document).ready(function(){
window.name = "{\"current\":\"IBM\",\"list\":[\"IBM\",\"AAPL\",\"FB\"]}";
myStocks = new Map();
$('.sidenav').sidenav();
ttt = JSON.parse(window.name);
ttt.list.forEach(function(x){
document.getElementById("mystocks").innerHTML+=("afterend",
`<div id ="`+x+`"class="card mylight-blue">
<div class="card-content white-text">
<span class="card-title"><span class="sname">`+x+`</span><span class="sprice">$`+"5"+`</span></span>
<div class="chartDiv">
<canvas class="stockChart" width="200" height="100"></canvas>
</div>
<div class="twts"></div>
<div class="sent"><div class="pos"></div><div class="nut"></div><div class="neg"></div></div>
</div>
<div class="card-action">
<a href="index.html?`+x+`">More info</a>
</div>
</div>`);
myStocks[x] = new Stock(x);
});
tickerIter = 0;
refreshCard(ttt.list[tickerIter]);
//ttt.list.forEach(a => myStocks[a] = new Stock(a));
// ttt.list.forEach(
// function(a){
// refreshCard(a);
// }
// );
});
function addStockData(chart, label, data) {
if(chart.data.labels[chart.data.labels.length-1] === label){
return;
}
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
//chart.update();
}
function addData(label, data, ticker){
if(myStocks[ticker].chart===null){
data_g.datasets[0].data = data;
data_g.labels = label;
myStocks[ticker].chart = new Chart($('#'+ticker+' .stockChart')[0], {
type: 'line',
data: data_g,
options: options_g
});
//console.log("iuy");
}
myStocks[ticker].price = '$'+data[data.length-1];
addStockData(myStocks[ticker].chart, label[label.length-1], data[data.length-1]);
renderChart(ticker);
}
function addTweets(ticker, tweets){
//console.log(ticker);
myStocks[ticker].tweets = tweets;
myStocks[ticker].currenttweetsaccountedfor = false;
renderTweets(ticker);
//some update sentiment
}
function addSentiment(values, a, b/*ticker, pos, nut,neg*/){
sents = new Map();
sents['neutral'] = 0;
sents['positive'] = 0;
sents['negative'] = 0;
for(t=0;t<values.length;t++){
sents[values[t]]++;
}
ticker = ztik123;
pos = sents['positive']/values.length;
nut = sents['neutral']/values.length;
neg = sents['negative']/values.length;
if(myStocks[ticker].currenttweetsaccountedfor === false){
if(myStocks[ticker].ps === -1){
myStocks[ticker].ps = pos;
myStocks[ticker].ns = neg;
myStocks[ticker].nus = nut;
}else{
newps = myStocks[ticker].ps * myStocks[ticker].tweetSentCount + pos * myStocks[ticker].tweets.length
newns = myStocks[ticker].ns * myStocks[ticker].tweetSentCount + neg * myStocks[ticker].tweets.length
newnus = myStocks[ticker].nus * myStocks[ticker].tweetSentCount + nut * myStocks[ticker].tweets.length
myStocks[ticker].tweetSentCount += myStocks[ticker].tweets.length;
myStocks[ticker].ps = newps/myStocks[ticker].tweetSentCount;
myStocks[ticker].ns = newns/myStocks[ticker].tweetSentCount;
myStocks[ticker].nus = newnus/myStocks[ticker].tweetSentCount;
myStocks[ticker].currenttweetsaccountedfor = true;
}
}
renderSentiment(ticker);
}
function renderTweets(ticker){
let ele = $('#'+ticker+' .twts')[0];
ele.innerHTML = "";
for(i = 0;i < 3;i++){
var qt = document.createElement("blockquote");
qt.innerHTML = myStocks[ticker].tweets[i];
ele.appendChild(qt);
}
//ijhgfd
updateSentiment(myStocks[ticker].tweets);
}
function renderChart(ticker){
$('#'+ticker+' .sprice')[0].innerHTML = myStocks[ticker].price;
// while(myStocks[ticker].chart === null){
// }
myStocks[ticker].chart.update();
query(ticker, 10);
}
function renderSentiment(ticker){
$('#'+ticker+' .nut')[0].style.width = ''+(myStocks[ticker].nus*100+'%');
$('#'+ticker+' .neg')[0].style.width = ''+(myStocks[ticker].ns*100+'%');
$('#'+ticker+' .pos')[0].style.width = ''+(myStocks[ticker].ps*100+'%');
if(tickerIter+1 < ttt.list.length)
{
tickerIter++;
//console.log("refresh "+ttt.list[tickerIter]+"st "+tickerIter);
refreshCard(ttt.list[tickerIter]);
}else{
tickerIter = 0;
}
}
function refreshCard(ticker){
ztik123 = ticker;
updateStock(ticker, 'day');
}
|
function check() {
var u = document.getElementById("inputID").value;
var statue =false;
$.ajax({
url: "checkID.action",
data : {"userID":u},
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
datatype : "json",
async: false,
success:function(data) {
if(data.p=="false") {
document.getElementById("inputID").setCustomValidity("该用户名已经存在");
document.getElementById("inoutID").focus();
}
else {
document.getElementById("inputID").setCustomValidity("");
statue= checkPassword();
}
}
});
return statue;
}
function login() {
var u = document.getElementById("userID").value;
var p = document.getElementById("userPassword").value;
var statue =false;
$.ajax({
url: "login.action",
data : {"userID":u,"password":p},
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
datatype : "json",
async: false,
success:function(data) {
if(data.p=="id") {
document.getElementById("userPassword").setCustomValidity("");
document.getElementById("userID").setCustomValidity("该账号不存在");
document.getElementById("inoutID").focus();
}
if(data.p=="password"){
document.getElementById("userID").setCustomValidity("");
document.getElementById("userPassword").setCustomValidity("密码错误");
document.getElementById("inoutID").focus();
}
if(data.p=="pass") {
document.getElementById("userID").setCustomValidity("");
document.getElementById("userPassword").setCustomValidity("");
statue = true;
}
}
});
return statue;
}
function checkPassword()
{
var pass1 = document.getElementById("inputPassword");
var pass2 = document.getElementById("inputPasswordAgain");
if (pass1.value != pass2.value) {
document.getElementById("inputPasswordAgain").setCustomValidity("两次密码不一致");
document.getElementById("inputPasswordAgain").setCustomValidity.focus();
return false;
}
else {
pass2.setCustomValidity("");
return true;
}
}
|
import React from 'react';
import { describe, add } from '@sparkpost/libby-react';
import { UnstyledLink, Stack } from '@sparkpost/matchbox';
function DemoWrapper(props) {
return <a>{props.children}</a>;
}
describe('UnstyledLink', () => {
add('with an onClick', () => (
<UnstyledLink onClick={() => console.log('click')}>A link</UnstyledLink>
));
add('with an external link', () => (
<UnstyledLink to="https://google.com" external>
Google
</UnstyledLink>
));
add('wrapper components', () => (
<>
<UnstyledLink as={({ children }) => <a>{children}</a>}>A Function</UnstyledLink>
<UnstyledLink as={DemoWrapper}>A Component</UnstyledLink>
</>
));
add('disabled', () => (
<Stack>
<UnstyledLink disabled>Disabled Link without href</UnstyledLink>
<UnstyledLink disabled to="#">
Disabled Link with href
</UnstyledLink>
<UnstyledLink disabled onClick={() => console.log('i should not be clickable')}>
Disabled Link with onClick
</UnstyledLink>
<UnstyledLink disabled to="#" onClick={() => console.log('i should not be clickable')}>
Disabled Link with onClick and href
</UnstyledLink>
</Stack>
));
add('text props', () => (
<>
<UnstyledLink mr={400} color="purple.600" to="https://google.com" external>
A link
</UnstyledLink>
<UnstyledLink mr={400} color="green.700">
A link
</UnstyledLink>
</>
));
});
|
/*EXPECTED
2
3
5
7
11
*/
class _Main {
static function main (args : string[]) : void {
function * prime () : Generator.<void,number> {
NEXT:
for (var n = 2; true; ++n) {
for (var m = 2; m * m <= n; ++m) {
if (n % m == 0)
continue NEXT;
}
yield n;
}
}
var g = prime();
for (var i = 0; i < 5; ++i) {
log g.next().value;
}
}
}
|
const User = require("../models/user");
const bcrypt = require("bcryptjs");
module.exports = {
createUser: async function(args, req) {
const { email, name, password } = args.UserInput;
const existingUser = await User.findOne({ email });
if (existingUser) {
const error = new Error("User exists already!");
throw error;
}
const hashedPw = await bcrypt.hash(password, 12);
const user = new User({ email, name, password: hashedPw });
const createdUser = await user.save();
return { ...createdUser._doc, _id: createdUser._id.toString() };
}
};
|
/**
* Created by nick on 16-6-3.
*/
/**
* 引入依赖模块
*/
var express = require('express'),
http = require('http'),
routes = require('./routes'),
bodyParser = require( 'body-parser' ), //新增模块引用
path = require('path');
var app = express(),
server = http.Server(app);
/**
* 设置
*/
app.set('port', process.env.PORT || 3000); //服务启动端口
app.set('views', __dirname + '/views'); //视图文件
app.set('view engine', 'ejs'); //页面引擎
app.use('/', express.static(path.join(__dirname, 'assets'))); //静态文件路径
app.use( bodyParser.urlencoded({ extended: false }));
routes.all(app); //原app.get替换成 routes,所有的请求走routes.all里定义的函数
server.listen( app.get('port'), function(){ //监听服务端口
console.log( 'root server listening on port' + app.get( 'port' ));
});
server.on('close', function(){
console.log( 'close' );
});
|
var CaseManager = require("./common/CaseManager");
class DivorceCase {
constructor() {
this.caseManager = new CaseManager();
}
async createCase(isAccessibilityTest) {
var caseData = {
'Petitioner Solicitor Phone number':'0987654321',
'Marriage date':'01-01-2005',
'Fact': '5-year separation',
'Date the petitioner decided the marriage was over':'01-01-2011',
'Date the petitioner and respondent started living apart': '01-01-2012',
"Respondent's solicitor's Phone number": "02012345678"
};
await this.caseManager.createCase(caseData, isAccessibilityTest);
}
}
module.exports = DivorceCase;
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Menu } from 'antd'
import {
DesktopOutlined,
PieChartOutlined,
FileOutlined,
TeamOutlined,
UserOutlined
} from '@ant-design/icons'
import Icons from '@conf/icons'
import { Link, withRouter } from 'react-router-dom'
import { defaultRoutes } from '@conf/routes'
const { SubMenu } = Menu
// 获取redux中的 数据和方法
@withRouter
@connect(state => ({ permissionList: state.user.permissionList }))
class SiderMenu extends Component {
// 定义函数在函数中遍历数据进行动态渲染
renderMenu = menus => { // 将需要变量的数组传递进来
return menus.map(menu => { // 遍历得到的新数组返回出去
// 遍历完成后判断菜单是否需要渲染,通过hidden的属性值进行判断
if(menu.hidden) return
// 通过icon字符串找到对应的icon组件
const Icon = Icons[menu.icon]
if(menu.children && menu.children.length) {
// 若遍历的菜单有二级菜单则对二级菜单进行渲染
return(
<SubMenu key={menu.path} icon={<Icon/>} title={menu.name}>
{menu.children.map(secMenu =>{ // 遍历二级菜单
if(secMenu.hidden) return //若hidden为ture则不渲染
return <Menu.Item key={menu.path + secMenu.path}>
{/* 动态改变地址栏路径 */}
<Link to={menu.path + secMenu.path} >{secMenu.name}</Link>
</Menu.Item>
})}
</SubMenu>
)
}else{
// 只有一级菜单
return( // 这里return是给新数组添加一个菜单组件
<Menu.Item key={menu.path} icon={<PieChartOutlined/>}>
{/* 点击的一级菜单的路由路径是‘/’ 则不修改地址栏路径 */}
{menu.path === '/' ? <Link to='/'>{menu.name}</Link> : menu.names}
</Menu.Item>
)
}
})
}
render() {
const path = this.props.location.pathname
console.log(this.props);
//
const reg = /[/][a-z]*/ // 提取一级菜单路径的正则
const firstPath = path.match(reg)[0]
return (
<>
<Menu
theme='dark'
// 默认高亮的菜单项
defaultSelectedKeys={[path]}
mode='inline'
// 默然展开的一级菜单
defaultOpenKeys={[firstPath]}
>
{/* 调用函数遍历数据 */}
{this.renderMenu(defaultRoutes)}
{this.renderMenu(this.props.permissionList)}
</Menu>
</>
)
}
}
export default SiderMenu
|
import _ from "lodash";
import {
REQUEST_BOOK_LIST,
REQUEST_BOOK,
ADD_BOOK,
DELETE_BOOK,
UPDATE_BOOK,
UPDATE_BOOK_AVAILABILITY,
SET_SHOW_MODE
} from "./constants/ActionTypes";
const INITIAL_STATE = {
bookList: [],
book: {},
show: "store"
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case REQUEST_BOOK_LIST:
return { ...state, bookList: action.payload };
case REQUEST_BOOK:
return { ...state, book: action.payload };
case ADD_BOOK:
return { ...state, bookList: [...state.bookList, action.payload] };
case DELETE_BOOK:
const deleteId = action.payload;
const deleteIdx = _.findIndex(state.bookList, ["id", deleteId]);
return {
...state,
bookList: [
...state.bookList.slice(0, deleteIdx),
...state.bookList.slice(deleteIdx + 1)
]
};
case UPDATE_BOOK:
const updateBook = action.payload;
const updateIdx = _.findIndex(state.bookList, ["id", updateBook.id]);
return {
...state,
bookList: [
...state.bookList.slice(0, updateIdx),
updateBook,
...state.bookList.slice(updateIdx + 1)
]
};
case UPDATE_BOOK_AVAILABILITY:
const { id, book } = action.payload;
const idx = _.findIndex(state.bookList, ["id", id]);
return {
...state,
bookList: [
...state.bookList.slice(0, idx),
book,
...state.bookList.slice(idx + 1)
]
};
case SET_SHOW_MODE:
return { ...state, show: action.payload };
default:
return state;
}
};
|
import React from 'react'
import CommentItem from '../components/comments/CommentItem'
const Comments = (props) => {
let {comments, likeSubmitter, objectindex} = props
let indx=-1
let listComment = comments.map((item, index) => {
console.log("Key", indx)
indx++
return (
<CommentItem
key={index}
index={indx}
comment={item.comment}
likes={item.likes}
poster={item.poster}
postdate={item.postdate}
likeSubmitter={likeSubmitter}
objectindex={objectindex}
/>
)
});
return (
<div>
{listComment}
</div>
)
}
export default Comments
|
import React , {useEffect,useState,useContext,useRef} from 'react';
import axios from 'axios'
import {Card,Loading,BreadCrumb} from "../../../components";
import UserIcon from "../../../components/UserIcon";
import {APP_URL, ROOMS_PAGE, ROOMS_PAGE_API} from "../../../urls/AppBaseUrl";
const EditRoom = (props) => {
const [room,setRoom] = useState({})
const [loading,setLoading] = useState(true);
const avatarBtn = useRef(null);
const [previewAvatar,setPreviewAvatar] = useState("");
const [progress,setProgress] = useState(0);
console.log(room)
useEffect(() => {
getRoom();
},[]);
const chooseAvatar = (e) => {
e.preventDefault();
avatarBtn.current.click();
}
const avatarBtnChange = () => {
setRoom({...room,image: avatarBtn.current.files[0]})
setPreviewAvatar(URL.createObjectURL(avatarBtn.current.files[0]))
}
const updateRoom = (e) => {
// e.preventDefault();
// let formData = new FormData();
// formData.append('name', room.name);
// formData.append('image', room.image);
// formData.append('type', room.type);
// formData.append('_method', 'PATCH');
// axios({
// method:'POST',
// url : ROOMS_PAGE_API + room.id,
// data:formData,
// headers : {
// authorization : "Bearer " + auth.token,
// "Content-Type" : 'multipart/form-data'
// }
// })
// .then(res => {
// dispatchGlobalState(setToastShowAction())
// dispatchGlobalState(setToastMessage("Room edited successfully",`${room.name} is edited`))
// props.history.push('/app/rooms/'+ room.id)
// })
// .catch(err => {
// dispatchGlobalState(setToastShowAction())
// dispatchGlobalState(setToastMessage("Error, try again",`${room.name} failed to edit`))
// })
}
const getRoom = () => {
// axios({
// url: ROOMS_PAGE_API+ props.match.params.id,
// method: "GET",
// headers : {
// authorization : 'Bearer '+ auth.token,
// }
// })
// .then(res => {
// setRoom(res.data.data)
// setLoading(false)
// })
}
const render = () => {
if(loading) {
return (
<Loading>
<Loading.Large />
</Loading>
)
}else {
return (
<div className="room-page">
<BreadCrumb>
<BreadCrumb.Item url={APP_URL}>
Dashboard
</BreadCrumb.Item>
<BreadCrumb.Item url={ROOMS_PAGE}>
Rooms
</BreadCrumb.Item>
<BreadCrumb.Item url={ROOMS_PAGE+room.id}>
{
room.name
}
</BreadCrumb.Item>
<BreadCrumb.Active>
Edit
</BreadCrumb.Active>
</BreadCrumb>
<div className="form-container mr-auto ml-auto" style={{width:'500px'}} >
<Card style={{margin:"0 auto"}}>
<Card.Header>
<Card.Title>
Edit Room
</Card.Title>
</Card.Header>
<form className="form" onSubmit={updateRoom}>
<div className="form-group form-group-custom">
<label htmlFor="name"><i className="far fa-comments" /></label>
<input type="text" className="form-control"
value={room.name}
onChange={(e) => setRoom({...room,name:e.target.value})}
/>
</div>
<div className="form-group form-group-custom">
<label htmlFor="name"><i className="fas fa-users-slash" /></label>
<select
className="form-control select"
onChange={ e=> setRoom({...room, type:e.target.value})}
value={room.type}
>
<option value="0">Private</option>
<option value="1">Public</option>
</select>
</div>
<div className="form-group form-group-custom">
<label htmlFor="file" className="mr-2"><i className="fa fa-image"></i></label>
<input ref={avatarBtn} onChange={avatarBtnChange} type="file" className="d-none" />
<button id="file" className="upload-icon"
onClick={chooseAvatar}>
Upload Avatar
</button>
</div>
{
previewAvatar !== '' &&
<div className="form-group form-group-custom">
<UserIcon img={previewAvatar} alt="preview" />
</div>
}
{
progress > 0 && (
<div>
<progress min="0" max="100" value={progress} />
<span>{ progress } %</span>
</div>
)
}
<button className="btn btn-primary">Update</button>
</form>
</Card>
</div>
</div>
)
}
}
return render()
}
export default EditRoom;
|
const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = new Sequelize('licentaDB', 'root', '', {
dialect: 'mysql'
})
class Therapist extends Model {}
Therapist.init({
// Model attributes are defined here
id: {
type: DataTypes.NUMBER,
primaryKey: true
},
id_user: {
type: DataTypes.NUMBER,
foreignKey: true
}
}, {
// Other model options go here
sequelize, // We need to pass the connection instance
modelName: 'Therapist', // We need to choose the model name
tableName: 'therapist',
timestamps: false
});
Therapist.prototype.classrooms = async function() {
const classrooms = await this.getClassrooms();
return classrooms.map((classroom) => {
return {
name: classroom.name,
link: `/classrooms/${classroom.id}/show`,
id: classroom.id
}
})
}
module.exports = Therapist;
|
import React from 'react';
import { connect } from 'react-redux';
import ReactTooltip from 'react-tooltip';
import { MdEdit, MdDelete, MdRemoveRedEye, MdSettings, MdEuroSymbol } from 'react-icons/lib/md';
import { reset } from 'redux-form';
import { selectMember } from '../../actions/member.actions';
import { addMembership } from '../../actions/membership.action';
import { MonthDatas } from '../../models/datas';
import { getTrigrammeMonth } from '../../reducers/session.reducers';
import { checkMemberships } from '../../reducers/membership.reducers';
const ItemMember = ({item, appDOM, session, memberships, dispatch}) => (
<div>
<a data-tip data-for={'tooltip-member' + item.id} data-event="click focus">
<span className="bigramme">MN</span>
<p>
<span>{item.member.firstName}</span><br/>
{item.member.lastName}
<span className="month">{getTrigrammeMonth(item, session.labelSession, MonthDatas) }</span>
</p>
</a>
<ReactTooltip className="tooltip-member" place="right" globalEventOff="click" id={'tooltip-member' + item.id} type="light" effect="solid">
<div className="tooltip">
<a><MdRemoveRedEye /> Visualiser</a>
<a onClick={() => dispatch(addMembership(session, item.id))}
className={(checkMemberships(memberships, session, item.id)) ? 'no-active': ''}
><MdEuroSymbol />
Cotiser
</a>
<a onClick={
() => {
dispatch(selectMember(item.id));
appDOM.refs.refAdd.show();
dispatch(reset('memberForm'));
}}>
<MdEdit /> Modifier</a>
<a><MdDelete /> Supprimer</a>
<a onClick={
() => {
appDOM.refs.refSetting.show();
dispatch(reset('settingForm'));
dispatch(selectMember(item.id));
}}>
<MdSettings /> Paramètrer
</a>
</div>
</ReactTooltip>
</div>
);
const mapStateToProps = state => ({
session: state.session,
memberships: state.memberships
});
export default connect(mapStateToProps)(ItemMember);
|
function windowSize() {
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerWidth;
viewportheight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewportwidth = document.documentElement.clientWidth;
viewportheight = document.documentElement.clientHeight;
}
// older versions of IE
else {
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
viewportheight = document.getElementsByTagName('body')[0].clientHeight;
}
var size = new Object();
size.width = viewportwidth;
size.height = viewportheight;
return size;
}
function resizeElement(element)
{
var size = windowSize();
$(element).width(size.width);
$(element).height(size.height);
}
function fixDigits(number){
if (number < 10){
return "0" + number;
}
return number;
}
|
"use strict";
require('dotenv').config()
const algoliasearch = require('algoliasearch');
const axios = require('axios');
const appid = process.env.ALGOLIA_APPID;
const token = process.env.ALGOLIA_TOKEN;
const client = algoliasearch(appid, token);
const index = client.initIndex('forge_search');
const endpoint = 'https://forge-blog.netlify.com/api'
index.setSettings({
searchableAttributes: [
'title',
'content_html'
],
customRanking: [
'desc(popularity)'
]
});
const getForgeData = async () => {
try {
const response = await axios.get(endpoint);
return response.data.items;
} catch (e) {
console.error(e);
}
};
const updateAlgolia = async () => {
try {
getForgeData().then(result => index.addObjects(result));
} catch (e) {
console.error(e);
}
};
updateAlgolia();
|
const firebaseConfig = {
apiKey: "AIzaSyBa5hU_wLkB5qMAtxsy0fxxwZERbg9PlPE",
authDomain: "creative-agency-71b3d.firebaseapp.com",
databaseURL: "https://creative-agency-71b3d.firebaseio.com",
projectId: "creative-agency-71b3d",
storageBucket: "creative-agency-71b3d.appspot.com",
messagingSenderId: "979688065562",
appId: "1:979688065562:web:8628a1aa386df53377dfa3"
};
export default firebaseConfig;
|
import React, { useState } from 'react'
import { useHistory } from 'react-router-dom'
import './style.css'
const Login = () => {
const history = useHistory()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const Login = () => {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (email.length === 0 || password.length === 0) {
alert('All fields are required')
}
else if (!pattern.test(email)) {
alert('invalid email address')
}
else {
let users = JSON.parse(localStorage.getItem('users')) || []
users = users.filter((user) => user.email === email)
if (users.length === 0) {
alert('user not found')
} else if (users[0].password !== password) {
alert('Invalid Email or Password !')
} else {
history.push('/home')
}
}
}
return (
<>
<div className="d-flex align-items-center justify-content-center" style={{ height: '100vh', backgroundColor: '#10558c' }}>
<div className='col-lg-4 col-9'>
<h1 className="text-white text-center mb-5">Log in!</h1>
<div className="position-relative">
<input type="email" id="email" className="text form-control my-3 bg-transparent text-white" value={email} onChange={(e) => { setEmail(e.target.value) }} placeholder="Email Address" />
<label className="inputlabel" style={{ backgroundColor: '#10558c' }}>Email Address</label>
</div>
<div className="position-relative">
<input type="password" id="inputPassword5" className="text form-control bg-transparent text-white" value={password} onChange={(e) => { setPassword(e.target.value) }} placeholder="Password" />
<label className="inputlabel" style={{ backgroundColor: '#10558c' }}>Password</label>
</div>
<div className="bottom-action clearfix mt-2">
<label className="float-start form-check-label text-white"><input type="checkbox" /> Remember me</label>
<a href="/" className="float-end text-white">Forgot Password?</a>
</div>
<div className="d-grid gap-2 col-6 mx-auto mt-5">
<span className="btn btn-light" type="button" onClick={() => Login()}>Log in</span>
</div>
<p className="text-white mt-4 mx-auto col-lg-7 col-sm-4">Don't have account ?<a href='/Signup' className="text-light"> Sign up here</a></p>
</div>
</div>
</>
)
}
export default Login
|
import React, {
Component,
PropTypes,
} from 'react'
import {
View,
Image,
StyleSheet,
Text,
Button
} from 'react-native'
import { ACCENT_COLOR, PRIMARY_TEXT } from '@resources/colors'
import moment from 'moment'
import Panel from '@components/Panel'
export default class VoucherItem extends Component {
static defaultProps = {}
static propTypes = {}
constructor(props) {
super(props)
this.state = {}
}
render() {
const {
utilizado,
token,
restaurante,
promocao,
onUtilizarClick,
utilizadoEm,
validoAte,
} = this.props
const vencido = moment() > validoAte
return (
<Panel style={[styles.container, (utilizado || vencido) && styles.utilizado]}>
<Image
resizeMode={Image.resizeMode.contain}
source={{uri: restaurante.logoUrl}}
style={styles.logo} />
<View style={styles.leftColumn}>
<Image
style={styles.voucherSideImage}
source={require('@assets/images/voucher_side.png')}
resizeMode={Image.resizeMode.cover}
/>
</View>
<View style={styles.rightColumn}>
<Text style={styles.voucherText}>Voucher</Text>
<Text style={styles.promocaoText}>{promocao.nome}</Text>
{
vencido ?
<Text>Voucher vencido em {moment(validoAte).format('DD/MM')}</Text>
:
utilizado ?
<Text>Voucher utilizado em {moment(utilizadoEm).format('DD/MM')}</Text>
:
<Button
onPress={() => {}}
color={ACCENT_COLOR}
title={`UTILIZAR ATÉ ${moment(validoAte).format('DD/MM')}`}
/>
}
</View>
</Panel>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'row',
backgroundColor: 'white',
},
utilizado: {
backgroundColor: 'rgba(255, 255, 255, 0.1)',
opacity: 0.5,
},
voucherSideImage: {
flex: 1,
width: 30,
height: null,
opacity: 0.1,
},
leftColumn: {
backgroundColor: ACCENT_COLOR,
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
width: 30
},
rightColumn: {
alignItems: 'center',
justifyContent: 'center',
flex: 1,
padding: 10
},
logo: {
width: 55,
height: 40,
position: 'absolute',
right: 5,
top: 5
},
voucherText: {
fontSize: 46,
color: ACCENT_COLOR,
textAlign: 'center',
textAlignVertical: 'center',
},
promocaoText: {
color: PRIMARY_TEXT,
marginTop: 5,
marginBottom: 5
},
})
|
import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
class AddFileForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
description: '',
file: null
};
this.handleChange = this.handleChange.bind(this);
this.handleFile = this.handleFile.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
handleFile(event) {
this.setState({ file: event.target.files[0] });
}
handleSubmit(event) {
event.preventDefault();
const { name, description, file } = this.state;
const { subjectId } = this.props;
this.props.onSubmit({
name: name,
description: description,
file: file,
subjectId: subjectId
});
}
render() {
const { name, description } = this.state;
const { progress } = this.props;
return (
<form className="form" onSubmit={this.handleSubmit}>
<label htmlFor="name" className="form__label">Nazwa</label>
<input type="text" id="name" className="input" placeholder="Nazwa"
name="name" onChange={this.handleChange} value={name} required />
<label htmlFor="description" className="form__label">Opis pliku</label>
<textarea id="description" rows="10" className="input"
placeholder="Opis pliku" name="description"
onChange={this.handleChange} value={description} required></textarea>
<label htmlFor="file" className="form__label">Plik</label>
<input type="file" id="file" className="input"
onChange={this.handleFile} required />
<Button text="Dodaj plik" submit />
{progress ?
<span> {progress}% wysłano</span>
: ''}
</form>
);
}
}
AddFileForm.propTypes = {
subjectId: PropTypes.string.isRequired,
progress: PropTypes
.oneOfType([PropTypes.bool, PropTypes.number]).isRequired,
onSubmit: PropTypes.func.isRequired
};
export default AddFileForm;
|
var form = $("#collegeList");
var collegeSelect = $("<select name='department' id='department'>");
var majorSelect = $("<select name='major' id='major'>");
var classSelect = $("<select name='className' id='className'>");
$(document).ready(function() {
console.log("加载学院班级信息开始!");
console.log("初始化表单");
initForm();
console.log("初始化监听器");
initCollegeListener();
initMajorListener();
setCollegeData();
});
/**
* 通过后台显示的数据显示下拉框,后台需要传入{college:1,major:1,class:1}和最头的data
* 然后在callback中添加select和 监听事件
* @param data
*/
//获取学院信息
function setCollegeData() {
$.getJSON("college/college!showCollege?type=depart", function(data) {
var depInfos = data.depInfos;
$.each(depInfos, function(index, value) {
var departNo = value.departNo;
var department = value.department;
var option = $("<option value='" + department + "' id='"+departNo+"' >" + department
+ "</option>");
collegeSelect.append(option);
});
});
}
//获取专业信息
function setMajorData(value) {
$.getJSON("college/college!showCollege?type=major&departNo="+value,function(data){
var majors = data.majors;
majorSelect.empty();
var firstMajorData = $("<option value='-1'>全部</option>");
majorSelect.append(firstMajorData);
$.each(majors, function(index, value) {
var major = value.major;
var majorNo = value.majorNo;
var option = $("<option value='" + major + "' id='"+majorNo+"' >" + major
+ "</option>");
majorSelect.append(option);
});
});
}
//初始化学院下拉框的监听事件
function initCollegeListener() {
collegeSelect.change(function(event){
var collegeSelect = document.getElementById("department");
var value;
for(var i=0;i<collegeSelect.options.length;i++)
if(collegeSelect.options[i].selected){
value=collegeSelect.options[i].id;
}
if(value!=-1){
setMajorData(value);
}else{
alert("请选择具体的学院");
}
});
}
//初始化专业的下拉框的监听事件
function initMajorListener() {
majorSelect.change(function(){
var college;
var value;
var collegeSelect = document.getElementById("department");
//获得选中option的id
for(var i=0;i<collegeSelect.options.length;i++)
if(collegeSelect.options[i].selected){
college=collegeSelect.options[i].id;
}
var majorSelect = document.getElementById("major");
//获得选中option的id
for(var i=0;i<majorSelect.options.length;i++)
if(majorSelect.options[i].selected){
value=majorSelect.options[i].id;
}
var url = "college/college!showCollege?type=class";
if(value==-1&& college==-1){
alert("请选择学院");
return ;
}else if(value==-1&& college!=-1){
url=url+"&departNo="+college;
}else if(value!=-1){
url=url+"&majorNo="+value;
}
$.getJSON(url,function(data){
var classs = data.classInfos;
classSelect.empty();
var firstMajorData = $("<option value='-1'>全部</option>");
classSelect.append(firstMajorData);
$.each(classs, function(index, value) {
var className = value.className;
var classNo = value.classNo;
var option = $("<option value='" + className + "' >" + className
+ "</option>");
classSelect.append(option);
});
});
});
}
//初始化表单
function initForm() {
var firstMajor = $("<option value='-1'>无</option>");
var firstMajorData = $("<option value='-1'>全部</option>");
var firstClassData = $("<option value='-1'>全部</option>");
var input = $("<input name='student' value='输入学号或者姓名' id='studentNoOrName' size='14'>");
var button = $("#accurateSearch");
//插入下拉框
form.append("学院 ");
collegeSelect.appendTo(form);
form.append(" 方向 ");
majorSelect.appendTo(form);
form.append(" 班级 ");
classSelect.appendTo(form);
collegeSelect.append(firstMajor);
majorSelect.append(firstMajorData);
classSelect.append(firstClassData);
form.append(" ");
input.appendTo(form);
form.append(" ");
//添加失焦获焦事件
$.focusblur("#studentNoOrName");
form.append(button);
button="";
}
//input失去焦点和获得焦点jquery焦点事件插件
jQuery.focusblur = function(focusid) {
var focusblurid = $(focusid);
var defval = focusblurid.val();
focusblurid.focus(function(){
var thisval = $(this).val();
if(thisval==defval){
$(this).val("");
}
});
focusblurid.blur(function(){
var thisval = $(this).val();
if(thisval==""){
$(this).val(defval);
}
});
};
|
const React=require('react')
const styled=require('styled-components').default
const styles={
body:{
background:'#444',
padding:'10px'
},
box:{
background:'#fff',
padding:'20px 20px 5px'
}
}
const Main=styled.div`
div.box:not(:last-child){
margin-bottom:10px
}
`
const Title = styled.div`
line-height:25px;
min-height:50px;
img{
width:50px;
height:50px;
}
`
const Comment=styled.ul`
list-style:none;
font-style:normal;
margin:10px 0;
padding:0;
background:#eee;
line-height:25px;
font-size:14px;
li{
padding:8px 30px;
text-align:justify;
display:block;
}
li:not(.more){
p:before{
content:'';
display:block;
clear:both;
}
p{ margin:0;padding:0;
span{
float:right;
i{
font-style:normal;
}
img{
display:inline-block;
width:15px;
vertical-align: initial;
}
}
}
p:after{
content:'';
clear:both;
display:block;
}
}
li:not(:first-child){
border-top:1px solid #d9d9d9
}
li.more{
text-align:center;
a{
margin:0;padding:0;
text-decoration:none;
color:#096dd9;
}
}
em{
font-style:normal;
color:#eb7350
}
`
const Image = styled.div`
float:left
`
const Detail=styled.div`
margin-left:60px;
a{
display:block;
font-size:14px;
font-weight:bold;
color:#000;
text-decoration:none;
}
p{
margin:0;
padding:0;
text-align:justify;
}
`
class CommentTpl extends React.Component{
constructor (props){
super(props)
this.state={
commentState:[]
}
this.count=5;
}
render(){
const {data,config,label}=this.props
return (
<Main style={styles.body}>
{
data.map((item,index)=>{
this.state.commentState.push({state:false,count:5,text:'查看更多',icon:'down'})
return (
<div className='box' style={styles.box} key={index}>
<Title>
<Image>
<img
onError={(e)=>{
e.target.src="http://dlweb.sogoucdn.com/vr/images/7575.png"
}}
src={item.avatar}/>
</Image>
<Detail >
<a href="javascript:void(0)">{item.name}</a>
<small>{item.time}</small>
<p>{item.text}</p>
</Detail>
</Title>
{
item.comments&&!!item.comments.length&&<Comment>
{ item.comments.map((comment,subindex)=>{
if(subindex<this.state.commentState[index].count){
return (
<li key={subindex}>
<p>
<em>{comment.name}</em>:
{!!comment.prefixs&&'回复'}
{!!comment.prefixs&&<em>{comment.prefixs}</em>}
{comment.text}
{/*<span><Icon type="like" /><i>{comment.liked!=0?comment.liked:''}</i></span>*/}
<span><img src='https://dlweb.sogoucdn.com/vr/images/icon_lvff/like_1.png'/><i>{comment.liked!=0?comment.liked:''}</i></span>
</p>
</li>
)
}
})
}
{
item.comments&&item.comments.length>this.count&&
<li className='more' ref={(sef)=>{this.more=sef}}>
<a href='javascript:void(0)'
onClick={this.loadMore.bind(this,index)}>
{this.state.commentState[index].text}
{/*<Icon type={this.state.commentState[index].icon}/>*/}
</a>
</li>
}
</Comment>
}
</div>
)
})
}
</Main>
)
}
loadMore(clickIndex){
const {data,config}=this.props
const commentState=this.state.commentState
commentState[clickIndex].state=!commentState[clickIndex].state;
commentState[clickIndex].text='查看更多';
commentState[clickIndex].count=this.count;
commentState[clickIndex].icon='down';
if(commentState[clickIndex].state){
commentState[clickIndex].text='收起';
commentState[clickIndex].icon='up';
commentState[clickIndex].count=data[clickIndex].comments.length;
// commentState[clickIndex].count=get(data[clickIndex],config.commentName,'','array').length;
}
this.setState({
commentState:commentState
})
}
}
CommentTpl.defaultProps={
data:[{
text:'建设银行深圳分行校招待遇到底怎样啊,收到的offer没提。↵求问各位前辈,求详解。[微笑][微笑][微笑]',
name:'曲灵风',
author:'匿名发布:曲灵风',
avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',
time:'17-12-21',
comments:[{name:'文聘',prefix:'',text:'开始你的表演建设银行深圳分行校招待遇到底怎样啊,收到的offer没提。↵求问各位前辈,求详解。[微笑][微笑][微笑]建设银行深圳分行校招待遇到底怎样啊,收到的offer没提。↵求问各位前辈,求详解。[微笑][微笑][微笑]建设银行深圳分行校招待遇到底怎样啊,收到的offer没提。↵求问各位前辈,求详解。[微笑][微笑][微笑]',avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',liked:64568451},
{name:'萧让',prefix:'',text:'m',avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',liked:45456462},
{name:'曲灵风',prefix:'文聘:',text:'求详解[可怜]',liked:3},
{name:'曲灵风',prefix:'萧让:',text:'求详解',liked:5}]
},{
text:'应届生第一年年终奖发吗?发多少?',
name:'法正',
author:'匿名发布:法正',
avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',
time:'1天内'
},{
text:'应届生第一年年终奖发吗?发多少?',
name:'法正',
author:'匿名发布:法正',
avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',
time:'1天内',
comments:[{name:'元始天尊',prefix:'',text:'所以?',liked:1},
{name:'萧让',prefix:'',text:'m',avatar:'http://i9.taou.com/maimai/p/aurl/v3/avatar_xuesheng.png',liked:2},
{name:'曲灵风',prefix:'文聘:',text:'求详解[可怜]',liked:3},
{name:'萧让',prefix:'',text:'m',liked:4},
{name:'曲灵风',prefix:'文聘:',text:'求详解[可怜]',liked:5},
{name:'萧让',prefix:'',text:'m',liked:6},
{name:'曲灵风',prefix:'文聘:',text:'求详解+1[可怜]',liked:7}]
}],
config:{
}
}
module.exports=CommentTpl
|
import React, {Component} from 'react'
class IndividualProduct extends Component {
constructor() {
super()
}
render() {
return (
<div className = 'individual-product-container1 shadow-lg p-3 mb-5 rounded'>
<h3>{this.props.item.productName}</h3>
PRICE: {this.props.item.price}
<br/>
ITEMS REMAINING: {this.props.item.available}
<div style = {{marginTop: '45px', bottom: '0', right: '0', textAlign: 'right', color: 'white'}}>
<button style = {{background: 'none', padding: '0', border: 'none', color: 'white'}} onClick = {() => this.props.remove(this.props.item._id)}>REMOVE</button>
</div>
</div>
)
}
}
export default IndividualProduct
|
(function ($, undefined) {
$.namespace('inews.property.event');
inews.property.event.EventTypeDlg = function (options) {
var body, field, select, button;
var el, self = this;
this._options = options;
body = $('<div></div>').addClass('ia-event-type').addClass('ia-event-dlg');
if (this._options.id) body.attr('id', this._options.id);
field = $('<div></div>').addClass('field').appendTo(body);
$('<label></label>').html(MESSAGE['IA_EVENT_TYPE_EVENTTYPE']).appendTo(field);
select = $('<select></select>').attr('id', 'ia-event-type-eventtype').appendTo(field);
if (!this._options.isDocument) {
$('<option></option>').val('click').html(MESSAGE['IA_EVENT_TYPE_EVENTTYPE_CLICK']).appendTo(select);
} else {
$('<option></option>').val('scroll').html(MESSAGE['IA_EVENT_TYPE_EVENTTYPE_SCROLL']).appendTo(select);
}
//$('<option></option>').val('after').html(MESSAGE['IA_EVENT_TYPE_EVENTTYPE_AFTER']).appendTo(select);
$('<option></option>').val('custom').html(MESSAGE['IA_EVENT_TYPE_EVENTTYPE_CUSTOM']).appendTo(select);
field = $('<div></div>').addClass('field').addClass('eventtype-option').addClass('hidden').appendTo(body);
$('<label></label>').html(MESSAGE['IA_EVENT_TYPE_CUSTOMEVENT']).appendTo(field);
$('<input></input>').attr('id', 'ia-event-type-customevent').attr('type', 'text').appendTo(field);
field = $('<div></div>').addClass('field').addClass('eventtype-option').addClass('hidden').appendTo(body);
$('<label></label>').html(MESSAGE['IA_EVENT_TYPE_POSITION']).appendTo(field);
$('<input></input>').attr('id', 'ia-event-type-position').attr('type', 'text').appendTo(field);
select = $('<select></select>').attr('id', 'ia-event-type-position-unit').appendTo(field);
$('<option></option>').val('%').html('%').appendTo(select);
$('<option></option>').val('px').html('px').appendTo(select);
field = $('<div></div>').addClass('field').appendTo(body);
$('<label></label>').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE']).appendTo(field);
select = $('<select></select>').attr('id', 'ia-event-type-actiontype').appendTo(field);
$('<option></option>').val('style').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_STYLE']).appendTo(select);
if (!this._options.isDocument) {
$('<option></option>').val('scroll').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_SCROLL']).appendTo(select);
}
$('<option></option>').val('link').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_LINK']).appendTo(select);
$('<option></option>').val('play').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_PLAY']).appendTo(select);
$('<option></option>').val('fireevent').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_FIREEVENT']).appendTo(select);
$('<option></option>').val('script').html(MESSAGE['IA_EVENT_TYPE_ACTIONTYPE_SCRIPT']).appendTo(select);
$('<hr></hr>').appendTo(body);
button = $('<div></div>').addClass('buttonset').appendTo(body);
$('<button></button>').attr('id', 'ia-event-type-detect').attr('data-action', BTN_DETECT).addClass('hidden').html(MESSAGE['DETECT']).appendTo(button);
$('<button></button>').attr('id', 'ia-event-type-ok').attr('data-action', BTN_OK).html(MESSAGE['OK']).appendTo(button);
$('<button></button>').attr('id', 'ia-event-type-cancel').attr('data-action', BTN_CANCEL).html(MESSAGE['CANCEL']).appendTo(button);
this.dlg = new inews.Dialog({
width: 240,
//height: 82,
modal: true,
el: body,
title: MESSAGE['IA_EVENT_TYPE'],
showCloseBtn: false
});
this._el = this.dlg.getEl();
if (this._options.data) {
if (!this._options.data.eventpos) this._options.data.eventpos = [0, '%'];
$(this._el).find('#ia-event-type-eventtype').val(this._options.data.type);
$(this._el).find('#ia-event-type-customevent').val(this._options.data.customevent);
$(this._el).find('#ia-event-type-position').val(this._options.data.eventpos[0]);
$(this._el).find('#ia-event-type-position-unit').val(this._options.data.eventpos[1]);
$(this._el).find('#ia-event-type-actiontype').val(this._options.data.actiontype);
}
$(this._el).find('#ia-event-type-eventtype').on(EVT_CHANGE, function () {
var eventtype = $(this).val();
$(self._el).find('.field.eventtype-option').addClass('hidden');
switch (eventtype) {
case 'scroll':
self._el.find('#ia-event-type-detect').removeClass('hidden');
self._el.find('.field #ia-event-type-position').parent().removeClass('hidden');
//self.dlg.height(108);
break;
case 'custom':
self._el.find('#ia-event-type-detect').addClass('hidden');
self._el.find('.field #ia-event-type-customevent').parent().removeClass('hidden');
//self.dlg.height(108);
break;
default:
self._el.find('#ia-event-type-detect').addClass('hidden');
//self.dlg.height(82);
break;
}
});
$(this._el).find('#ia-event-type-eventtype').trigger(EVT_CHANGE);
$(this._el).find('.buttonset button').on(EVT_MOUSECLICK, function (e) {
var action = $(this).attr('data-action');
var data = self.getData();
if (action == BTN_DETECT) {
self._detect();
return;
} else if (action == BTN_OK) {
if (data.type == 'scroll' && isNaN(data.eventpos[0])) {
alert(MESSAGE['IA_EVENT_TYPE_INVALID_SCROLL_POSITION']);
return;
}
}
self._el.trigger(EVT_BUTTONCLICK, [action]);
self.close();
e.preventDefault();
e.stopPropagation();
});
};
inews.property.event.EventTypeDlg.prototype._detect = function () {
var self = this;
var nowData = this.getData();
var detectDlg;
var posPx, orientation;
orientation = $('.editor-area').IEditor('getOrientation');
if (!isNaN(parseFloat(nowData.eventpos[0]))) {
if (nowData.eventpos[1] == '%') {
if (orientation == ORIENTATION_LANDSCAPE) {
posPx = ($('.editor-area .editor').height() * (parseFloat(nowData.eventpos[0]) / 100)).toFixed(4);
} else {
posPx = ($('.editor-area .editor').width() * (parseFloat(nowData.eventpos[0]) / 100)).toFixed(4);
}
} else {
posPx = nowData.eventpos[0];
}
} else {
posPx = 0;
}
detectDlg = new inews.property.event.EventScrollToDetectDlg({
id: 'ia-event-type-scroll-detect',
position: posPx
});
this.dlg.hide();
$(detectDlg._el).one(EVT_BUTTONCLICK, function (e, action) {
if (action == BTN_APPLY) {
var nowData = self.getData();
var scrollPos;
if (orientation == ORIENTATION_LANDSCAPE) {
scrollPos = $('.editor-area').scrollLeft();
if (nowData.eventpos[1] == '%') {
scrollPos = ((scrollPos / $('.editor-area .editor').height()) * 100).toFixed(4);
}
} else {
scrollPos = $('.editor-area').scrollTop();
if (nowData.eventpos[1] == '%') {
scrollPos = ((scrollPos / $('.editor-area .editor').width()) * 100).toFixed(4);
}
}
$(self._el).find('#ia-event-type-position').val(scrollPos);
}
self.dlg.show();
});
};
inews.property.event.EventTypeDlg.prototype.close = function () {
var el = this.dlg.getEl();
$(el).find('#ia-event-type-eventtype').off(EVT_CHANGE);
$(el).find('.buttonset button').off(EVT_MOUSECLICK);
this.dlg.close();
};
inews.property.event.EventTypeDlg.prototype.getData = function () {
var el = this.dlg.getEl();
return {
type: $(el).find('#ia-event-type-eventtype').val(),
customevent: $(el).find('#ia-event-type-customevent').val(),
eventpos: [$(el).find('#ia-event-type-position').val(), $(el).find('#ia-event-type-position-unit').val()],
actiontype: $(el).find('#ia-event-type-actiontype').val()
};
};
inews.property.event.EventTypeDlg.prototype.getEl = function () {
return this._el;
};
}(jQuery));
|
const elephanttrunk = require("../objects/abilitys/elephanttrunk");
function elephanttrunkuse(aobjids, entities, creator) {
if (entities[creator] != undefined) {
if (!entities[creator].isdead) {
var objids = aobjids.giveid(true);
var a = new elephanttrunk(objids, entities[creator].id, entities[creator].mouth.x, entities[creator].mouth.y, entities[creator].angle, entities[creator].radius * 1.2)
entities[objids] = a;
}
}
}
elephanttrunkuse.prototype = {}
module.exports = elephanttrunkuse
|
import React from 'react';
import 'tachyons';
export const Demo_18 = ({ img, name, description }) => {
return (
<div
className='bg-light-gray dib br3 pa3 ma2 grow bw1 shadow-5 dim'
style={({ background: '#eeeeeb' }, { boxShadow: '24px 24px 48 #c3c3cl' })}
>
<img
className='br3'
style={{ height: '200px' }}
src={require(`../image/${img}.PNG`)}
alt='demo'
/>
<h2 className=''>{name}</h2>
<p>{description}</p>
</div>
);
};
export default Demo_18;
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | paper data table pagination', function(hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function() {
this.set('noop', function() {});
});
test('it renders startOffset - endOffset of total', async function(assert) {
this.setProperties({
page: 1,
limit: 10,
total: null
});
await render(hbs`{{paper-data-table-pagination onChangeLimit=noop page=page limit=limit total=total}}`);
// await pauseTest();
assert.dom('.buttons > .label').doesNotExist('Hidden if no total given');
this.set('total', 13);
assert.dom('.buttons > .label').hasText('1 - 11 of 13');
this.set('page', 2);
assert.dom('.buttons > .label').hasText('11 - 13 of 13', 'endOffset is capped at total');
});
});
|
angular.module("stepfoods", ['ui.bootstrap'])
.directive("background",function(){
return {
link: function (scope, element, attrs) {
element.css({'background':attrs.background});
},
restrict: 'A'
};
})
.directive("borderTopColor",function(){
return {
link: function (scope, element, attrs) {
element.css({'borderTopColor':attrs.borderTopColor});
},
restrict: 'A'
};
});
|
'use strict'
const User = require('../models/user.model')
const Bike = require('../models/bike.model')
const Dock = require('../models/dock.model')
const Station = require('../models/station.model')
const config = require('../config')
const httpStatus = require('http-status')
const uuidv1 = require('uuid/v1')
const APIError = require('../utils/APIError')
const mongoose = require('mongoose')
// Find the station and respond
exports.update = async (req, res, next) => {
try {
if(Object.keys(req.query).length === 0) throw new APIError(`Station ID Field can not be empty`, httpStatus.NOT_FOUND)
await Station.findOneAndUpdate(
{ 'station_id': req.query.station_id },
{ 'station_name': req.body.station_name,
'latitude': req.body.latitude,
'longitude': req.body.longitude
}
)
res.json({message: 'Updated Successfully'})
} catch (error) {
return next()
}
}
// Find the station and respond
exports.delete = async (req, res, next) => {
try {
if(Object.keys(req.query).length === 0) throw new APIError(`Station ID Field can not be empty`, httpStatus.NOT_FOUND)
await Station.findOneAndDelete({station_id: req.query.station_id});
res.json({message: 'Okay'})
} catch (error) {
return next()
}
}
// Find the station and respond
exports.find = async (req, res, next) => {
try {
if(Object.keys(req.query).length === 0) throw new APIError(`Station ID Field can not be empty`, httpStatus.NOT_FOUND)
Station.findOne({station_id: req.query.station_id}).exec((err,station) =>{
try {
if(!station) throw new APIError(`No station associated with id ${req.query.station_id}`, httpStatus.NOT_FOUND)
res.json({station: station})
} catch (error) {
return next()
}
})
} catch (error) {
return next()
}
}
exports.locate = async (req, res, next) => {
try {
Station.find({}).exec((err,stations) =>{
console.log(stations)
res.json({stations: stations})
})
} catch (error) {
return next()
}
}
exports.locateAll = async (req, res, next) => {
try {
Station.find({}). populate({
path: 'docks',
// Get Bikes of Docks - populate the 'bike' array for dock
populate: { path: 'bike' , options: {limit: 1}}
}).exec((err,stations) =>{
console.log(stations)
res.json({stations: stations})
})
} catch (error) {
return next()
}
}
//Station Registering
exports.register = async (req, res, next) => {
try {
const body = req.body
const station = new Station(body)
const savedStation = await station.save()
res.status(httpStatus.CREATED)
res.send(savedStation.transform())
} catch (error) {
return next(Station.checkDuplicateIDError(error))
}
}
|
import axios from 'axios'
import Consts from '../../../utils/consts'
import qs from 'qs'
import moment from 'moment'
export const getProfiles = () => {
return dispatch => {
axios.get(Consts.API_URL + "/Profiles?access_token=" + JSON.parse(localStorage.getItem('_user')).id)
.then(resp => {
dispatch({ type: 'GET_PROFILES', payload: resp })
}).catch(err => console.log(err.response.data))
}
}
export const getHistoryTasks = (fieldsToFilter = []) => {
const userId = JSON.parse(localStorage.getItem('_user')).userId
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
const countData = await axios.get(Consts.API_URL + "/Profiles/" + userId + "/taskHistory/count?" + access_token)
let filter = '?'
if (fieldsToFilter.length > 0 && fieldsToFilter[0].label !== "fromTo") {
filter += 'filter={"where":{"and":['
fieldsToFilter.map(f => {
if (f.label !== "fromTo") { filter += '{"' + f.label + '":"' + f.value + '"},' }
})
filter = filter.substring(0, filter.length - 1);
filter += ']}}'
}
else if (fieldsToFilter.length > 1) {
filter += 'filter={"where":{"and":['
fieldsToFilter.map(f => {
if (f.label !== "fromTo") { filter += '{"' + f.label + '":"' + f.value + '"},' }
})
filter = filter.substring(0, filter.length - 1);
filter += ']}}'
}
const query = Consts.API_URL + "/Profiles/" + userId + "/taskHistory" + filter + "&" + access_token
const taskData = await axios.get(query)
var after = taskData.data
if (fieldsToFilter.length !== 0) {
fieldsToFilter.map(f => {
if (f.label === "fromTo") {
after = []
taskData.data.map(d => {
if (moment(d.createdAt).local().format("YYYY-MM-DD") <= f.value.split(" ")[3] && moment(d.createdAt).local().format("YYYY-MM-DD") >= f.value.split(" ")[1]) {
after.push(d)
}
})
}
})
}
const resp = {
rows: after,
pages: Math.ceil(countData.data / 10)
}
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
dispatch({ type: 'GET_HISTORY_TASKS', payload: resp })
return resp
}
}
}
export const getActiveTasks = (fieldsToFilter = []) => {
const userId = JSON.parse(localStorage.getItem('_user')).userId
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
/* To show pagination correctly, we need to get a task count, on another query */
const countData = await axios.get(Consts.API_URL + "/Profiles/" + userId + "/taskList/count?" + access_token)
/* 1st line - 'where' that limits the tasks to those associated by userId or teamId: {"where": {"or": [{"assignedToId": profileId},{"assignedToId": teamId}]} */
/* 3rd line - sorting (ref: https://loopback.io/doc/en/lb2/Order-filter.html) */
/* 4th line - filtering (ref: https://loopback.io/doc/en/lb2/Where-filter.html) <- filtering not working properly */
/* 5th line - pagination (ref: https://loopback.io/doc/en/lb2/Skip-filter.html) */
// let filter = "?"/* + encoded + "&" */
//sorted.map((s, i) => filter += "filter[order]" + (sorted.length > 1 ? "[" + i + "]" : "") + "=" + s.id + "%20" + (s.desc ? "DESC" : "ASC") + "&")
// filter += "filter[limit]=" + pageSize + "&filter[skip]=" + (pageSize * page)
//let filter = '{"include": {"relation":"instances", "scope": { "where": { "createdAt":{ "gt": "2018-06-11T08:45:33.106Z"} } } } }'
let filter = '?'
if (fieldsToFilter.length > 0 && fieldsToFilter[0].label !== "fromTo") {
filter += 'filter={"where":{"and":['
fieldsToFilter.map(f => {
if (f.label !== "fromTo") { filter += '{"' + f.label + '":"' + f.value + '"},' }
})
filter = filter.substring(0, filter.length - 1);
filter += ']}}'
} else if (fieldsToFilter.length > 1) {
filter += 'filter={"where":{"and":['
fieldsToFilter.map(f => {
if (f.label !== "fromTo") { filter += '{"' + f.label + '":"' + f.value + '"},' }
})
filter = filter.substring(0, filter.length - 1);
filter += ']}}'
}
const query = Consts.API_URL + "/Profiles/" + userId + "/taskList" + filter + "&" + access_token
const taskData = await axios.get(query)
var after = taskData.data
//console.log(taskData.data)
if (fieldsToFilter.length !== 0) {
fieldsToFilter.map(f => {
if (f.label === "fromTo") {
after = []
taskData.data.map(d => {
if (moment(d.createdAt).local().format("YYYY-MM-DD") <= f.value.split(" ")[3] && moment(d.createdAt).local().format("YYYY-MM-DD") >= f.value.split(" ")[1]) {
after.push(d)
}
})
}
})
}
const resp = {
rows: after,
pages: Math.ceil(countData.data / 10)
}
return onSuccess(resp, fieldsToFilter)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp, fieldsToFilter) {
var corrective = 0
var preventive = 0
var evolutionary = 0
resp.rows.map(r => {
if (r.taskCatalog.type === "corrective") { corrective++ }
else if (r.taskCatalog.type === "preventive") { preventive++ }
else if (r.taskCatalog.type === "evolutionary") { evolutionary++ }
})
const result = {
data: resp.rows,
corrective: corrective,
preventive: preventive,
evolutionary: evolutionary,
}
if (fieldsToFilter.length === 0) {
dispatch({ type: 'GET_ACTIVE_TASKS', payload: result })
dispatch({ type: 'GET_TASKS', payload: result })
}
return resp
}
}
}
export const getFeedTasks = (userId) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
// console.log("UPDATE")
const resp = await axios.get(Consts.API_URL + "/Profiles/" + userId + "/taskList?" + access_token)
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err.response.data)
return err
}
function onSuccess(resp) {
dispatch({ type: 'GET_ACTIVE_TASKS', payload: resp })
return resp.data
}
}
}
export const updateTask = (taskData, taskId) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
// console.log("UPDATE")
const resp = await axios.put(Consts.API_URL + "/TaskCatalogs/" + taskId + "?" + access_token, qs.stringify(taskData))
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
dispatch({ type: 'END_TASK', payload: resp })
return resp
}
}
}
export const endTask = (taskData, taskId, action) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
const resp = await axios.post(Consts.API_URL + "/TaskInstances/" + taskId + "/" + action + "?" + access_token, taskData)
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
dispatch({ type: 'ERROR', payload: err })
console.log(err.response.data)
return err
}
function onSuccess(resp) {
dispatch({ type: 'END_TASK', payload: resp })
return resp
}
}
}
export const createTask = (taskData) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
const resp = await axios.post(Consts.API_URL + "/TaskCatalogs?" + access_token, qs.stringify(taskData))
//console.log("CRIAR")
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err.response.data)
}
function onSuccess(resp) {
dispatch({ type: 'DELETE_TASK' })
return resp
}
}
}
export const getTask = (id) => {
const userId = JSON.parse(localStorage.getItem('_user')).userId
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
let filter = "?filter[where][id]=" + id
const query = Consts.API_URL + "/Profiles/" + userId + "/taskList" + filter + "&" + access_token
const resp = await axios.get(query)
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
/* dispatch({ type: 'GET_ACTIVE_TASKS', payload: resp }) */
return resp
}
}
}
export const getInstance = (catalogId) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
const query = Consts.API_URL + "/TaskCatalogs" + catalogId + "/activeInstance?" + access_token
const resp = await axios.get(query)
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
/* dispatch({ type: 'GET_ACTIVE_TASKS', payload: resp }) */
return resp
}
}
}
export const getEventProfile = (eventId, instanceId, context) => {
const access_token = "access_token=" + JSON.parse(localStorage.getItem('_user')).id
return async dispatch => {
try {
const query = Consts.API_URL + "/" + context + "/" + instanceId + "/events/" + eventId + "/by?" + access_token
const resp = await axios.get(query)
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
return resp
}
}
}
export const getManagerData = (begin, end, teamId) => {
const access_token = "&access_token=" + JSON.parse(localStorage.getItem('_user')).id
const userId = JSON.parse(localStorage.getItem('_user')).userId
return async dispatch => {
try {
let team = teamId
if (team === undefined) {
const teamData = await axios.get(Consts.API_URL + "/Profiles/" + userId + "?" + access_token)
team = teamData.data.teamId
}
const baseTaskQuery = Consts.API_URL + "/Teams/" + team + "/taskList?"
const baseChecklistQuery = Consts.API_URL + "/Teams/" + team + "/checklist/active?"
const filterAlarmTasks = "filter=" + JSON.stringify({
where: {
and: [
{
'createdAt': {
between: [begin, end]
}
},
{
'alarmInstanceId': {
exists: true
}
}
]
}
})
const filterChecklistTasks = "filter=" + JSON.stringify({
where: {
and: [
{
'createdAt': {
between: [begin, end]
}
},
{
'checkpointId': {
exists: true
}
}
]
}
})
const filterChecklists = "filter=" + JSON.stringify({
where: {
'createdAt': {
between: [begin, end]
}
}
})
const respAlarmTasks = await axios.get(baseTaskQuery + filterAlarmTasks + access_token)
const respChecklistTasks = await axios.get(baseTaskQuery + filterChecklistTasks + access_token)
const respMiscTasks = await axios.get(baseTaskQuery + access_token)
const resp = {
tasks: {
alarm: respAlarmTasks.data,
checklist: respChecklistTasks.data,
misc: respMiscTasks.data
},
}
return onSuccess(resp)
} catch (err) {
return onError(err)
}
function onError(err) {
console.log(err.response.data)
dispatch({ type: 'ERROR', payload: err })
return err
}
function onSuccess(resp) {
return resp
}
}
}
export const saveTask = (data) => {
return async dispatch => {
try {
dispatch({ type: 'SAVE_TASK', payload: data })
return true
} catch (err) {
return false
}
}
}
|
import MicroTaskQueue from './micro-task-queue';
//TODO: sniff for nextTick or setImmediate
export default class NextFrameScheduler {
constructor(taskQueueGap) {
this._timeouts = [];
this._queue = new MicroTaskQueue(taskQueueGap || 0);
}
schedule(delay, state, work) {
var argsLen = arguments.length;
if(argsLen === 2) {
work = state;
state = delay;
delay = 0;
}
else if(argsLen === 1) {
work = delay;
state = undefined;
delay = 0;
}
if(delay === 0) {
this._queue.enqueue(state, work, this);
}
else if(delay > 0) {
var self = this;
// TODO: will this be more performant if it's using a MicroTaskQueue for each delay (cleared after frame end)?
var id = window.setTimeout(() => {
work(self, state);
}, delay);
this._timeouts.push(id);
}
}
dispose() {
if(this._queue) {
this._queue.dispose();
}
while(this._timeouts.length) {
window.clearTimeout(this._timeouts.shift());
}
}
}
|
import React, {Component} from 'react';
import { Text, View, TouchableHighlight } from 'react-native';
import PropTypes from 'prop-types';
export default class FormText extends Component {
render( ){
const { disabled, text, onPress, style } = this.props;
const opacityStyle = disabled ? 0.2 : null;
return(
<View>
<TouchableHighlight
onPress = {onPress}
style={{opacity: opacityStyle}}>
<Text style = {style}>
{ text }
</Text>
</TouchableHighlight>
</View>
);
}
}
FormText.propTypes = {
text: PropTypes.string.isRequired,
onPress: PropTypes.func,
styles: PropTypes.object,
};
|
const readline = require("readline")
const rl = readline.createInterface({input : process.stdin, output : process.stdout}) //Utilisé afin de pouvoir lire des données en entrée
module.exports = rl
|
const jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer");
import connectDb from "../../../../utils/connectDb";
import User from "../../../../models/User";
import generateInline from "../../../../templates/verifyForgotPassword";
import baseUrl from "../../../../utils/baseUrl";
connectDb();
const handler = async (req, res) => {
switch (req.method) {
case "POST":
await handlePostRequest(req, res);
break;
default:
res.status(405).send(`Method ${req.method} not allowed`);
break;
}
};
// @route POST api/verification/send/forgotPassword
// @desc send user email with link to verify their registered email address
// @res
// @access Public
async function handlePostRequest(req, res) {
const { userEmail } = req.body;
try {
//verify user exists
const user = await User.findOne({ email: userEmail });
if (!user) {
return res.status(400).send("Bad Request");
}
//create JWT to store user id
const payload = {
verifyUserId: user._id,
basis: "password_reset",
};
const verificationToken = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2d",
});
//create verification link with jwt
const passwordResetLink = `${baseUrl}/verify/resetPassword?token=${verificationToken}`;
//genereate email html
let htmlBody = generateInline(passwordResetLink);
//create nodemailer instance
var transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
var mailOptions = {
from: `BoardRack <${process.env.EMAIL_USER}>`,
to: userEmail,
subject: "Password Reset",
html: htmlBody,
};
//send email
let info = await transporter.sendMail(mailOptions);
if (!info) {
res.status(500).send("Could Not Send Email");
}
res.status(200).send("Email Sent");
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
export default handler;
|
import axios from 'axios'
import { sleep } from '@utils';
class WavesAPIService {
checkDataTXGetterTry = 0;
checkTokenTry = 0;
async getDataTX(id) {
let nodeHost = (['tokenrating.wavesexplorer.com', 'tokenrating.philsitumorang.com'].includes(window.location.host))
? 'https://nodes.wavesnodes.com'
: 'https://pool.testnet.wavesnodes.com';
try {
const data = await axios.get(`${nodeHost}/transactions/info/${id}`);
return data.data;
} catch (err) {
console.log('!!!!!!!!!', err);
return null;
}
}
// TO DO use waitForTx from waves-transactions
async checkDataTX(id) {
return new Promise( async (resolve, reject) => {
const result = await this.getDataTX(id);
if (result === null) {
this.checkDataTXGetterTry++;
if (this.checkDataTXGetterTry >= 30) {
// return reject(translate('check_data_tx_error_cant_find_tx'));
return reject();
}
await sleep(2000);
resolve(this.checkDataTX(id));
} else {
resolve(result);
}
});
}
async waitForTokenExist(assetId) {
return new Promise( async (resolve, reject) => {
const res = await axios.get(`/api/v1/token/isExists?assetId=${assetId}`);
const isExists = res.data.isExists;
if (isExists) {
resolve(res.data);
} else {
this.checkTokenTry++;
if (this.checkTokenTry >= 30) {
return reject();
}
await sleep(2000);
resolve(this.waitForTokenExist(assetId));
}
});
}
}
const wavesApiService = new WavesAPIService();
export default wavesApiService;
|
import React, { Component } from 'react'
import Style from './index.scss'
class PopRight extends Component{
constructor (props) {
super(props)
}
handleClick(e){
e.stopPropagation
}
render () {
let {popData, show} = this.props
return (
<div className={Style.popright} style={{width: show? '450px': '0px'}} onClick={this.handleClick}>
<div dangerouslySetInnerHTML={{__html: popData}} className={Style.content}>
</div>
</div>
)
}
}
export default PopRight
|
const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const config = require('./config.js');
const webpack = require('webpack');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const {
app,
modulesPath,
staticPath,
} = config;
module.exports = merge(common, {
entry: {
[app]: [
'react-hot-loader/patch',
'webpack-dev-server/client',
'webpack/hot/only-dev-server',
path.resolve(__dirname, '../src/index.dev.jsx'),
],
},
output: {
filename: '[name].js',
},
devtool: 'eval',
module: {
rules: [
{
test: /\.jsx?$/,
enforce: 'pre',
loader: 'eslint-loader',
exclude: modulesPath,
},
{
test: /\.jsx?$/,
loader: 'babel-loader?cacheDirectory',
exclude: modulesPath,
},
{
test: /\.s(c|a)ss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: `${app}-[hash:6]`,
sourceMap: true,
minimize: false,
},
},
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')(),
],
},
},
{
loader: 'sass-loader',
options: {
loadPath: path.resolve(__dirname, '../'),
},
},
],
exclude: [modulesPath, staticPath],
}, {
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize: false,
},
},
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')(),
],
},
},
],
include: [modulesPath, staticPath],
}, {
test: /\.(png|jpe?g|gif|woff|woff2|ttf|eot)$/,
loader: 'url-loader',
}, {
test: /\.svg$/,
loader: 'raw-loader',
},
],
},
plugins: [
// 打开webpack热加载模块
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
// 跳过编译时出错的代码
new webpack.NoEmitOnErrorsPlugin(),
// 确保新引入包时强制重新编译项目
new WatchMissingNodeModulesPlugin(modulesPath),
],
});
|
function getSecondsToTomorrow() {
var now = new Date();
var tommorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
var diff = tommorrow - now;
return Math.floor(diff / 1000);
}
console.log(getSecondsToTomorrow());
|
jQuery(document).foundation();
/*********
accordions
*********/
jQuery(function accordions() {
jQuery('.accordionContent').hide();
jQuery('.accordionTitle').on('click', function () {
jQuery('.accordionTitle').removeClass('open');
if (jQuery(this).next('.accordionContent').is(':hidden')) {
jQuery(this).toggleClass('open');
jQuery('.accordionContent').slideUp();
jQuery(this).next('.accordionContent').slideToggle();
} else {
jQuery(this).next('.accordionContent').slideToggle();
}
});
});
/*
* Put all your regular jQuery in here.
*/
jQuery(document).ready(function() {
/*********
mobile nav
*********/
jQuery('#mobileNav').on('click', function (e) {
if (jQuery(document).width() <= 640) {
e.preventDefault();
e.stopPropagation();
jQuery('#mobileNav').children('span').fadeToggle('fast');
jQuery('.main_nav').slideToggle('fast');
}
});
jQuery(document).on('click', function () {
if (jQuery(document).width() <= 640) {
jQuery('#mobileNav').children('span').removeAttr('style');
jQuery('.main_nav').slideUp('fast');
}
});
}); /* end of as page load scripts */
|
'use strict';
const FeedParser = require('feedparser');
const request = require('request');
const sharp = require('sharp');
const imagemin = require('imagemin');
const fileType = require('file-type');
const routes = {
hello(req, res) {
return res.send('🙋🙋♂️');
},
feeds(req, res) {
const url = req.query.url;
const feedRequest = request({
url: url,
gzip: true
});
const feedParser = new FeedParser({
addmeta: true,
normalize: true
});
let items = [];
feedRequest.on('error', () => res.sendStatus(500));
feedRequest.on('response', response => {
if (response.statusCode !== 200) {
return feedRequest.emit('error', new Error('Bad status code'));
}
feedRequest.pipe(feedParser);
});
feedParser.on('error', () => res.sendStatus(500));
feedParser.on('readable', () => {
let item;
while ((item = feedParser.read())) {
items.push(item);
}
});
feedParser.on('end', () => res.send(items));
},
assets(req, res) {
const {url, width, height} = req.query;
request(url, {
encoding: null,
gzip: true
}, (error, response, body) => {
if (error || response.statusCode !== 200) {
return res.sendStatus(500);
}
sharp(body)
.resize(parseInt(width, 10), parseInt(height, 10))
.png()
.toBuffer()
.then(outputBuffer => {
res.set('Content-Type', 'image/png');
return res.send(outputBuffer);
})
.catch(() => res.sendStatus(500));
});
},
optimize(req, res) {
const input = req.query.url;
request(input, {
encoding: null,
gzip: true
}, (error, response, body) => {
if (error || response.statusCode !== 200) {
return res.sendStatus(500);
}
const plugins = [
require('imagemin-svgo')(),
require('imagemin-gifsicle')(),
require('imagemin-jpegtran')(),
require('imagemin-optipng')(),
require('imagemin-zopfli')({more: true})
];
// If the user agent accepts WebP send it
const acceptHeader = req.headers.accept || '';
if (/image\/webp/.test(acceptHeader)) {
plugins.push(require('imagemin-webp')());
}
imagemin.buffer(body, {plugins: plugins})
.then(outputBuffer => {
res.set('Content-Type', fileType(outputBuffer).mime);
return res.send(outputBuffer);
})
.catch(() => res.sendStatus(500));
});
},
proxy(req, res) {
const url = req.query.url;
request(url, {
gzip: true,
encoding: null
}, (error, response, body) => {
if (error || response.statusCode !== 200) {
return res.sendStatus(404);
}
res.set({
'Content-Type': response.headers['Content-Type'],
'Cache-Control': response.headers['Cache-Control'] ?
response.headers['Cache-Control'] : 'max-age=3600'
});
return res.send(body);
});
},
manifests(req, res) {
const base64 = req.query.base64;
res.set('Content-Type', 'application/manifest+json');
return res.send(new Buffer(base64, 'base64').toString());
}
};
module.exports = routes;
|
import React, { Component, PropTypes } from 'react';
import s from "./Comment.css";
import {HeaderPortrait} from "../../components";
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import ClassName from 'classnames';
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
let {className,...other} = this.props;
return(
<div className={ClassName([s.list,className])}>
<HeaderPortrait {...other} />
</div>
)
}
}
export default withStyles(s)(Comment);
|
import React from "react";
import NextLink from "next/link";
import cn from "../../utils/classnames";
import "./Link.css";
export default function Link({
href = "",
postfix = null,
prefix = null,
full = false,
children,
style,
target,
}) {
const classNames = cn({
link: true,
"link--full": full,
});
return (
<NextLink href={href}>
<a style={style} target={target} className={classNames}>
{prefix && <span className="link__prefix">{prefix}</span>}
<span className="link__el">{children}</span>
{postfix && <span className="link__postfix">{postfix}</span>}
</a>
</NextLink>
);
}
|
(function () {
angular
.module('myApp')
.controller('MultiViewController', MultiViewController)
.component('multiView', multiViewComponent());
function multiViewComponent() {
return {
restrict: 'E',
templateUrl: "./app/components/multiView.html",
controller: 'MultiViewController',
controllerAs: 'ctrl'
}
}
MultiViewController.$inject = ['confirmModalService', 'localStorageService', 'todoItemConstructor', 'editTodoModalService', 'newTitleModalService', 'utilService'];
function MultiViewController(confirmModalService, localStorageService, todoItemConstructor, editTodoModalService, newTitleModalService, utilService) {
var ctrl = this;
ctrl.newTodo = [];
ctrl.userLists = localStorageService.getStorageSync('lists');
ctrl.addNewTodo = addNewTodo;
ctrl.completeTodo = completeTodo;
ctrl.openEditTodoModal = openEditTodoModal;
ctrl.deleteTodo = deleteTodo;
ctrl.renameList = renameList;
ctrl.openConfirmDeleteModal = openConfirmDeleteModal;
//////////
function addNewTodo(todoTitle, listIndex) {
debugger;
if (todoTitle !== '' && todoTitle !== undefined) {
var newTodoObj = new todoItemConstructor.Todo(todoTitle);
ctrl.userLists[listIndex].todos.push(newTodoObj);
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
ctrl.newTodo = [];
}
}
function completeTodo() {
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
}
function openEditTodoModal(todoObj) {
editTodoModalService.editTodoModal(todoObj, handleEditedTodo);
}
function handleEditedTodo(todoObj) {
var listIndex = utilService.returnIndexFromItemId(ctrl.userLists, todoObj.firstListId);
var todoIndex = utilService.returnIndexFromItemId(ctrl.userLists[listIndex].todos, todoObj.todo.id);
switch (todoObj.operation) {
case 'delete':
ctrl.userLists[listIndex].todos.splice(todoIndex, 1);
break;
case 'save':
ctrl.userLists[listIndex].todos.splice(todoIndex, 1, todoObj.todo);//edit
break;
default:
console.log('default');
}
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
ctrl.currList = utilService.getItemFromArrayById(ctrl.userLists, ctrl.listId);
}
function deleteTodo(todoIndex, listId) {
var listIndex = utilService.returnIndexFromItemId(ctrl.userLists, listId);
ctrl.userLists[listIndex].todos.splice(todoIndex, 1);
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
ctrl.currList = utilService.getItemFromArrayById(ctrl.userLists, ctrl.listId);
}
function renameList(newTitleObj) {
if (utilService.doesItemTitleExists(ctrl.userLists, newTitleObj.newListTitle)) {
newTitleObj.cb = ctrl.renameList;
newTitleModalService.inputNewTitleModal(newTitleObj);
} else {
newTitleObj.listIndex = ctrl.userLists.findIndex(function (list) {
return list.id === newTitleObj.listId
});
ctrl.userLists[newTitleObj.listIndex].title = newTitleObj.newListTitle;
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
}
}
function openConfirmDeleteModal(listId) {
confirmModalService.confirmModal(handleDeleteList, listId);
}
function handleDeleteList(listId) {
var listIndex = ctrl.userLists.findIndex(function (list) {
return list.id === listId
});
ctrl.userLists.splice(listIndex, 1);
ctrl.userLists = localStorageService.populateStorage('lists', ctrl.userLists);
}
}
})();
|
const webpack = require("webpack")
const env = process.env.ELEVENTY_ENV || "production"
module.exports = {
output: {
libraryTarget: "var",
library: "App"
},
plugins: [
new webpack.DefinePlugin({
ENV: JSON.stringify(env),
GOOGLE_ANALYTICS_ID: JSON.stringify(process.env.GOOGLE_ANALYTICS_ID),
ANALYTICS_APP_NAME: JSON.stringify(process.env.ANALYTICS_APP_NAME)
})
],
mode: env,
watch: env === "development"
}
|
import { Selector } from 'testcafe';
import { getButtonText, createBaseTestSetup } from '../helpers'
import configData from "../configuration.json";
fixture.skip`AdditionalFunctionalCases:`
.page`http://localhost:8080/`
.before(async t => { })
.beforeEach(async t => {
console.log('Before each test')
await t.setTestSpeed(0.1)
await t.setPageLoadTimeout(5000) // maximum value 0
})
.after(async t => { })
.afterEach(async t => { })
test.skip('Visiter user clicks on Quit game', async t => {
var data = configData.SERVER_URL
console.log(data)
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Main user clicks on Quit game', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Opponent user clicks on Quit game', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Main user Refresh the Live session', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Opponent user : Refresh the live session', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Verify when the MainUser user quits the session', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Verify when the MainUser user quits the session', async t => {
// currently , system terminates the session for all users if third user clicks on Quit Game button
})
test.skip('Verify casting: E1 to A1', async t => {
})
test.skip('Verify casting: E1 to H1', async t => {
})
test.skip('Verify casting: E8 to H8', async t => {
})
test.skip('Verify casting: E8 to H8', async t => {
})
test.skip('Verify casting: After A1 is already moved once', async t => {
})
test.skip('Verify casting: After H1 is already moved once', async t => {
})
test.skip('Verify casting: After E1 is already moved once', async t => {
})
test.skip('Verify casting: After A8 is already moved once', async t => {
})
test.skip('Verify casting: After H8 is already moved once', async t => {
})
test.skip('Verify casting: After E8 is already moved once', async t => {
})
test.skip('Verify casting: After E8 is has been checked once', async t => {
})
test.skip('Verify casting: After E1 is has been checked once', async t => {
})
test.skip('Verify move direction: Knight', async t => {
// can be for black and white
})
test.skip('Verify player can not move opponet peices', async t => {
})
test.skip('Verify player can not move peices in wrong place', async t => {
// This will include all peices and their direction
// we can re verify after dragging and dropping if it is moved or not
})
test.skip('Verify valid move direction : Knight', async t => {
// can be for black and white
// But I require certain modification in the xpath locator or on the board
// Undo MOVE for option for test env - otherwise need to recreate board again each time
// peiceCanMoveFromTo(A2 ,C1)
// peiceCanMoveFromTo(A2 ,C3)
})
test.skip('Verify valid move direction : Rook', async t => {
// can be for black and white
})
test.skip('Verify valid move direction : Bishop', async t => {
// can be for black and white
})
test.skip('Verify valid move direction : King', async t => {
// can be for black and white
})
test.skip('Verify valid move direction : Queen', async t => {
// can be for black and white
})
test.skip('Verify valid move direction : Pawn', async t => {
// Also check its working correctly after opponent's turn
// can be for black and white
// Single move forward
// double move forward
// move forward is Stopped as there is piece in front of it
// move cross
// Also at the end of black line - PAWN can create the valid (QUEEN-ROOK-Bishop-Knight)
})
test.skip('Verify casting rules ', async t => {
// The castling must be kingside or queenside.
// Neither the king nor the chosen rook has previously moved.
// There are no pieces between the king and the chosen rook.
// The king is not currently in check.
// The king does not pass through a square that is attacked by an enemy piece.
// The king does not end up in check. (True of any legal move.)
})
test.skip('Verify captures rules ', async t => {
// for each peice
})
test.skip('White to black: Verify move : check', async t => {
// can also check this condition with different peceis
// like check with pawn - queen ...
})
test.skip('Black to White: Verify move : check', async t => {
// can also check this condition with different peceis
})
test.skip('Black to White: Verify move : check mate', async t => {
// can also check this condition with different peceis
})
test.skip('White to black: Verify move : check mate', async t => {
// can also check this condition with different peceis
})
test.skip('White player quits game: on his turn', async t => {
})
test.skip('White player quits game: Not on his turn', async t => {
})
test.skip('White player turn: server connection lost', async t => {
})
test.skip('black player turn: server connection lost', async t => {
})
test.skip('White player quits game: connection lost from server', async t => {
})
test.skip('Black player quits game: connection lost from server', async t => {
})
test.skip('Black player quits game: on his turn', async t => {
})
test.skip('Black player quits game: Not on his turn', async t => {
})
test.skip('Verify time over for : White', async t => {
// It is not applicable for this test suite
})
test.skip('Verify time over for : Black', async t => {
// It is not applicable for this test suite
})
test.skip('Verify time over for : White', async t => {
// It is not applicable for this test suite
})
test.skip('Verify time over for : Black', async t => {
// It is not applicable for this test suite
})
|
import React from "react";
import InoContact from "./contacts/info";
import FormsContact from "./contacts/form";
const ContactIndex = () => (
<section className="no-contact">
<div className="container">
<div className="row justify-content-center">
<div className="col-12 ">
<div className="se_contact_excerpt row justify-content-center has-ovlay ">
<div className="bg-ovelay"></div>
<FormsContact />
<InoContact />
</div>
</div>
</div>
</div>
</section>
);
export default ContactIndex;
|
$(function() {
$.ajax({
url: "/menulist",
cache: false,
success: function(data){
var menuList = JSON.parse(data);
generateMenu(menuList,$('#cssmenu'));
}
});
});
function generateMenu( menuList, parentContainer){
var parentUL = $('<ul></ul>').appendTo(parentContainer);
for( var i=0; i< menuList.length; i++)
{
var li = $('<li></li>').appendTo(parentUL);
var anchor = $('<a></a>').attr('href',menuList[i].link?menuList[i].link:'#').text(menuList[i].title).appendTo(li);
if(menuList[i].link && (menuList[i].link.indexOf('http')!==-1))
anchor.attr('target','_blank');
if (menuList[i].children && menuList[i].children.length > 0)
{
$('<span class="parentli"></span>').appendTo(li);
generateMenu(menuList[i].children,li);
}
}
}
|
import AddressCascader from './address-cascader.vue'
export default AddressCascader
|
import React, { Component } from 'react';
import {getUserPreferenceData, deleteUserData} from '../serviceclient';
import Button from 'react-bootstrap/Button';
import { Redirect } from 'react-router-dom';
class GetUserPreferences extends Component {
state = {userPreferenceData:[], redirect:false}
componentDidMount(){
getUserPreferenceData(sessionStorage.cardButtonID).then(data => {
this.setState({userPreferenceData : data })
})
}
cardDeleteFunction = (e) => {
e.preventDefault();
deleteUserData(e.target.value).then(function(response){
console.log("delete response",response)
})
this.setState({redirect : true})
}
render() {
const {redirect} = this.state;
if (redirect) {
return <Redirect to='/ConsultantView' push="true"/>;
}
const preferenssiprintti = this.state.userPreferenceData.map(value => {
return (<ul key={value.person_id}>
<li>{value.fieldofinterest1}</li>
<li>{value.fieldofinterest2}</li>
<li>{value.fieldofinterest3}</li>
<li>{value.technology1}</li>
<li>{value.technology2}</li>
<li>{value.technology3}</li>
<li>{value.position1}</li>
<li>{value.position2}</li>
<li>{value.position3}</li>
{console.log(sessionStorage.cardButtonID)}
<Button onClick={this.cardDeleteFunction} value={sessionStorage.cardButtonID}>Delete user</Button>
</ul>
)
})
return (
<div>
{preferenssiprintti[preferenssiprintti.length -1]}
</div>
);
}
}
export default GetUserPreferences;
|
import { StackNavigator, TabNavigator } from 'react-navigation';
import { CareAssessment, CareAssessmentInput } from '../../screens';
const options = {
}
export default StackNavigator({
CareAssessment: { screen: CareAssessment },
CareAssessmentInput: { screen: CareAssessmentInput },
}, options);
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { createActivity } from "../actions/cmsActions";
import { fetchItineraries } from "../actions/itinerariesActions";
import { Link } from "react-router-dom";
import Header from "../components/layout/Header";
import Card from "@material-ui/core/Card";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import FilledInput from "@material-ui/core/FilledInput";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Icon from "@material-ui/core/Icon";
class Cmsactivity extends Component {
constructor() {
super();
this.state = {
errors: {},
itineraries: [],
title: "",
image: null,
activitykey: "",
authorid: "",
selectedFile: null,
previewFile: null
};
// this.onChange = this.onChange.bind(this);
}
// ERROR MAPPING
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
}
componentDidMount() {
this.props.fetchItineraries();
}
// IMAGE INFO
fileChangedHandler = event => {
this.setState({
image: event.target.files[0],
previewFile: URL.createObjectURL(event.target.files[0])
});
};
//SUBMIT
onSubmit = e => {
e.preventDefault();
const formData = new FormData();
formData.append("title", this.state.title);
formData.append("activitykey", this.state.activitykey);
formData.append("image", this.state.image);
formData.append("authorid", this.props.auth.user.id);
//CREATE ACTION
this.props.createActivity(formData);
// alert("Upload successful");
this.setState({
title: "",
activitykey: "",
image: null,
selectedFile: null,
previewFile: null
});
};
// FORM INFO
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
render() {
const { errors } = this.state;
const previewFile = this.state.previewFile;
const cmstitle = (
<React.Fragment>
<Header title={"Create Activities"} />
<div className="cmsTitletext">
<p>Fill out the form below to create a new Activity.</p>
<p>Or click below to edit an existing activity.</p>
<div>
<Link to="/cmsactivity/editactivity">
<Button variant="outlined">Edit Activities</Button>
</Link>
</div>
</div>
</React.Fragment>
);
const selectActivity = (
<React.Fragment>
<FormControl variant="filled">
<InputLabel htmlFor="filled-itin-simple">
Select Itinerary:
</InputLabel>
<Select
className="selectForms"
value={this.state.activitykey}
onChange={this.onChange}
type="select"
name="activitykey"
input={<FilledInput name="activitykey" id="filled-itin-simple" />}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{this.props.itineraries.itineraries.map(itin => {
let cityName = itin.cityurl
.split("_")
.map(s => s.charAt(0).toUpperCase() + s.substring(1))
.join(" ");
return (
<MenuItem key={itin._id} value={itin.activitykey}>
{itin.title} - {cityName}
</MenuItem>
);
})}
</Select>
</FormControl>
</React.Fragment>
);
const cmsbody = (
<React.Fragment>
<div className="itineraryCard">
<Card raised className="commentForm">
<form
encType="multipart/form-data"
noValidate
onSubmit={this.onSubmit}
>
<div>
<TextField
className="commentFormInput"
id="outlined-with-placeholder"
label="Please enter Activity Title:"
placeholder=""
margin="normal"
variant="outlined"
type="text"
name="title"
value={this.state.title}
onChange={this.onChange}
errorform={errors.title}
/>
</div>
{errors.title && (
<div className="invalid-feedback">{errors.title}</div>
)}
{selectActivity}
</form>
<div className="cmsUploadimage">
Upload Activity Image.
<input type="file" onChange={this.fileChangedHandler} />
</div>
{/* SUBMIT BUTTON VALIDATION */}
{this.state.image === null ||
!this.state.title ||
!this.state.activitykey ? (
<React.Fragment>
<div className="cmsAction">
<Button variant="outlined" color="primary" disabled>
Create Activity!<Icon>save</Icon>
</Button>
</div>
<div>
<p className="cmsimagerequired">
*Fill out Form to enable Create Activity.
</p>
</div>
</React.Fragment>
) : (
<React.Fragment>
<div className="cmsAction">
<Button
variant="outlined"
color="primary"
onClick={this.onSubmit}
value="Submit"
>
Create Activity!<Icon>save</Icon>
</Button>
</div>
</React.Fragment>
)}
</Card>
<div className="cmsTitletext">
<h3>Preview Your Image Below : </h3>
</div>
</div>
</React.Fragment>
);
const noPreview = (
<div>
<Card />
</div>
);
const preview = (
<div>
<Card raised>
<div className="cmsImageDiv">
<img alt="cmsImage" src={this.state.previewFile} />
</div>
</Card>
</div>
);
return (
<React.Fragment>
{cmstitle}
{cmsbody}
{previewFile === null ? noPreview : preview}
</React.Fragment>
);
}
}
Cmsactivity.propTypes = {
createActivity: PropTypes.func,
fetchItineraries: PropTypes.func,
auth: PropTypes.object,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
itineraries: state.itineraries,
profile: state.profile,
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ createActivity, fetchItineraries }
)(Cmsactivity);
|
class Calculator {
constructor(k, f) {
if (isNaN(k) || isNaN(f)) {
throw new Error("Given value is not a number!");
} else if (k === "" || f === "") {
throw new Error("Given value is empty!");
}
this.k = Number(k);
this.f = Number(f);
}
add = () => this.k + this.f;
substract = () => this.k - this.f
multiply = () => this.k * this.f;
divide = () => {
if (this.f === 0) throw new Error("You cannot divide by 0!");
return this.k / this.f;
}
}
function values() {
const k = prompt("Enter first number:");
const f = prompt("Enter second number");
try {
const calc = new Calculator(k, f);
console.log(`Add = ${calc.add()}`);
console.log(`Substract = ${calc.substract()}`);
console.log(`Multiply = ${calc.multiply()}`);
console.log(`Divide = ${calc.divide()}`);
} catch (error) {
alert(error.message);
}
}
values();
|
var compareAst = require('..');
suite('compareAst', function() {
test('whitespace', function() {
compareAst('\tvar a=0;\n \t a +=4;\n\n', 'var a = 0; a += 4;');
});
suite('dereferencing', function() {
test('identifier to literal', function() {
compareAst('a.b;', 'a["b"];');
});
test('literal to identifier', function() {
compareAst('a["b"];', 'a.b;');
});
});
test('IIFE parenthesis placement', function() {
compareAst('(function() {}());', '(function() {})();');
});
test.skip('variable lists', function() {
compareAst('var a; var b;', 'var a, b;');
});
test('variable binding', function() {
compareAst(
'(function(a, b) { console.log(a + b); })(1, 3);',
'(function(__UNBOUND0__, __UNBOUND1__) {' +
'console.log(__UNBOUND0__ + __UNBOUND1__);' +
'}) (1,3);',
{ varPattern: /__UNBOUND\d+__/ }
);
});
test('string binding', function() {
compareAst(
'a["something"];"something2";"something";',
'a["__STR1__"]; "__STR2__"; "__STR1__";',
{ stringPattern: /__STR\d+__/ }
);
});
test('string binding with object dereferencing', function() {
compareAst(
'a.b;',
'a["_s1_"];',
{ stringPattern: /_s\d_/ }
);
});
test('variable binding and string binding', function() {
compareAst(
'a["b"];',
'_v1_["_s1_"];',
{ stringPattern: /_s\d_/, varPattern: /_v\d_/ }
);
});
test('custom comparator', function() {
var vals = [3, 4];
var threeOrFour = function(actual, expected) {
if (actual.type !== 'Literal' || expected.type !== 'Literal') {
return;
}
if (vals.indexOf(actual.value) > -1 &&
vals.indexOf(expected.value) > -1) {
return true;
}
};
compareAst(
'a.b + 3',
'a["b"] + 4',
{ comparators: [threeOrFour] }
);
});
suite('expected failures', function() {
function noMatch(args, expectedCode) {
try {
compareAst.apply(null, args);
} catch(err) {
if (!(err instanceof compareAst.Error)) {
throw new Error(
'Expected a compareAst error, but caught a generic ' +
'error: "' + err.message + '"'
);
}
if (err.code === expectedCode) {
return;
}
throw new Error(
'Expected error with code "' + expectedCode +
'", but received error with code "' + err.code + '".'
);
}
throw new Error('Expected an error, but no error was thrown.');
}
test('unmatched statements', function() {
noMatch(['', 'var x = 0;'], 3);
noMatch(['var x = 0;', ''], 3);
});
test('parse failure', function() {
noMatch(['var a = !;', 'var a = !;'], 1);
});
test('name change', function() {
noMatch(['(function(a) {});', '(function(b) {});'], 3);
});
test('value change', function() {
noMatch(['var a = 3;', 'var a = 4;'], 3);
});
test('dereferencing', function() {
noMatch(['a.b;', 'a["b "];'], 3);
});
test('double variable binding', function() {
noMatch([
'(function(a, b) { console.log(a); });',
'(function(__UNBOUND0__, __UNBOUND1__) { console.log(__UNBOUND1__); });',
{ varPattern: /__UNBOUND\d+__/ }
],
2
);
});
test('double string binding', function() {
noMatch([
'var a = "one", b = "two", c = "three";',
'var a = "_s1_", b = "_s2_", c = "_s1_";',
{ stringPattern: /_s\d_/ },
],
2
);
});
test('double string binding (through object dereference)', function() {
noMatch([
'a.a; a.b; a.c;',
'a["_s1_"]; a["_s2_"]; a["_s1_"];',
{ stringPattern: /_s\d/ },
],
2
);
});
test('extra statements', function() {
noMatch(['a;', ''], 3);
});
test('unmatched member expression', function() {
noMatch(['a.b;', '3;'], 3);
});
});
});
|
import { gsap } from 'gsap'
export default {
enter({ current, next }) {
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
const transitionTitle = document.querySelector('.transition__title')
const transitionBackground = document.querySelector(
'.transition__background'
)
console.log('transitionBackground', transitionBackground)
transitionTitle.innerHTML = next.container.dataset.barbaNamespace
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
return gsap
.timeline({
onComplete: () => {
transitionTitle.innerHTML = ''
},
})
.set(transitionBackground, { clearProps: 'all' })
.set(transitionTitle, { y: 100 })
.to(transitionBackground, {
duration: 0.7,
x: '0',
ease: 'power4',
onComplete: () => {
current.container.style.display = 'none'
},
})
.to(
transitionTitle,
0.5,
{
y: 0,
opacity: 1,
ease: 'power4',
},
0.1
)
.from(next.container, {
duration: 0.1,
opacity: 0,
ease: 'power4',
})
.to(
transitionBackground,
{
duration: 0.7,
x: '100%',
ease: 'power4.inOut',
},
1
)
.to(
transitionTitle,
0.7,
{
y: -100,
opacity: 0,
ease: 'power4.inOut',
},
0.8
)
.then()
},
}
|
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Import LitElement base class and html helper function
import { LitElement, html } from 'lit-element';
export class NewTileElement extends LitElement {
/**
* Define properties. Properties defined here will be automatically
* observed.
*/
static get properties() {
return {
displayNewTile: {type:String},
tileTitle: {type:String},
tileComments:{type:String},
tilePicture: {type:String},
tileDetails:{type:String},
newImagePath:{type:String}
};
}
/**
* In the element constructor, assign default property values.
*/
constructor() {
// Must call superconstructor first.
super();
// Initialize properties
this.tileTitle='';
this.tileComments='';
this.tileDetails='';
this.imageData='';
this.newImagePath='';
this.displayNewTile='none';
}
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
console.log(`${propName} changed. oldValue: ${oldValue}`);
});
}
onTileDataChange(type,changedData){
let newTileEvent = new CustomEvent('tile-event',{
detail:{
type:type,
changedData:changedData
}
});
this.clearData();
this.dispatchEvent(newTileEvent);
}
imageUpload(e){
console.dir(e);
let image=e.target;
this.newImagePath=URL.createObjectURL(e.target.files[0]);
console.dir(image);
console.log(this.imageData)
}
tileAddNewStory(){
let changedData={
id:null,
title:this.tileTitle,
comments:this.tileComments,
details:this.tileDetails,
rating:0,
like:'',
picture:this.newImagePath
}
this.onTileDataChange('newTile',changedData);
}
clearData(){
this.tileTitle='';
this.tileComments='';
this.tileDetails='';
this.imageData='';
this.newImagePath='';
}
mapInput(e){
let inputTmp=e.target;
if(inputTmp.id==='tileTitle'){
this.tileTitle=inputTmp.value;
}
else if(inputTmp.id==='tileComments'){
this.tileComments=inputTmp.value;
}
else if(inputTmp.id==='tileDetails'){
this.tileDetails=inputTmp.value;
}
console.log(e.target);
}
getTileTitle(){
return html`<input id="tileTitle" class="input-field" @change="${this.mapInput}" .value="${this.tileTitle}" type="text" placeholder="Title" name="usrnm">`;
}
/**
/**
* Define a template for the new element by implementing LitElement's
* `render` function. `render` must return a lit-html TemplateResult.
*/
render() {
return html`
<link rel="stylesheet" href="./src/css/newTile.css">
<style>
:host { display: block; }
:host([hidden]) { display: none; }
</style>
<form style="max-width:500px;margin:auto" style="display: ${this.displayNewTile}">
<h2>Add Story</h2>
<div class="input-container">
<i class="icon"><iron-icon icon="icons:folder-shared"></iron-icon></i>
${this.getTileTitle()}
</div>
<div class="input-container">
<i class="icon"><iron-icon @click="" icon="icons:lightbulb-outline"></iron-icon></i>
<input id="tileComments" @change="${this.mapInput}" class="input-field" type="text" .value="${this.tileComments}" placeholder="Summery" name="email">
</div>
<div class="input-container ">
<label class="icon">
<i class=" fileContainer"><iron-icon icon="icons:camera-enhance"></iron-icon></i>
<span class="fileContainer">
<input id="newTileImage" @change="${this.imageUpload}" value="${this.imageData}" type="file"/>
</span>
</label>
<input class="input-field" disabled type="text" placeholder="Image Data" name="image">
</div>
<div class="input-container ">
${this.newImagePath? html` <img class="w3-circle myImg" src="${this.newImagePath}" style="width:100%">`:html``}
</div>
<div class="container1">
<label for="subject">Details</label>
<textarea class="mytextarea" id="tileDetails" @change="${this.mapInput}" .value="${this.tileDetails}" id="subject" name="subject" placeholder="Write whatever you want" style="height:200px"></textarea>
</div>
<button type="button" @click="${this.tileAddNewStory}" class="btn">Add</button>
</form>
`;
}
}
// Register the element with the browser
customElements.define('new-tile-element', NewTileElement);
|
var maxIncreaseKeepingSkyline = function(grid) {
let row = [];
let col = [];
for (let i = 0; i < grid.length; i++) {
let rowmax = grid[i][0];
for (let j = 0; j < grid[i].length; j++) {
rowmax = Math.max(rowmax, grid[i][j]);
}
row[i] = rowmax;
}
for (let i = 0; i < grid[0].length; i++) {
let colmax = grid[0][i];
for (let j = 0; j < grid.length; j++) {
colmax = Math.max(colmax, grid[j][i])
}
col[i] = colmax
}
let count = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid.length; j++) {
let newheight = Math.min(row[i], col[j])
count = count + (newheight - grid[i][j])
}
}
return count
};
console.log(maxIncreaseKeepingSkyline([[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]))
|
$(function(){
$('.page-header').each(function(){
//전역변수
let $헤더 = $(this)
$윈도우 = $(windw)
$('body').append('<div class="page-header-clone"> </div>')
$헤더.contents().clone().appendTo('page-header-clone')
$윈도우.scroll(function(){
//변수처리하면 훨씬 편함
//지역변수
let $스크롤값 = $(windw).scrollTop(),
$헤더위치값 = $헤더.offset().top,
//보더와 패딩값 높이값
$헤더높이값 = $헤더.outerHeight()
$헤더복제 = $('.page-header-clone')
// 만약 (윈도우의 스크롤 값 > 헤더의 위치값)
if($스크롤값 > ($헤더위치값 + $헤더높이값)){
$헤더복제.addClass('visible')
}else{
$헤더복제.removeClass('visible')
}
})
})
})
|
/*global $:false,_:false,Handlebars:false*/
(function () {
'use strict';
angular
.module('musicalisimo')
.directive('artistsSearch', function () {
return {
restrict: 'A',
scope: {
onArtistSelect: '&',
artistsSearch: '&'
},
template: '<div id="artistSearch"><input class="typeahead" type="text" placeholder="Search for artist"></div>',
controller: function ($element, $scope) {
function findMatches(q, sync, async) {
$scope
.artistsSearch()(q)
.then(artists => async(artists));
}
$($element).find('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: _.debounce(findMatches, 200),
limit: 20,
display: 'name',
templates: {
suggestion: Handlebars.compile('<div><strong>{{name}}</strong> – {{listeners}}</div>')
}
})
.on('typeahead:selected', onAutocompleted);
function onAutocompleted($e, artist) {
$scope.onArtistSelect()(artist);
$($element).find('.typeahead').typeahead('val', '');
}
}
};
});
})();
|
/**
* Checkout.com Magento 2 Payment module (https://www.checkout.com)
*
* Copyright (c) 2017 Checkout.com (https://www.checkout.com)
* Author: David Fiaty | integration@checkout.com
*
* License GNU/GPL V3 https://www.gnu.org/licenses/gpl-3.0.en.html
*/
/*browser:true*/
/*global define*/
define(
[
'jquery',
'CheckoutCom_Magento2/js/view/payment/method-renderer/cc-form',
'Magento_Vault/js/view/payment/vault-enabler',
'CheckoutCom_Magento2/js/view/payment/adapter',
'Magento_Checkout/js/model/quote',
'mage/url',
'Magento_Checkout/js/model/payment/additional-validators'
],
function ($, Component, VaultEnabler, CheckoutCom, quote, url, additionalValidators) {
'use strict';
return Component.extend({
defaults: {
active: true,
template: 'CheckoutCom_Magento2/payment/hosted'
},
/**
* @returns {string}
*/
getHostedUrl: function() {
return CheckoutCom.getPaymentConfig()['hosted_url'];
},
/**
* @returns {string}
*/
getPublicKey: function() {
return CheckoutCom.getPaymentConfig()['public_key'];
},
/**
* @returns {string}
*/
getPaymentMode: function() {
return CheckoutCom.getPaymentConfig()['payment_mode'];
},
/**
* @returns {string}
*/
getPaymentToken: function() {
return CheckoutCom.getPaymentConfig()['payment_token'];
},
/**
* @returns {string}
*/
getQuoteValue: function() {
//return CheckoutCom.getPaymentConfig()['quote_value'];
return (quote.getTotals()().grand_total*100).toFixed(2);
},
/**
* @returns {string}
*/
getQuoteCurrency: function() {
return CheckoutCom.getPaymentConfig()['quote_currency'];
},
/**
* @returns {string}
*/
getRedirectUrl: function() {
return url.build('checkout_com/payment/placeOrder');
},
/**
* @returns {string}
*/
getCancelUrl: function() {
return window.location.href;
},
/**
* @returns {string}
*/
getDesignSettings: function() {
return CheckoutCom.getPaymentConfig()['design_settings'];
},
/**
* @returns {void}
*/
saveSessionData: function() {
// Prepare the session data
var sessionData = {saveShopperCard: $('#checkout_com_enable_vault').is(":checked")};
// Send the session data to be saved
$.ajax({
url : url.build('checkout_com/shopper/sessionData'),
type: "POST",
data : sessionData,
success: function(data, textStatus, xhr) { },
error: function (xhr, textStatus, error) { } // todo - improve error handling
});
},
/**
* @returns {string}
*/
beforePlaceOrder: function() {
// Get self
var self = this;
// Validate before submission
if (additionalValidators.validate()) {
// Set the save card option in session
self.saveSessionData();
// Submit the form
$('#checkout_com-hosted-form').submit();
}
}
});
}
);
|
var formFriend = {};
(function () {
function render(elementId, form, qName, node, graph, result, whenDone) {
form.innerHTML = '';
if (node.message) {
var label = document.createElement('label');
label.className = 'form-friend-message';
label.textContent = node.message;
form.appendChild(label);
}
if (node.number) {
var input = document.createElement('input');
input.type = 'number';
input.min = node.number.min;
input.max = node.number.max;
input.className = 'form-friend-number';
form.appendChild(input);
var buttonElem = document.createElement('button');
buttonElem.className = 'form-friend-button form-friend-number-button';
buttonElem.textContent = node.number.text || 'Next';
buttonElem.onclick = function () {
result[qName] = parseInt(input.value);
if (node.number.goesTo === 'done') {
graph.done && render(elementId, form, 'done', graph.done, graph, result, whenDone);
whenDone(result);
} else {
render(elementId, form, node.number.goesTo, graph[node.number.goesTo], graph, result, whenDone);
}
};
form.appendChild(buttonElem);
}
if (node.input) {
var input = document.createElement('input');
input.type = 'text';
input.className = 'form-friend-text';
form.appendChild(input);
var buttonElem = document.createElement('button');
buttonElem.className = 'form-friend-button form-friend-text-button';
buttonElem.textContent = node.input.text || 'Next';
buttonElem.onclick = function () {
result[qName] = input.value;
if (node.input.goesTo === 'done') {
graph.done && render(elementId, form, 'done', graph.done, graph, result, whenDone);
whenDone(result);
} else {
render(elementId, form, node.input.goesTo, graph[node.input.goesTo], graph, result, whenDone);
}
};
form.appendChild(buttonElem);
}
if (node.checkboxes) {
var boxes = [];
(node.checkboxes.values || []).forEach(function (box, i) {
var chkbox = document.createElement('input');
chkbox.type = 'checkbox';
chkbox.className = 'form-friend-checkbox';
var id = elementId + '-ff-chkbox-' + i;
chkbox.id = id;
chkbox.value = box.savesAs;
var label = document.createElement('label');
label.htmlFor = id;
label.innerHTML = box.text;
form.appendChild(chkbox);
boxes.push(chkbox);
form.appendChild(label);
});
var buttonElem = document.createElement('button');
buttonElem.className = 'form-friend-button form-friend-checkbox-button';
buttonElem.textContent = node.checkboxes.text || 'Next';
buttonElem.onclick = function () {
result[qName] = boxes
.filter(function (box) { return box.checked; })
.map(function (box) { return box.value; });
if (node.checkboxes.goesTo === 'done') {
graph.done && render(elementId, form, 'done', graph.done, graph, result, whenDone);
whenDone(result);
} else {
render(elementId, form, node.checkboxes.goesTo, graph[node.checkboxes.goesTo], graph, result, whenDone);
}
};
form.appendChild(buttonElem);
}
(node.buttons || []).forEach(function (button) {
var buttonElem = document.createElement('button');
buttonElem.className = 'form-friend-button';
buttonElem.textContent = button.text;
buttonElem.onclick = function () {
if (button.savesAs) { result[qName] = button.savesAs };
if (button.goesTo === 'done') {
graph.done && render(elementId, form, 'done', graph.done, graph, result, whenDone);
whenDone(result);
} else {
render(elementId, form, button.goesTo, graph[button.goesTo], graph, result, whenDone);
}
};
form.appendChild(buttonElem);
});
}
formFriend.attach = function (elementId, formGraph, whenDone) {
var root = document.getElementById(elementId);
var form = document.createElement('div');
form.className = 'form-friend-form';
root.appendChild(form);
render(elementId, form, 'friendAndEnter', formGraph.friendAndEnter, formGraph, {}, whenDone);
};
})();
|
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { NavLinks } from '../utils'
import Logo from '../images/logo.jpg'
export default function Navbar() {
const [open, setOpen] = useState(false)
return (
<nav
className='navbar bd-navbar '
role='navigation'
aria-label='main navigation'
>
<div className='navbar-brand'>
<Link className='navbar-item' to='/'>
<img src={Logo} alt='logo' style={{ width: 150, height: 250 }} />
</Link>
<span
role='button'
className='navbar-burger'
aria-label='menu'
aria-expanded='false'
data-target='navbarBasicExample'
onClick={() => setOpen(!open)}
>
<span aria-hidden='true' />
<span aria-hidden='true' />
<span aria-hidden='true' />
</span>
</div>
<div className={open ? 'navbar-menu is-active' : 'navbar-menu'}>
<div className='navbar-end '>
{NavLinks.map((item, index) => (
<>
<Link
key={index}
to={item.link}
className='navbar-item has-text-link is-capitalized is-narrow-mobile'
onClick={() => setOpen(false)}
>
{item.name}
</Link>
<hr className='navbar-divider'></hr>
</>
))}
<div className='navbar-item is-hidden-mobile'>
<button className='button is-primary has-text-white is-capitalized px-3 py-2 is-size-5'>
start learning
</button>
</div>
</div>
</div>
</nav>
)
}
|
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import models from './src/models';
import routes from './src/routes';
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.options('*', cors()); // include before other routes
app.use('/users', routes.users);
app.use((req, res, next) => {
req.context = {
models,
me: models.users[1],
};
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
|
define(function(require,exports,module){
var proto;
function Pagination() {
}
proto = Pagination.prototype;
proto.init = function (config) {
this.base_href = config.base_href;
this.total_rows = config.total_rows;
this.per_page = config.per_page;
this.num_links = config.num_links;//当前选择的页码之前和之后的出现的页码数
this.active_classname = config.active_classname;
};
proto.createLink = function (currentPage) {
currentPage = currentPage || 1;
var total_page = Math.ceil(this.total_rows / this.per_page);
var start, end;
var num_links = this.num_links;
var len = 2 * num_links + 1;
var base_href = this.base_href;
var prev, next, first, last, commonpage = '';
var active = this.active_classname;
if (this.total_rows <= this.per_page)
return '';
if (total_page <= 1)
return '';
if(currentPage>total_page)
currentPage=total_page;
if (total_page <= len) {
start = 1;
end = total_page;
}
else {
start = currentPage - num_links > 0 ? currentPage - num_links : 1;
end = currentPage + num_links < total_page ? currentPage + num_links : total_page;
if (start == 1)
end = 2 * num_links + 1;
if (end == total_page)
start = total_page - 2 * num_links;
}
first = "<li class='spc-page'><a href=" + base_href + "/1>第一页</a></li>";
last = "<li class='spc-page'><a href=" + base_href + "/" + total_page + ">最后一页</a></li>";
prev = "<li class='spc-page'><a href=" + base_href + "/" + (currentPage - 1 <= 0 ? 1 : currentPage - 1) + ">上一页</a></li>";
next = "<li class='spc-page'><a href=" + base_href + "/" + (currentPage + 1 >= total_page ? total_page : currentPage + 1) + ">" +
"下一页</a></li>";
for (var i = start; i <= end; i++) {
if (i == currentPage)
commonpage += "<li><a class=" + active + " href=" + base_href + "/" + i + ">" + i + "</a></li>"
else
commonpage += "<li><a href=" + base_href + "/" + i + ">" + i + "</a></li>";
}
return first + prev + commonpage + next + last;
};
exports.create = function () {
return new Pagination();
};
});
|
// contactController.js
// Import contact model
const Car = require('../models/carModel');
const path = require('path');
const util = require('util')
const multer = require('multer');
const csv = require('csv-parser');
const fs = require('fs')
const upload = multer({ dest: 'tmp/csv/' });
// Handle index actions
exports.list = function (req, res) {
Car.get(function (err, car) {
if (err) {
res.json({
status: "error",
message: err,
});
}
res.json({
status: "success",
message: "Operation handled successfully",
data: car
});
});
};
// Handle create planning actions
exports.new = function (req, res) {
var car = new Car();
car.placa = req.body.placa
car.marca = req.body.marca
car.modelo = req.body.modelo
car.empleado = req.body.empleado
car.fechaIngreso = req.body.fechaIngreso
car.fechaSalida = req.body.fechaSalida
car.descripcion = req.body.descripcion
car.procedimiento = req.body.procedimiento
car.estado = req.body.estado
// save the current planning and check for errors
car.save(function (err) {
// Check for validation error
if (err)
res.json(err);
else
res.json({
message: 'New car created!',
data: car
});
});
};
// Handle view contact info
exports.view = function (req, res) {
Car.findById(req.params.car_id, function (err, car) {
if (err)
res.send(err);
res.json({
message: 'Car planning details loading..',
data: car
});
});
};
exports.view_plate = function (req, res) {
let args = [
{ $match: { placa: req.params.plate}}
]
Car.aggregate(args, function (err, car_jobs) {
if (err)
res.send(err);
res.json({
message: 'Car planning details loading..',
data: car_jobs
});
});
};
// Handle update car info
exports.update = function (req, res) {
Car.findById(req.params.car_id, function (err, car) {
if (err)
res.send(err);
car.placa = req.body.placa
car.marca = req.body.marca
car.modelo = req.body.modelo
car.empleado = req.body.empleado
car.fechaIngreso = req.body.fechaIngreso
car.fechaSalida = req.body.fechaSalida
car.descripcion = req.body.descripcion
car.procedimiento = req.body.procedimiento
car.estado = req.body.estado
// save the contact and check for errors
car.save(function (err) {
if (err)
res.json(err);
res.json({
message: 'Car Info updated',
data: car
});
});
});
};
// Handle delete car
exports.delete = function (req, res) {
Car.deleteOne({
_id: req.params.car_id
}, function (err, car) {
if (err)
res.send(err);
res.json({
status: "success",
message: 'Car deleted'
});
});
};
exports.upload_csv = function (req, res) {
var cars = []
fs.createReadStream('./planning.csv')
.pipe(csv( {skipLines: 2}))
.on('data', (row) => {
cars.push(row)
})
.on('end', () => {
console.log(cars);
});
};
|
import React,{Component} from 'react';
import {StyleSheet,View,Text} from 'react-native';
import PropTypes from 'prop-types';
export default class Column extends Component{
static propTypes = {
mainAxisAlignment: PropTypes.string,
crossAxisAlignment: PropTypes.string,
}
static defaultProps = {
mainAxisAlignment: require("./AxiosAlignment").cross.start,
crossAxisAlignment: require("./AxiosAlignment").main.start,
}
render(){
return (
<View
children={this.props.children}
style={styles.column}
/>
)
}
}
const styles = StyleSheet.create({
column:{
flexDirection: 'column',
}
})
|
import { GraphQLID, GraphQLNonNull, GraphQLString } from 'graphql'
import imageType from '../types/story'
import resolve from '../resolvers/createImage'
import { OrganizationInput } from '../types/inputs'
const createImage = {
name: 'createImage',
type: imageType,
args: {
id: {
type: GraphQLID
},
organization: {
type: OrganizationInput
},
title: {
type: GraphQLString
},
description: {
type: GraphQLString
}
},
resolve
}
export default createImage
|
/**
* jQuery plugin to detect font being used to render an element.
*
* Inspired by and extended from the answer at:
* http://stackoverflow.com/questions/15664759/jquery-how-to-get-assigned-font-to-element
*/
// Strips quotes from start and end of string
String.prototype.unquoted = function() {
return this.replace(/(^("|'))|(("|')$)/g, '');
};
(function($) {
$.fn.detectFont = function() {
var fonts = $(this).css('font-family').split(',');
if (fonts.length === 1) {
return fonts[0].unquoted();
}
var element = $('<div />');
$('body').append(element);
element
.css({
'clear':'both',
'display':'inline-block',
'font-family':$(this).css('font-family'),
'font-size':$(this).css('font-size'),
'font-weight':$(this).css('font-weight'),
'white-space':'nowrap'
})
.html($(this).html());
var detectedFont = null;
for (var f in fonts) {
var clone = element.clone().css({
'visibility': 'visible',
'font-family': fonts[f].unquoted()
}).appendTo('body');
if (element.width() === clone.width()) {
clone.remove();
detectedFont = fonts[f].unquoted();
break;
}
clone.remove();
}
element.remove();
return detectedFont;
};
})(jQuery);
|
_viewer=this;
$("#TS_BMSH_RULE_POST-POST_FUHAO_div").find("span:last").find("div").css("width","50px");
$("#TS_BMSH_RULE_POST-POST_YEAR_FUHAO_div").find("span:last").find("div").css("width","50px");
$("#TS_BMSH_RULE_POST-POST_YEAR_div").css("margin-left","-35%");
$("#TS_BMSH_RULE_POST-POST_DUTIES_div").css("margin-left","-35%");
$("#TS_BMSH_RULE_POST-POST_DUTIES").css("cursor","pointer");
$("#TS_BMSH_RULE_POST-POST_DUTIES").unbind('click').bind('click',function(){
var xls = $("#TS_BMSH_RULE_POST-POST_XL__NAME").val();
var lb = $("#TS_BMSH_RULE_POST-POST_TYPE__NAME").val();
var extwhere = "";
var table = "TS_ORG_POSTION";
var radioval = $("input[name='TS_BMSH_RULE_POST-POST_ZD']:checked").val();
if(radioval==2){
if(lb==""){
alert("请先选择类别");
return false;
}
if(xls == ""||xls=='全部'){
if(lb=="专业类"){
extwhere = 'AND POSTION_TYPE_NAME =^'+lb+'^';
table="TS_ORG_POSTION_K";
}else{
extwhere = 'AND POSTION_TYPE_NAME =^'+lb+'^';
}
}else{
extwhere = 'AND POSTION_TYPE_NAME =^'+lb+'^ AND POSTION_SEQUENCE=^'+xls+'^';
}
}else{
table="TS_ORG_POSTION_K";
}
var configStr = table+",{'TARGET':'','SOURCE':'POSTION_SEQUENCE~POSTION_NAME'," +
"'HIDE':'','EXTWHERE':'"+extwhere+" AND POSTION_LEVEL=^3^','TYPE':'single','HTMLITEM':''}";
var options = {
"config" :configStr,
"parHandler":_viewer,
"formHandler":_viewer.form,
"replaceCallBack":function(idArray) {//回调,idArray为选中记录的相应字段的数组集合
var ids = idArray.POSTION_NAME;
$("#TS_BMSH_RULE_POST-POST_DUTIES").val(ids);
}
};
var queryView = new rh.vi.rhSelectListView(options);
queryView.show(event,[],[0,495]);
})
/* $('#TS_BMSH_RULE_POST-POST_TYPE').unbind("click").bind('change', function() {
alert("a");
$("#TS_BMSH_RULE_POST-POST_DUTIES").val("");
$("#TS_BMSH_RULE_POST-POST_XL__NAME").val("");
});
*/
/* $("#TS_BMSH_RULE_POST-POST_TYPE").change(function(){
$("#TS_BMSH_RULE_POST-POST_DUTIES").val("");
$("#TS_BMSH_RULE_POST-POST_XL__NAME").val("");
})
*/
|
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-console */
let formidable = require('formidable')
let uuid = require('node-uuid')
let fs = require('fs')
let express = require('express')
let http = require('http')
let path = require('path')
let app = express()
let allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
res.header('Access-Control-Allow-Headers', 'Content-Type')
next()
}
app.use(allowCrossDomain)
function nodeUpload(req, callback, next) {
let form = new formidable.IncomingForm()
form.encoding = 'utf-8'
form.uploadDir = `${__dirname}/uploads/`
form.maxFieldsSize = 10 * 1024 * 1024
// 解析
form.parse(req, (err, fields, files) => {
if (err) return callback(err)
for (let file in files) {
if ({}.hasOwnProperty.call(files, file)) {
// 后缀名
let extName = path.extname(files[file].name)
// 重命名,以防文件重复
let avatarName = uuid() + extName
// 移动的文件目录
let newPath = form.uploadDir + avatarName
fs.renameSync(files[file].path, newPath)
fields[file] = {
size: files[file].size,
path: newPath,
name: files[file].name,
type: files[file].type,
extName
}
}
}
callback(null, fields)
})
}
app.post('/upload', (req, res, next) => {
nodeUpload(req, (err, fields) => {
res.json(fields)
}, next)
})
http.createServer(app).listen(8002, () => {
console.log('Express server listening on port 8002')
})
|
let zoomIn = document.querySelectorAll(".zoom-in");
let expand = document.getElementById("expand");
// console.log(zoomIn);
for (let i = 0; i < zoomIn.length; i++){
zoomIn[i].addEventListener("click", () => {
// console.log(zoomIn[i].outerHTML);
expand.style.display = "flex";
let imgdiv = document.createElement("div");
let backdiv = document.createElement("div");
imgdiv.innerHTML = zoomIn[i].outerHTML;
imgdiv.classList.add("expand-img");
let controldiv = document.createElement("div");
let leftdiv = document.createElement("div");
let rightdiv = document.createElement("div");
controldiv.appendChild(leftdiv);
controldiv.appendChild(rightdiv);
controldiv.classList.add("control-div");
expand.appendChild(imgdiv);
expand.appendChild(controldiv);
backdiv.innerHTML = `<img id="back" src="image/back.png">`;
backdiv.classList.add("back-div");
expand.appendChild(backdiv);
let j = i;
rightdiv.addEventListener("click", () => {
j++;
j = j % zoomIn.length;
imgdiv.innerHTML = `${zoomIn[j].outerHTML}`;
});
leftdiv.addEventListener("click", () => {
if (j == 0) {
j = zoomIn.length - 1;
} else {
j--;
}
j = j % zoomIn.length;
imgdiv.innerHTML = `${zoomIn[j].outerHTML}`
});
document.getElementById("back").addEventListener("click",()=>{
expand.style.display = "none";
imgdiv.style.display = "none";
imgdiv.innerHTML = "";
controldiv.style.display = "none";
controldiv.innerHTML = "";
backdiv.style.display = "none";
backdiv.innerHTML = "";
});
});
}
// let detailWrapper = document.querySelectorAll('.detail-wrapper');
// detailWrapper.forEach((eachDetailWrapper, index) => {
// eachDetailWrapper.addEventListener("mouseover", descriptionText);
// function descriptionText(){
// console.log(eachDetailWrapper, index);
// }
// eachDetailWrapper.addEventListener("mouseleave", () => {
// eachDetailWrapper.removeEventListener("mouseover", descriptionText);
// });
// });
|
import React from 'react'
import {connect} from 'react-redux'
import userReducer from './Redux/reducers/userReducer'
class Alert extends React.Component{
render(){
return(
<div>
{this.props.user.username}
<br/>
{this.props.user.password}
<br/>
{this.props.user.address}
<br/>
{this.props.user.number}
</div>
)
}
}
function mapStateToProps (state){
return {
user:state.userReducer
}
}
export default connect(mapStateToProps)(Alert)
|
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Check from '@material-ui/icons/Check';
import SettingsIcon from '@material-ui/icons/Settings';
import GroupAddIcon from '@material-ui/icons/GroupAdd';
import VideoLabelIcon from '@material-ui/icons/VideoLabel';
import StepConnector from '@material-ui/core/StepConnector';
import { Typography, Button, InformationBox } from 'components';
import { Col, Row } from 'reactstrap';
import store from '../../containers/App/store';
import { setDepositInfo } from '../../redux/actions/deposit';
import { getAppCustomization } from "../../lib/helpers";
import _ from 'lodash';
import './index.css';
import allow from 'assets/allow.png';
import { CopyText } from '../../copy';
import { connect } from "react-redux";
const QontoConnector = withStyles({
alternativeLabel: {
top: 10,
left: 'calc(-50% + 16px)',
right: 'calc(50% + 16px)',
},
active: {
'& $line': {
borderColor: 'white',
},
},
completed: {
'& $line': {
borderColor: 'grey',
},
},
line: {
borderColor: "white",
borderTopWidth: 3,
borderRadius: 1,
},
})(StepConnector);
const useQontoStepIconStyles = makeStyles({
root: {
color: 'transparent',
display: 'flex',
height: 22,
alignItems: 'center',
},
active: {
color: 'white',
},
circle: {
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: 'currentColor',
},
completed: {
color: 'white',
zIndex: 1,
fontSize: 18,
},
});
function QontoStepIcon(props) {
const classes = useQontoStepIconStyles();
const { active, completed } = props;
return (
<div
className={clsx(classes.root, {
[classes.active]: active,
})}
>
{completed ? <Check className={classes.completed} /> : <div className={classes.circle} />}
</div>
);
}
QontoStepIcon.propTypes = {
active: PropTypes.bool,
completed: PropTypes.bool,
};
const useColorlibStepIconStyles = makeStyles({
root: {
backgroundColor: 'transparent',
zIndex: 1,
width: 50,
backgroundColor : 'transparent',
height: 50,
display: 'flex',
borderRadius: '50%',
justifyContent: 'center',
alignItems: 'center',
},
active: {
boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
},
completed: {
},
});
function ColorlibStepIcon(props) {
const classes = useColorlibStepIconStyles();
const { active, completed } = props;
const icons = {
1: <SettingsIcon />,
2: <GroupAddIcon />,
3: <VideoLabelIcon />,
};
return (
<div
className={clsx(classes.root, {
[classes.active]: active,
[classes.completed]: completed,
})}
>
{icons[String(props.icon)]}
</div>
);
}
ColorlibStepIcon.propTypes = {
active: PropTypes.bool,
completed: PropTypes.bool,
icon: PropTypes.node,
};
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
margin : 'auto',
backgroundColor : 'transparent',
},
stepLabel : {
color : 'white'
},
button: {
marginRight: theme.spacing(1),
},
instructions: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
},
}));
const HorizontalStepper = (props) => {
const { steps, nextStep, alertCondition, alertIcon, alertMessage, showStepper } = props;
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
let step = steps[activeStep];
const { pass, title, content, condition, first, last, closeStepper, showCloseButton = true, nextButtonLabel, showBackButton = true } = step;
const {ln} = props;
const { skin } = getAppCustomization();
const copy = CopyText.horizontalStepperIndex[ln];
if(pass){handleNext();}
if(nextStep && (activeStep+1 < steps.length)){
handleNext();
store.dispatch(setDepositInfo({key : 'nextStep', value : false}));
}
function handleNext() {
setActiveStep(prevActiveStep => prevActiveStep + 1);
}
function handleBack() {
if(!steps[activeStep-1]){return }
let previousPass = steps[activeStep-1].pass;
if(previousPass){
setActiveStep(prevActiveStep => prevActiveStep - 1);
}
setActiveStep(prevActiveStep => prevActiveStep - 1);
}
function handleReset() {
setActiveStep(0);
}
return (
<div className={classes.root}>
<div styleName='stepper-root'>
{showStepper ?
<Stepper alternativeLabel activeStep={activeStep} connector={<QontoConnector />}>
{steps.map( ({label}) => (
<Step key={label}>
<StepLabel className={classes.stepLabel} StepIconComponent={QontoStepIcon}>
<Typography
variant={'small-body'} color={'casper'}>{label}
</Typography>
</StepLabel>
</Step>
))}
</Stepper>
: null}
</div>
{
title ?
<div styleName='container-title'>
<Typography variant={'x-small-body'} color={'white'}>
{title}
</Typography>
</div>
:
null
}
{alertCondition ? <InformationBox message={alertMessage} image={!_.isEmpty(alertIcon) ? alertIcon : allow}/> : content}
<div>
{activeStep === steps.length ? (
<div>
<Typography className={classes.instructions}>
{copy.INDEX.TYPOGRAPHY.TEXT[0]}
</Typography>
<Button onClick={handleReset} className={classes.button}>
{copy.INDEX.BUTTON.TEXT[0]}
</Button>
</div>
) : (
<div styleName='buttons'>
{
last
? (
<div>
<Row>
{
showBackButton
?
<Col md={showCloseButton ? 6 : 12}>
<div styleName='button-stepper'>
<Button disabled={activeStep === 0} onClick={handleBack} className={classes.button} theme="primary">
<Typography variant={'small-body'} color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}> {copy.INDEX.TYPOGRAPHY.TEXT[1]} </Typography>
</Button>
</div>
</Col>
:
null
}
{
showCloseButton
? (
<Col md={6}>
<div styleName='button-stepper'>
<Button
variant="contained"
disabled={!condition}
color="primary"
onClick={closeStepper}
className={classes.button}
theme="primary"
>
<Typography variant={'small-body'} color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}> {copy.INDEX.TYPOGRAPHY.TEXT[2]} </Typography>
</Button>
</div>
</Col>
)
:
null
}
</Row>
</div>
) : (
<div>
{
!first
? (
<Row>
{
showBackButton ?
<Col md={6}>
<div styleName='button-stepper'>
<Button disabled={activeStep === 0} onClick={handleBack} className={classes.button} theme="primary">
<Typography variant={'small-body'} color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}> {copy.INDEX.TYPOGRAPHY.TEXT[3]} </Typography>
</Button>
</div>
</Col>
:
null
}
<Col md={showBackButton ? 6 : 12}>
<div styleName='button-stepper'>
<Button
variant="contained"
disabled={!condition}
color="primary"
onClick={handleNext}
className={classes.button}
theme="primary"
>
<Typography variant={'small-body'} color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}>{nextButtonLabel ? nextButtonLabel : copy.INDEX.TYPOGRAPHY.TEXT[4]} </Typography>
</Button>
</div>
</Col>
</Row>
) : (
<Row>
<Col md={12}>
<div styleName='button-stepper'>
<Button
variant="contained"
disabled={!condition}
color="primary"
onClick={handleNext}
className={classes.button}
theme="primary"
>
<Typography variant={'small-body'} color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}>{nextButtonLabel ? nextButtonLabel : copy.INDEX.TYPOGRAPHY.TEXT[5]} </Typography>
</Button>
</div>
</Col>
</Row>
)
}
</div>
)
}
</div>
)}
</div>
</div>
);
}
function mapStateToProps(state){
return {
profile : state.profile,
ln: state.language
};
}
export default connect(mapStateToProps)(HorizontalStepper);
|
import React from 'react'
import Layout from '../../components/Layout'
import BlogRollConferencias from '../../components/BlogRollConferencias'
export default class BlogIndexPage extends React.Component {
render() {
return (
<Layout>
<div
className="full-width-image-container margin-top-0"
style={{
backgroundImage: `url('/img/conferencia.jpg')`,
}}
>
<h1
className="has-text-weight-bold is-size-1"
style={{
boxShadow: '0.5rem 0 0 #FFF, -0.5rem 0 0 #FFF',
backgroundColor: '#FFF',
color: '#1E59A8',
padding: '1rem',
}}
>
Conferencias
</h1>
</div>
<section className="section">
<div className="container">
<div className="content">
<BlogRollConferencias />
</div>
</div>
</section>
</Layout>
)
}
}
|
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
gulp.task('less',function(){
gulp.src('./app/less/*.less')
.pipe($.less())//这是插件,专门用来处里less文件的
.pipe(gulp.dest('./dist/css'))
.pipe($.minifyCss())//这是压缩的
.pipe($.rename('index.min.css'))//这是重命名
.pipe(gulp.dest('./dist/css'))
});
|
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static(__dirname + '/static'));
// app.use(express.views(__dirname + '/views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile("./index.html");
});
app.get('/search/:foo', function(req, res) {
var url = 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&';
var q = req.params.foo;
var fullUrl = url + 'q=' + q;
request({url: fullUrl}, function(error, response, body) {
var dataObj = JSON.parse(body);
// res.render('index', {data: dataObj});
res.send(dataObj);
});
});
app.listen(3000);
|
/**
* Return true if all the letters in the `phrase`
* are present in the `pattern`.
*
* Comparison should be case insensitive. Meaning
* phrase 'A' contains pattern 'a'.
*/
function hasAllLetters(pattern, phrase) {
// Only change code below this line
phrase = phrase.toLowerCase().split('');
pattern = pattern.toLowerCase().split('');
for (let i = 0; i < phrase.length; i++) {
if (phrase[i] === ' ') i++;
if (pattern.indexOf(phrase[i]) === -1) return false;
else return true;
}
// Only change code above this line
}
// Tests
test(hasAllLetters('abcdef', 'Dead Beef'), true, 'Dead Beef');
test(hasAllLetters('abcdef', 'Some phrase'), false, 'Some phrase');
test(hasAllLetters('Happy New Year', 'nyh'), true, 'nyh');
function test(actual, expected, testName = '') {
if (actual !== expected) {
const errorMessage = `Test ${testName} failed: ${actual} is not equal to expected ${expected}`;
console.error(errorMessage);
} else {
console.log(`Test ${testName} passed!`);
}
}
|
({
assignLeadHelper : function(component, event, helper, recordId){
helper.callServer(
component,
"c.assignLeadToCurrentUser",
function(result){
var success = true;
var msg = "Lead Assignment successful!";
var type= "success";
if(result!="true"){
msg = "You don't have access to assign the record. Please contact your System Administrator.";
type = "error"
success = false;
}
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
"mode": "dissmissible",
"title": "Assign To Me",
"message": msg,
"type": type,
duration: 20000
});
resultsToast.fire();
// Refresh View if update successful
if(success){
$A.get("e.force:refreshView").fire();
}
// Close quick action
$A.get("e.force:closeQuickAction").fire();
},{
leadId : recordId
}
);
}
})
|
import { state } from "./state";
import { localStorageSync } from "./utils";
import { handleVideoSubmit, handleVideoDelete } from "./ui";
import { loadPlayerScript, createNewPlayer } from "./player";
const form = document.querySelector("#linkInputForm");
const init = () => {
loadPlayerScript();
localStorageSync();
window.onYouTubePlayerAPIReady = createNewPlayer();
window.addEventListener("storage", (e) => {
state.playlist = JSON.parse(e.newValue);
});
form.addEventListener("submit", (e) => handleVideoSubmit(e));
document.addEventListener("click", (e) => handleVideoDelete(e));
};
init();
|
const constants = require('./constants');
function addParentOptionsForCommand(options, command) {
for (let parentOptionName in constants.ParentOptionsDictionary) {
if (options.hasOwnProperty(parentOptionName)) {
let parentOption = constants.ParentOptionsDictionary[parentOptionName];
command.push(parentOption.command);
//Todo: verify typing
if (parentOption.type) {
command.push(options[parentOptionName]);
}
}
}
}
module.exports = {
addParentOptions : addParentOptionsForCommand
};
|
var express = require('express');
var router = express.Router();
//===================================================================================================
//Post functionality for adding Help Request records to database
router.post('/addpatient', function(req, res){
var db = req.db;
//capture request variables for handoff to database
var BedNumber = req.body.BedNumber;
var Help = req.body.Help;
var Prio = req.body.Prio;
var collection = db.get('usercollect');
//insert new information to usercollect database
collection.insert({
"BedNumber": BedNumber,
"Help": Help,
"Prio": Prio,
"TimeIn": Date()
}, function (err, doc){
if(err) {
//error handling
res.send("Error in adding record to database");
}
else{
//forward to patient page
res.redirect("patient/patient");
}
});
});
//===================================================================================================
// GET functions - Routes requests to the proper html/ejs pages!
//direct to homepage/index - two options!
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/index', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/personalindex', function(req, res) {
res.render('personalindex', { title: 'Express' });
});
router.get('/patientindex', function(req, res) {
res.render('patientindex', { title: 'Express' });
});
//====================================================================================================
//This export function should remain the LAST LINE in the file
module.exports = router;
|
import React from 'react';
import {
Card, Button, CardImg, CardTitle, CardText, CardColumns,
CardSubtitle, CardBody, Navbar
} from 'reactstrap';
import './Main/app.css';
import Slider from './Slider/Slider';
import Slide from './slide/slide';
const Example = (props) => {
return (
<div>
{/* <div className="slider">
<Slider style={{height: "10vh"}}/>
</div> */}
<Slide style={{height: "10vh"}}/>
<div className="blog-search">
<div className="row justify-content-center">
<div className="col-12 col-md-10 col-lg-8">
<form className="card card-sm">
<div className="card-body row no-gutters align-items-center">
<div className="col-auto">
<i className="fas fa-search h4 text-body" />
</div>
{/*end of col*/}
<div className="col">
<input className="form-control form-control-lg form-control-borderless" type="search" placeholder="Search Items" />
</div>
{/*end of col*/}
<div className="col-auto">
<button className="btn btn-lg btn-success" type="submit">Search</button>
</div>
{/*end of col*/}
</div>
</form>
</div>
{/*end of col*/}
</div></div>
<div className="blog"><h1>Categories</h1>
<div className="row">
<a
href="/clothes"
className="col-md-3 categories category_left tint"
style={{
background:
'url(https://i.pinimg.com/564x/87/94/3c/87943c5d7832c46e98132891cf1e386f.jpg)',
}}
>
<div align="center">
<h3>Clothes</h3>
</div>
</a>
<a
href="/laptops"
className="col-md-3 categories tint"
style={{
background:
'url(https://i.pinimg.com/564x/d4/01/97/d401971b6a9f4413694bb6b4bbe2a0da.jpg)',
}}
>
<div align="center">
<h3>Laptops and Accessories</h3>
</div>
</a>
<a
href="/mobilephones"
className="col-md-3 categories tint"
style={{
background:
'url(https://i.pinimg.com/564x/73/14/33/731433d5f5c692ce85e203a4002c6360.jpg)',
}}
>
<div align="center">
<h3>Phones and Accessories</h3>
</div>
</a>
<hr/>
<div className="container">
<h1>Our Featured Products</h1>
<div className="row">
<div className="col-md-3 col-sm-6">
<div className="product-grid6">
<div className="product-image6">
<a href="#">
<img className="pic-1" src="https://i.pinimg.com/564x/bd/4a/1f/bd4a1f697a9c09a10e96d42ac6dbe556.jpg" />
</a>
</div>
<div className="product-content">
<h3 className="title"><a href="#">Men's Shirt</a></h3>
<div className="price">$11.00
<span>$14.00</span>
</div>
</div>
<ul className="social">
<li><a href data-tip="Quick View"><i className="fa fa-search" /></a></li>
<li><a href data-tip="Add to Wishlist"><i className="fa fa-shopping-bag" /></a></li>
<li><a href data-tip="Add to Cart"><i className="fa fa-shopping-cart" /></a></li>
</ul>
</div>
</div>
<div className="col-md-3 col-sm-6">
<div className="product-grid6">
<div className="product-image6">
<a href="#">
<img className="pic-1" src="https://i.pinimg.com/564x/be/5c/22/be5c22b559f1c5ef754e7339b937a31a.jpg" />
</a>
</div>
<div className="product-content">
<h3 className="title"><a href="#">Women's Red Top</a></h3>
<div className="price">$8.00
<span>$12.00</span>
</div>
</div>
<ul className="social">
<li><a href data-tip="Quick View"><i className="fa fa-search" /></a></li>
<li><a href data-tip="Add to Wishlist"><i className="fa fa-shopping-bag" /></a></li>
<li><a href data-tip="Add to Cart"><i className="fa fa-shopping-cart" /></a></li>
</ul>
</div>
</div>
<div className="col-md-3 col-sm-6">
<div className="product-grid6">
<div className="product-image6">
<a href="#">
<img className="pic-1" src="https://i.pinimg.com/564x/93/f6/92/93f692e8385feb03ec37de7cde2956ce.jpg" />
</a>
</div>
<div className="product-content">
<h3 className="title"><a href="#">Men's Shirt</a></h3>
<div className="price">$11.00
<span>$14.00</span>
</div>
</div>
<ul className="social">
<li><a href data-tip="Quick View"><i className="fa fa-search" /></a></li>
<li><a href data-tip="Add to Wishlist"><i className="fa fa-shopping-bag" /></a></li>
<li><a href data-tip="Add to Cart"><i className="fa fa-shopping-cart" /></a></li>
</ul>
</div>
</div>
<div className="col-md-3 col-sm-6">
<div className="product-grid6">
<div className="product-image6">
<a href="#">
<img className="pic-1" src="https://i.pinimg.com/564x/2f/74/31/2f7431be6b2743ed6b2af5be44fc048a.jpg" />
</a>
</div>
<div className="product-content">
<h3 className="title"><a href="#">Men's Shirt</a></h3>
<div className="price">$11.00
<span>$14.00</span>
</div>
</div>
<ul className="social">
<li><a href data-tip="Quick View"><i className="fa fa-search" /></a></li>
<li><a href data-tip="Add to Wishlist"><i className="fa fa-shopping-bag" /></a></li>
<li><a href data-tip="Add to Cart"><i className="fa fa-shopping-cart" /></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{/* <Footer/> */}
</div>
);
};
export default Example;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.