text stringlengths 7 3.69M |
|---|
$(function() {
$('.error').hide();
$("#reply-submit").click(function() {
// validate and process form here
$('.error').hide();
if (CKEDITOR.instances.replycontent.getData() == '') {
$("label#replycontent_error").show();
$("#replycontent").focus();
return false;
}
alert(CKEDITOR.instances.replycontent.getData());
return false;
});
});
|
const mongoose = require('mongoose')
const siteSchema = new mongoose.Schema({
aboutImage :{ type: String, required: "Boş Geçilemez"},
contactImage :{ type: String, required: "Boş Geçilemez"},
contactText :{ type: String, required: "Boş Geçilemez"},
aboutText :{ type: String, required: "Boş Geçilemez"}
})
module.exports = mongoose.schema("site",siteSchema) |
angular.module('compassCourseBuilder.Controllers', [])
.controller('HomeController', function ($scope) {
})
.controller('CoordinatesController', function ($scope, $ionicModal) {
//Properties
$scope.isLoading = false;
$scope.Marks = [];
$scope.NewMark = new Mark("", "", "", "");
$scope.Error = "";
//Methods
$scope.clearForm = function () {
$scope.NewMark.Name = "";
$scope.NewMark.Latitude = "";
$scope.NewMark.Longitude = "";
$scope.NewMark.Description = "";
$scope.Error = "";
}
$scope.validateCoords = function () {
var pattern = new RegExp("-?[0-9]{1,3}[.][0-9]+");
console.log("RegEx: " + pattern);
var lat = $scope.NewMark.Latitude;
var long = $scope.NewMark.Longitude;
var isValidLat = pattern.test(lat); //+- 90
console.log("isValidLat: " + isValidLat);
var isValidLong = pattern.test(long); //+- 180
console.log("isValidLong: " + isValidLong);
if (isValidLat && isValidLong) {
if ((parseInt(lat) <= 90) && (parseInt(lat) >= -90) && (parseInt(long) <= 180) && (parseInt(long) >= -180)) {
return true;
}
else {
console.log("Coordinates wrong range!");
return false;
}
}
return false;
}
$scope.getLocation = function () {
$scope.isLoading = true;
navigator.geolocation.getCurrentPosition(
function (position) { //onSuccess()
$scope.NewMark.Latitude = position.coords.latitude;
$scope.NewMark.Longitude = position.coords.longitude;
$scope.isLoading = false;
console.log("Coordinates received from GPS: (" + $scope.NewMark.Latitude + ", " + $scope.NewMark.Longitude + ")");
},
function () { //onError()
$scope.isLoading = false;
console.log('Error getting coordinates from GPS');
});
}
$scope.addMark = function () {
if (($scope.NewMark.Name.length != 0) && ($scope.NewMark.Latitude.length != 0) && ($scope.NewMark.Longitude.length != 0)) {
if ($scope.validateCoords()) {
$scope.Marks.push(new Mark($scope.NewMark.Name, $scope.NewMark.Latitude, $scope.NewMark.Longitude, $scope.NewMark.Description));
$scope.clearForm();
$scope.openModal();
}
else {
$scope.Error = "Invalid coordinates";
}
}
else {
$scope.Error = "Missing required field(s)";
}
}
$ionicModal.fromTemplateUrl('contact-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
$scope.modal = modal;
})
$scope.openModal = function () {
$scope.modal.show();
}
$scope.closeModal = function () {
$scope.modal.hide();
};
$scope.$on('$destroy', function () {
$scope.modal.remove();
});
})
.controller('CoursesController', function ($scope) {
});
|
const db = require("../database/config.js");
const Data_Sensor = require("../models/data_sensor");
const List_Alat = require("../models/list_alat");
const Report = require("../models/report");
List_Alat.hasMany(Data_Sensor, {
as: "Data_Sensor3",
foreignKey: "listAlatId",
});
Data_Sensor.belongsTo(List_Alat, {
as: "List_Alat3",
foreignKey: "listAlatId",
});
List_Alat.hasMany(Report, { as: "Report3", foreignKey: "listAlatId" });
Report.belongsTo(List_Alat, { as: "List_Alat3", foreignKey: "listAlatId" });
async function ConvertToYearly() {
const ID = await Report.findAll({
attributes: [[db.fn("DISTINCT", db.col("listAlatId")), "id"]],
raw: true,
});
for (let i = 0; i < ID.length; i++) {
const data = await Report.findAll({
where: {
listAlatId: ID[i].id,
},
raw: true,
});
// console.log(data);
let data_monthly = data.filter((x) => x.tag == "monthly");
if (data_monthly.length == 12) {
await Report.destroy({
where: {
tag: "monthly",
listAlatId: ID[i].id,
},
raw: true,
});
let report_yearly = {
temp_avg: avg(data_monthly, "temp_avg"),
temp_min: min(data_monthly, "temp_min"),
temp_max: max(data_monthly, "temp_max"),
ppg_avg: avg(data_monthly, "ppg_avg"),
ppg_min: min(data_monthly, "ppg_min"),
ppg_max: max(data_monthly, "ppg_max"),
ekg_avg: avg(data_monthly, "ekg_avg"),
ekg_min: min(data_monthly, "ekg_min"),
ekg_max: max(data_monthly, "ekg_max"),
nivac_avg: avg(data_monthly, "nivac_avg"),
nivac_min: min(data_monthly, "nivac_min"),
nivac_max: max(data_monthly, "nivac_max"),
tag: "yearly",
listAlatId: ID[i].id,
};
await Report.create(report_yearly);
}
// console.log("data dengan tag daily:", data_daily);
}
}
module.exports = ConvertToYearly;
function min(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let min = Math.min.apply(Math, baru);
return min;
}
function max(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let max = Math.max.apply(Math, baru);
return max;
}
function avg(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
let sum = baru.reduce((total, value) => {
return total + value;
});
const count = baru.length;
let result = sum / count;
return Number(result.toFixed(2));
}
function min(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let min = Math.min.apply(Math, baru);
return min;
}
function max(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let max = Math.max.apply(Math, baru);
return max;
}
function avg(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
let sum = baru.reduce((total, value) => {
return total + value;
});
const count = baru.length;
let result = sum / count;
return Number(result.toFixed(2));
}
|
const fizzBuzzArrey = [];
function getFizzBuzz(firstInput, secondInput){
for(let i = 1; i < 100; i++){
let added = false;
if (i % firstInput == 0) {
added = true;
fizzBuzzArrey.push("fizz");
}
if(i % secondInput == 0){
added = true;
fizzBuzzArrey.push("buzz");
}
if(i % firstInput == 0 && i% secondInput == 0){
added = true;
fizzBuzzArrey.push("fizzBuzz");
}
if(!added){
fizzBuzzArrey.push(i);
}
}
}
getFizzBuzz(4, 12);
console.log(fizzBuzzArrey);
// Second Exercise
const positiveWords = ['happy', 'awesome', 'super'];
const negativeWords = ['boring', 'hate', 'bad'];
function getSentimentScore(str) {
}
const sentimentScoreObject = getSentimentScore('I am mega super awesome happy');
console.log(sentimentScoreObject);
/*
{
score: 3,
negativeWords: [],
}
*/ |
import React from 'react'
import { StyleSheet } from 'quantum'
const styles = StyleSheet.create({
self: {
background: '#d3e0e5',
fontSize: '12px',
lineHeight: '30px',
width: '100%',
},
})
const Title = ({ children }) => (
<div className={styles()}>
{children}
</div>
)
export default Title
|
const mongoose = require('mongoose');
const careersSchema = mongoose.Schema({
fullname: { type: String, required: true },
email: { type: String, required: true },
role: { type: String, required: true },
fileUrl: { type: String, required: true },
whyJoin: { type: String, required: true },
});
module.exports = mongoose.model('Careers', careersSchema);
|
class TicketEditor extends React.Component {
state = {
ticket: {}
}
findTicketById = (id) =>
findTicketById(id)
.then(ticket => this.setState({ticket}))
componentDidMount = () => {
const id = window.location.search.split("=")[1]
this.findTicketById(id)
}
savePrice = () =>
changePrice(this.state.ticket)
saveSeat = () =>
changeSeat(this.state.ticket)
saveDate = () =>
changeDate(this.state.ticket)
saveTime = () =>
changeTime(this.state.ticket)
saveTicketFan = () =>
changeTicketFan(this.state.ticket)
saveTicketGame = () =>
changeTicketGame(this.state.ticket)
render() {
return(
<div className="container">
<h1>Ticket Editor: <br/> Fan ID: {this.state.ticket.ticket_fan_id} <br/> Game ID: {this.state.ticket.ticket_game_id} </h1>
Price: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
price: event.target.value}})}
className="form-control"
value={this.state.ticket.price}/>
<button onClick={this.savePrice}>
Save Price
</button> <br/> <br/>
Seat: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
seat: event.target.value}})}
className="form-control"
value={this.state.ticket.seat}/>
<button onClick={this.saveSeat}>
Save Seat
</button> <br/> <br/>
Date: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
date: event.target.value}})}
className="form-control"
value={this.state.ticket.date}/>
<button onClick={this.saveDate}>
Save Date
</button> <br/> <br/>
Time: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
time: event.target.value}})}
className="form-control"
value={this.state.ticket.time}/>
<button onClick={this.saveTime}>
Save Time
</button> <br/> <br/>
Fan ID, current Fan ID: {this.state.ticket.ticket_fan_id}: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
ticket_fan: event.target.value}})}
className="form-control"
value={this.state.ticket.ticket_fan}/>
<button onClick={this.saveTicketFan}>
Save Fan ID
</button> <br/> <br/>
Game ID, current Game ID: {this.state.ticket.ticket_game_id}: <input
onChange={(event) => this.setState({
ticket: {
...this.state.ticket,
ticket_game: event.target.value}})}
className="form-control"
value={this.state.ticket.ticket_game}/>
<button onClick={this.saveTicketGame}>
Save Game ID
</button> <br/> <br/>
<a href="ticket-list-fan.html">
Done
</a>
</div>
)
}
}
ReactDOM.render(
<TicketEditor/>, document.getElementById("root"))
|
var page;
var frameModule = require("tns-core-modules/ui/frame");
var observableModule = require("tns-core-modules/data/observable");
var user = new observableModule.fromObject({
pin: "",
showDetails: false,
secret: ""
});
exports.loaded = function (args) {
page = args.object;
page.bindingContext = user;
};
var clipboard = require("nativescript-clipboard");
const modalViewModule = "views/success/success-page";
function copyText(args){
clipboard.setText(user.status).then(function() {
page.getViewById('copyClipboard').text = "Copied Successfully!"
console.log("OK, copied to the clipboard");
})
}
exports.copyText = copyText;
function openModal(args) {
const mainView = args.object;
const option = {
context: { username: "test_username", password: "test" },
closeCallback: (username, password) => {
// Receive data from the modal view. e.g. username & password
alert(`Username: ${username} : Password: ${password}`);
},
fullscreen: true
};
frameModule.Frame.topmost().showModal(modalViewModule, option);
}
exports.openModal = openModal;
exports.signIn = function () {
let message = page.getViewById('email').text
let statusLabel = page.getViewById('status')
fetch("https://theopensuite.com/api/snaps", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
secret: message,
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
user.status = response.url
statusLabel.text = response.url
user.showDetails = true
}).then(() => {
})
.catch((e) => {
});
};
const homePage = {
moduleName: "views/login/login-page",
animated: true,
// Set up a transition property on page navigation.
transition: {
name: "curl",
duration: 380,
curve: "easeIn"
}};
exports.goHome = function() {
user.showDetails = false
frameModule.Frame.topmost().navigate(homePage)
} |
import reimbursementApi from '@/api/reimbursement'
import commonJS from '@/common/common'
import userApi from '@/api/user'
export default {
data () {
return {
table: {
content: [],
totalElements: 0,
pageable: {
pageNumber: commonJS.getPageNumber('reimbursementItemList.pageNumber'),
pageSize: commonJS.getPageSize('reimbursementItemList.pageSize')
}
},
page: {
pageSizes: [10, 30, 50, 100, 300]
},
companyList: commonJS.companyList,
currentRow: null,
searchDialog: false,
search: commonJS.getStorageContentObject('reimbursementItemList.search'),
needReimbursementSum: null,
totalReimbursementSum: null,
multipleSelection: [],
reimbursementNeedPay: [{
code: 'YES',
name: '是'
}, {
code: 'NO',
name: '否'
}, {
code: 'BANK',
name: '银行'
}],
locationList: commonJS.locationList,
approveStatusList: commonJS.approveStatusList,
currentKindList: [],
typeList: commonJS.typeList,
roles: [],
jobType: ''
}
},
methods: {
// 显示控制
showControl (key) {
if (key === 'generateReimbursementSummary' || key === 'selectionColumn' || key === 'approveButton') {
return commonJS.isAdminInArray(this.roles)
}
// 没有特殊要求的不需要角色
return true
},
// 检查是否选择了一条记录
checkSelectRow () {
if (this.currentRow === null) {
this.$message({
message: '请选择一条记录!',
type: 'info',
showClose: true
})
return false
}
return true
},
// 新增
add () {
this.$router.push('/salary/reimbursementItem')
},
// 修改
modify () {
if (this.checkSelectRow()) {
this.$router.push({
path: '/salary/reimbursementItem',
query: {
mode: 'modify',
reimbursementItem: this.currentRow
}
})
}
},
// 删除选中记录
deleteById () {
if (this.checkSelectRow()) {
this.$confirm('确认要删除报销吗?', '确认信息', {
distinguishCancelAndClose: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then(() => {
reimbursementApi.deleteById(this.currentRow.id).then(
res => {
if (res.status === 200) {
this.$message({
message: '删除成功!',
type: 'success',
showClose: true
})
this.query()
} else {
this.$message.error('删除失败!')
}
})
})
}
},
// 查看
detail () {
if (this.checkSelectRow()) {
this.$router.push({
path: '/salary/reimbursementItem',
query: {
mode: 'detail',
reimbursementItem: this.currentRow
}
})
}
},
// 查询后台数据
query () {
window.localStorage['reimbursementItemList.search'] = JSON.stringify((typeof (this.search) === 'undefined' || typeof (this.search) !== 'object') ? {} : this.search)
window.localStorage['reimbursementItemList.pageNumber'] = this.table.pageable.pageNumber
window.localStorage['reimbursementItemList.pageSize'] = this.table.pageable.pageSize
let query = {
'currentPage': this.table.pageable.pageNumber,
'pageSize': this.table.pageable.pageSize,
'userName': this.search.userName,
'approveStatus': this.search.approveStatus,
'needPay': this.search.needPay,
'date': this.search.date,
'location': this.search.location,
'company': this.search.company,
'paymentMonth': this.search.paymentMonth,
'type': this.search.type,
'kind': this.search.kind,
'invoiceNo': this.search.invoiceNo,
'sum': this.search.sum,
'description': this.search.description
}
reimbursementApi.queryPage(query).then(res => {
if (res.status !== 200) {
this.$message.error({
message: '查询失败,请联系管理员!'
})
return
}
this.table = res.data.page
this.totalReimbursementSum = res.data.totalReimbursementSum
this.needReimbursementSum = res.data.needReimbursementSum
this.table.pageable.pageNumber = this.table.pageable.pageNumber + 1
this.searchDialog = false
})
},
// 行变化
rowChange (val) {
this.currentRow = val
},
// 页尺寸变化
sizeChange (val) {
this.table.pageable.pageSize = val
this.query()
},
// 当前页变化
currentChange (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 上一页 点击
prevClick (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 下一页 点击
nextClick (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 搜索对话框,确定按钮
sureSearchDialog () {
this.table.pageable.pageNumber = 1
this.query()
},
// 发送地点转换器
locationFormatter (row) {
if (row.location === 'Shanghai') {
return '上海'
} else if (row.location === 'Beijing') {
return '北京'
} else if (row.location === 'Shenyang') {
return '沈阳'
} else if (row.location === 'Wuhan') {
return '武汉'
} else if (row.location === 'Nanjing') {
return '南京'
} else if (row.location === 'Enshi') {
return '恩施'
}
},
// 公司转换器
companyFormatter (row) {
for (let c of commonJS.companyList) {
if (c.code === row.company) {
return c.name
}
}
},
// 是否报销转换器
needPayFormatter (row) {
if (row.needPay === 'YES') {
return '是'
} else if (row.needPay === 'NO') {
return '否'
} else if (row.needPay === 'BANK') {
return '银行'
}
},
// 报销类别转换器
typeFormatter (row) {
if (row.type === 'Transportation') {
return '交通'
} else if (row.type === 'Travel') {
return '差旅'
} else if (row.type === 'Communication') {
return '通讯'
} else if (row.type === 'Office') {
return '办公'
} else if (row.type === 'Service') {
return '服务'
} else if (row.type === 'Recruit') {
return '招聘'
} else if (row.type === 'Other') {
return '其他'
}
},
// 报销转换器
kindFormatter (row) {
if (row.kind === 'Parking') {
return '停车费'
} else if (row.kind === 'InternalAirTicket') {
return '国内机票'
} else if (row.kind === 'InternalTrainTicket') {
return '国内高铁/火车'
} else if (row.kind === 'TaxiSubway') {
return '出租车/地铁/其他市内交通'
} else if (row.kind === 'DriveTheFare') {
return '自驾车费'
} else if (row.kind === 'NationalAirTicket') {
return '国际机票'
} else if (row.kind === 'TravelHotel') {
return '差旅住宿费'
} else if (row.kind === 'TravelMeal') {
return '差旅餐饭'
} else if (row.kind === 'Communication') {
return '通讯费'
} else if (row.kind === 'OfficeRent') {
return '办公室租金'
} else if (row.kind === 'ITFee') {
return 'IT费用'
} else if (row.kind === 'Training') {
return '培训费'
} else if (row.kind === 'Print') {
return '打印费'
} else if (row.kind === 'Tool') {
return '文具费'
} else if (row.kind === 'Postage') {
return '快递费'
} else if (row.kind === 'Drug') {
return '药品'
} else if (row.kind === 'Candidate') {
return '候选人招待费'
} else if (row.kind === 'Client') {
return '客户招待费'
} else if (row.kind === 'Employee') {
return '员工内部招待费'
} else if (row.kind === 'Consultant') {
return '外包员工招待费'
} else if (row.kind === 'BodyCheck') {
return '体检费'
} else if (row.kind === 'Recruit') {
return '招聘费'
} else if (row.kind === 'InsuranceAndHousefund') {
return '五险一金'
} else if (row.kind === 'Insurance') {
return '各类保险'
} else if (row.kind === 'Tax') {
return '各类税收'
} else if (row.kind === 'Other') {
return '其他'
}
},
// 处理行选择变更
handleSelectionChange (val) {
this.multipleSelection = val
},
// 选中项审批通过
approveSelection () {
if (this.multipleSelection.size === 0) {
this.$message({
message: '请先选择要审批的记录!',
type: 'info',
showClose: true
})
} else {
this.$confirm('确认要审批通过选中项吗?', '确认信息', {
distinguishCancelAndClose: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then(() => {
reimbursementApi.approveSelection(this.multipleSelection).then(res => {
if (res.status === 200) {
// 刷新列表
this.query()
this.$message({
message: '审批成功!',
type: 'success',
showClose: true
})
}
})
})
}
},
// 清空查询条件
clearQueryCondition () {
this.search = {}
window.localStorage['reimbursementItemList.search'] = {}
},
// 下载报销项
downloadReimbursementItem () {
let query = {
'currentPage': this.table.pageable.pageNumber,
'pageSize': this.table.pageable.pageSize,
'userName': this.search.userName,
'approveStatus': this.search.approveStatus,
'needPay': this.search.needPay,
'date': this.search.date,
'location': this.search.location,
'company': this.search.company,
'paymentMonth': this.search.paymentMonth,
'type': this.search.type,
'kind': this.search.kind,
'invoiceNo': this.search.invoiceNo,
'sum': this.search.sum,
'description': this.search.description
}
reimbursementApi.downloadReimbursementItem(query).then(res => {
if (res.status === 200) {
this.$message({
message: '下载成功!',
type: 'success',
showClose: true
})
}
})
},
// 类别变更事件
typeChange (value) {
this.search.kind = ''
if (value === 'Transportation') {
this.currentKindList = commonJS.transportationKindList
} else if (value === 'Travel') {
this.currentKindList = commonJS.travelKindList
} else if (value === 'Communication') {
this.currentKindList = commonJS.communicationKindList
} else if (value === 'Office') {
this.currentKindList = commonJS.officeKindList
} else if (value === 'Service') {
this.currentKindList = commonJS.serviceKindList
} else if (value === 'Recruit') {
this.currentKindList = commonJS.recruitKindList
} else if (value === 'Other') {
this.currentKindList = commonJS.otherKindList
}
}
},
created () {
// 通过入参获取查询数据
if (typeof (this.$route.query.mode) !== 'undefined' && this.$route.query.mode === 'query') {
let params = this.$route.query.row
this.search.userName = params.userName
this.search.currentPage = 1
this.search.pageSize = 10
this.search.approveStatus = 'Approved'
this.search.needPay = 'YES'
this.search.paymentMonth = params.paymentMonth
this.query()
}
// 获取当前用户的角色列表
userApi.findSelf().then(res => {
if (res.status === 200) {
this.roles = res.data.roles
this.jobType = res.data.jobType
}
})
this.query()
}
}
|
import { windowsAppDriverCapabilities } from 'selenium-appium'
const { platform } = require('./jest.setup.windows');
switch (platform) {
default:
throw "Unknown platform: " + platform;
}
|
$(function () {
/* Menu nav toggle */
$(".menu-burger__header").click((function () {
$(".menu").toggleClass("open-menu")
}))
$('.projects__slider').slick({
arrows: false,
dots: false,
autoplay: true,
slidesToShow: 3,
slidesToScroll: 1,
swipeToSlide: true,
centerMode: false,
variableWidth: false,
responsive: [{
breakpoint: 1200,
settings: {
slidesToShow: 3,
variableWidth: true,
centerMode: true,
//infinite: true,
}
},
{
breakpoint: 1030,
settings: {
slidesToShow: 2,
variableWidth: true,
centerMode: true,
//infinite: false,
}
},
{
breakpoint: 992,
settings: {
slidesToShow: 1,
variableWidth: true,
centerMode: false,
}
},
{
breakpoint: 770,
settings: {
slidesToShow: 1,
variableWidth: true,
centerMode: false,
//infinite: true,
}
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
centerMode: false,
}
},
]
});
$('.partners__slider-items').slick({
arrows: false,
dots: false,
slidesToShow: 4,
slidesToScroll: 1,
swipeToSlide: true,
responsive: [{
breakpoint: 1305,
settings: {
slidesToShow: 3,
// variableWidth: true,
infinite: true,
}
},
{
breakpoint: 1025,
settings: {
slidesToShow: 3,
infinite: true,
}
},
{
breakpoint: 770,
settings: {
slidesToShow: 3,
// variableWidth: true,
infinite: true,
}
},
{
breakpoint: 690,
settings: {
slidesToShow: 2,
autoplay: true,
}
},
{
breakpoint: 570,
settings: {
autoplay: true,
speed: 1000,
slidesToShow: 2,
centerMode: false,
}
},
// {
// breakpoint: 569,
// settings: {
// autoplay: true,
// slidesToShow: 1,
// // infinite: true,
// variableWidth: true,
// centerMode: false,
// }
// },
// {
// breakpoint: 499,
// settings: {
// autoplay: true,
// slidesToShow: 2,
// centerMode: false,
// }
// },
{
breakpoint: 455,
settings: {
autoplay: true,
slidesToShow: 1,
centerMode: false,
}
},
]
});
});
let mainSlider = new Swiper('.main-slider', {
loop: true,
spaceBetween: 40,
allowTouchMove: false,
navigation: {
nextEl: '.main-slider__next',
prevEl: '.main-slider__prev',
},
}); |
//uc first method
//ucfirst('hi'); #'Hi'
export default function (str) {
str += '';
var f = str.charAt(0)
.toUpperCase();
return f + str.substr(1);
}; |
import { LOAD_MORE_REPOS } from "./githubReposAction";
const initialState = {
githubRepos: []
};
const githubReposReducer = (state = initialState, {type,payload}) => {
switch (type) {
case LOAD_MORE_REPOS:
return {...state, githubRepos: [...state.githubRepos, ...payload]};
default:
return state;
}
};
export default githubReposReducer |
import React, { Component } from "react";
import "./Login.scss";
import TextInput from "../../components/commonUI/TextInput";
import CheckBox from "../../components/commonUI/CheckBox";
import Button from "../../components/commonUI/Button";
import { Link, Redirect } from "react-router-dom";
import Cookies from "universal-cookie";
import * as SessionAction from '../../actions/SessionActions.js';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
isLogned: false,
username: "",
usernameMes: "",
password: "",
passwordMes: "",
remember: false
};
}
componentWillMount() {
var cookies = new Cookies();
var isLogined = false;
if (cookies.get("token")) {
isLogined = true;
} else {
isLogined = false;
}
this.setState({
isLogined: isLogined
});
}
componentDidMount() {
document.title = "Đăng nhập trang web";
}
handleSubmitForm(event) {
event.preventDefault();
}
ValidInput() {
var isValid = true;
if (this.state.username.length == 0) {
this.state.usernameMes = "Không thể để trống trường này";
isValid = false;
}
if (this.state.password.length == 0) {
this.state.passwordMes = "Không thể để trống trường này";
isValid = false;
}
return isValid;
}
LoginEvent() {
this.setState({ log: "Đang đăng nhập..." });
if (this.ValidInput()) {
const { login } = this.props.actions;
const user = { username: this.state.username, password: this.state.password, remember: this.state.remember };
login(user, this.props.history);
}
}
setStateForm(key, value) {
this.setState({
[key]: value
});
if (this.state[key + "Mes"] !== "" && value !== "") {
this.setState({
[key + "Mes"]: ""
});
}
}
render() {
var { isLogined } = this.state;
if (isLogined) {
return <Redirect to="/" />;
}
return (
<div className="login-container">
<div className="title-log">Đăng nhập</div>
<div className="login-content">
<form
className="login-form"
onSubmit={event => this.handleSubmitForm(event)}
>
<TextInput
display="Tên đăng nhập"
id="username"
value="admin"
onChanged={(key, value) => this.setStateForm(key, value)}
alert={this.state.usernameMes}
/>
<TextInput
display="Mật khẩu"
id="password"
value="admin"
onChanged={(key, value) => this.setStateForm(key, value)}
alert={this.state.passwordMes}
/>
<div>
<Link to="forgot" className="forgot-password">
Quên mật khẩu?
</Link>
</div>
<CheckBox
display="Ghi nhớ đăng nhập"
id="remember"
onChanged={(key, value) => this.setStateForm(key, value)}
/>
<div className="login-btn-container">
<Button
display="Đăng nhập"
submit="submit"
style="rep-btn"
onClick={() => {
this.LoginEvent();
}}
/>
<Link to="/signup">
<Button
display="Tạo tài khoản mới"
type="btn-Green"
style="rep-btn"
/>
</Link>
</div>
</form>
<div className="break-line-block">
<span>HOẶC</span>
</div>
<div className="social-panel">
<div className="social-btn-container">
<Button
display=" Đăng nhập với Facebook"
icon="fab fa-facebook"
type="btn-Blue"
style="rep-btn"
onClick={() => {}}
/>
<Button
display=" Đăng nhập với Google"
icon="fab fa-google"
type="btn-del"
style="rep-btn mat1em"
onClick={() => {}}
/>
</div>
</div>
</div>
</div>
);
}
}
const mapDispatch = dispatch => {
return {
actions: bindActionCreators(SessionAction, dispatch)
};
};
export default connect(
null,
mapDispatch
)(Login); |
import React, { useState } from 'react';
import { Modal, Button } from 'antd';
function Works() {
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
const handleOk = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
}
return (
<div className='block worksBlock'>
<div className='container-fluid'>
<div className='titleHolder'>
<h1>How it works</h1>
<p>This is a very good company for solving problem</p>
</div>
<div className='contentHolder'>
<Button type="primary" onClick={showModal}>
<i className='fas fa-play'></i>
</Button>
</div>
<Modal
title="Python Project"
visible={isModalVisible}
onCancel={handleCancel}
footer={null}
>
<iframe title='Python Project' width='100%'
height='350'
src="https://www.youtube.com/watch?v=p0G_ED0XR2M&t=148s">
</iframe>
</Modal>
</div>
</div>
)
}
export default Works
|
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
const config = {
apiKey: "AIzaSyC8f76v8QnpSlg5yBmf98_q8SydIkzQvPI",
authDomain: "zeez-the-plug.firebaseapp.com",
databaseURL: "https://zeez-the-plug.firebaseio.com",
projectId: "zeez-the-plug",
storageBucket: "zeez-the-plug.appspot.com",
messagingSenderId: "963392532122",
appId: "1:963392532122:web:6b0194ab2a8b4bd9b67923",
measurementId: "G-PYL8YDY0KP"
}
export const CreateUserProfileDocument = async (user, additionalData) => {
if (!user) return;
const userRef = firestore.doc(`users/${user.uid}`)
const Snapshot = await userRef.get()
if(!Snapshot.exists){
const CreatedAt = new Date()
const {displayName, email } = user
try {
await userRef.set({
displayName,
email,
CreatedAt,
...additionalData
})
} catch (error) {
console.log('error creating user', error.message)
}
}
return userRef
}
export const convertColleectionSnapShotToMap =(collections) => {
const transFormedCollection = collections.docs.map(doc => {
const {title, items} = doc.data()
return{
routeName:encodeURI(title.toLowerCase()),
id:doc.id,
title,
items
}
})
return transFormedCollection.reduce((acc, collection)=>{
acc[collection.title.toLowerCase()] =collection
return acc
}, {})
}
firebase.initializeApp(config)
export const auth = firebase.auth()
export const firestore = firebase.firestore()
const google = new firebase.auth.GoogleAuthProvider()
google.setCustomParameters({prompt: 'select_account'})
export const SighInWithGoogle = () => auth.signInWithPopup(google)
|
var base = require("./karma.conf.js");
module.exports = function (config) {
"use strict";
base(config);
config.set({
singleRun: true,
browsers: ['PhantomJS'],
plugins: [
"karma-phantomjs-launcher",
'karma-jasmine',
'karma-coverage',
'karma-jasmine-jquery'
]
});
}; |
function displayLink(content, id, blockNumber) {
var link = document.getElementById(id);
var linkText = content.blocks[blockNumber].cta.text;
var url = content.blocks[blockNumber].cta.url.gben;
link.innerHTML = "<a href='" + url + "'>" + linkText + "</a>"
}
|
/**
* A set of Esy-specific bash generation helpers.
*
* @flow
*/
import outdent from 'outdent';
import {ESY_STORE_PADDING_LENGTH, ESY_STORE_VERSION} from './constants';
export const defineScriptDir = outdent`
#
# Define $SCRIPTDIR
#
SOURCE="\${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$SCRIPTDIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
`;
export const defineEsyUtil = outdent`
#
# Esy utility functions
#
esyStrLength() {
# run in a subprocess to override $LANG variable
LANG=C /bin/bash -c 'echo "\${#0}"' "$1"
}
esyRepeatCharacter() {
chToRepeat=$1
times=$2
printf "%0.s$chToRepeat" $(seq 1 $times)
}
esyGetStorePathFromPrefix() {
ESY_EJECT__PREFIX="$1"
# Remove trailing slash if any.
ESY_EJECT__PREFIX="\${ESY_EJECT__PREFIX%/}"
ESY_STORE_VERSION="${ESY_STORE_VERSION}"
prefixLength=$(esyStrLength "$ESY_EJECT__PREFIX/$ESY_STORE_VERSION")
paddingLength=$(expr ${ESY_STORE_PADDING_LENGTH} - $prefixLength)
# Discover how much of the reserved relocation padding must be consumed.
if [ "$paddingLength" -lt "0" ]; then
echo "$ESY_EJECT__PREFIX is too deep inside filesystem, Esy won't be able to relocate binaries"
exit 1;
fi
padding=$(esyRepeatCharacter '_' "$paddingLength")
echo "$ESY_EJECT__PREFIX/$ESY_STORE_VERSION$padding"
}
`;
|
var OAuth = require('oauth');
require('dotenv').config();
var util = require('../helpers/forGetContent')
var oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
process.env.APP_CONSUMER_KEY,
process.env.APP_SECRET_KEY,
'1.0A',
null,
'HMAC-SHA1'
);
var getHome = function(req, res) {
oauth.get(
`https://api.twitter.com/1.1/statuses/home_timeline.json`,
process.env.USER_TOKEN,
process.env.USER_SECRET_KEY,
function (e, data){
if (e) {
res.send(e);
} else {
res.send(data)
}
})
}
var getUserTimeline = function(req, res) {
if(req.params.username !== undefined) {
var user = req.params.username
} else {
var user = '';
}
oauth.get(
`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${user}`,
process.env.USER_TOKEN,
process.env.USER_SECRET_KEY,
function (e, data){
if (e) res.send(e);
res.send(data)
})
}
module.exports = {
getHome, getUserTimeline
};
|
export const getLanguageCode = (lang) => {
switch (lang.toLowerCase()) {
case "dutch":
return "nl";
case "arabic":
return "ar";
case "french":
return "fr";
case "german":
return "de";
case "gujarati":
return "gu";
case "hindi":
return "hi";
case "urdu":
return "ur";
case "japanese":
return "ja";
default:
//english
return "en";
}
};
|
/**
* A path through the network graph. Composed of PathSegments (which
* are in turn composed of a sequence of graph edges)
*/
export default class NetworkPath {
/**
* NetworkPath constructor
* @param {Object} parent the parent object (a RoutePattern or Journey)
*/
constructor(parent) {
this.parent = parent
this.segments = []
}
clearGraphData(segment) {
this.segments.forEach(function (segment) {
segment.clearGraphData()
})
}
/**
* addSegment: add a new segment to the end of this NetworkPath
*/
addSegment(segment) {
this.segments.push(segment)
segment.points.forEach(function (point) {
point.paths.push(this)
}, this)
}
getRenderedSegments() {
let renderedSegments = []
this.segments.forEach(function (pathSegment) {
renderedSegments = renderedSegments.concat(pathSegment.renderedSegments)
})
return renderedSegments
}
/**
* getPointArray
*/
getPointArray() {
const points = []
for (let i = 0; i < this.segments.length; i++) {
const segment = this.segments[i]
if (
i > 0 &&
segment.points[0] ===
this.segments[i - 1].points[this.segments[i - 1].points.length - 1]
) {
points.concat(segment.points.slice(1))
} else {
points.concat(segment.points)
}
}
return points
}
}
|
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = setupDatabase;
var _sequelize = _interopRequireDefault(require("sequelize"));
var sequelize = null;
function setupDatabase(config) {
if (!sequelize) {
sequelize = new _sequelize["default"](config);
}
return sequelize;
} |
import Vue from 'vue'
import Vuex from 'vuex'
import { auth } from './auth.module'
import { movies } from './movies.module'
import { actors } from './actors.module'
import { users } from './users.module'
import { categories } from './categories.module'
import { directors } from './directors.module'
import { characters } from './characters.module'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
auth,
movies,
actors,
users,
categories,
directors,
characters
},
})
export default store |
//Page des fonctions et introductions
// exemple : la fonction ransom () " aléatoire"
document.getElementById('p1').innerHTML = Math.random(); // Ici on exécute le code " caché" derrière la fonction, on appel la fonction ou on l'invoque.
// replace()
let discours1 = 'Bonjour je suis un caméléon';
// console.log(discours1);
let discours2 = discours1.replace('un caméléon', 'un chat'); // Le nom de la fonction est suivie d'un couple de parenthèses qui contiennent le plus souvent des arguments.
document.getElementById('p2').innerHTML = discours2;
//création de fonctions
function randomX100() {
return Math.random() * 100;
}
// console.log(randomX100());
document.getElementById('p3').innerHTML = randomX100();
// -2-Une simple multiplication
function multiplier(nbr1,nbr2) {
return(' Multiplions ' + nbr1 + ' x' + nbr2 + '=' + (nbr1 * nbr2));
}
// console.log(multiplier(2,6)); // le 2 et le 6 correspond à nbr1 et nbr2
document.getElementById('p4').innerHTML = multiplier (145,9);
//exercice
function soustraction(nbr1,nbr2) {
return(' Soustraction ' + nbr1 + ' - ' + nbr2 + '=' + (nbr1 - nbr2));
}
document.getElementById('p5').innerHTML = soustraction (10,2);
function addition(nbr1,nbr2) {
return(' Addictionnons ' + nbr1 + '+' + nbr2 + '=' + (nbr1 + nbr2));
}
document.getElementById('p6') .innerHTML = addition ( 20,5);
function modulo(nbr1,nbr2) {
return(' Le modulo ' + nbr1 + '%' + nbr2 + '=' + (nbr1 % nbr2));
}
document.getElementById('p7').innerHTML = modulo (30,3); |
var APP = this.APP || {};
(function($, F, A) {
$(function() {
var input = $('#query'),
indexList = $('#index-list'),
index = $('#index'),
docList = $('#doc-list'),
clear = $('#clear'),
hide = $('#hide-index'),
codes = 'pre.sh_oracle',
indexTemplate = $('#index-template'),
docTemplate = $('#doc-template'),
sandbox = A.sandbox.create(),
docModule = A.doc.create(docTemplate, docList, docListData, sandbox),
tocModule = A.toc.create(indexTemplate, index, indexList, docListData, sandbox),
autModule = A.autocomplete.create(input, sandbox),
srchModule = A.search.create(docListData, sandbox),
btnModule = A.button.create(clear, hide, sandbox);
cpyModule = A.clipboard.create(codes);
srchModule.init();
autModule.init(docListData);
tocModule.init();
docModule.init();
btnModule.init();
cpyModule.init();
});
}(jQuery, FINN, APP)); |
"use strict"
var Dimension = function () {
this.ID;
// Declre an object to store the organization ID
this.OrganizationID;
// Declare an object to store teh friendly name
this.Name;
// Declare an object to store the description
this.Description;
// Declare an object to store the assigned role for this dimension
this.Role;
// Declare an object to store the active state flag
this.isActive;
this.Load = loadData;
// this.loadDimensionsByOrg = loadDimensionsByOrg;
// this.Save = saveData;
// this.Update = updateData;
function loadData(Url, ID, callback) {
// declare a local variable to store the constructed URL
var targetUrl;
if (ID != undefined) {
targetUrl = Url + "/" + ID;
// Make the asynchronous AJAX call to get the data
$.when($.getJSON(targetUrl)).then(function (data, textStatus, jqXHR) { callback(data); });
}
}
} |
#pragma strict
function Start () {
var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = Vector3(0.1851258, 1.212802, -2.374351);
cube.transform.Rotate(0f,0f,0f);
cube.transform.localScale=Vector3(1.59038,0.5006871,2.594095);
cube.AddComponent("BoxCollider");
cube.AddComponent("MeshRenderer");
var cube2 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube2.transform.position = Vector3(0.1851258, 1.341494, -0.5406924);
cube2.transform.Rotate(0f,0f,0f);
cube2.transform.localScale=Vector3(1.59038,0.5006871,-1.219515);
cube2.AddComponent("BoxCollider");
cube2.AddComponent("MeshRenderer");
var cube3 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube3.transform.position = Vector3(0.1851258, 1.1578, -0.7438473);
cube3.transform.Rotate(90f,0f,0f);
cube3.transform.localScale=Vector3(1.59038,0.5006871,-0.4055409);
cube3.AddComponent("BoxCollider");
cube3.AddComponent("MeshRenderer");
var cube4 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube4.transform.position = Vector3(0.1851258, 2.302082, -0.6670475);
cube4.transform.Rotate(0f,0f,0f);
cube4.transform.localScale=Vector3(1.59038,0.5006871,-0.9767075);
cube4.AddComponent("BoxCollider");
cube4.AddComponent("MeshRenderer");
var cube5 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube5.transform.position = Vector3(0.862036,1.413467,-2.371165);
cube5.transform.Rotate(0f,0f,0f);
cube5.transform.localScale=Vector3(0.2406305,0.5006871,2.594095);
cube5.AddComponent("BoxCollider");
cube5.AddComponent("MeshRenderer");
var cube6 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube6.transform.position = Vector3(0.1851258,0.8510752,-0.6853967);
cube6.transform.Rotate(0f,0f,0f);
cube6.transform.localScale=Vector3(1.59038,0.5006871,3.349324);
cube6.AddComponent("BoxCollider");
cube6.AddComponent("MeshRenderer");
var cube7 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube7.transform.position = Vector3(0.1851258,1.341675,0.5007968);
cube7.transform.Rotate(12.13944f,0f,0f);
cube7.transform.localScale=Vector3(1.59038,0.5006871,-0.9767075);
cube7.AddComponent("BoxCollider");
cube7.AddComponent("MeshRenderer");
var cube8 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube8.transform.position = Vector3(0.1851258,0.8510752,-1.995752);
cube8.transform.Rotate(0f,0f,0f);
cube8.transform.localScale=Vector3(1.59038,0.5006871,3.349324);
cube8.AddComponent("BoxCollider");
cube8.AddComponent("MeshRenderer");
var cube9 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube9.transform.position = Vector3(0.1851258,2.009713,-0.2253701);
cube9.transform.Rotate(70.31223f,0f,0f);
cube9.transform.localScale=Vector3(1.59038,0.5006871,-0.9767076);
cube9.AddComponent("BoxCollider");
cube9.AddComponent("MeshRenderer");
var cube10 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube10.transform.position = Vector3(0.1851258,1.841046,-0.6670475);
cube10.transform.Rotate(0f,0f,0f);
cube10.transform.localScale=Vector3(1.59038,0.5006871,-0.9767075);
cube10.AddComponent("BoxCollider");
cube10.AddComponent("MeshRenderer");
var cube11 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube11.transform.position = Vector3(0.1699725,1.413467,-3.546809);
cube11.transform.Rotate(0f,90f,0f);
cube11.transform.localScale=Vector3(0.2406305,0.5006871,1.326656);
cube11.AddComponent("BoxCollider");
cube11.AddComponent("MeshRenderer");
var cube12 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube12.transform.position = Vector3(-0.5009881,1.413467,-2.374882);
cube12.transform.Rotate(0f,0f,0f);
cube12.transform.localScale=Vector3(0.2406305,0.5006871,2.594095);
cube12.AddComponent("BoxCollider");
cube12.AddComponent("MeshRenderer");
var cylinder : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.position = Vector3(1.081525,0.8510752,0.2259815);
cylinder.transform.Rotate(90f,270f,0f);
cylinder.transform.localScale= Vector3(1.225088,0.09770568,1.225088);
cylinder.AddComponent("CapsuleCollider");
cylinder.AddComponent("MeshRenderer");
var cylinder2 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder2.transform.position = Vector3(-0.7125183,0.8510752,-2.906469);
cylinder2.transform.Rotate(90f,270f,0f);
cylinder2.transform.localScale= Vector3(1.225088,0.09770568,1.225088);
cylinder2.AddComponent("CapsuleCollider");
cylinder2.AddComponent("MeshRenderer");
var cylinder3 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder3.transform.position = Vector3(1.081525,0.8510752,-2.906469);
cylinder3.transform.Rotate(90f,270f,0f);
cylinder3.transform.localScale= Vector3(1.225088,0.09770568,1.225088);
cylinder3.AddComponent("CapsuleCollider");
cylinder3.AddComponent("MeshRenderer");
var cylinder4 : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder4.transform.position = Vector3(-0.7125183,0.8510752,0.2259815);
cylinder4.transform.Rotate(90f,270f,0f);
cylinder4.transform.localScale= Vector3(1.225088,0.09770568,1.225088);
cylinder4.AddComponent("CapsuleCollider");
cylinder4.AddComponent("MeshRenderer");
}
function Update () {
} |
// React
import React, {useEffect, useState} from 'react';
// ChartJS
import { Bar, Scatter, defaults } from "react-chartjs-2";
// Styles
import './Chart.css'
// Animation is causing troubles
defaults.animation = false;
const Chart = ({ series }) => {
const [seriesData, setSeriesData] = useState({});
// Convert data to ChartJS format
useEffect(() => {
const labels = [];
const data = [];
series.forEach(point => {
labels.push(point.x);
data.push(point.y);
});
setSeriesData({
labels: labels,
datasets: [{
data: data,
backgroundColor: [
'#95ca3e',
'rgb(18, 31, 61)',
],
}],
});
}, [series])
return (
<div className="Chart">
{/* Bars Chart */}
<div className="chart">
<Bar
// redraw={true}
data={seriesData}
options={{
plugins: {
title: {
display: true,
text: "Barras"
},
legend: {
display: false,
}
}
}}
/>
</div>
{/* Scatter Chart */}
<div className="chart">
<Scatter
data={seriesData}
options={{
plugins: {
title: {
display: true,
text: "Puntos"
},
legend: {
display: false,
}
}
}}
/>
</div>
</div>
);
}
export default Chart; |
var moment = require('moment');
var R = require('ramda');
// Loops over object and returns new object with functions bound to the original object
var demethodizeMap = R.mapObj.idx(function (fn, fnName, obj) {
return R.invoker(fnName, obj);
});
// Pulls off all the moment methods
var fm = demethodizeMap(moment.fn);
// Pulls off all the moment.duration methods
var fd = demethodizeMap(moment.duration.fn);
// Export the new object
module.exports = exports = R.mixin(fm, {duration: fd}); |
OC.L10N.register(
"files_external",
{
"Step 1 failed. Exception: %s" : "Стъпка 1 - неуспешна. Грешка: %s",
"Step 2 failed. Exception: %s" : "Стъпка 2 - неуспешна. Грешка: %s",
"External storage" : "Външно дисково пространство",
"Google Drive App Configuration" : "Настройки на Google Drive приложение",
"Error verifying OAuth2 Code for " : "Грешка при проверката на на OAuth2 код за",
"Personal" : "Личен",
"System" : "Системен",
"Grant access" : "Разреши достъп",
"Error configuring OAuth1" : "Грешка при настройка на OAuth1",
"Please provide a valid app key and secret." : "Моля, дайте валидни ключ за приложението и тайна.",
"Generate keys" : "Генериране на криптографски ключове",
"Error generating key pair" : "Грешка при генериране на криптографски ключове",
"All users. Type to select user or group." : "Всички потребители. Въведете за да изберете потребител или група.",
"(group)" : "(група)",
"Compatibility with Mac NFD encoding (slow)" : "Съвместимост с Mac NFD encoding (бавно)",
"Unknown auth backend \"{b}\"" : "Неизвестна достоверност на бекенд \"{b}\"",
"Please make sure that the app that provides this backend is installed and enabled" : "Моля уверете се, че приложението, което предоставя този бекенд е инсталирано и активирано",
"Admin defined" : "Админстраторът е дефиниран ",
"Saved" : "Запазено",
"Disabling external storage will unmount all storages for all users, are you sure ?" : "Деактивирането на външното хранилище ще деактивира всички хранилища за всички потребители, сигурни ли сте?",
"Disable external storage" : "Деактивиране на външното съхранение",
"No URL provided by backend " : "Няма URL адрес предоставен от бекенд",
"Error getting OAuth2 URL for " : "Грешка при получаването на URL адрес от OAuth2 за",
"Empty response from the server" : "Празен отговор от сървъра",
"Couldn't access. Please logout and login to activate this mount point" : "Неуспешен достъп. Моля, излезте и влезте за да активирате тази точка на монтиране",
"Couldn't get the information from the ownCloud server: {code} {type}" : "Неуспешно приемане на информация от ownCloud сървър: {code} {type}",
"Couldn't get the list of external mount points: {type}" : "Неуспешно приемане на списък от монтирани външни точки: {type}",
"There was an error with message: " : "Възникна греша със съобщение:",
"External mount error" : "Грешка при монтиране на външен диск",
"Couldn't get the list of Windows network drive mount points: empty response from the server" : "Неуспешно намиране на списъка с мрежови Windows дискове: празен отговор от сървъра",
"Some of the configured external mount points are not connected. Please click on the red row(s) for more information" : "Някои от конфигурираните външни дискове не са свързани. Моля, натиснете на редът(овете) в червено за допълнителна информация.",
"Please enter the credentials for the {mount} mount" : "Моля, въведете потребителско име и парола за свързване с {mount}",
"Username" : "Потребителско Име",
"Password" : "Парола",
"Credentials saved" : "Потребителското име и парола са запазени",
"Credentials saving failed" : "Запазването на потребителското име и парола е неуспешно",
"Credentials required" : "Потребителското име и парола са задължителни",
"Save" : "Запазване",
"Storage with id \"%i\" not found" : "Хранилище с име \"%i\" не е намерено",
"Invalid backend or authentication mechanism class" : "Невалиден бекенд или клас механизъм за удостоверяване",
"Invalid mount point" : "Невалиден път за монитиране на файлова система",
"Objectstore forbidden" : "Objectstore е забранен",
"Invalid storage backend \"%s\"" : "Невалиден бекенд на хранилище \"%s\"",
"Not permitted to use backend \"%s\"" : "Не е позволено използването на бекенд \"%s\"",
"Not permitted to use authentication mechanism \"%s\"" : "Не е позволено да се използва механизъм за удостоверяване \"%s\"",
"Unsatisfied backend parameters" : "Неудволетворени бекенд параметри",
"Unsatisfied authentication mechanism parameters" : "Неудовлетворени параметри на механизма за удостоверяване",
"Insufficient data: %s" : "Недостатъчни данни: %s",
"%s" : "%s",
"Storage with id \"%i\" is not user editable" : "Хранилището с id \"%i\" не може да се редактира от потребителя",
"OAuth1" : "OAuth1",
"App key" : "App key",
"App secret" : "App secret",
"OAuth2" : "OAuth2",
"Client ID" : "Client ID",
"Client secret" : "Client secret",
"OpenStack" : "OpenStack",
"Tenant name" : "Tenant име",
"Identity endpoint URL" : "URL адрес на крайна точка за идентичност",
"Rackspace" : "Rackspace",
"API key" : "API ключ",
"RSA public key" : "RSA публичен ключ",
"Public key" : "Публичен ключ",
"WebDAV" : "WebDAV",
"URL" : "Интернет Адрес",
"Remote subfolder" : "Външна подпапка",
"Secure https://" : "Сигурен https://",
"Google Drive" : "Google Drive",
"Local" : "Локален",
"Location" : "Местоположение",
"ownCloud" : "ownCloud",
"SFTP" : "SFTP",
"Host" : "Host",
"Root" : "Root",
"SFTP with secret key login" : "SFTP вписване с таен ключ",
"SMB / CIFS" : "SMB / CIFS",
"Share" : "Споделяне",
"Domain" : "Домейн",
"SMB / CIFS using OC login" : "SMB / CIFS използвайки OC профил",
"Username as share" : "Потребителско име, когато се споделя",
"<b>Note:</b> " : "<b>Бележка:</b> ",
"<b>Note:</b> The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Note:</b> PHP подръжката на cURL не е включена или инсталирана. Монтирането на %s е невъзможно. Моля поискайте от системния администратор да я инсталира.",
"<b>Note:</b> \"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Забележка:</b> \"%s\" не е инсталирана. Монтирането на %s е невъзможно. Моля поискайте от системния администратор да я инсталира.",
"No external storage configured" : "Няма настроено външно дисково пространство",
"You can add external storages in the storage settings" : "Можете да добавите външни хранилища в настройките за съхранение",
"Name" : "Име",
"Storage type" : "Тип дисково пространство",
"Scope" : "Обхват",
"Enable encryption" : "Активиране на криптиране",
"Set read-only" : "Задайте само за четене",
"Enable previews" : "Активиране на преглед",
"Enable sharing" : "Активиране на споделяне",
"Check for changes" : "Проверка за промени",
"Never" : "Никога",
"Once every direct access" : "Веднъж на всеки директен достъп",
"External Storage" : "Външно Дисково Пространство",
"Enable external storage" : "Активиране на външното хранилище",
"External storage has been disabled by the administrator" : "Външното хранилище е деактивирано от администратора",
"Folder name" : "Име на папката",
"Authentication" : "Оторизация",
"Configuration" : "Настройки",
"Available for" : "Достъпно за",
"Add storage" : "Добави дисково пространство",
"Advanced settings" : "Разширени настройки",
"Delete" : "Изтрий",
"Allow users to mount external storage" : "Разрешаване на потребители да прикачват външни дискови устройства",
"Allow users to mount the following external storage" : "Разреши на потребителите да прикачват следното външно дисково пространство",
"Allow sharing on user-mounted external storages" : "Разрешаване на споделянето на монтирани от потребителя външни хранилища"
},
"nplurals=2; plural=(n != 1);");
|
import PickListView from './PickListView'
export default PickListView; |
var fs = require('fs');
var util = require('util');
var exec = require('child_process').exec;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({ dest: '/home/admin/khk-paparazzi/uploads/' });
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.listen(4000);
app.get("/", function(req, res){
res.render("index", {"token":Math.floor(Math.random()*2048).toString(16), backgrounds:fs.readdirSync(__dirname + "/public/images/show")});
});
var totalUploads = {};
var currentUploads = {};
var erroredUploads = {};
function removeUpload(filename, token){
for(var i=0; i<currentUploads[token].length; i++){
if(currentUploads[token][i].filename == filename){
currentUploads[token].splice(i,1);
return;
}
}
}
var currentJobs = 0;
var maxJobs = 10;
var jobCounter = 0;
function checkThenRun(cmd, job){
if(currentJobs >= maxJobs){
console.log("Warning: Max number of current jobs met, waiting 200ms");
setTimeout(function(){checkThenRun(cmd, job);}, 200);
}else{
currentJobs++;
var child = exec(cmd, function(error, stdout, stderr){
if(error) console.log('Job:'+job+' Error: ' + error);
else console.log('Job:'+job+' Synced! ' + stdout);
currentJobs--;
});
}
}
app.post("/upload", upload.array("photos", 50), function(req, res){
var token = req.body.token;
console.log(token);
res.redirect("/status?token="+token);
totalUploads[token] = req.files.length;
currentUploads[token] = req.files.slice(0, req.files.length);
erroredUploads[token] = [];
req.files.forEach(function(file){
if(file.mimetype.split("/")[0] == "image"){
var originalPath = file.path;
var newPath = __dirname + "/public/images/show/" + file.filename + "." +file.originalname.split(".")[file.originalname.split(".").length-1]
var dirs = fs.readdirSync(__dirname + "/uploads");
console.log(originalPath, newPath, dirs);
fs.rename(originalPath, newPath, function(err){
if(err){
erroredUploads[token].push(file.originalname);
removeUpload(file.filename, token);
console.log(err);
}else{
var child = exec("chown admin:admin " + newPath, function(error, stdout, stderr){
if(error) console.log("Ownership change, failed", error);
});
removeUpload(file.filename, token);
cmd = 'scp -pr "' + newPath + '" ' + 'khk@10.0.0.10:"' + "/home/admin/photos/_Current (Spring 2016)/unsorted".replace(/(["\s'$`\\()])/g,'\\$1') + '"';
var job = ++jobCounter;
console.log('Job:'+job+'\('+currentJobs+'/'+maxJobs+'\) Add/Sync: ', cmd);
checkThenRun(cmd, job);
}
});
}else{
fs.unlink(file.path);
erroredUploads[token].push(file.originalname);
removeUpload(file.filename, token);
}
});
});
app.get("/status", function(req, res) {
res.render("status", {token:req.query.token});
});
app.get("/statusupdate", function(req, res){
var token = req.query.token;
res.status(200).send({total:totalUploads[token], pending:currentUploads[token].length, errors:erroredUploads[token]});
});
module.exports = app;
|
var searchData=
[
['send_5fdebug',['SEND_DEBUG',['../group___debug___exported___types.html#ggacb1775677105967978fae4d9155cca26aa8996ee795e2d49fb83539a0ac88342e',1,'debug.h']]],
['state_5fdebug',['STATE_DEBUG',['../group___debug___exported___types.html#ggacb1775677105967978fae4d9155cca26a0cad8d390f2e4ac93049277fd291a95e',1,'debug.h']]]
];
|
(function () {
'use strict';
var nsb = {
'el': document.getElementById('nsb')
};
nsb.controller = function () {
var ctrl = this;
ctrl.data = {};
nsb.el.addEventListener('nsb', function (event) {
var body = event.detail;
if (body.departures.length > 0) {
body.next = body.departures[0];
body.upcoming = body.departures.slice(1, 5);
} else {
body.next = null;
body.upcoming = [];
}
ctrl.data = body;
m.render(nsb.el, nsb.view(ctrl));
});
};
nsb.view = function (c) {
if (Object.keys(c.data).length === 0) {
return m('p', 'Waiting for data');
}
var rows = c.data.upcoming.map(function (departure) {
return m('tr', [
m('td', departure.departure),
m('td', departure.arrival),
m('td', departure.duration)
]);
});
return [
m('p.fade', [
'Neste tog fra ',
m('em', c.data.from),
' til ',
m('em', c.data.to),
' går ',
m('em', c.data.date)
]),
m('h1', c.data.next.departure),
m('h2.fade', [
'Ankomst: ',
m('em', c.data.next.arrival),
' (',
m('em', c.data.next.duration),
')'
]),
m('table', [
m('tr.fade', [
m('th', 'Avgang'),
m('th', 'Ankomst'),
m('th', 'Reisetid')
])
].concat(rows)),
m('p', {class: 'fade updated-at'}, 'Sist oppdatert: ' +
c.data.updatedAt)
];
};
if (nsb.el !== null) {
m.module(nsb.el, nsb);
}
})();
|
// document.onload = () => {
const foods = [
{
name: "suon nuong",
address: "33 dong cat",
img: "https://scontent.fhan2-1.fna.fbcdn.net/v/t1.0-9/93910160_2395152850775198_6628136360324628480_n.jpg?_nc_cat=102&_nc_sid=110474&_nc_ohc=XU6hNjGX4gQAX_1OBnw&_nc_ht=scontent.fhan2-1.fna&oh=0424bf7ec87dc6a458874a3e2ead85a7&oe=5ED315F0"
},
{
name: "hin xien nuong",
address: "ngo 135 phuong mai",
img: "https://thucthan.com/media/2018/05/thit-xien-nuong/cach-lam-thit-xien-nuong.jpg"
},
{
name: "hin nuong",
address: "xxx chua lang",
img: "https://thucthan.com/media/2018/05/thit-xien-nuong/cach-lam-thit-xien-nuong.jpg"
},
{
name: "bun oc",
address: "nha co lan, khuong thuong",
img: "https://goldenapple.com.vn/wp-content/uploads/2015/11/7_168634-1024x1024.jpg"
},
{
name: "pho ga tron",
address: "43 ma tay",
img: "https://daubepgiadinh.vn/wp-content/uploads/2017/02/pho-ga-tron.jpg"
},
{
name: "pho cuon",
address: "25-27 ngu xa",
img: "https://vncooking.com/files/cuisine/2019/01/26/pho-cuon-la-mieng-bcoq.jpg"
},
{
name: "oc",
address: "88 cua bac, ba dinh",
img: "https://images.foody.vn/res/g26/252787/prof/s576x330/foody-mobile-33-jpg-383-636033127781449474.jpg"
},
{
name: "my van than",
address: "54 hang chieu, dong xuan",
img: "https://lh3.googleusercontent.com/proxy/hvLLe3FnaBX20sW4AHdABkoP3hUM5_ZT3-ykm3Cad_Ovz7YRsoXaEHEYF3kG24zie8rgtqT6Y7vy6MrEiRvrjb-yRtw4M4xyMNWOuQ-p9GzcaIqdQqOSq6fxKw"
},
{
name: "nam chua ran",
address: "36 tam thuong, hang gai",
img: "https://shipdoandemff.com/wp-content/uploads/2017/06/Nem-chua-r%C3%A1n-ShipdoandemFF.jpg"
},
{
name: "banh duc nong",
address: "le ngoc han",
img: "https://thoidai.com.vn/stores/news_dataimages/trang.chu/112019/30/21/5449_2.jpg"
},
{
name: "banh duc nong",
address: "ngo 46c pham ngoc thach",
img: "https://thoidai.com.vn/stores/news_dataimages/trang.chu/112019/30/21/5449_2.jpg"
},
{
name: "pho ga tron",
address: "43 ma may",
img: "https://www.iunauan.com/images/600x459/anh1-iunauan.com-taliyv847114436.jpg?1541772790738"
},
{
name: "bun thang",
address: "48 pho cau go (ba duc)",
img: "https://daynauan.info.vn/wp-content/uploads/2018/08/bun-thang.jpg"
},
{
name: "banh trang",
address: "86 hang trong (co toan)",
img: "https://channel.vcmedia.vn/k:prupload/164/2014/11/img20141126011515754/banh-trang-tron-co-toan-86-hang-trong-hut-gioi-tre-ha-thanh.jpg"
},
{
name: "shabu shabu on yasai",
address: "nhieu dia chi",
img: "https://cdn.pastaxi-manager.onepas.vn/content/uploads/articles/nguyenhuong/onyasailethanhton/on-yasai-shabu-shabu-le-thanh-ton-11.jpg"
},
{
name: "burger",
address: "114 xuan dieu",
img: "https://images.foody.vn/res/g3/26353/s750x750/6f48ce63-13d9-4505-828a-bddddf5b3aad.jpg"
},
{
name: "hinhin quay",
address: "40 an duong, tay ho",
img: "https://monngonchuabenh.com/wp-content/uploads/2019/01/hinh-anh-vit-quay-bac-kinh.jpg"
},
{
name: "xoi xeo suon cay",
address: "630 truong chinh",
img: "https://media.foody.vn/images/15078703_363527810664962_1098888384492902905_n(1).jpg"
},
{
name: "sua chua",
address: "109b ngo 1a ton that tung (co oanh)",
img: "https://image-us.eva.vn/upload/2-2019/images/2019-05-03/1556854488-400-thumbnail_schema_article.jpg"
},
{
name: "banh black forest",
address: "109 duong lang",
img: "https://www.finedininglovers.com/sites/g/files/xknfdk626/files/styles/recipe_full_desktop/public/Original_17100_l-7690-l-7670-Foresta-Nera.png?itok=uR8yLVaO"
},
{
name: "hot dog",
address: "xxx o cho dua",
img: "https://kenh14cdn.com/thumb_w/640/2017/hotdog-3-1498504126008-157-36-943-1561-crop-1498504618220.jpg"
},
{
name: "hin nuong",
address: "kiot 16 ngo 298 tay son",
img: "https://thucthan.com/media/2018/05/thit-xien-nuong/cach-lam-thit-xien-nuong.jpg"
},
{
name: "com ga hoi an",
address: "huu danh vo thuc",
img: "https://thucthan.com/media/2018/07/com-ga/cach-nau-com-ga.jpg"
},
{
name: "spaghetty by vth",
address: "XXX XXX",
img: "https://www.inspiredtaste.net/wp-content/uploads/2019/03/Spaghetti-with-Meat-Sauce-Recipe-1-1200.jpg"
},
{
name: "banh crepe",
address: "93 ho dac di",
img: "https://ameovat.com/wp-content/uploads/2016/08/cach-lam-banh-crepe-600x453.jpg"
},
{
name: "banh trang cuon hin namnam",
address: "xxx pham ngoc thach",
img: "https://shipdoandemff.com/wp-content/uploads/2017/06/B%C3%A1nh-tr%C3%A1ng-th%E1%BB%8Bt-heo-shipdoandemff.jpg"
},
{
name: "bun oc suon",
address: "XXX XXX",
img: "https://media.foody.vn/res/g12/111781/prof/s/foody-mobile-bun-oc-jpg-918-636148001109710751.jpg"
},
{
name: "pizza",
address: "pizza hut",
img: "https://images.jdmagicbox.com/comp/delhi/y2/011pxx11.xx11.170113010527.r2y2/catalogue/pizza-hut-mori-gate-delhi-pizza-outlets-3jjvm65.jpg"
},
{
name: "pizza",
address: "domino",
img: "https://aeonmall-long-bien.com.vn/wp-content/uploads/2018/12/domino-pizza-750x468.jpg"
},
{
name: "bingsu",
address: "XXX XXX",
img: "https://toplist.vn/images/800px/kem-bingsu-tran-duy-hung-274767.jpg"
},
{
name: "bo ap chao",
address: "17 ngo 82 chua lang",
img: "https://image.baophapluat.vn/w800/Uploaded/2020/zsgkqzztgymu/2017_01_03/2_idmf.jpg"
},
{
name: "bun tron nam",
address: "150 dai tu",
img: "https://kenh14cdn.com/2019/6/13/32-15604349732101707241699.jpg"
},
{
name: "pho hin",
address: "pho di bo",
img: "https://fantasea.vn/wp-content/uploads/2018/08/Ph%E1%BB%9F-Th%C3%ACn-H%C3%A0-N%E1%BB%99i.jpg"
},
{
name: "bun rieu cua",
address: "84 ba trieu",
img: "https://thucthan.com/media/2019/07/bun-rieu-cua/bun-rieu-cua.png"
},
{
name: "gimbap by vth",
address: "XXX XXX",
img: "https://www.seriouseats.com/2020/01/20200122-gimbap-vicky-wasik-24-1500x1125.jpg"
}
]
const nextFoodButton = document.getElementsByClassName("food-choose__next-button")[0];
const foodTitle = document.getElementsByClassName("food-choose__title")[0];
const foodAddress = document.getElementsByClassName("food-choose__address")[0];
const foodImage = document.getElementsByClassName("food-choose__image")[0];
console.log(nextFoodButton);
nextFoodButton.addEventListener("click", () => {
nextFoodButton.style.display = "none";
let changeFood = setInterval(() => {
const randomIndex = Math.floor((Math.random() * foods.length))
const randomFood = foods[randomIndex];
console.log(randomIndex);
foodTitle.textContent = randomFood.name;
foodAddress.textContent = randomFood.address;
foodImage.src = randomFood.img;
},100)
setTimeout(() => {
nextFoodButton.style.display = "block";
clearInterval(changeFood)
},5000)
})
// } |
import {
NETINFO_SET_STATUS,
} from '../constants/ActionTypes'
const initialState = {
type: ''
};
export function netinfo(state = initialState, action = {}) {
const { type, payload } = action;
switch (type) {
case NETINFO_SET_STATUS: {
return {...state, type: payload};
}
}
return state
}
|
import React from 'react'
import styled from 'styled-components';
function Login() {
return (
<Container>
<CTA>
<CTALogoOne src="cta-logo-one.svg"/>
<SignUp>
Get All There
</SignUp>
<Description>
Wanted to add some description.
</Description>
<CTALogoTwo src="cta-logo-two.png"/>
</CTA>
</Container>
)
}
export default Login
const Container = styled.div`
position: relative;
height: calc(100vh - 70px);
display: flex;
align-items: top;
justify-content: center;
&:before{
background-position: top;
background-size: cover;
background-repeat: no-repeat;
background-image: url("login-background.jpg");
content: "";
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
opacity: 0.7;
z-index: -1;
}
`
const CTA = styled.div`
max-width: 650px;
padding: 80px 40px;
width: 90%;
display: flex;
flex-direction:column;
margin-top: 100px;
align-items: center;
`
const CTALogoOne = styled.img`
`
const SignUp = styled.a`
width: 100%;
background-color: #0063e5;
font-weight:bold;
padding: 17px 0;
color: #f9f9f9;
border-radius: 4px;
text-align: center;
font-size: 18px;
cursor:pointer;
transition: all 250ms;
letter-spacing: 1.5px;
margin-top: 8px;
margin-bottom: 12px;
&:hover {
background: #0483ee;
}
`
const Description = styled.pattern`
font-size: 11px;
letter-spacing: 1.5px;
text-align: center;
line-height: 1.5;
`
const CTALogoTwo = styled.img`
width: 90%;
` |
/* Nested Functions and Closures
*/
var say = function firstWord(string1) {
function secWord(string2){
return (string1+" "+string2);
};
return secWord;
};
var ans = say("Hello")("World");
console.log(ans);
var ans1 = say("Peanut")("Butter");
console.log(ans1);
var ans2 = say("Harry")("Potter");
console.log(ans2); |
import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Tweet } from 'components'
import * as usersLikesActions from 'redux/modules/usersLikes'
const { func, object, bool, number } = PropTypes
const TweetContainer = React.createClass({
propTypes: {
numberOfLikes: number,
isLiked: bool.isRequired,
handleDeleteLike: func.isRequired,
addAndHandleLike: func.isRequired,
hideLikeCount: bool.isRequired,
tweet: object.isRequired,
hideReplyBtn: bool.isRequired
},
contextTypes: {
router: PropTypes.object.isRequired
},
getDefaultProps: function () {
return {
hideLikeCount: false,
hideReplyBtn: false
}
},
goToProfile (e) {
e.stopPropagation()
this.context.router.push('/' + this.props.tweet.get('uid'))
},
handleClick (e) {
e.stopPropagation()
this.context.router.push('/tweetDetail/' + this.props.tweet.get('tweetId'))
},
render () {
return (
<Tweet
goToProfile={this.goToProfile}
onClick={this.props.hideReplyBtn === true ? null : this.handleClick}
tweet={this.props.tweet}
{...this.props} />
)
}
})
function mapStateToProps ({tweets, likeCount, usersLikes}, props) {
return {
tweet: tweets.get(props.tweetId),
hideLikeCount: props.hideLikeCount,
hideReplyBtn: props.hideReplyBtn,
isLiked: usersLikes[props.tweetId] === true,
numberOfLikes: likeCount[props.tweetId]
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators(usersLikesActions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(TweetContainer)
|
const express = require("express");
const UserModel = require('../models/users.js');
const pagination = require('../util/pagination.js');
const router = express.Router();
//权限验证
router.use((req,res,next)=>{
if(req.userInfo.isAdmin){
next()
}else{
res.send('<h1>请用管理员账号登录</h1>');
}
})
//显示后台首页
router.get('/',(req,res)=>{
res.render('admin/index',{
userInfo:req.userInfo
});
})
//显示用户列表
router.get('/users',(req,res)=>{
const options = {
page:req.query.page,
model:UserModel,
query:{},
projection:'-password -__v',
sort:{_id:1}
};
pagination(options)
.then(data=>{
res.render('admin/user_list',{
userInfo:req.userInfo,
users:data.docs,
page:data.page,
list:data.list,
pages:data.pages,
url:'/admin/users'
})
})
})
module.exports = router; |
import { connect } from "react-redux";
import withStyles from "@material-ui/core/styles/withStyles";
import componentsStyle from "../assets/jss/material-kit-react/views/components";
import SingleProductComponent from "../views/ProductPages/SingleProduct";
import { getShopLocation } from "../routes/routingSystem";
const mapStateToProps = state => ({
products: state.products,
customerReview: state.customerReview,
front: state.front,
shopLocation: getShopLocation(),
});
const SingleProduct = connect(
mapStateToProps,
)(SingleProductComponent);
export default withStyles(componentsStyle)(SingleProduct);
|
import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import {
useParams
} from "react-router-dom";
import Navigation from '../Navigation';
import { Row, Col } from 'antd';
import Display from './Display';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
button: {
margin: theme.spacing(1),
},
emptyTable: {
paddingTop: theme.spacing(1),
paddingBottom: theme.spacing(1),
height: '100%',
backgroundColor: '#e6eded',
transitionDuration: '0.5s',
transition: '0.5s',
'&:hover': {
backgroundColor: "rgb(247, 247, 247,0.8)",
transition: '0.5s',
},
padding:'2%'
}
}));
const DetailedAcc = () => {
const classes = useStyles();
let { acc_no } = useParams();
const apiUrl = useSelector(state => state.ApiReducer);
const [accountInfos, setaccountInfos] = useState({});
// const [transferFrom, setTransferFrom] = useState([]);
// const [transferTo, setTransferTo] = useState([]);
const [transfers, setTransfers] = useState([]);
useEffect(() => {
async function GetFromTransfer(apiUrl, acc_no) {
const resultFrom = await axios(
`${apiUrl}/transfer/getFrom/${acc_no}`,
);
const resultTo = await axios(
`${apiUrl}/transfer/getTo/${acc_no}`,
);
if (resultFrom.data.length > 0 && resultTo.data.length > 0) {
setTransfers([...resultFrom.data, ...resultTo.data]);
}
else if (resultFrom.data.length === 0 && resultTo.data.length > 0) {
setTransfers([...resultTo.data]);
}
else if (resultFrom.data.length > 0 && resultTo.data.length === 0) {
setTransfers([...resultFrom.data]);
}
}
async function GetAccountInfos(apiUrl, acc_no) {
const result = await axios(
`${apiUrl}/accounts/getAcc/${acc_no}`,
);
setaccountInfos(result.data[0]);
}
//axios.get(`${apiUrl}/accounts?account_no=${acc_no}`).then((data) => { setaccountInfos(data.data[0]) });
//axios.get(`${apiUrl}/transfer?from_no=${acc_no}`).then((data) => { settransferInfos(data.data) });
GetFromTransfer(apiUrl, acc_no);
GetAccountInfos(apiUrl, acc_no);
return () => { }
}, [])
// hesap adı
// vade türü
// hesap yeri
// hesap no
// iban
// bakiye
// hesap açılış tarihi
// son işlem
// hesap hareketleri
// hesabı kapat
return (
<div>
<Row>
<Col span={7}>
<Navigation />
</Col>
<Col span={17}>
<Col span={10} style={{ margin: "1%" }} >
<Paper elevation={3} component="div" className={classes.emptyTable}>
<h2>{accountInfos.account_name}</h2>
<span>{accountInfos.account_type}</span>
<p>{accountInfos.account_no}</p>
<p>{accountInfos.iban}</p>
<p>{accountInfos.whereIs}</p>
<h4>{accountInfos.balance + " " + accountInfos.currency }</h4>
</Paper>
</Col>
{
transfers &&
<Display transfers={transfers} accountInfos={accountInfos} />
}
{/* {
transfers.map((data) => data.from_no === accountInfos.account_no ?
<div key={data.id}> <span>{data.from_no}</span> <span>{data.to_no}</span> - <span>{data.total}</span></div>
:
<div key={data.id}> <span>{data.from_no}</span> <span>{data.to_no}</span> + <span>{data.total}</span></div>)
} */}
</Col>
</Row>
</div>
)
}
export default DetailedAcc
|
var ServantCardClass = function ($interface, serialNumber, servantData) {
let _self = this;
let $skillTable;
let $ascensionTable;
let materialStorage = {
"ascension" : {
"sw" : false,
"totalMaterial" : {}
},
"skill" :[
{
"sw" : false,
"totalMaterial" : {}
},
{
"sw" : false,
"totalMaterial" : {}
},
{
"sw" : false,
"totalMaterial" : {}
}
]
};
_self.init = function() {
// console.log(serialNumber);
$interface.insertAfter('.main-title');
_self.initInterface();
_self.setEvent();
$interface.show();
}
_self.initInterface = function() {
$interface.find('.servant-name').html(`No.${servantData.id}<br/>${servantData.svtCnName}`);
$interface.find('.servant-img').attr("src", servantData.imgSrc);
$interface.find('.mtype-choose img').addClass("icon-unselect");
$interface.find('.skill-icon').each( function (index, icon) {
$(icon).attr('skillIndex', index );
});
$skillTable = $interface.find('.skill-material-table');
$skillTable.hide();
$skillTable.find('tbody').empty();
$ascensionTable = $interface.find('.ascension-material-table');
$ascensionTable.hide();
$ascensionTable.find('tbody').empty();
}
_self.setEvent = function() {
$interface.find('.servant-delete-button').click(function(){
window.mainComponent.removeServant(_self.getUuid());
})
$interface.find('.hide-material-check').change(function(){
if($(this).prop('checked')) {
$interface.find('.hide-area').hide();
}
else {
$interface.find('.hide-area').show();
}
})
$interface.find('.ascension-icon').click( function (){
if(materialStorage.ascension.sw) {
$interface.find('.ascension-icon').addClass("icon-unselect");
materialStorage.ascension.sw = false;
}
else {
$interface.find('.ascension-icon').removeClass("icon-unselect");
materialStorage.ascension.sw = true;
}
_self.displayAscensionTable();
window.mainComponent.recalculateTotalMaterial();
});
$interface.find('.skill-icon').click( function (){
let $skillIcon = $(this);
let skillIndex = $skillIcon.attr('skillIndex');
if(materialStorage.skill[skillIndex].sw) {
$skillIcon.addClass("icon-unselect");
materialStorage.skill[skillIndex].sw = false;
}
else {
$skillIcon.removeClass("icon-unselect");
materialStorage.skill[skillIndex].sw = true;
}
_self.displaySkillTable(skillIndex);
window.mainComponent.recalculateTotalMaterial();
});
}
_self.displayAscensionTable = function() {
$ascensionTable.find('tbody').empty();
materialStorage.ascension.totalMaterial = {};
$ascensionTable.hide();
if(materialStorage.ascension.sw) {
let startAscension = $interface.find(".ascension-select.start-lv").val();
let endAscension = $interface.find(".ascension-select.end-lv").val();
let maxRow = 1;
// display data and storage data
for(let trNo = 0; trNo < maxRow; trNo++) {
$tr = $(document.createElement("tr"));
$ascensionTable.find('tbody').append( $tr );
$.each(servantData.ascension, function(index, ascension){
let $td = $(document.createElement("td"));
let lv = index + 1;
$tr.append($td);
if(startAscension <= lv && endAscension >= lv && ascension.length > trNo) {
let singleAscension = ascension[trNo];
let material = window.dataService.getMaterialData(singleAscension.name);
$td.html(`<img class='material-icon' src='${material.imgSrc}'><div>${singleAscension.cnt}</div>`);
// add to totalMaterial
if(materialStorage.ascension.totalMaterial[singleAscension.name] == null ) {
materialStorage.ascension.totalMaterial[singleAscension.name] = singleAscension.cnt;
}
else {
materialStorage.ascension.totalMaterial[singleAscension.name] += singleAscension.cnt;
}
}
maxRow = (ascension.length > maxRow) ? ascension.length : maxRow;
});
}
$ascensionTable.show();
}
}
_self.displaySkillTable = function(toggleSkillIndex) {
let displayCheck = false;
$.each(materialStorage.skill, function(index, skill) {
if(skill.sw) displayCheck = true;
})
$skillTable[(displayCheck) ? "show" : "hide"]();
}
_self.getMaterialStorage = function() {
return materialStorage;
}
_self.getInterface = function() {
return $interface;
}
_self.getUuid = function() {
return serialNumber;
}
_self.init();
} |
const Joi = require('@hapi/joi');
//validation
const addContactValidation = data => {
const schema = {
name : Joi.string()
.required(),
mobileNumber : Joi.number().min(11).regex(/^(?:\+88|01)?(?:\d{11}|\d{13})$/),
};
return Joi.validate(data,schema);
};
module.exports.addContactValidation = addContactValidation; |
import { useDispatch, useSelector } from "react-redux";
import * as d3 from "d3";
import { dbscan, scale } from "../services";
import slice from "../slice.js";
import { Responsive } from "./Responsive.js";
import { HorizontalField } from "./HorizontalField.js";
function ProjectionChart({ width, height }) {
const dispatch = useDispatch();
const topics = useSelector(({ topics }) => topics);
const selectionRadius = useSelector(({ selectionRadius }) => selectionRadius);
const selectedTopics = useSelector(
({ selectedTopics }) => new Set(selectedTopics)
);
const margin = { left: 10, right: 10, top: 10, bottom: 10 };
const contentWidth = width - margin.left - margin.right;
const contentHeight = height - margin.top - margin.bottom;
const { x, y, s } = scale(topics, contentWidth, contentHeight);
function xScale(cx) {
return (cx - x) * s;
}
function yScale(cy) {
return (cy - y) * s;
}
const line = d3
.line()
.x((item) => xScale(item.x))
.y((item) => yScale(item.y));
const timeFormat = d3.timeFormat("%Y-%m-%d %H:%M");
return (
<svg viewBox={`0 0 ${width} ${height}`}>
<g transform={`translate(${margin.left}, ${margin.top})`}>
<g transform={`translate(${contentWidth / 2},${contentHeight / 2})`}>
<g>
<path
fill="none"
stroke="lightgray"
strokeWidth="3"
opacity="0.5"
d={line(topics)}
/>
</g>
<g>
{topics.map((item, i) => {
return (
<g
key={i}
className="is-clickable"
opacity={
selectedTopics.size === 0 || selectedTopics.has(item.id)
? 1
: 0.1
}
style={{
transitionProperty: "opacity",
transitionDuration: "1s",
transitionTimingFunction: "ease",
}}
transform={`translate(${xScale(item.x)}, ${yScale(item.y)})`}
onClick={async () => {
if (selectedTopics.has(item.id)) {
dispatch(slice.actions.selectTopics([]));
return;
}
const { clusters } = await dbscan(
topics.map(({ x, y }) => [x, y]),
selectionRadius,
1
);
for (const cluster of clusters) {
for (const id of cluster) {
if (id === item.id) {
dispatch(slice.actions.selectTopics(cluster));
return;
}
}
}
}}
>
<circle r={item.r0} opacity="0.7" fill={item.color}>
<title>
{timeFormat(new Date(item.time))}-
{timeFormat(new Date(item.stopTime))}
</title>
</circle>
</g>
);
})}
</g>
</g>
</g>
</svg>
);
}
export function ProjectionView() {
const dispatch = useDispatch();
const selectionRadius = useSelector(({ selectionRadius }) => selectionRadius);
return (
<div style={{ position: "relative", width: "100%", height: "100%" }}>
<div className="p-3">
<HorizontalField label="Selection Radius">
<div className="field has-addons">
<div className="control">
<button
disabled={selectionRadius <= 0}
className="button"
onClick={() => {
dispatch(
slice.actions.updateSelectionRadius(selectionRadius - 1)
);
}}
>
<span className="icon">
<i className="fas fa-minus" />
</span>
</button>
</div>
<div className="control is-expanded">
<input
className="input"
type="number"
min="0"
value={selectionRadius}
onChange={(event) => {
dispatch(
slice.actions.updateSelectionRadius(+event.target.value)
);
}}
/>
</div>
<div className="control">
<button
className="button"
onClick={() => {
dispatch(
slice.actions.updateSelectionRadius(selectionRadius + 1)
);
}}
>
<span className="icon">
<i className="fas fa-plus" />
</span>
</button>
</div>
</div>
</HorizontalField>
</div>
<div
style={{
position: "absolute",
top: "64px",
right: 0,
bottom: 0,
left: 0,
}}
>
<Responsive
render={(width, height) => (
<ProjectionChart width={width} height={height} />
)}
/>
</div>
</div>
);
}
|
'use strict'
const crypto = require('crypto');
const http = require('http');
const https = require('https');
const querystring = require('querystring');
const Buffer = require('buffer').Buffer;
const xml2js = require('xml2js');
const moment = require('moment');
const request = require('superagent');
const config = require('../../config');
module.exports = class WxPayDataBase {
constructor(wxPayData) {
this.wxPayData = wxPayData;
}
setSign() {
let sign = this.makeSign();
this.wxPayData.sign = sign;
return sign;
}
toXml() {
let builder = new xml2js.Builder({
cdata: true,
rootName: 'xml'
});
let xml = builder.buildObject(this.wxPayData);
return xml;
}
makeSign(toBeSigned) {
toBeSigned = toBeSigned || this.wxPayData;
let str = '';
for (var key of Object.keys(toBeSigned).sort())
str += key + '=' + toBeSigned[key] + '&';
str += 'key=' + config.weixin.mch_key;
let buff = new Buffer(str);
let binary = buff.toString('binary');
const hash = crypto.createHash('md5').update(binary).digest('hex');
return hash;
}
*getWxPayParams() {
let wxPayDataBase = this;
wxPayDataBase.setSign();
let postBody = wxPayDataBase.toXml();
let res = yield request
.post(config.weixin.prepayUrl + config.weixin.prepayPath)
.set('Content-Type', 'application/xml')
.send(postBody);
let resJson = yield xml2jsPromise(res.text);
let jsApiData = resJson.xml;
let timeStampStr = moment().format('x');
let jsApiParams = {
appId: '' + jsApiData.appid,
nonceStr: '' + jsApiData.nonce_str,
package: 'prepay_id=' + jsApiData.prepay_id,
signType: 'MD5',
timeStamp: timeStampStr
};
if(typeof resJson.xml === 'undefined' || resJson.xml.return_code === 'FAIL')
throw new Error(resJson.xml.return_msg);
jsApiParams.paySign = wxPayDataBase.makeSign(jsApiParams);
return jsApiParams;
}
}
function xml2jsPromise(xmlText) {
return new Promise((resolve, reject) => {
xml2js.parseString(xmlText, (err, result) => {
if(err) return reject(err);
else return resolve(result);
});
});
} |
lyb.parse();
lyb.ajax(ctx + 'SysHospital/detail?id=' + params.id, {
success: function (result) {
if (result.success) {
var data = result.data || {};
document.getElementById('hospital_img').innerHTML = '<img alt="" src="' + data.pic + '" style="width: 100%;height: 100%;vertical-align: top;"/>';
document.getElementById('inst').innerHTML = data.description || '';
document.getElementById('name').innerHTML = data.name || '';
var address = document.getElementById('address');
address.innerHTML = data.address || '';
address.dataset.name = data.name;
address.dataset.address = data.address;
address.dataset.latitude = data.lat;
address.dataset.longitude = data.lng;
address.addEventListener('click', function (ev) {
daohang(this.dataset);
});
document.getElementById('phone').innerHTML = '<a class="red-color" href="tel:' + data.phone + '">' + data.phone + '</a>';
}
}
});
lyb.wxSign(['checkJsApi', 'hideMenuItems', 'showMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'openLocation'], function () {
wx.hideMenuItems({
menuList: ["menuItem:copyUrl", "menuItem:share:weiboApp", "menuItem:favorite", "menuItem:share:facebook", "menuItem:share:QZone", "menuItem:share:email", "menuItem:share:brand", "menuItem:readMode", "menuItem:originPage", "menuItem:editTag", "menuItem:delete"] // 要显示的菜单项,所有menu项见附录3
});
wx.showMenuItems({
menuList: ["menuItem:share:timeline", "menuItem:openWithSafari", "menuItem:openWithQQBrowser", "menuItem:share:appMessage", "menuItem:share:qq"] // 要显示的菜单项,所有menu项见附录3
});
wx.onMenuShareTimeline({
title: window.shareCommonTitle, // 分享标题
link: ctx + 'html/index.html', // 分享链接
imgUrl: '//image-1252304461.file.myqcloud.com/image/' + (window.lybMp ? 'lyb-logo' : 'big-logo') + '.jpg', // 分享图标
success: function () {
lyb.alert('分享成功!');
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
wx.onMenuShareAppMessage({
title: window.shareCommonTitle, // 分享标题
desc: window.shareCommonDesc, // 分享描述
link: ctx + 'html/index.html', // 分享链接
imgUrl: '//image-1252304461.file.myqcloud.com/image/' + (window.lybMp ? 'lyb-logo' : 'big-logo') + '.jpg',
success: function () {
lyb.alert('分享成功!');
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
});
function daohang(data) {
wx.openLocation({
latitude: parseFloat(data.latitude), // 纬度,浮点数,范围为90 ~ -90
longitude: parseFloat(data.longitude), // 经度,浮点数,范围为180 ~ -180。
name: data.name, // 位置名
address: data.address, // 地址详情说明
// scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
infoUrl: 'https://mp.zanchina.com' // 在查看位置界面底部显示的超链接,可点击跳转
});
} |
Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3, "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5.
for ( var i = 1; i <= 100; i++ )
{
if ( i%3 === 0 && i%5 === 0 )
{
console.log( i + " FizzBuzz" );
}
else if ( i%3 === 0 )
{
console.log(i+ " Fizz" );
}
else if ( i%5 === 0 )
{
console.log(i+ " Buzz" );
}
else
{
console.log(i);
}
}
|
function render(){
const productStore = localStrorageUtil.getProducts();
HeaderPage.render(productStore.length);
productsPage.render();
}
let CATALOG = [];
fetch('server/catalog.json')
.then(res => res.json())
.then(body => {
CATALOG = body;
render();
})
.catch(error => {
console.log(error);
});
|
import React, { useContext } from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/Layout';
import Helmet from 'react-helmet';
import classes from './contact.module.scss';
import ContactCard from '../components/ContactCard/ContactCard';
import {
GlobalStateContext,
SiteFocus,
} from '../context/GlobalContextProvider';
import PageTransition from 'gatsby-plugin-page-transitions';
const ContactPageTemplate = ({
title,
codeContactMethods,
musicContactMethods,
}) => {
const state = useContext(GlobalStateContext);
const titleClassName =
state.siteFocus === SiteFocus.Code ? classes.blueText : classes.greenText;
return (
<section className={classes.contact}>
<Helmet titleTemplate='%s | Henry Fellerhoff'>
<title>{title}</title>
</Helmet>
<div className={classes.container}>
<h1 className={`${classes.pageTitle} ${titleClassName}`}>{title}</h1>
{codeContactMethods && musicContactMethods ? (
state.siteFocus === SiteFocus.Code ? (
codeContactMethods.map(contactMethod => {
return <ContactCard details={contactMethod} titleIsBlue />;
})
) : (
musicContactMethods.map(contactMethod => {
return <ContactCard details={contactMethod} />;
})
)
) : (
<></>
)}
</div>
</section>
);
};
const ContactPage = ({ data }) => {
const { frontmatter } = data.markdownRemark;
return (
<Layout>
<PageTransition>
<ContactPageTemplate
title={frontmatter.title}
codeContactMethods={frontmatter.codeContactMethods}
musicContactMethods={frontmatter.musicContactMethods}
/>
</PageTransition>
</Layout>
);
};
export default ContactPage;
export const contactPageQuery = graphql`
query ContactPage {
markdownRemark(frontmatter: { templateKey: { eq: "contact-page" } }) {
frontmatter {
title
codeContactMethods {
text
method
href
iconName
}
musicContactMethods {
text
method
href
iconName
}
}
}
}
`;
|
angular.module('DealersApp')
.controller('CategoriesListController', ['$scope', function ($scope) {
/*
* The controller that manages the Categories view.
*/
$scope.elements = $scope.categories;
}]); |
describe('测试demo', function() {
it('应该返回字符串', function() {
chai.expect(nodebase()).to.be.equal('this is nodebase test');
});
}); |
// bucle FOR
var numero = 100
for(var i = 1; i <= numero; i++){
console.log(" vamos por le numero: "+i)
//debugger
} |
export const addToList = (data) => {
return {
type: 'ADD_POST',
payload: data
}
}
export const updatePost = (id, data) => {
return {
type: 'UPDATE',
id,
payload: data
}
}
export const deletePost = (id) => {
return {
type: 'DELETE_POST',
id
}
}
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const specialization = sequelize.define('specialization', {
code: DataTypes.STRING,
name: DataTypes.STRING,
total_credit: DataTypes.INTEGER
}, {});
specialization.associate = function(models) {
// associations can be defined here
models.specialization.hasMany(models.student, {
foreignKey: "specialization_id"
});
};
return specialization;
}; |
module.exports = target => async context => {
const { app, data, result } = context
await Promise.all(
target.map(async ({
targetService, sourceIdKey, targetKey, isArray = true
}) =>
app.service(targetService).patch(
data[sourceIdKey],
isArray
? { $push: { [targetKey]: result._id } }
: { [targetKey]: result._id }
)
)
)
return context
}
|
import 'cross-fetch/polyfill';
import ApolloClient from 'apollo-boost'
const client = new ApolloClient({uri: 'https://graph.qa.f1.flexdrive.com/'})
export default client
|
// @flow strict
import * as React from 'react';
import { View } from 'react-native';
import type { TranslationType } from '@kiwicom/mobile-localization';
import { AdaptableLayout, StyleSheet, Text } from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
type Props = {|
+title: TranslationType,
+content: React.Node,
|};
export default function FlightListLayout(props: Props) {
return (
<React.Fragment>
<Text style={styles.subtitle}>{props.title}</Text>
<AdaptableLayout
renderOnNarrow={props.content}
renderOnWide={<View style={styles.tabletWrapper}>{props.content}</View>}
/>
</React.Fragment>
);
}
const styles = StyleSheet.create({
subtitle: {
marginTop: 10,
marginBottom: 12,
color: defaultTokens.colorTextSecondary,
},
tabletWrapper: {
flexDirection: 'row',
flexWrap: 'wrap',
},
});
|
;
(function() {
window.teads = {
};
window.onerror = function(msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "Teads.js script error";
var errorJson = {
message: msg,
url: url,
line: lineNo,
column: columnNo,
object: JSON.stringify(error)
};
window.teads.error(JSON.stringify(errorJson));
return false;
};
window.teads.error = function error(errorJson) {
window.webkit.messageHandlers.error.postMessage(errorJson);
};
window.teads.engineLoaded = function engineLoaded() {
window.webkit.messageHandlers.engineLoaded.postMessage("");
};
window.teads.engineInitiated = function engineInitiated() {
window.webkit.messageHandlers.engineInitiated.postMessage("");
};
window.teads.preload = function preload() {
window.webkit.messageHandlers.preload.postMessage("");
};
window.teads.getUserId = function getUserId(userId) {
var jsonVariables = {
"userId": userId
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.getUserId.postMessage(jsonString)
}
window.teads.httpCall = function httpCall(callId, url, method, headersString, formString, timeout) {
var jsonVariables = {
"callId": callId,
"url": url,
"method": method,
"headersString": headersString,
"formString": formString,
"timeOut": timeout
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.httpCall.postMessage(jsonString)
}
window.teads.slotRequest = function slotRequest() {
window.webkit.messageHandlers.slotRequest.postMessage("");
};
window.teads.noAd = function noAd(code, message) {
var jsonVariables = {
"code": code,
"message": message
}
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.noAd.postMessage(jsonString)
}
window.teads.ad = function ad(mimeType, ratio, response, adParameters) {
var jsonVariables = {
"mimeType": mimeType,
"ratio": ratio,
"response": response,
"adParameters": adParameters
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.ad.postMessage(jsonString)
}
window.teads.configureViews = function configureViews(json) {
var jsonVariables = {
"json": json
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.configureViews.postMessage(jsonString)
}
window.teads.updateView = function updateView(json) {
var jsonVariables = {
"json": json
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.updateView.postMessage(jsonString)
}
window.teads.start = function start() {
window.webkit.messageHandlers.start.postMessage("");
};
window.teads.resume = function resume() {
window.webkit.messageHandlers.resume.postMessage("");
};
window.teads.pause = function pause() {
window.webkit.messageHandlers.pause.postMessage("");
};
window.teads.openSlot = function openSlot(duration) {
var jsonVariables = {
"duration": duration
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.openSlot.postMessage(jsonString)
}
window.teads.closeSlot = function closeSlot(duration) {
var jsonVariables = {
"duration": duration
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.closeSlot.postMessage(jsonString)
}
window.teads.setVolume = function setVolume(volume, transitionDuration, isForcedByUser) {
var jsonVariables = {
"volume": volume,
"transitionDuration": transitionDuration,
"isForcedByUser": isForcedByUser
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.setVolume.postMessage(jsonString);
};
window.teads.showEndScreen = function showEndScreen() {
window.webkit.messageHandlers.showEndScreen.postMessage("");
}
window.teads.hideEndScreen = function hideEndScreen() {
window.webkit.messageHandlers.hideEndScreen.postMessage("");
}
window.teads.openFullscreen = function openFullscreen(json) {
var jsonVariables = {
"json": json
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.openFullscreen.postMessage(jsonString);
}
window.teads.closeFullscreen = function closeFullscreen() {
window.webkit.messageHandlers.closeFullscreen.postMessage("");
}
window.teads.reset = function reset() {
window.webkit.messageHandlers.reset.postMessage("");
}
window.teads.rewind = function rewind() {
window.webkit.messageHandlers.rewind.postMessage("");
}
window.teads.openBrowser = function openBrowser(url) {
var jsonVariables = {
"url": url
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.openBrowser.postMessage(jsonString);
}
window.teads.openDialog = function openDialog(id, title, description, cancelButton, cancelButtonId, okButton, okButtonId) {
var jsonVariables = {
"id": id,
"title": title,
"description": description,
"cancelButton": cancelButton,
"cancelButtonId": cancelButtonId,
"okButton": okButton,
"okButtonId": okButtonId
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.openDialog.postMessage(jsonString);
}
window.teads.reward = function reward(value, type) {
var jsonVariables = {
"value": value,
"type": type
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.reward.postMessage(jsonString);
}
window.teads.closeDialog = function closeDialog(identifier) {
var jsonVariables = {
"identifier": identifier
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.closeDialog.postMessage(jsonString);
}
window.teads.debug = function debug(message) {
var jsonVariables = {
"message": message
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.debug.postMessage(jsonString);
}
})();
;
(function() {
window.teadsSdkPlayerInterface = {
};
window.teadsSdkPlayerInterface.handleVpaidEvent = function handleVpaidEvent(json) {
var jsonVariables = {
"json": json
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.handleVpaidEvent.postMessage(jsonString);
}
window.teadsSdkPlayerInterface.vpaidLoaded = function vpaidLoaded() {
window.webkit.messageHandlers.vpaidLoaded.postMessage("");
}
window.teadsSdkPlayerInterface.loadError = function loadError(error) {
var jsonVariables = {
"message": error
};
var jsonString = JSON.stringify(jsonVariables);
window.webkit.messageHandlers.loadError.postMessage(jsonString);
}
})();
|
describe('buttons - button().trigger()', function() {
dt.libs({
js: ['jquery', 'datatables', 'buttons'],
css: ['datatables', 'buttons']
});
describe('Check the defaults', function() {
var table;
dt.html('basic');
it('Ensure its a function', function() {
table = $('#example').DataTable({
dom: 'Bfrtip',
buttons: [{ text: 'first' }]
});
expect(typeof table.button().trigger).toBe('function');
});
it('Returns an API instance', function() {
expect(table.button(0).trigger() instanceof $.fn.dataTable.Api).toBe(true);
});
});
describe('Functional tests', function() {
var table;
var count = 0;
dt.html('basic');
it('Does nothing if no action on button', function() {
table = $('#example').DataTable({
dom: 'Bfrtip',
buttons: [
{ text: 'first' },
{
text: 'second',
action: function() {
count++;
}
}
]
});
table.button(0).trigger();
expect(count).toBe(0);
});
it('Does stuff if action on button', function() {
table.button(1).trigger();
expect(count).toBe(1);
});
dt.html('basic');
it('Opens a collection', function() {
table = $('#example').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'collection',
text: 'Table control',
buttons: [{ text: 'first' }, { text: 'second' }, { text: 'third' }]
}
]
});
expect($('.dt-button').length).toBe(1);
table.button(0).trigger();
expect($('.dt-button').length).toBe(4);
});
});
});
|
$(function(){
var navLinks = $('a', $('#navbar'));
navLinks.each(function(){
if ($(this).prop('href') == window.location.href) {
$(this).addClass('active-page');
$(this).parents('li').addClass('active-page');
$(this).css('color','#fff');
$(this).css('background-color', 'transparent');
$(this).css('cursor', 'default');
}
});
});
|
'use strict';
module.exports = {
STORAGE_PREFIX: 'ev-str'
};
|
module.exports = (function() {
return {
tweet: function() {
var env = require('jsdom').env ;
//read in file
var data;
env({ file: "../data/total-fry.txt",
done: function (errors, window) {
if (errors)
{console.log("Error: ",errors);}
var $ = require('jquery')(window);
//get data out of text file and put into array
data = $("body").text();
}});
setInterval(function () {
if(data!=undefined){
//get rid of newlines, double spaces and quote marks
data = data.replace(/\n/g,' ');
data = data.replace(/ /g,' ');
data = data.replace(/\"/g,'');
data = data.replace(/\)/g,'');
data = data.replace(/\(/g,'');
// split into individual words
var words = data.split(" ");
//console.log(words);
/*
//begin with two random consecutive words, the first of which is capitalised
var capital = 0;
var give_up = 0;
while (!capital)
{
var index = Math.floor(Math.random()*words.length);
// check that the first letter is capitalised
if (words[index][0] == words[index][0].toUpperCase() && words[index].indexOf("\"") == -1)
{
capital = 1;
}
give_up +=1;
if (give_up > 200)
{
break;
}
}
*/
//begin with two random consecutive words, the second of which ends in punctuation
var end_of_sentence = 0;
var give_up = 0;
while (!end_of_sentence)
{
var index = Math.floor(Math.random()*words.length);
// check for punctuation
if (words[index][words[index].length - 1] == '.')
{
end_of_sentence = 1;
}
give_up +=1;
if (give_up > 200)
{
// just go with whatever word you ended up with
break;
}
}
answer = [words[index].slice(0,words[index].length-1), words[index-1]];
var checkindices = [index, index+1];
var lenout = 2;
give_up = 0;
// measure length of answer
var length_of_answer = 0;
for (var l = 0; l < answer.length; l++)
{
length_of_answer += answer[l].length;
}
// add spaces to length count
length_of_answer += answer.length-1;
while (length_of_answer < 100)
{
// from the first two words, find all instances of the second one within the text>
var indices = new Array();
for (var i = 2; i < words.length; i++)
{
// check that the first word matches
if (words[i] == answer[answer.length-2])
{
//console.log(words[i],words[i-1],answer[answer.length-2],answer[answer.length-1])
// check that the second word matches
if (words[i-1] == answer[answer.length-1])
{
indices.push(i-2);
}
}
}
// pick next word at random from pool of words
var newindex = Math.floor(Math.random()*indices.length);
var next_word = words[indices[newindex]];
//console.log(next_word,answer)
answer.push(next_word);
// also save the index
checkindices.push(indices[newindex]);
lenout +=1;
if (next_word)
{
length_of_answer += next_word.length + 1;
}
give_up +=1;
if (give_up >200)
{
break;
}
}
/* var lastword = answer.slice(-1);
var lastcharacter = lastword[0].slice(-1);
var appendedcharacter = '';
// End with punctuation
if (lastcharacter != '.' || lastcharacter != '?' || lastcharacter != '!')
{
appendedcharacter = '.';
}
*/
answer = answer.reverse();
answer = (answer.join(" ")+'.');
return answer
data = undefined
}},100);
}
};
})();
|
import { renderHook } from '@testing-library/react-hooks';
import * as server from '../back-end/server.js';
import { useData } from './useData';
import { when } from 'jest-when'
import { responseStatus } from '../constants';
const getControlledPromise = () => {
let deferred;
const promise = new Promise((resolve, reject) => {
deferred = { resolve, reject };
});
return { deferred, promise }
}
describe('useData', () => {
it('handles loading state correctly', async () => {
const { deferred, promise } = getControlledPromise();
server.mockFetch = jest.fn(() => promise);
const { result, waitForNextUpdate } = renderHook(useData);
expect(result.current.isLoading).toBe(true);
deferred.resolve();
await waitForNextUpdate();
expect(result.current.isLoading).toBe(false);
})
}
);
describe('when got data successfully', () => {
it('handles successfull state correctly', async () => {
server.mockFetch = jest.fn()
when(server.mockFetch).calledWith('/variant').mockResolvedValue({ body: { id: "1", parent_frame_id: "2", key_name: '$BodyCopyText', isHidden: false } });
when(server.mockFetch).calledWith('/columns').mockResolvedValue({
body: [{
id: '1',
parent_frame_id: '2',
size_id: 1,
key_name: '$CtaSize',
is_hidden: false,
parent_creative_variant_id: 12
}]
});
const { result, waitForNextUpdate } = renderHook(useData);
await waitForNextUpdate();
expect(result.current.variant).toMatchObject({ id: "1", parentFrameId: "2", keyName: '$BodyCopyText', isHidden: false });
expect(result.current.columns).toMatchObject([{
id: '1',
parentFrameId: '2',
sizeId: 1,
keyName: '$CtaSize',
isHidden: false,
parentCreativeVariantId: 12
}]);
})
});
describe('when get error during the request', () => {
it('handles error state correctly ', async () => {
const { deferred, promise } = getControlledPromise();
server.mockFetch = jest.fn(() => promise);
const { result, waitForNextUpdate } = renderHook(useData);
deferred.reject('Fetch error');
await waitForNextUpdate();
expect(result.current.error).toStrictEqual('Fetch error');
})
it('handles showPopup state correctly ', async () => {
const { deferred, promise } = getControlledPromise();
server.mockFetch = jest.fn(() => promise);
const { result, waitForNextUpdate } = renderHook(useData);
deferred.reject(new Error(responseStatus.UNAUTHORIZED));
await waitForNextUpdate();
expect(result.current.showPopup).toBe(true);
})
});
|
var gulp = require('gulp'),
merge2 = require('merge2'),
bowerFiles = require('main-bower-files'),
del = require('del'),
browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var srcs = require('./gulp/sources.json');
//var allUrls = require('./gulp/urls.json');
var isProd = false;
var cssBrowsersSupported = ['last 2 versions', 'iOS 8'];
gulp.task('build:prod', function() {
isProd = true;
return gulp.start('build');
});
// Static Server + watching scss/html files
gulp.task('build', ['cleanWWW', 'vendor', 'js', 'sass', 'html', 'assets'], function() {
$.util.log($.util.colors.green('\n\n\nBUILD SUCCESSFUL'));
});
gulp.task('default', ['cleanWWW', 'pluginStubs', 'vendor', 'js', 'sass', 'html', 'assets'], function() {
$.util.log($.util.colors.green('\n\n\nBUILD SUCCESSFUL'));
browserSync.init({
server: "www"
});
gulp.watch(srcs.js, ['js']);
gulp.watch([
'develop/source/elements/**/*.scss',
'develop/source/sass/**/*.scss'
], ['sass']);
gulp.watch(srcs.html, ['html']);
});
//=====================================================
gulp.task('cleanWWW', function() {
del.sync(['www/**', '!www']);
});
function getUrlSrcs() {
// var sourceUrls = isProd ? allUrls.prod : allUrls.dev;
// return gulp.src(srcs.urlStorage)
// .pipe($.replace(/##serverHost##/, sourceUrls.host))
// .pipe($.replace(/##findadocHost##/, sourceUrls.findadoc));
}
gulp.task('js', function() {
return gulp.src(srcs.urlStorage)
//getUrlSrcs()
.pipe($.addSrc(srcs.js))
.pipe($.sourcemaps.init())
.pipe($.plumber({
errorHandler: reportError
}))
.pipe($.babel({
presets: ['es2015']
}))
.on('error', reportError)
.pipe($.concat('bundled.js'))
.pipe($.if(isProd, $.uglify().on('error', function(e) {
console.log(e);
})))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('www/js'))
.pipe(browserSync.stream());
});
gulp.task('pluginStubs', function() {
return gulp.src(srcs.pluginStubs)
.pipe($.concat('cordova.js'))
.pipe(gulp.dest('www'));
});
gulp.task('vendor', function() {
return gulp.src(bowerFiles())
.pipe($.concat('vendor.min.js'))
.pipe($.uglify().on('error', function(e) {
console.log(e);
}))
.pipe(gulp.dest('www/js'));
});
gulp.task('sass', function() {
return gulp.src(srcs.sass)
.pipe($.sourcemaps.init())
.pipe($.plumber({
errorHandler: reportError
}))
.pipe($.sass({style: 'expanded'}))
.on('error', reportError)
.pipe($.autoprefixer({browsers: cssBrowsersSupported}))
.pipe($.concat('style.css'))
.pipe($.sourcemaps.write('sourcemaps'))
.pipe(gulp.dest('www/css'))
.pipe(browserSync.stream({match: '**/*.css'}));
});
gulp.task('html', function() {
gulp.src(srcs.html)
.pipe(gulp.dest('www'))
.pipe(browserSync.stream());
});
gulp.task('assets', function() {
gulp.src(srcs.assets)
.pipe(gulp.dest('www/assets'))
});
gulp.task('browser-sync', function() {
browserSync({
open: false,
server: {
baseDir: 'www'
}
});
});
function getTestJs() {
return merge2(
gulp.src(bowerFiles().concat(srcs.vendorTest)),
getUrlSrcs()
.pipe($.addSrc(srcs.js))
.pipe($.addSrc(srcs.test))
.pipe($.cached('testJs'))
.pipe($.babel({
presets: ['es2015']
}))
.pipe($.remember('testJs')),
gulp.src(srcs.sass)
.pipe($.sass({style: 'expanded'}))
.on('error', $.util.log)
.pipe($.autoprefixer({browsers: cssBrowsersSupported}))
.pipe($.concat('style.css')),
gulp.src(srcs.assets, {base: 'develop/source/'})
);
}
gulp.task('test', function() {
getTestJs()
.pipe($.jasmineBrowser.specRunner({console: true}))
.pipe($.jasmineBrowser.headless());
});
gulp.task('test:watch', ['test'], function() {
getTestJs();
var watchedThings = srcs.js.concat(srcs.test);
$.watch(watchedThings, function(vinyl) {
if (vinyl.event === 'change') {
delete $.cached.caches['testJs'][vinyl.path];
}
gulp.start('test');
});
});
gulp.task('jasmine', function() {
getTestJs()
.pipe($.watch(srcs.js.concat(srcs.test)))
.pipe($.watch(srcs.sass))
.pipe($.jasmineBrowser.specRunner())
.pipe($.jasmineBrowser.server({port: 8888}));
});
var reportError = function(error) {
var lineNumber = (error.lineNumber) ? 'LINE ' + error.lineNumber + ' -- ' : '';
$.notify({
title: 'Task Failed [' + error.plugin + ']',
message: lineNumber + 'See console.',
sound: 'Basso'
}).write(error);
$.util.beep();
// Pretty error reporting
var report = '';
var chalk = $.util.colors.white.bgRed;
report += chalk('TASK:') + ' [' + error.plugin + ']\n';
report += chalk('PROB:') + ' ' + error.message + '\n';
if (error.lineNumber) { report += chalk('LINE:') + ' ' + error.lineNumber + '\n'; }
if (error.fileName) { report += chalk('FILE:') + ' ' + error.fileName + '\n'; }
console.error(report);
this.emit('end');
};
|
const express = require("express")
const asyncHandler = require("express-async-handler")
const verifyToken = require("./middlewares/verifyToken");
const ObjectId = require("mongodb").ObjectId
const router = express.Router()
let categories;
// Middleware to get category collection object from app locals
router.use((req, res, next) => {
categories = req.app.get("category")
next()
})
// Get all categories
router.get("/", asyncHandler(async (req, res) => {
const categoriesArray = await categories.find().toArray()
res.status(200).json({
status: "success",
payload: {
categories: categoriesArray
}
})
}))
// Add category
router.post("/addCategory", verifyToken, asyncHandler(async (req, res) => {
const category = req.body
await categories.insertOne(category)
res.status(201).json({
status: "success",
message: "category added"
})
}))
// Delete category
router.post("/deleteCategory", verifyToken, asyncHandler(async (req, res) => {
const category = req.body
await categories.deleteOne({ categoryName: category.categoryName })
res.status(200).json({
status: "success",
message: "category deleted"
})
}))
// Update category
router.post("/updateCategory", verifyToken, asyncHandler(async (req, res) => {
const category = req.body
await categories.updateOne({ _id: new ObjectId(category._id) }, { $set: { categoryName: category.categoryName } })
res.status(200).json({
status: "success",
message: "category deleted"
})
}))
module.exports = router |
/**
* Created by lekanterragon on 4/1/17.
*/
(function($) {
"use strict";
var base_url = $('#base_url').val();
var handle_error = function (error, error_id) {
var error_text = '<div class="alert alert-danger alert-dismissible" role="alert">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span' +
' aria-hidden="true">×</span></button>'+ error + '</div>';
$('#'+error_id).html(error_text);
};
var handle_success = function (success, success_id) {
var success_text = '<div class="alert alert-info alert-dismissible" role="alert">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span' +
' aria-hidden="true">×</span></button>'+ success + '</div>';
$('#'+success_id).html(success_text);
};
var handle_alerts = function (uri, title, message) {
if(uri){
var current_uri = window.location.pathname;
if(current_uri == uri){
sweetAlert(title, message)
}
}else{
swal(title, message)
}
};
var handle_redirect = function (remove, replace) {
var url = window.location.href.replace(remove, '');
window.location.href = url+replace;
};
var generate_id = function (length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
var startRegistration = function () {
$('#mainregisterBtn').on('click', function (event) {
event.preventDefault();
if ($('#checkbox-signup').is(":checked")){
var payload = {'email': $('#email').val(),
'name': $('#name').val(),
'reg_num': $('#reg_num').val(),
'password': $('#password').val(),
'temp_id': generate_id(5),
'action' : 'create'
};
var verify_password = $('#verify_password').val();
if(payload['password'] != verify_password){
handle_error('Your passwords should match.', 'error')
}
else{
if(payload['password'].length < 5){
handle_error('Your passwords should be more than 5 characters.', 'error')
}
else{
var register_url = $('#register_url').val();
console.log(register_url);
$.ajax({
url : register_url,
type: "POST",
data : JSON.stringify(payload),
contentType: 'application/json',
dataType:"json",
success : function (response) {
var ver_id = response[0].data.tempID;
var replace = '/register?action=verify&verID='+ver_id;
handle_redirect('/register', replace)
},
error : function(xhr, errmsg, err){
if (xhr.responseJSON.error_code == 'HOSPEXISTS'){
localStorage.setItem('errors', 'Hospital already exists');
// handle_redirect('/plans', '')
handle_error('Hospital already exists', 'HOSPEXISTS')
}
}
})
}
}
}
else
handle_error('You have to agree to our terms and conditions', 'error')
})
};
var updateHospitalDetails = function () {
$("#updateHospital").on('click', function (event) {
event.preventDefault();
var payload = {
'name': $('#name').val(),
'email': $('#email').val(),
'address': $('#address').val(),
'description': $('#description').val(),
'action': 'update',
'hospital_id': $('#hospital_id').val()
};
var hospital_url= $('#hospital_url').val();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
$.ajax({
url : hospital_url,
type: "POST",
data : JSON.stringify(payload),
contentType: 'application/json',
dataType:"json",
success : function (response) {
console.log(response[0].data);
console.log("Your Data has been saved");
var success = "Successfully saved changes";
handle_success(success,'success');
},
error : function(xhr, errmsg, err){
console.log(xhr);
handle_error("Make sure your inputs are correct",'error');
}
})
});
};
var addPatient = function () {
$('#addPatient').on('click', function(event){
event.preventDefault();
var payload= {
'first_name': $('#first_name').val(),
'last_name': $('#last_name').val(),
'email': $('#email').val(),
'hospital_id': $('#hospital_id').val(),
'action':'create'
};
var patient_url = $('#patient_url').val();
$.ajax({
url : patient_url,
type: "POST",
data : JSON.stringify(payload),
contentType: 'application/json',
dataType:"json",
success:function(response){
var success = "Successfully added New patient";
handle_success(success,'success');
},
error:function(xhr, errmsg,err){
console.log(xhr);
handle_error("Make sure your inputs are correct and use a unique email",'error');
}
})
});
};
var requestService = function () {
$('#requestService').on('click', function(event) {
event.preventDefault();
var payload = {
'name': $('#service_name').val(),
'short_description': $('#short_description').val(),
'long_description': $('#long_description').val(),
'action': 'create'
};
var service_url = $('#service_url').val();
$.ajax({
url: service_url,
type: "POST",
data: JSON.stringify(payload),
contentType: 'application/json',
dataType: "json",
success: function (response) {
console.log(response[0].data);
console.log("data created");
var success = "Successfully requested for a service";
handle_success(success, 'success');
},
error: function (xhr, errmsg, err) {
console.log(xhr);
handle_error("Make sure your inputs are correct", 'error');
}
})
});
};
var check_for_errors = function () {
var errors = localStorage.getItem('errors');
if (errors){
localStorage.removeItem('errors');
handle_error(errors)
}
};
check_for_errors();
handle_alerts('/dashboard/service-info', 'Choose Services', 'Choose the services of your choice to move on.');
startRegistration();
updateHospitalDetails();
addPatient();
requestService();
})(window.jQuery); |
// Initialize Firebase
var config = {
apiKey: "AIzaSyCuigfBbczrJwUOFp88IFHlhf5pX2qfUmQ",
authDomain: "traintime-93a75.firebaseapp.com",
databaseURL: "https://traintime-93a75.firebaseio.com",
projectId: "traintime-93a75",
storageBucket: "traintime-93a75.appspot.com",
messagingSenderId: "434144199213"
};
firebase.initializeApp(config);
var database = firebase.database();
var timerIntervalID = "";
var counter = 0
var dataArray = [];
function calculateTimeRemainder(firstTime, frequency){
// First Time (pushed back 1 year to make sure it comes before current time)
var firstTimeConverted = moment(firstTime, "HH:mm").subtract(1, "years");
var diffTime = moment().diff(moment(firstTimeConverted), "minutes");
return (diffTime % frequency);
};
function minutesAway(firstTime, frequency) {
return (frequency - calculateTimeRemainder(firstTime, frequency));
}
function nextArrivalTime(firstTime, frequency){
return(moment().add(minutesAway(firstTime, frequency), "minutes").format("hh:mm"));
}
function displayRecord(sp){
var row = {}
row = {key:sp.key, value:sp.val()};
//push each record into an array so we can use it with setInterval
dataArray.push(row);
var tfrequency = sp.val().frequency;
var tFirstTime = sp.val().firstTime;
var row = $("<tr>");
var cols = '<td><span class="fas fa-pencil-alt float-left" data-key="' + sp.key + '"></span></td>' +
'<td><span class="fas fa-trash float-left" data-key="' + sp.key + '"></span></td>' +
'<td>'+ sp.val().name + '</td>' +
'<td>'+ sp.val().destination + '</td>' +
'<td>'+ tfrequency + '</td>' +
'<td>'+ nextArrivalTime(tFirstTime, tfrequency) + '</td>' +
'<td>'+ minutesAway(tFirstTime, tfrequency) + '</td>';
row.addClass(sp.key);
row.append(cols);
$("table tbody").append(row)
//console.log(dataArray);
}
$(".addData").on("click", function (event) {
event.preventDefault();
var newTrain = {
name: $("#formGroupTrainName").val().trim(),
destination: $("#formGroupDestination").val().trim(),
firstTime: $("#formGroupFirstTrainTime").val().trim(),
frequency: $("#formGroupFrequency").val().trim(),
dateAdded: firebase.database.ServerValue.TIMESTAMP
};
database.ref().push(newTrain);
$(".add").hide();
$(".update").hide();
$(".schedule").show();
});
$(document).on("click", ".fa-trash", function(){
database.ref($(this).attr('data-key')).remove()
.then(function() {
console.log("Remove succeeded.")
})
.catch(function(error) {
console.log("Remove failed: " + error.message)
});
});
$(document).on("click", ".fa-pencil-alt", function(){
//get record
alert("you touched the pencil")
$(".schedule").hide();
database.ref($(this).attr('data-key'))
.once("value").then(function(sp) {
$("#formGroupUpdateTrainName").val(sp.val().name);
$("#formGroupUpdateDestination").val(sp.val().destination);
$("#formGroupUpdateFirstTrainTime").val(sp.val().firstTime);
$("#formGroupUpdateFrequency").val(sp.val().frequency);
//console.log(sp.val().name);
//console.log(sp.val().destination);
});
$(".updateData").attr("data-key", $(this).attr('data-key'));
$(".update").show();
});
$(".updateData").on("click", function(){
var updatedSchedule = {
name: $("#formGroupUpdateTrainName").val().trim(),
destination: $("#formGroupUpdateDestination").val().trim(),
firstTime: $("#formGroupUpdateFirstTrainTime").val().trim(),
frequency: $("#formGroupUpdateFrequency").val().trim(),
dateUpdated: firebase.database.ServerValue.TIMESTAMP
};
console.log(updatedSchedule);
console.log($(this).attr('data-key'))
database.ref().child($(this).attr('data-key')).update(updatedSchedule)
$(".update").hide();
$(".schedule").show();
});
$(".addTrain").on("click", function(){
$(".add").show();
$(".schedule").hide();
})
database.ref().on("child_added", function(sp) {
//console.log(sp.key);
displayRecord(sp);
}, function(error) {
console.log("Error: " + error.code);
});
database.ref().on("child_removed", function(sp){
$('.'+sp.key).remove()
});
database.ref().on("child_changed", function(sp){
//alert("Hey child changed " + sp.key)
});
$(document).ready(function(){
$(".add").hide();
$(".update").hide();
$(".schedule").show();
//timerIntervalID = setInterval(updateTable, 10000);
//alert("In ready")
});
function updateTable(){
counter++;
alert("I was called");
if (counter >= 2){
clearInterval(timerIntervalID);
}
}
$(document).on('click', 'tr', function(){
//alert("you clicked on a row");
});
|
'use strict';
(function () {
var tabs = document.querySelectorAll('.sale__tab-link');
var tabLists = document.querySelectorAll('.sale__tab');
var removeActive = function () {
tabLists.forEach(function (list) {
list.classList.remove('sale__tab--active');
});
tabs.forEach(function (el) {
el.classList.remove('sale__tab-link--active');
});
};
if (tabs && tabLists) {
tabs.forEach(function (tab, i) {
tab.addEventListener('click', function (evt) {
evt.preventDefault();
removeActive();
tab.classList.add('sale__tab-link--active');
tabLists[i].classList.add('sale__tab--active');
});
});
}
})();
|
import { before, GET, POST, route } from 'awilix-express'
import { authenticate } from '../ApiController';
import OtpMapper from "../feature/auth/mapper/OtpMapper";
@route('/otp')
export default class OtpController {
constructor(
{
getChannelUseCase,
verifyUserUseCase,
verifyCodeUseCase,
getCodeUseCase
}
) {
this.getChannelUseCase = getChannelUseCase;
this.verifyUserUseCase = verifyUserUseCase;
this.verifyCodeUseCase = verifyCodeUseCase;
this.getCodeUseCase = getCodeUseCase;
}
@route('/channel/:username')
@GET()
async getChannelUsername(req, res, next) {
try {
const mapper = new OtpMapper()
const param = mapper.getChannel(req.params)
const result = await this.getChannelUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/channel')
@GET()
@before([authenticate])
async getChannel(req, res, next) {
try {
const mapper = new OtpMapper()
const param = mapper.getChannel(req.decoded)
const result = await this.getChannelUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/verify-user')
@POST()
async verifyUser(req, res, next) {
try {
const mapper = new OtpMapper()
const param = mapper.verifyUser(req.body)
const result = await this.verifyUserUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/verify-code')
@POST()
async verifyCode(req, res, next) {
try {
const mapper = new OtpMapper()
const param = mapper.verifyCode(req.body)
const result = await this.verifyCodeUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/code/:refCode')
@GET()
async getCode(req, res, next) {
try {
const mapper = new OtpMapper()
const param = mapper.getCode(req.params)
const result = await this.getCodeUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
}
|
import Feed from "../../models/feeds";
import { feed as feedValidator } from "./validators";
import { idValidator } from "../../utils/model";
export async function create(ctx) {
const { user } = ctx.state;
const params = ctx.request.smartParams;
const error = feedValidator(params);
if (error) {
ctx.throw(400, error);
}
const entityFields = {
...params,
creator: user._id
};
const entity = new Feed(entityFields);
await entity.save();
ctx.body = {
feed: await Feed.populate(entity, {
path: "creator",
select: "displayName"
})
};
}
export async function get(ctx) {
const entities = await Feed.find().populate({
path: "creator",
select: "displayName"
});
ctx.body = {
feeds: entities
};
}
export async function getOne(ctx, next) {
const { id } = ctx.request.smartParams;
if (idValidator(id)) {
ctx.throw(400, "Bad news item ID");
}
const entity = await Feed.findById(id).populate({
path: "creator",
select: "displayName"
});
if (!entity) {
ctx.throw(404, "News item not found");
}
ctx.body = {
feed: entity
};
if (next) {
return next();
}
}
export async function update(ctx) {
const params = ctx.request.smartParams;
const { user } = ctx.state;
const { feed } = ctx.body;
const error = feedValidator(params);
if (error) {
ctx.throw(400, error);
}
if (!feed.creator.equals(user._id)) {
ctx.throw(403, "Not authorized to edit this news item");
}
Object.assign(feed, params);
await feed.save();
ctx.body = {
feed
};
}
export async function remove(ctx) {
const { user } = ctx.state;
const { feed } = ctx.body;
if (!feed.creator.equals(user._id)) {
ctx.throw(403, "Not authorized to delete this news item");
}
await feed.remove();
ctx.body = {
_id: feed._id
};
}
|
import React, { Component } from 'react';
import threeEntryPoint from './threejs/threeEntryPoint';
import "./synthViz.css";
// implementing React and Three.js together based off of https://itnext.io/how-to-use-plain-three-js-in-your-react-apps-417a79d926e0
export default class SynthViz extends Component {
// pass reference to div to entry point function
componentDidMount() {
threeEntryPoint(this.threeRootElement);
}
// render three.js canvas container
render () {
return (
<div className="synthviz-page" ref={element => this.threeRootElement = element} />
);
}
}
|
var speed;
var maxspeed = 50;
var Penality;
function sp(speed) {
if (speed > maxspeed) {
console.log(`violated the speed limit`);
penality = speed * 100;
console.log(`fine to be paid: ${penality}`);
} else {
console.log("Vehicle is in good speed");
}
}
sp(10);
sp(100);
|
"use strict";
//navBar displaiblity script
window.onload = function() { //Removes menu button if the navBar is already displayed
if (window.getComputedStyle(document.getElementById('navBar').children[0]).display != 'none') {
document.getElementById('navBar').children[1].style.display = 'none';
}
window.addEventListener('resize', function() { //Removes or replaces menu button on resize
if (window.getComputedStyle(document.getElementById('navBar').children[0]).display != 'none') {
document.getElementById('navBar').children[1].style.display = 'none';
}
else {
document.getElementById('navBar').children[1].style.display = 'block';
}
});
};
function toggleNavBar() {
var navBar = document.getElementById('navBar').children[1];
if (window.getComputedStyle(navBar).display != 'none') {
navBar.style.display = 'none';
}
else {
navBar.style.display = 'block';
}
} |
document.getElementById("btnTong").onclick = function () {
var soN = document.getElementById("soN").value;
var soHangChuc = Math.floor(soN/10);
var soHangDonVi = Math.floor(soN%10);
var tong = soHangChuc + soHangDonVi;
document.getElementById("divShowInfo").innerHTML = "Tổng hai kí số là: " + tong;
document.getElementById("divShowInfo").style.backgroundColor = "red";
document.getElementById("divShowInfo").style.color = "white";
document.getElementById("divShowInfo").style.fontSize = "30px";
document.getElementById("divShowInfo").style.textAlign = "center";
}; |
'use strict';
var expect = require('chai').expect;
var d = require('../src/uniform');
describe('#d', function(){
it('skdflds', function(){
var res = d.f(0,0);
expect(res).to.equal(1);
});
});
|
export function split(x1, y1, x2, y2, x3, y3, x4, y4, t) {
return {
left: _split(x1, y1, x2, y2, x3, y3, x4, y4, t),
right: _split(x4, y4, x3, y3, x2, y2, x1, y1, 1 - t, true)
}
}
function _split(x1, y1, x2, y2, x3, y3, x4, y4, t, reverse) {
let x12 = (x2 - x1) * t + x1
let y12 = (y2 - y1) * t + y1
let x23 = (x3 - x2) * t + x2
let y23 = (y3 - y2) * t + y2
let x34 = (x4 - x3) * t + x3
let y34 = (y4 - y3) * t + y3
let x123 = (x23 - x12) * t + x12
let y123 = (y23 - y12) * t + y12
let x234 = (x34 - x23) * t + x23
let y234 = (y34 - y23) * t + y23
let x1234 = (x234 - x123) * t + x123
let y1234 = (y234 - y123) * t + y123
if (reverse) {
return [x1234, y1234, x123, y123, x12, y12, x1, y1]
}
return [x1, y1, x12, y12, x123, y123, x1234, y1234]
}
|
const productModel = require('../model/productModel');
const getAllProducts = async (req, res) => {
try {
const data = await productModel.getAllProducts_Mod();
// console.log('Dados novos', data);
return res.status(200).json(data);
} catch (error) {
return res.status(400).res.json(error);
}
};
const insertProduct = async (req, res) => {
try {
const { nome, descricao, preco, quantidade } = req.body;
// console.log('Inserir', nome, descricao, preco, quantidade);
const newProduct = await productModel.insertProducts_Mod(
nome,
descricao,
preco,
quantidade
);
return res.status(200).json(newProduct);
} catch (error) {
return res.status(400).json(error);
}
};
const removeProduct = async (req, res) => {
try {
const { id } = req.params;
await productModel.deleteProduc_Mod(id);
return res.status(200).json({ message: 'Produto excluido com sucesso.' });
} catch (error) {
return res.status(400).json({ message: 'Erro ao excluir produto', error });
}
};
const updateProduct = async (req, res) => {
try {
const { id } = req.params;
// console.log('id', id);
const { nome, descricao, preco, quantidade } = req.body;
if (quantidade < 0)
return res
.status(400)
.json({ message: 'Quantidade não pode ser negativo' });
// console.log('Update', id, nome, descricao, preco, quantidade);
await productModel.updateProduct_Mod(
id,
nome,
descricao,
preco,
quantidade
);
return res.status(200).json({ message: 'Produto atualizado com sucesso.' });
} catch (error) {
return res
.status(400)
.json({ message: 'Erro ao atualizar produto', error });
}
};
module.exports = {
getAllProducts,
insertProduct,
removeProduct,
updateProduct,
};
|
// this register.js is for register page
// here is a bug in firefox: focus event has to happened before blur, the solution is setTimeout, the method is learned from https://blog.csdn.net/weixin_30438813/article/details/95036694
// username on blur check
$("#username").blur(function () {
checkAvailable("username");
});
// email on blur check
$("#email").blur(function () {
checkAvailable("email");
checkEmailFormat($("#email").val());
});
// password on blur check match
$("#password2").blur(function () {
if($(this).val()!=$("#password").val()){ // if not match show hint
$(".error-password").show("normal");
window.setTimeout(function () { // see top of the register.js
$("#password2").focus(); // focus input field
});
}
else if($(this).val()==$("#password").val()) $(".error-password").hide("normal"); // if match hide hint
});
// check username or email is exist in database
function checkAvailable(input) {
console.log("checking "+input+"..."); // test
let dataSet={"username": "", "email": ""};
if(input=="username"){
let inputValue=$("#username").val(); // get username
dataSet[input]=inputValue;
}else if(input=="email"){
let inputValue=$("#email").val(); // get e-mail
dataSet[input]=inputValue;
}
$.ajax({
url: "/checkavailable",
data: dataSet,
type: "post",
dataType: "json",
success: function (data) {
// console.log(data["ucode"]);
if(data["ucode"]!=undefined){
if(data["ucode"]=="1"){
$(".error-user").show("normal"); // if exist show hint
$("#username").focus();
}
else if(data["ucode"]=="0") $(".error-user").hide("normal");
}
if(data["ecode"]!=undefined){
if(data["ecode"]=="1"){
$(".error-email").show("normal"); // if exist show hint
$("#email").focus();
}
else if(data["ecode"]=="0") $(".error-email").hide("normal");
}
},
error: function () {
console.log("Network error");
}
});
}
// check e-mail format
function checkEmailFormat(val){
let regex=/^[a-zA-Z0-9\_\-\!\#\$\%\&\'\*\+\-\=\?\^\_\`\{\|\}\~\.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
if(regex.test(val)){
$(".error-email-format").hide("normal");
console.log("email format true");
}
else{
$(".error-email-format").show("normal");
window.setTimeout(function () { // see top of the register.js
$("#email").focus();
});
console.log("email format false");
}
} |
import React from "react";
import "./App.css";
import Navbar from "./components/Navbar/Navbar";
import { HomePage } from "./pages/home/HomePage";
import { AboutPage } from "./pages/about/AboutPage";
import { ContactPage } from "./pages/contact/ContactPage";
import Switch from "react-bootstrap/esm/Switch";
import { Route } from "react-router-dom";
import OurServicesPage from "./pages/ourServices/OurServicesPage";
import { CalculatorsPage } from "./pages/calculators/CalculatorsPage";
import { InfoBottom } from "./components/info-bottom/InfoBottom";
import { Footer } from "./components/footer/Footer";
import {
AssetFinance,
Business,
FirstHome,
Investing,
PreApproval,
Refinancing,
} from "./components/our-services/ServicesInfo";
import ScrollToTop from "./components/scroll-to-top/ScrollToTop";
function App() {
return (
<div className="App">
<Navbar />
<Switch>
<ScrollToTop />
<Route exact path="/" component={HomePage} />
<Route exact path="/our_services" component={OurServicesPage} />
<Route
exact
path="/our_services/asset-finance"
component={AssetFinance}
/>
<Route
exact
path="/our_services/business-commercial"
component={Business}
/>
<Route exact path="/our_services/first-home" component={FirstHome} />
<Route exact path="/our_services/investing" component={Investing} />
<Route
exact
path="/our_services/pre-approval"
component={PreApproval}
/>
<Route exact path="/our_services/refinancing" component={Refinancing} />
<Route exact path="/about" component={AboutPage} />
<Route path="/calculators" component={CalculatorsPage} />
<Route exact path="/contact" component={ContactPage} />
</Switch>
<InfoBottom />
<Footer />
</div>
);
}
export default App;
|
import React from "react";
import Img from "components/Common/Img";
import strengthImg from "assets/img/new-successful-resumes/famous/elon-musk/ornaments/strenghts.jpg";
export default function Strengths({ section, description, image, data }) {
return (
<section
id={section}
className="m-md-bottom-13">
<div className="container">
<div className="Grid full-width">
<div className="Grid-cell--md-6 Grid-cell--xs-12 p-md-left-10">
<article className="resume-article">
<h2>Strenghts</h2>
<p>{description}</p>
{data.map((item, index) => (
<div key={index}>
<h6>{item.title}</h6>
<p>{item.description}</p>
</div>
))}
</article>
</div>
<div className="famous-resume--illustration-holder Grid-cell--md-6 Grid-cell--xs-12 m-sm-top-3 m-xs-top-5 m-md-top-6 p-md-left-10 m-bottom-7 Grid--selfCenter">
<Img
width="595"
sizes={image.childImageSharp.sizes}
alt=""
/>
</div>
</div>
</div>
</section>
);
}
|
function sum() {
return [].reduce.call(arguments, function(a,b) {
return a + b;
});
}
function mul() {
return [].reduce.call(arguments, function(a,b) {
return a * b;
});
}
function applyAll(func) {
return func.apply(this, [].slice.call(arguments, 1));
}
console.log(applyAll(sum, 1,2,3));
console.log(applyAll(mul, 2,3,4));
console.log(applyAll(Math.max, 2,-2,3));
console.log(applyAll(Math.min, 2,-2,3)); |
module.exports={
database:'mongodb+srv://ghada:amazona123@cluster0.xrn3z.mongodb.net/amazona?retryWrites=true&w=majority' ,
port:3030,
secret:'ghadaezzatmoonlight789852'
} |
// 无法动态匹配面包屑,存储路由数据
const RouteData = [
{
name: "常用集合",
path: "/mobx/app/user",
key: "1",
parentKey: "sub1",
data: [
{ name: "常用集合", path: "/mobx/app/user" }
]
},
{
name: "新建",
path: "/mobx/app/newuser",
key: "1",
parentKey: "sub1",
data: [
{ name: "常用集合", path: "/mobx/app/user" },
{ name: "新建", path: "/mobx/app/newuser" },
]
},
{
name: "个人管理",
path: "/mobx/app/useredit",
key: "2",
parentKey: "sub1",
data: [
{ name: "常用集合", path: "/mobx/app/user" },
{ name: "个人管理", path: "/mobx/app/useredit" },
]
},
{
name: "table",
path: "/mobx/app/table",
key: "7",
parentKey: "sub1",
data: [
{ name: "常用集合", path: "/mobx/app/user" },
{ name: "其他", path: "/mobx/app/table" },
]
},
{
name: "其他",
path: "/mobx/app/else",
key: "3",
parentKey: "sub1",
data: [
{ name: "常用集合", path: "/mobx/app/user" },
{ name: "其他", path: "/mobx/app/else" },
]
},
{
name: "第三方",
path: "/mobx/app/group",
key: "4",
parentKey: "sub2",
data: [
{ name: "第三方", path: "/mobx/app/group" },
]
},
{
name: "RTSP",
path: "/mobx/app/rtsp",
key: "4",
parentKey: "sub2",
data: [
{ name: "第三方", path: "/mobx/app/group" },
{ name: "RTSP", path: "/mobx/app/rtsp" },
]
},
{
name: "三级联动",
path: "/mobx/app/area",
key: "5",
parentKey: "sub2",
data: [
{ name: "第三方", path: "/mobx/app/group" },
{ name: "三级联动", path: "/mobx/app/area" },
]
},
{
name: "首页",
path: "/mobx",
key: "0",
parentKey: "0",
data: [
{ name: "首页", path: "/mobx" }
]
},
{
name: "测试",
path: "/mobx/app/test",
key: "6",
parentKey: "",
data: [
{ name: "首页", path: "/mobx" },
{ name: "测试", path: "/mobx/app/test" }
]
},
]
export default RouteData; |
/*global define*/
define([
'underscore',
'backbone',
'models/wine-model'
], function (_, Backbone, WineModel) {
'use strict';
var WinesCollection = Backbone.Collection.extend({
model: WineModel,
url: '/wines'
});
return WinesCollection;
}); |
function PedidosController(app) {
/* #region Variáveis */
this._app = app;
var Pedido = app.models.pedido;
var Reserva = app.models.reserva;
var Impressao = app.models.impressao;
var Usuario = app.models.usuario;
var Log = app.models.log;
var ObjectId = app.config.dbConnection.Types.ObjectId;
var tiposAtualizacao = {
criacao: 'Criação',
alteracao: 'Edição',
exclusao: 'Exclusão',
restauracao: 'Restauração'
};
/* #endregion */
/* #region Auxiliares */
var validaSenha = function (senha) {
return Usuario.find({ senha: senha })
.then(function (usuario) {
if (senha) {
if (usuario && usuario.length > 0) {
return Promise.resolve({ email: usuario[0].email, nome: usuario[0].nome, perfil: usuario[0].perfil });
} else {
return Promise.reject('Senha incorreta! Usuário não localizado.');
}
}
});
}
var atualizaReservas = function (pedido, tipo) {
const data = app.moment(pedido.horario).startOf('day').toDate();
console.log('Atualizando reservas de acordo com o pedido ' + pedido._id + ' para a data ' + data.toString());
const itens = pedido.itens.map(item => {
return { item: item, data: data, tipo: tipo }
});
return new Promise(function (resolve, reject) {
app.async.eachSeries(itens, atualizaReservaItem, function (err) {
if (err) {
reject(err);
} else {
resolve(pedido);
}
});
});
}
var atualizaReservaItem = function ({ item, data, tipo }, callback) {
console.log(item._id, item.semPimenta, data, tipo);
Reserva.find({ 'item._id': item._id, data: data, 'item.semPimenta': item.semPimenta }, function (err, result) {
if (err) {
callback(`Erro ao buscar reserva: ${JSON.stringify(err)}`);
return;
}
if (!result.length) {
console.log('Nenhuma reserva encontrada para o item ' + item._id);
callback();
return;
}
console.log('Atualizando reserva ' + result[0]._id);
var reserva = result[0];
Reserva.findOneAndUpdate({ _id: reserva._id },
{ $set: { qtdaVendida: getQtdaVendidaReserva(reserva, item, tipo) } },
{ new: true },
function (err) {
if (err) {
callback(`Erro ao atualizar reserva: ${JSON.stringify(err)}`);
} else {
callback();
}
});
});
}
var getQtdaVendidaReserva = function (reserva, item, tipo) {
switch (tipo) {
case tiposAtualizacao.criacao:
case tiposAtualizacao.restauracao:
return reserva.qtdaVendida + item.quantidade;
case tiposAtualizacao.exclusao:
return reserva.qtdaVendida - item.quantidade;
default:
throw 'Tipo Inválido';
}
}
var geraIdItens = function (pedido) {
if (pedido.itens) {
pedido.itens.forEach(function (item) {
if (!item.hasOwnProperty('_id') || !item._id) {
item._id = new ObjectId();
}
});
}
return pedido;
}
var cloneObject = function (obj) {
return JSON.parse(JSON.stringify(obj));
}
// Obtem um cópia do pedido, com as quantidades dos itens ajustadas
// de forma a poder atulizar as reservar, usando tiposAtualizacao.criacao
var getDiferencaReserva = function (pedidoAnterior, novoPedido) {
var diferenca = cloneObject(novoPedido);
// Atualiza os itens comuns entre o anterior e o novo, mantendo os itens adicionais do novo
diferenca.itens.forEach(function (item) {
var itemAnterior = pedidoAnterior.itens.find(i => i._id == item._id && i.semPimenta == item.semPimenta);
if (itemAnterior) {
item.quantidade = item.quantidade - itemAnterior.quantidade;
}
});
// Itens removidos
var itensRemovidos = pedidoAnterior.itens.filter(function (item) {
return !novoPedido.itens.find(i => i._id == item._id && i.semPimenta == item.semPimenta);
}).map(function (item) { // Multiplica a quantidade por -1
item.quantidade = item.quantidade * -1;
return item;
});
diferenca.itens = diferenca.itens.concat(itensRemovidos);
return diferenca;
}
// Retorna array com todos os pedidos recorrentes de mesma origem e data maior ou igual,
// ou retorna array somente com o pedido, se não for recorrente
var buscaPedidosRecorrentes = function (id) {
return Pedido.findOne({ _id: id })
.then(function (pedido) {
var pedidoOrigem = getIdPedidoOrigemRecorrencia(pedido);
if (pedidoOrigem) {
const data = app.moment(pedido.horario).startOf('day').toDate();
return Pedido.find({
horario: { $gte: data },
$or: [
{ 'recorrencia.pedidoOrigem': pedidoOrigem },
{ _id: pedidoOrigem }
]
});
} else {
return Promise.resolve([pedido]);
}
});
}
var getIdPedidoOrigemRecorrencia = function (pedido) {
var pedidoOrigem = null;
if (pedido.recorrencia && pedido.recorrencia.repetirAte) {
if (pedido.recorrencia.pedidoOrigem)
pedidoOrigem = pedido.recorrencia.pedidoOrigem;
else
pedidoOrigem = pedido._id;
}
return pedidoOrigem
}
/* #endregion */
/* #region GET */
this.getAll = function (callback) {
Pedido.find({}).sort('horario').exec(callback);
}
this.getByData = function (data, callback) {
var inicioDia = app.moment(data).startOf('day').toDate();
var fimDia = app.moment(data).endOf('day').toDate();
Pedido.find({
horario: {
$gte: inicioDia,
$lt: fimDia
}
}).sort('horario').exec(callback);
}
this.getAggregatedByData = function (data, callback) {
var inicioDia = app.moment(data).startOf('day').toDate();
var fimDia = app.moment(data).endOf('day').toDate();
Pedido.aggregate([{
$match: {
horario: {
$gte: inicioDia,
$lt: fimDia
},
$or: [{ exclusao: { $exists: false } }, { exclusao: null }]
}
}, {
$unwind: {
path: "$itens"
}
}, {
$group: {
_id: "$itens._id",
item: {
$push: "$itens"
},
quantidade: {
$sum: "$itens.quantidade"
}
}
}, {
$project: {
_id: 0,
item: { $arrayElemAt: ["$item", 0] },
quantidade: 1
}
}, {
$project: {
nome: '$item.nome',
tipo: '$item.tipo',
valor: '$item.valor',
unidade: '$item.unidade',
quantidade: '$quantidade',
detalhes: '$item.detalhes'
}
}]).sort('_id.nome').exec(callback);
}
this.get = function (id, callback) {
Pedido.findOne({ _id: id }, callback);
}
/* #endregion */
/* #region POST */
this.post = function (pedido, usuario, callback) {
pedido = geraIdItens(pedido);
salvarPedido(pedido, usuario)
.then(function (novoPedido) {
callback(null, novoPedido);
}).catch(callback);
}
var salvarPedido = function (pedido, { email, nome }) {
return new Pedido(pedido).save()
.then(function (novoPedido) {
if (pedido.recorrencia && !pedido.recorrencia.pedidoOrigem) {
pedido._id = novoPedido._id;
return criaRecorrencia(pedido).then(() => Promise.resolve(novoPedido));
}
return Promise.resolve(novoPedido);
}).then(function (novoPedido) {
return new Log({
pedidoId: novoPedido._id,
logs: [
{
horario: new Date(),
usuario: {
email: email,
nome: nome
},
tipo: tiposAtualizacao.criacao,
},
]
}).save().then(function () {
return Promise.resolve(novoPedido);
});
}).then(function (novoPedido) {
return atualizaReservas(novoPedido, tiposAtualizacao.criacao);
});
}
// Cria os próximos pedidos recorrentes. Retorna uma promisse com o pedido original
var criaRecorrencia = function (pedido) {
if (!pedido.recorrencia || !pedido.recorrencia.repetirAte ||
!pedido.recorrencia.dias || !pedido.recorrencia.dias.length) {
return Promise.resolve([pedido]);
}
var promises = [];
let data = app.moment(pedido.horario).add(1, 'days').toDate();
const repetirAte = app.moment(pedido.recorrencia.repetirAte).toDate();
while (app.moment(data).startOf('day').toDate() <= repetirAte) {
// Verifica se é um dos dias da semana que deve se repetir o pedido
if (pedido.recorrencia.dias.indexOf(data.getDay()) >= 0) {
const novoPedido = Object.assign({}, pedido);
delete novoPedido._id;
novoPedido.horario = data;
novoPedido.recorrencia.pedidoOrigem = pedido._id;
promises.push(salvarPedido(novoPedido, novoPedido.usuario));
}
data = app.moment(data).add(1, 'days').toDate();
}
return Promise.all(promises);
}
/* #endregion */
/* #region PUT */
this.put = function (id, pedido, { email, nome, senha }, confirmacao = false, atualizaRecorrentes, callback) {
pedido = geraIdItens(pedido);
validaSenha(senha).then(function (usuario) {
if (confirmacao) pedido.usuario = usuario;
if (atualizaRecorrentes) {
return buscaPedidosRecorrentes(id)
.then((pedidos) => Promise.all(pedidos.map((p) => {
const novoHorario = new Date(pedido.horario);
const dataHora = new Date(p.horario).setHours(novoHorario.getHours(), novoHorario.getMinutes(), novoHorario.getSeconds());
const pedidoASerAtualizado = {
...pedido,
...{
_id: p._id,
horario: dataHora,
recorrencia: p.recorrencia
}
};
return Pedido.findOneAndUpdate({ _id: p._id }, pedidoASerAtualizado, { new: false });
}))).then((pedidos) => Promise.resolve(pedidos && pedidos.length >= 1 ? pedidos[0] : null));
}
return Pedido.findOneAndUpdate({ _id: id }, pedido, { new: false });
}).then(function (result) {
if (result === null) throw 'Pedido não localizado!';
if (confirmacao) { // Se for somente confirmação pedido
if (result && result.usuario && result.usuario.email !== email) {
return Promise.all([
atualizaReservas(getDiferencaReserva(result, pedido), tiposAtualizacao.criacao),
Log.findOneAndUpdate({ pedidoId: id }, { $set: { 'logs.0.usuario': { email: email, nome: nome } } })
]);
} else {
return atualizaReservas(getDiferencaReserva(result, pedido), tiposAtualizacao.criacao);
}
} else {
return Promise.all([
atualizaReservas(getDiferencaReserva(result, pedido), tiposAtualizacao.criacao),
Log.findOneAndUpdate({ pedidoId: id }, {
$push: {
logs: {
horario: new Date(),
usuario: {
email: email,
nome: nome
},
tipo: tiposAtualizacao.alteracao,
pedido: result
}
}
})
]);
}
}).then(function () {
callback(null, pedido);
}).catch(callback);
}
/* #endregion */
/* #region DELETE */
this.delete = function (id, senha, deleteRecorrentes, callback) {
var usuario = null;
validaSenha(senha).then(function (usuarioBD) {
usuario = usuarioBD;
if (usuario.perfil !== 'Administrador') {
throw 'Usuário sem permissão para excluir!';
}
if (deleteRecorrentes) {
return buscaPedidosRecorrentes(id)
.then((pedidos) => Promise.all(pedidos.map(p => deletePedidoLogicamente(p._id, usuario))))
.then((pedidos) => Promise.resolve(pedidos && pedidos.length >= 1 ? pedidos[0] : null));
} else {
return deletePedidoLogicamente(id, usuario);
}
}).then(function (result) {
callback(null, result);
}).catch(function (erro) {
callback(erro);
});
}
var deletePedidoLogicamente = function (id, usuario) {
return Pedido.findOneAndUpdate({ _id: id }, {
$set: {
exclusao: {
horario: new Date(),
usuario: {
email: usuario.email,
nome: usuario.nome
}
}
}
}, { new: false }).then(function (pedidoAnterior) {
return Promise.all([
Pedido.findOne({ _id: id }), // Retorna o pedido atualizado
Log.findOneAndUpdate({ pedidoId: id }, {
$push: {
logs: {
horario: new Date(),
usuario: { email: usuario.email, nome: usuario.nome },
tipo: tiposAtualizacao.exclusao,
pedido: pedidoAnterior
}
}
})
]);
}).then(function (result) {
return atualizaReservas(result[0], tiposAtualizacao.exclusao);
});
}
var deletePedidoFisicamente = function (id) {
return Pedido.findOneAndDelete({ _id: id })
.then(function (pedido) {
if (pedido.exclusao && pedido.exclusao.horario) {
return Promise.resolve(pedido);
}
return Promise.all([
atualizaReservas(pedido, tiposAtualizacao.exclusao),
Log.findOneAndDelete({ pedidoId: id })
]).then((result) => Promise.resolve(result[0]));
});
}
this.deleteAdmin = function (id, callback) {
buscaPedidosRecorrentes(id)
.then((pedidos) => Promise.all(pedidos.map(p => deletePedidoFisicamente(p._id))))
.then((pedidos) => Promise.resolve(pedidos && pedidos.length >= 1 ? pedidos[0] : null))
.then((result) => {
callback(null, result);
}).catch(callback);
}
/* #endregion */
/* #region Demais Endpoints */
this.restauraPedido = function (id, { email, nome }, callback) {
Pedido.findOneAndUpdate({ _id: id }, { $set: { exclusao: null } }, { new: false })
.then(function (pedido) {
return Promise.all([
atualizaReservas(pedido, tiposAtualizacao.restauracao),
Log.findOneAndUpdate({ pedidoId: id }, {
$push: {
logs: {
horario: new Date(),
usuario: {
email: email,
nome: nome
},
tipo: tiposAtualizacao.restauracao,
pedido: pedido
}
}
})
]);
}).then(function () {
return Pedido.findOne({ _id: id });
}).then(function (pedidoAtualizado) {
callback(null, pedidoAtualizado);
}).catch(callback);
}
this.deleteItem = function (idPedido, idItem, callback) {
Pedido.findOneAndUpdate({ _id: idPedido }, { $pull: { itens: { _id: idItem } } }, { new: false })
.then(function (result) {
const itens = result.itens.filter(i => i._id == idItem);
let item = null;
if (itens && itens.length > 0) {
item = itens[0];
} else {
throw 'Item não localizado.';
}
const data = app.moment(result.data).startOf('day').toDate();
atualizaReservaItem({ item: item, data: data, tipo: tiposAtualizacao.exclusao }, function (err) {
if (err) {
console.error(`Erro ao atualizar reservas: ${JSON.stringify(err)}`);
callback(err, result);
return;
}
callback(null, result);
});
}).catch(callback);
}
this.addItem = function (idPedido, item, callback) {
if (!item.hasOwnProperty('_id') || !item._id) {
item._id = new ObjectId();
}
Pedido.findOneAndUpdate({ _id: idPedido }, { $push: { itens: item } }, { new: true }, function (err, result) {
const data = app.moment(result.data).startOf('day').toDate();
atualizaReservaItem({ item: item, data: data, tipo: tiposAtualizacao.criacao }, function (err) {
if (err) {
console.error(`Erro ao atualizar reservas: ${JSON.stringify(err)}`);
callback(err, result);
return;
}
callback(null, result);
});
})
}
this.imprimePedido = function (id, usuario, callback) {
Pedido.findOne({ _id: id })
.then(function (pedido) {
if (!pedido.impressao.horario) {
pedido.impressao = {
usuario: {
nome: usuario.nome,
email: usuario.email
},
horario: new Date()
}
}
return Pedido.findOneAndUpdate({ _id: id }, { $set: { impressao: pedido.impressao } }, { new: true });
}).then(function (pedido) {
callback(null, pedido);
}).catch(callback);
}
this.addItens = function (idPedido, itens, callback) {
itens = itens.map(item => {
if (!item.hasOwnProperty('_id') || !item._id) {
item._id = new ObjectId();
}
return item;
});
Pedido.findOneAndUpdate({ _id: idPedido }, { $push: { itens: { $each: itens } } }, { new: true }, function (err, result) {
if (err) {
callback(err, result);
return;
}
const data = app.moment(result.data).startOf('day').toDate();
itens = itens.map(item => {
return { item: item, data: data }
});
app.async.eachSeries(itens, atualizaReservaItem, function (err) {
callback(err, result);
});
});
}
this.getLog = function (pedidoId, callback) {
Log.findOne({ pedidoId: pedidoId })
.then(function (log) {
callback(null, log);
}).catch(callback);
}
this.getImpressoes = function (callback) {
Impressao.find({ data: app.moment(new Date()).startOf('day').toDate() }, callback);
}
this.postImpressao = function (usuario, callback) {
new Impressao({ data: app.moment(new Date()).startOf('day').toDate(), usuario: usuario })
.save(callback);
}
/* #endregion */
}
module.exports = function (app) {
return new PedidosController(app);
} |
/*jshint strict:false, loopfunc:true*/
/*global describe, it*/
var ZSchema = require("../src/ZSchema");
describe("https://github.com/zaggino/z-schema/issues/41", function () {
var schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://jsonschema.net#",
"type": "array",
"required": false,
"items": {
"id": "http://jsonschema.net/5#",
"type": "object",
"required": false,
"properties": {
"identifiers": {
"id": "http://jsonschema.net/5/identifiers#",
"type": "array",
"required": false,
"items": {
"id": "http://jsonschema.net/5/identifiers/0#",
"type": "object",
"required": false,
"properties": {
"identifier": {
"id": "http://jsonschema.net/5/identifiers/0/identifier#",
"type": "string",
"required": false
}
}
}
},
"vital": {
"id": "http://jsonschema.net/5/vital#",
"type": "object",
"required": false,
"properties": {
"name": {
"id": "http://jsonschema.net/5/vital/name#",
"type": "string",
"required": false
},
"code": {
"id": "http://jsonschema.net/5/vital/code#",
"type": "string",
"required": false
},
"code_system_name": {
"id": "http://jsonschema.net/5/vital/code_system_name#",
"type": "string",
"required": false
}
}
},
"status": {
"id": "http://jsonschema.net/5/status#",
"type": "string",
"required": false
},
"date": {
"id": "http://jsonschema.net/5/date#",
"type": "array",
"required": false,
"items": {
"id": "http://jsonschema.net/5/date/0#",
"type": "object",
"required": false,
"properties": {
"date": {
"id": "http://jsonschema.net/5/date/0/date#",
"type": "string",
"required": false
},
"precision": {
"id": "http://jsonschema.net/5/date/0/precision#",
"type": "string",
"required": false
}
}
}
},
"interpretations": {
"id": "http://jsonschema.net/5/interpretations#",
"type": "array",
"required": false,
"items": {
"id": "http://jsonschema.net/5/interpretations/0#",
"type": "string",
"required": false
}
},
"value": {
"id": "http://jsonschema.net/5/value#",
"type": "integer",
"required": false
},
"unit": {
"id": "http://jsonschema.net/5/unit#",
"type": "string",
"required": false
}
}
}
};
it("should fail to compile the schema in sync mode because it's invalid", function (done) {
var validator = new ZSchema({ sync: true });
try {
validator.compileSchema(schema);
} catch (e) {
done();
}
});
});
|
import React, { Component } from 'react'
import { combineReducers, createStore } from 'redux'
import { Provider } from 'react-redux'
import reducers from './reducers'
import Lista from './Lista';
import Detalhes from './Detalhes';
import Adicionar from './Adicionar';
const estadoGeral = combineReducers(reducers);
export class App extends Component {
render() {
return (
<Provider store={createStore(estadoGeral)}>
<Adicionar />
<Lista />
<Detalhes />
</Provider>
);
}
}
export default App;
|
'use strict';
import { Paper, RaisedButton, TextField, Snackbar, Toggle, Styles } from 'material-ui';
let { Colors, Typography } = Styles;
let ThemeManager = new Styles.ThemeManager();
// ### Custom Styling
let style = {
loginWrapper: {
background : 'url(/assets/background-auth.jpg)',
backgroundSize : 'cover',
height : '100%',
position : 'fixed',
width : '100%'
},
loginSidebar: {
background : '#fff',
position : 'fixed',
right : 0,
top : 0,
height : '100%',
maxWidth : 480,
width : '100%'
},
loginBox : {
boxSizing : 'border-box',
marginLeft : 'auto',
marginRight : 'auto',
top : '50%',
padding : 100,
position : 'relative',
width : '100%',
WebkitTransform : 'translateY(-50%)'
},
h1 : {
marginBottom : 20,
textAlign: 'center'
},
loginInput : {
fontSize : 15,
marginTop : 5,
textAlign : 'center'
}
};
export default class Auth extends React.Component {
constructor() {
super();
this.state = {
email : '',
password : '',
errorMessage : '',
style : style
};
}
handleChange(name, e) {
var change = {};
change[name] = e.target.value;
this.setState(change);
}
submit(e) {
var self = this;
e.preventDefault();
Reach.auth.login(this.state.email, this.state.password, function (err) {
if (err) {
self.setState({
errorMessage : err.message
});
self.refs.invalid.show();
return;
}
self.context.router.transitionTo(self.props.query.nextPathname ? self.props.query.nextPathname : '/');
});
}
handleResize(e) {
let loginBoxWidth = this.refs.loginBox.getDOMNode().offsetWidth;
if (450 > loginBoxWidth) {
style.loginBox.padding = 35;
} else {
style.loginBox.padding = 100;
}
this.setState({
style : style
});
}
componentDidMount() {
window.addEventListener('resize', this.handleResize.bind(this));
this.handleResize.call(this);
}
render () {
return (
<div style={ style.loginWrapper } ref="loginWrapper">
<Paper style={ style.loginSidebar } zDepth={3} rounded={false}>
<div className="animated slideInRight" style={{ height : '100%', position : 'relative' }}>
<div style={ this.state.style.loginBox } ref="loginBox">
<h1 style={ style.h1 }>Reach Admin</h1>
<form onSubmit={this.submit.bind(this)}>
<TextField
type = "email"
value = { this.state.email }
onChange = { this.handleChange.bind(this, 'email') }
hintText = "Enter your email address"
fullWidth = { true }
style = { style.loginInput }
/>
<TextField
type = "password"
value = { this.state.password }
onChange = { this.handleChange.bind(this, 'password') }
hintText = "Enter your password"
fullWidth = { true }
style = { style.loginInput }
/>
<RaisedButton
label = "Login"
secondary = {true}
type = "submit"
style = {{ marginTop : 30, width : '100%' }}
/>
</form>
<div style={{ borderTop : '1px dashed #e0e0e0', marginTop : 20, textAlign : 'center', paddingTop : 15 }}>
Forgot your password? <a href="#" onClick="">Reset</a>
</div>
</div>
</div>
</Paper>
<Snackbar ref="invalid" message={ this.state.errorMessage } />
</div>
);
}
}
Auth.contextTypes = {
router : React.PropTypes.func
};
Auth.childContextTypes = {
muiTheme : React.PropTypes.object
}; |
import React from 'react';
import moment from 'moment';
import DatePicker from 'react-datepicker';
import styled from 'styled-components';
import IconButton from '@material-ui/core/IconButton';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import TodayIcon from '@material-ui/icons/Today';
import { withStyles } from '@material-ui/core/styles';
import 'react-datepicker/dist/react-datepicker.css';
const FlexContainer = styled.div`
${props => props.style}
display: flex;
align-items: center;
padding: 2px;
`;
const SelectedDate = styled.div`
flex: auto;
text-align: center;
font-weight: 700;
font-size: 22px;
color: #D44126;
text-transform: uppercase;
border: none;
font-family: "Gotham A", "Century Gothic", sans-serif;
`;
const styles = {
iconButton: {
flex: 'none',
width: 36,
height: 36,
padding: 2,
color: '#FFF',
fontSize: 18,
'&:hover': {
color: '#D44126',
cursor: 'pointer',
}
}
}
const DateNav = ({ dates, date, displayFormat, style, selectDate, classes }) => {
if (!dates) {
return null;
}
const selectedDate = moment.utc(date);
const selectedDateDisplay = dates.length === 0 ? 'NO DATES AVAILABLE' :
date === null ? '' :
selectedDate.format(displayFormat);
const availableDates = dates.map(waitTimeDate => moment.utc(waitTimeDate.date));
const selectedDateIndex = availableDates.findIndex(date => date.isSame(selectedDate));
const nextDateIndex = selectedDateIndex + 1;
const nextDate = nextDateIndex > 0 && nextDateIndex < availableDates.length ?
availableDates[nextDateIndex] :
null;
const previousDateIndex = selectedDateIndex - 1;
const previousDate = previousDateIndex >= 0 ?
availableDates[previousDateIndex] :
null;
const makeScrollDateHandler = date => {
return date ?
() => selectDate(date) :
null;
};
return (
<FlexContainer style={style}>
<div><IconButton onClick={makeScrollDateHandler(previousDate)} className={classes.iconButton}>
<ChevronLeftIcon />
</IconButton></div>
<SelectedDate>{selectedDateDisplay}</SelectedDate>
<DatePicker
includeDates={availableDates}
selected={selectedDate && selectedDate.isValid() ? selectedDate : null}
onChange={selectDate}
className={classes.iconButton}
customInput={<IconButton className={classes.iconButton}><TodayIcon /></IconButton>}
popperPlacement='bottom-end'
/>
<IconButton onClick={makeScrollDateHandler(nextDate)} className={classes.iconButton}>
<ChevronRightIcon />
</IconButton>
</FlexContainer>
);
};
export default withStyles(styles)(DateNav); |
/* this should all be converted into the mongo database, this is just for some initial data */
const sections = [
{ text: "About", key: "about" },
{ text: "Blog", key: "blog" },
{ text: "Contact", key: "contact" },
{ text: "Post a Blog", key: "post"}
];
module.exports.sections = sections;
|
const settings = {
zoom: 2,
}
|
import styled from 'styled-components';
export const Container = styled.div`
width:100%;
height: 95%;
display:flex;
flex-direction:row;
`;
export const LeftDiv = styled.div`
width:15%;
height:95%;
margin: 1em;
background-color:#fff;
`;
export const RightDiv = styled.div`
width:85%;
height:95%;
margin:1em;
display: flex;
flex-direction: column;
justify-content:space-between;
`; |
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require("body-parser");
const uuid = require("uuid");
const mongoose = require('mongoose');
const Models = require('./models.js');
const passport = require('passport');
const cors = require('cors');
const validator = require('express-validator');
require('./passport');
const Movies = Models.Movie;
const Users = Models.User;
// local connection:
// mongoose.connect('mongodb://localhost:27017/movieApiDB', { useNewUrlParser: true });
// deployed Mongo Atlas DB:
mongoose.connect('mongodb+srv://movieApiDBAdmin:18j197ft5sf7@movieapidb-5sm08.mongodb.net/movieApiDB?retryWrites=true&w=majority', { useNewUrlParser: true });
app.use(bodyParser.json());
app.use(morgan('common'));
app.use(cors()); // maybe order matters... try putting auth below this cors to avoid cors errors on auth calls
const auth = require('./auth')(app);
app.use(validator());
app.use(express.static('public'));
// GET requests
app.get('/', function (req, res) {
res.send('Welcome to the Movie API!');
});
app.get('/movies', passport.authenticate('jwt', { session : false }), function (req, res) {
Movies.find(function (err, movies) {
res.json(movies);
});
});
app.get('/movies/id/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
Movies.findOne({"_id": req.params.id}, function (err, movie) {
res.json(movie);
});
});
app.get('/movies/:title', passport.authenticate('jwt', { session : false }), function (req, res) {
Movies.find({ "Title": req.params.title }, function (err, movie) {
res.json(movie);
});
});
app.get('/users/:username', passport.authenticate('jwt', {session: false}), function (req, res) {
Users.findOne({ "Username": req.params.username }, function (err, user) {
console.log(user)
res.json(user);
});
});
app.get('/genre/:genre', passport.authenticate('jwt', { session : false }), function (req, res) {
Movies.findOne({ "Genre.Name": req.params.genre }, function (err, movie) {
res.json(movie.Genre);
});
});
app.get('/directors/:name', passport.authenticate('jwt', { session : false }), function (req, res) {
Movies.findOne({ "Director.Name": req.params.name }, function (err, movie) {
res.json(movie.Director);
});
});
app.post('/users', function (req, res) {
req.checkBody('Username', 'Username is required').notEmpty();
req.checkBody('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric()
req.checkBody('Password', 'Password is required').notEmpty();
req.checkBody('Email', 'Email is required').notEmpty();
req.checkBody('Email', 'Email does not appear to be valid').isEmail();
var errors = req.validationErrors();
if (errors) {
return res.status(422).json({ errors: errors });
}
let hashedPassword = Users.hashPassword(req.body.Password);
Users.findOne({ Username: req.body.Username })
.then(function (user) {
if (user) {
return res.status(400).send(req.body.Username + " already exists");
} else {
Users
.create({
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthday: req.body.Birthday
})
.then(function (user) { res.status(201).json(user) })
.catch(function (error) {
console.error(error);
res.status(500).send("Error: " + error);
})
}
}).catch(function (error) {
console.error(error);
res.status(500).send("Error: " + error);
});
});
app.put('/users/:username', passport.authenticate('jwt', { session : false }), function (req, res) {
req.checkBody('Username', 'Username is required').notEmpty();
req.checkBody('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric()
req.checkBody('Password', 'Password is required').notEmpty();
req.checkBody('Email', 'Email is required').notEmpty();
req.checkBody('Email', 'Email does not appear to be valid').isEmail();
var errors = req.validationErrors();
if (errors) {
return res.status(422).json({ errors: errors });
}
Users.findOneAndUpdate({ Username: req.params.username }, {
$set:
{
Username: req.body.Username,
Password: req.body.Password,
Email: req.body.Email,
Birthday: req.body.Birthday
}
},
{ new: true }, // This line makes sure that the updated document is returned
function (err, updatedUser) {
if (err) {
console.error(err);
res.status(500).send("Error: " + err);
} else {
res.json(updatedUser)
}
})
});
app.post('/users/:username/movies/:movieId', passport.authenticate('jwt', { session : false }), function (req, res) {
Users.findOneAndUpdate({ Username: req.params.username }, {
$push: { FavoriteMovies: req.params.movieId }
},
{ new: true },
function (err, updatedUser) {
if (err) {
console.error(err);
res.status(500).send("Error: " + err);
} else {
res.json(updatedUser)
}
})
});
app.delete('/users/:username/movies/:movieId', passport.authenticate('jwt', { session : false }), function (req, res) {
Users.findOneAndUpdate({ Username: req.params.username }, {
$pull: { FavoriteMovies: req.params.movieId }
},
{ new: true },
function (err, updatedUser) {
if (err) {
console.error(err);
res.status(500).send("Error: " + err);
} else {
res.json(updatedUser)
}
})
});
app.delete('/users/:username', passport.authenticate('jwt', { session : false }), function (req, res) {
Users.findOneAndRemove({ Username: req.params.username })
.then(function (user) {
if (!user) {
res.status(400).send(req.params.username + " was not found");
} else {
res.status(200).send(req.params.username + " was deleted.");
}
})
.catch(function (err) {
console.error(err);
res.status(500).send("Error: " + err);
});
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// listen for requests
// DEV ENV:
// app.listen(8080, () =>
// console.log('Listening on 8080.')
// );
// PROD ENV:
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
}); |
var _MOD_NAME = {
/*公共MOD文件*/
jqueryMod : __uri('../libs/jquery.min.js') //jquery
,common_mod : __uri('../libs/common.js') //基本函数库
,data_mod : __uri('../libs/data.js') //静态数据库
,error_mod : __uri('../libs/error.js') //错误码库
,store_mod : __uri('../libs/store_json2.min.js') //本地存储库
,head_mod : __uri('../component/head/head.js') //头部
,foot_mod : __uri('../component/foot/foot.js') //脚部
,plugins_mod : __uri('../component/plugins/plugins.js') //扩展组件库
,tinyscrollbar_mod : __uri('../libs/tinyscrollbar.js') //滚动条插件
,popup_mod : __uri('../component/popup/popup.js') //弹出框
,pagination_mod : __uri('../component/pagination/pagination.js') //分页
,calendar_mod : __uri('../component/calendar/calendar.js') //日期组件
,rangePlugins_mod : __uri('../libs/jquery.range.js') //拖动选择组件
,mzoom_mod : __uri('../libs/magiczoomplus.js') //图片放大镜组件
/*入口文件*/
,index_main : __uri('../js/index.js') //首页
/*MOD文件*/
,index_mod : __uri('../js/index_mod.js') //首页
}
var cutJs = function(s)
{
return s.substring(0,s.length-3);
}
require.config(
{
baseUrl : "/",
paths: {
/*公共MOD文件*/
'jquery' : cutJs(_MOD_NAME.jqueryMod) //jquery
,'common_mod' : cutJs(_MOD_NAME.common_mod) //基本函数库
,'data_mod' : cutJs(_MOD_NAME.data_mod) //静态数据库
,'error_mod' : cutJs(_MOD_NAME.error_mod) //错误码库
,'store_mod' : cutJs(_MOD_NAME.store_mod) //本地存储库
,'head_mod' : cutJs(_MOD_NAME.head_mod) //头部
,'foot_mod' : cutJs(_MOD_NAME.foot_mod) //脚部
,'plugins_mod' : cutJs(_MOD_NAME.plugins_mod) //扩展组件库
,'tinyscrollbar_mod' : cutJs(_MOD_NAME.tinyscrollbar_mod) //滚动条插件
,'popup_mod' : cutJs(_MOD_NAME.popup_mod) //弹出框
,'pagination_mod' : cutJs(_MOD_NAME.pagination_mod) //分页
,'calendar_mod' : cutJs(_MOD_NAME.calendar_mod) //日期组件
,'rangePlugins_mod' : cutJs(_MOD_NAME.rangePlugins_mod) //拖动选择组件
,'mzoom_mod' : cutJs(_MOD_NAME.mzoom_mod) //图片放大镜组件
/*入口文件*/
,'index_main' : cutJs(_MOD_NAME.index_main) //首页
/*MOD文件*/
,'index_mod' : cutJs(_MOD_NAME.index_mod) //首页
},
waitSeconds : 0,
shim : {
'mzoom_mod':{
deps:[],
exports: 'mzoom_mod'
}
,'store_mod':{
deps:[],
exports: 'store_mod'
}
,'bannerPlugins_mod' : ['jquery']
,'rangePlugins_mod' : ['jquery']
,'tinyscrollbar_mod' : ['jquery']
}
});
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var express_1 = __importDefault(require("express"));
var cors_1 = __importDefault(require("cors"));
var dbRoutes_1 = __importDefault(require("./routes/dbRoutes"));
require("reflect-metadata");
var typeorm_1 = require("typeorm");
var app = (0, express_1.default)();
var port = 5005;
(0, typeorm_1.createConnection)();
// Middleware
app.use((0, cors_1.default)());
app.use(express_1.default.json());
app.use("/geolocate", dbRoutes_1.default);
app.listen(port, function () {
console.log("Server express escuchando en http://localhost:" + port);
});
|
'use strict';
var utils = require('../utils/writer.js');
var AccessToken = require('../service/AccessTokenService');
module.exports.usersAccessGET = function usersAccessGET (req, res, next, username) {
AccessToken.usersAccessGET(username)
.then(function (response) {
utils.writeJson(res, response);
})
.catch(function (response) {
utils.writeJson(res, response);
});
};
|
import {num, arr} from 'types';
export default function minLength(length) {
return function innerMinLength(data) {
return arr(data).length >= num(length);
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.