text stringlengths 7 3.69M |
|---|
import React, { useEffect } from 'react';
import { observer, inject } from "mobx-react";
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogTitle from '@material-ui/core/DialogTitle';
const DeleteReportDialog = inject("store")(
observer((props) => {
useEffect(() => {
const ENTER_KEY_CODE = 13
const enterSubmit = (e) => {
if (e.keyCode == ENTER_KEY_CODE) {
const submitBtn = document.getElementById("submit")
submitBtn.click()
}
}
window.addEventListener('keyup', enterSubmit)
return function cleanup() {
window.removeEventListener('keyup', enterSubmit)
}
}, [])
const handleClose = () => {
props.store.set(
"isDeleteReportOpen",
false
)
}
const handleReportDelete = async () => {
try {
const url = props.store.backendUrl
const reportId = props.store.deleteReport.id
const response = await fetch(
`${url}/reports/${reportId}`,
{
headers: {
'Authorization': `Bearer ${props.store.accessToken}`
},
method: "DELETE"
}
)
if (response.ok) {
const accessToken = response.headers.get(
"Authorization"
)
props.store.set(
"accessToken",
accessToken
)
props.store.set(
"snackbarMsg",
'신고 내역 삭제 성공'
)
props.store.set(
"snackbarInfoOpen",
true
)
const remained = props.store.myReports.filter(
(rep) => rep.id != props.store.deleteReport.id
)
props.store.set(
"myReports",
remained
)
} else {
props.store.set(
"snackbarMsg",
`신고내역 삭제 실패`
)
props.store.set(
"snackbarErrorOpen",
true
)
}
} catch (err) {
props.store.set(
"snackbarMsg",
`신고내역 삭제 실패`
)
props.store.set(
"snackbarErrorOpen",
true
)
}
handleClose()
}
return (
<div>
{props.store.isDeleteReportOpen &&
<Dialog
open={props.store.isDeleteReportOpen}
onClose={handleClose}
style={{
minWidth: 350
}}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{`신고 내역 삭제`}
</DialogTitle>
<div style={{
flex: "1 1 auto",
padding: "8px 24px",
overflowY: "auto",
}}>
<div style={{
fontSize: "1rem",
fontWeight: 400,
lineHeight: 1.5,
letterSpacing: "0.00938em",
margin: 0,
marginBottom: 12,
color: "rgba(0,0,0,0.84)"
}}>
<div>
{`👮♀️신고 도메인 : ${props.store.deleteReport.spam_domain}`}
</div>
<div style={{ marginTop: 10 }}>
{`✉️ 신고 제목 : ${props.store.deleteReport.title}`}
</div>
<div style={{ marginTop: 10 }}>
해당 신고 내역을 정말로 삭제하시겠습니까?
</div>
</div>
</div>
<DialogActions>
<Button
onClick={handleClose}
color="primary">
취소
</Button>
<Button
id="submit"
onClick={handleReportDelete}
color="primary"
autoFocus>
삭제
</Button>
</DialogActions>
</Dialog>}
</div>
);
}))
export default DeleteReportDialog;
|
const express = require('express');
const axios = require('axios');
//const Joi = require('joi');
//const uuid = require('uuid');
const router = express.Router();
const mongoose = require('mongoose')
const Job = require('../../models/Job')
const Partner = require('../../models/Partner')
const Member = require('../../models/Member')
const EduOrg = require('../../models/EducationalOrganization')
//const validator = require('../../validations/jobValidations')
router.use(express.json())
// We will be connecting using database
const Admin = require('../../models/Admin')
const validator = require('../../Validations/AdminValidations')
const passport = require('passport');//for auth trial
const funcs = require('../../fn');
//import axios from 'axios';
router.get('/',async (req,res) => {
const admins = await Admin.find()
res.json({data: admins})
})
// router.get('/:id', passport.authenticate('jwt', { session: false }),async(req, res) =>{
router.get('/:id', passport.authenticate('jwt', { session: false }),async(req, res) =>{
try {
const id = req.params.id
const admin = await Admin.findById(id)
if(!admin) return res.status(404).send({error: 'Admin does not exist'})
data = `Name: ${admin.full_name} Email: ${admin.email} Username: ${admin.username}`;
res.json(data)
}
catch(error) {
// We will be handling the error later
console.log(error)
}
// res.json({data: admin})
})
router.post('/', async (req,res) => {
try {
const isValidated = validator.createValidation(req.body)
if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const newAdmin = await Admin.create(req.body)
res.json({msg:'Admin was created successfully', data: newAdmin})
}
catch(error) {
// We will be handling the error later
console.log(error)
}
})
router.put('/:id',passport.authenticate('jwt', { session: false }), async (req,res) => {
try {
const signedin = req.user.id
const admin2=await Admin.findById(req.user.id )
console.log(admin2)
if(admin2){
const adminid = admin2.id
console.log(adminid)
console.log(req.params.id)
if(adminid===req.params.id || admin2.super==="yes"){
console.log('in')
// res.status(404).send({error: 'Unauthorized'})
const id = req.params.id
const admin = await Admin.findById(id)
const ID = {"_id":id}
if(!admin) return res.status(404).send({error: 'Admin does not exist'})
const isValidated = validator.updateValidation(req.body)
if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedAdmin = await Admin.findOneAndUpdate(ID,req.body)
res.json({msg: 'Admin updated successfully',data:updatedAdmin})
}
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
// We will be handling the error later
console.log(error)
}
})
router.delete('/:id',passport.authenticate('jwt', { session: false }), async (req,res) => {
try {
const signedin = req.user.id
const admin2=await Admin.findById(req.user.id )
if(admin2){
const adminid = admin2.id
console.log(adminid)
console.log(req.params.id)
if(adminid===req.params.id || admin2.super==="yes"){
console.log("in")
const id = req.params.id
const deletedAdmin = await Admin.findByIdAndRemove(id)
res.json({msg:'Admin was deleted successfully', data: deletedAdmin})
}
}
else
res.json({err: "Unauthorized"})
}
catch(error) {
// We will be handling the error later
console.log(error)
}
})
// as an admin i can get all pending jobs
router.get('/p/pendingjobs',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
// const signedin = req.user.id
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const jobs = await funcs.getJobs()
const jobspending =[]
for(var i=0;i<jobs.data.data.length;i++){
if(jobs.data.data[i].state==="pending")
jobspending.push(jobs.data.data[i])}
res.json({data: jobspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// approve or reject a pending job
router.put('/approverejectjob/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
console.log('in')
const id = req.params.id
const job = await Job.findById(id)
const ID = {"_id":id}
if(!job) return res.status(404).send({error: 'job does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedjob = await Job.findOneAndUpdate(ID,req.body)
res.json({msg: 'Job updated successfully',data:updatedjob})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// get pending registered partners
router.get('/p/pendingpartners',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const partners = await funcs.getPartners()
const partnerspending =[]
for(var i=0;i<partners.data.data.length;i++){
if(partners.data.data[i].registered==="no")
partnerspending.push(partners.data.data[i])}
res.json({data: partnerspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// get pending members to register
router.get('/p/pendingmembers',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const members = await funcs.getMembers()
const memberspending =[]
for(var i=0;i<members.data.data.length;i++){
if(members.data.data[i].registered==="no")
memberspending.push(members.data.data[i])}
res.json({data: memberspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// get pending eduorg to register
router.get('/p/pendingeduorg',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const eduorgs = await funcs.getEduOrg()
const eduorgspending =[]
for(var i=0;i<eduorgs.data.data.length;i++){
if(eduorgs.data.data[i].registered==="no")
eduorgspending.push(eduorgs.data.data[i])}
res.json({data: eduorgspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// approve or reject a pending partner
router.put('/arpartner/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const partner = await Partner.findById(id)
const ID = {"_id":id}
if(!partner) return res.status(404).send({error: 'job does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedpartner = await Partner.findOneAndUpdate(ID,req.body)
res.json({msg: 'Job updated successfully',data:updatedpartner})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// approve or reject a pending partner
router.put('/armember/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const member = await Member.findById(id)
const ID = {"_id":id}
if(!member) return res.status(404).send({error: 'member does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedmember = await Member.findOneAndUpdate(ID,req.body)
res.json({msg: 'Member updated successfully',data:updatedmember})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// get pending eduorg to register
router.get('/p/pendingeduorg',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const eduorgs = await funcs.getEduOrg()
const eduorgspending =[]
for(var i=0;i<eduorgs.data.data.length;i++){
if(eduorgs.data.data[i].registered==="no")
eduorgspending.push(eduorgs.data.data[i])}
res.json({data: eduorgspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// get pending admins approved by super admin to register
router.get('/p/pendingadmins',passport.authenticate('jwt', { session: false }), async (req,res) => {
try{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const admins = await funcs.getAdmins()
const adminspending =[]
for(var i=0;i<admins.data.data.length;i++){
if(admins.data.data[i].registered==="no" && admins.data.data[i].super!=="yes")
adminspending.push(admins.data.data[i])}
res.json({data: adminspending})
}
else
res.status(404).send({error: 'Unauthorized'})
}
catch(error) {
console.log(error)
}
//res.json({data: jobs})}
})
// approve or reject a pending partner
router.put('/arpartner/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const partner = await Partner.findById(id)
const ID = {"_id":id}
if(!partner) return res.status(404).send({error: 'job does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedpartner = await Partner.findOneAndUpdate(ID,req.body)
res.json({msg: 'Job updated successfully',data:updatedpartner})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// approve or reject a pending partner
router.put('/armember/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const member = await Member.findById(id)
const ID = {"_id":id}
if(!member) return res.status(404).send({error: 'member does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedmember = await Member.findOneAndUpdate(ID,req.body)
res.json({msg: 'Member updated successfully',data:updatedmember})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// approve or reject a pending eduorg
router.put('/areduorg/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const eduorg = await EduOrg.findById(id)
const ID = {"_id":id}
if(!eduorg) return res.status(404).send({error: 'EduOrg does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatededuorg = await EduOrg.findOneAndUpdate(ID,req.body)
res.json({msg: 'EduOrg updated successfully',data:updatededuorg})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// approve or reject a pending eduorg
router.put('/aradmins/:id',passport.authenticate('jwt', { session: false }),async(req,res)=>{
const admin2=await Admin.findById(req.user.id )
//console.log(admin2)
if(admin2){
const id = req.params.id
const admin = await Admin.findById(id)
const ID = {"_id":id}
if(!admin) return res.status(404).send({error: 'Admin does not exist'})
//const isValidated = validator.updateValidation(req.body)
//if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedadmin = await Admin.findOneAndUpdate(ID,req.body)
res.json({msg: 'Admin updated successfully',data:updatedadmin})
}
else
res.status(404).send({error: 'Unauthorized'})
}
)
// router.put('/approverejectjob/:id', async (req,res) => {
// // const isValidated = validator.updateValidation(req.body)
// // if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
// // else{
// const job= await Job.findByIdAndUpdate(req.params._id, req.body)
// .exec()
// .then(r => {return res.json({data:job})
// .catch(err => {console.log(err); return res.status(400).send("No job found for provided ID") })
// }
// reject a pending job
// router.put('/rejectjob/:id',async(req,res)=>{
// const id = req.params.id
// const job = await Job.findById(id)
// const ID = {"_id":id}
// if(!job) return res.status(404).send({error: 'job does not exist'})
// //const isValidated = validator.updateValidation(req.body)
// //if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
// const updatedjob = await Job.findOneAndUpdate(ID,req.body)
// res.json({msg: 'Job updated successfully',data:updatedjob})
// })
module.exports = router;
|
import React, { Component } from 'react';
import Header from './Header';
class WhyAnniesPortal extends Component {
state = { }
render() {
return (
<div>
<Header></Header>
This is because..
</div>
);
}
}
export default WhyAnniesPortal;
//11.am on Friday CDT |
import Vue from "vue";
import Vuex from "vuex";
import state from "./states";
import actions from "./actions";
import mutations from "./mutations";
import home from "./module/home.js";
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions,
modules: {
home
}
});
|
(function(exports) {
const CHOOSERS = {
tenseName: TENSE_NAME_CHOOSER,
tenseSignum: TENSE_SIGNUM_CHOOSER,
verb: null,
noun1: null,
noun2: null,
noun2Signum: null
};
function initialize() {
$.get('/sententiae_images', function(images) {
Object.keys(images).forEach(function(category) {
if (VOCAB_CATEGORIES[category]) {
VOCAB_CATEGORIES[category].nounChooser = new Collection(images[category]);
}
});
setVocabChoosers();
chooseItemsWithVerb();
$('#sententiae').show()
$('#with-verb-button,#with-signa-button').attr('disabled', false);
});
}
function chooseItemsWithVerb() {
_setVerbText(CHOOSERS.verb.chooseRandom());
_setTenseText(CHOOSERS.tenseName.chooseRandom());
_setNounImages(
CHOOSERS.noun1.chooseRandom(),
CHOOSERS.noun2.chooseRandom()
);
}
function chooseItemsWithSigna() {
_setVerbText('');
_setTenseText(CHOOSERS.tenseSignum.chooseRandom(), true);
_setNounImages(
CHOOSERS.noun1.chooseRandom(),
CHOOSERS.noun2.chooseRandom(),
CHOOSERS.noun2Signum.chooseRandom()
);
}
function setVocabChoosers() {
const noun1Category = document.getElementById('noun1-select').value;
const noun2Category = document.getElementById('noun2-select').value;
CHOOSERS.noun1 = VOCAB_CATEGORIES[noun1Category].nounChooser;
CHOOSERS.noun2 = VOCAB_CATEGORIES[noun2Category].nounChooser;
CHOOSERS.noun2Signum = VOCAB_CATEGORIES[noun2Category].objectSignumChooser;
CHOOSERS.verb = VOCAB_CATEGORIES[noun2Category].verbChooser;
}
function _setVerbText(text) {
document.getElementById('verb').innerHTML = text;
}
function _setTenseText(text, isSignum) {
if (isSignum) {
$('#tense').html(text).addClass('text-signum Info-tense--signum');
} else {
$('#tense').html(text).removeClass('text-signum Info-tense--signum');
}
}
function _setNounImages(noun1Src, noun2Src, noun2Signum) {
document.getElementById('noun1').src = noun1Src;
document.getElementById('noun2').src = noun2Src;
document.getElementById('noun1-label').innerHTML = _getImageName(noun1Src);
document.getElementById('noun2-label').innerHTML = _getImageName(noun2Src);
document.getElementById('noun1-signum').innerHTML = noun2Signum ? SUBJECT_SIGNUM : '';
document.getElementById('noun2-signum').innerHTML = noun2Signum || '';
}
function _getImageName(path) {
return path.match(/\/([^/]+)\.(png|jpg|gif|svg)/)[1].replace(/-/g, ' ');
}
exports.initialize = initialize;
exports.chooseItemsWithVerb = chooseItemsWithVerb;
exports.chooseItemsWithSigna = chooseItemsWithSigna;
exports.setVocabChoosers = setVocabChoosers;
})(this);
|
toastr.options.progressBar = true;
toastr.options.preventDuplicates = true;
toastr.options.closeButton = true;
displayUpcomingTask();
displayInProgress();
$.widget.bridge('uibutton', $.ui.button);
$('[data-toggle="popover"]').popover();
function checkID(value) {
toastr.error(value);
}
$(document).ready(function() {
setInterval(timestamp, 1000);
});
function timestamp() {
$.ajax({
url: 'admin/timestamp.php',
success: function(data) {
$('#timestamp').html(data);
},
});
}
function addTask() {
$(".modal").modal("hide");
w3.show('#logoloader');
taskname = $("#inputTaskName").val();
clientname = $("#inputClientID").val();
notes = $("#inputNotes").val();
agent = $("#inputAgentID").val();
subtask = $("#subTasks").val();
tasktype= $("#inputTaskType").val();
// duedate = document.getElementById("inputDueDate").value;
$.ajax({
type: 'get',
url: './main.php',
data: {
taskname: taskname,
clientname: clientname,
notes: notes,
agent: agent,
// duedate: duedate,
subtask: subtask,
tasktype:tasktype
},
success: function (response) {
if (response.match("Task Created!")=='Task Created!') {
toastr.success(response);
document.getElementById("addTaskForm").reset();
displayUpcomingTask();
countProgress();
countUpcoming();
}
else {
toastr.error(response);
}
w3.hide('#logoloader');
}
});
return false;
}
function displayUpcomingTask() {
let content = '';
$.ajax({
type: 'get',
url: './main.php',
data: {
displayUpcoming: true,
tasktype_id:localStorage.getItem("tasktype_id")
},
success: function (response) {
if (response == '') {
$("#upcoming ul").html(content);
return false;
}
result = JSON.parse(response);
$.each(result, function (key, item) {
let str = JSON.stringify(item);
content += `<li class="task-warning ui-sortable-handle">
<!--
<div class="float-right">
<p class="" id="duedate">Due Date: <b>`+ item.DueDate + `</b></p>
</div> -->
<b>`+ item.TaskName + `</b>
<div class="clearfix"></div>
`+ nl2br(item.Notes) + `
<div class="mt-3">
<!-- <p class="mb-1">Employee:
<span><i>`+ item.name + `</i></span>
</p> -->
<p class="float-right">
<button class="btn btn-success btn-sm waves-effect waves-light" onclick='taskInfo(`+ str + `)' data-toggle="modal" data-target=".bd-example-modal-lg" ><i class="fas fa-eye"></i></button>
</p>
<p class="mb-2">Client:
<span><i>`+ item.client_name + `</i></span>
</p>
</div>
</li>`;
});
$("#upcoming ul").html(content);
}
});
return false;
}
function displayInProgress() {
let content = '';
$.ajax({
type: 'get',
url: './main.php',
data: {
displayProgress: true,
tasktype_id: localStorage.getItem("tasktype_id")
},
success: function (response) {
if (response == "") {
$("#inProgress ul").html(content);
return false;
}
result = JSON.parse(response);
$.each(result, function (key, item) {
let str = JSON.stringify(item);
content += `<li class="task-warning ui-sortable-handle" id="task1">
<!-- <div class="float-right">
<p class="" id="duedate">Due Date: <b>January 01, 2021</b></p>
</div> -->
<b>`+ item.TaskName + `</b>
<div class="clearfix"></div>
`+ nl2br(item.Notes) + `
<div class="mt-3">
<p class="float-right">
<button class="btn btn-success btn-sm waves-effect waves-light" onclick='taskInfo(`+ str + `)' data-toggle="modal" data-target=".bd-example-modal-lg" ><i class="fas fa-eye"></i></button>
</p>
<p class="mb-2">Client:
<span><i>`+ item.client_name + `</i></span>
</p>
</div>
</li>`;
});
$("#inProgress ul").html(content);
}
});
return false;
}
function taskInfo(data) {
w3.show('#logoloader');
if (data.total_time == null) {
data.total_time = '';
}
if (data.DateStarted == null) {
$("#btnPause").prop('disabled', true);
$("#btnStop").prop('disabled', true);
$("#btnFinish").prop('disabled', true);
} else {
if ($('#btnPlay').prop('disabled')) {
$("#modalStatus").html("Running");
} else {
$("#modalStatus").html("Paused");
}
}
$("#countUpcoming1").html(data.TaskName);
setButtonForProgress(data.callback_id);
$("#btnPlay").val(data.callback_id);
$("#btnPause").val(data.callback_id);
$("#btnStop").val(data.callback_id);
$("#btnDelete").val(data.callback_id);
$("#btnFinish").val(data.callback_id);
$("#btnSave").val(data.callback_id);
$("#inputDescription2").val(data.Notes);
$("#modalTaskName").html(data.TaskName);
$("#viewTaskName").val(data.TaskName);
$("#modalStartDate").html(data.DateStarted == null ? "---" : data.DateStarted);
$("#modalEndDate").html(data.DateEnded == null ? "---" : data.DateEnded);
$("#modalTimeSpent").html(data.total_time == "" ? "---" : data.total_time);
$("#inputSubTasks").val(data.sub_task);
$("#inputComments").val(data.comments);
$("#modalAgent").html(data.name);
$("#modalClient").html(data.client_name);
$("#modalDueDate").html(data.DueDate);
$("#viewTaskType").val(data.tasktype_id);
setInputClientView(data.tasktype_id);
$("#viewEmployee").val(data.user_id);
w3.hide('#logoloader');
}
function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function setButtonForProgress(cb_id) {
$.ajax({
type: 'get',
url: './main.php',
data: {
getTimeStatus: true,
cb_id: cb_id
},
success: function (response) {
if (response == '') {
$("#btnPlay").prop('disabled', false);
return false;
}
result = JSON.parse(response);
if (result.status == 1) {
$("#btnPlay").prop('disabled', false);
$("#btnPause").prop('disabled', true);
$("#btnStop").prop('disabled', true);
} else {
$("#btnPlay").prop('disabled', true);
$("#btnPause").prop('disabled', false);
$("#btnStop").prop('disabled', false);
$("#btnFinish").prop('disabled', false);
}
}
});
}
$("#btnPlay").click(function () {
$(".modal").modal("hide");
w3.show('#logoloader');
$.ajax({
type: 'get',
url: './main.php',
data: {
btnPlay: true,
cb_id: this.value,
},
success: function (response) {
if (response == 'updated') {
toastr.success("Task started");
displayInProgress();
displayUpcomingTask();
countUpcoming();
countProgress();
totalHoursToday();
} else {
toastr.error("There was an error!");
}
w3.hide('#logoloader');
}
});
});
$("#btnPause").click(function () {
$(".modal").modal("hide");
w3.show('#logoloader');
$.ajax({
type: 'get',
url: './main.php',
data: {
btnPause: true,
cb_id: this.value,
},
success: function (response) {
if (response == 'updated') {
toastr.success("Task Paused");
displayInProgress();
displayUpcomingTask();
countUpcoming();
countProgress();
totalHoursToday();
} else {
toastr.error("There was an error!");
}
w3.hide('#logoloader');
}
});
});
$("#btnStop").click(function () {
if (confirm("Are you sure you want to stop and reset this task?")) {
$(".modal").modal("hide");
w3.show('#logoloader');
$.ajax({
type: 'get',
url: './main.php',
data: {
btnStop: true,
cb_id: this.value,
},
success: function (response) {
if (response == 'stopped') {
$(".modal").modal("hide");
toastr.success("Task Stopped");
displayInProgress();
displayUpcomingTask();
countUpcoming();
countProgress();
totalHoursToday();
} else {
toastr.error("There was an error!");
}
w3.hide('#logoloader');
}
});
}
});
$("#btnDelete").click(function () {
if (confirm("Are you sure you want to delete this task?")) {
$(".modal").modal("hide");
w3.show('#logoloader');
$.ajax({
type: 'get',
url: './main.php',
data: {
btnDelete: true,
cb_id: this.value,
},
success: function (response) {
if (response == 'deleted') {
$(".modal").modal("hide");
toastr.success("Task Deleted");
displayInProgress();
displayUpcomingTask();
} else {
toastr.error("There was an error!");
}
w3.hide('#logoloader');
}
});
}
});
$("#btnFinish").click(function () {
$(".modal").modal("hide");
w3.show('#logoloader');
$.ajax({
type: 'get',
url: './main.php',
data: {
btnFinish: true,
cb_id: this.value,
},
success: function (response) {
if (response == 'updated') {
$(".modal").modal("hide");
toastr.success("Task Finish!");
displayInProgress();
displayUpcomingTask();
} else {
toastr.error(response);
}
w3.hide('#logoloader');
}
});
});
$("#btnSave").click(function () {
$(".modal").modal("hide");
w3.show('#logoloader');
notes = $("#inputDescription2").val();
subtask = $("#inputSubTasks").val();
comments = $("#inputComments").val();
taskname = $("#viewTaskName").val();
tasktype = $("#viewTaskType").val();
client = $("#viewClient").val();
employee = $("#viewEmployee").val();
DateStarted = $("#modalStartDate").val();
$.ajax({
type: 'post',
url: './main.php',
data: {
btnSave: true,
cb_id: this.value,
notes: notes,
subtask: subtask,
comments: comments,
taskname: taskname,
DateStarted : DateStarted,
tasktype: tasktype,
client: client,
employee: employee,
},
success: function (response) {
if (response == 'updated') {
toastr.success("Task Saved!");
displayInProgress();
displayUpcomingTask();
} else {
toastr.error(response);
}
w3.hide('#logoloader');
}
});
return false;
});
/*
function countUpcoming(){
$.ajax({
success: function(data) {
var rowCount = $('#upcoming').html(data).find('ul').length;
$("#countUpcoming").val(rowCount);
}
});
*/
countProgress();
function countProgress() {
$.ajax({
url: './main.php',
type: 'get',
data:{
countProgress: true
},
success: function(data) {
let str = data.replace(/""/g, "");
$('#countProgress').html(str);
},
});
}
countUpcoming();
function countUpcoming() {
$.ajax({
url: './main.php',
type: 'get',
data:{
countUpcoming: true
},
success: function(data) {
let str = data.replace(/""/g, "");
$('#countUpcoming').html(str);
},
});
}
totalHoursToday();
function totalHoursToday() {
$.ajax({
url: './main.php',
type: 'get',
data:{
totalHoursToday: true
},
success: function(data) {
$("#totalHoursToday").html(data == null ? "00:00:00" : data);
},
});
}
|
var name = "World!";
(function () {
if (typeof name === "undefined") {
var name = "Mr. Bond";
alert("Goodbye, " + name);
} else {
alert("Hello, " + name);
}
})(); |
import createReducer from 'rdx/utils/create-reducer';
import types from 'rdx/modules/plugins/types';
export default {
plugins: createReducer({}, {
[types.REGISTER](state, action) {
const pluginsByRoles = { ...state };
if (!Array.isArray(action.payload)) {
return state;
}
action.payload.forEach((plugin) => {
const { role } = plugin;
if (role) {
if (!pluginsByRoles[role]) {
pluginsByRoles[role] = [];
}
pluginsByRoles[role].push(plugin);
}
});
return pluginsByRoles;
},
}),
};
|
const banner = [{
name: 'Graph',
path: 'graph'
}, {
name: 'Screen',
path: 'screen'
}, {
name: 'HostGroups',
path: 'portal'
}, {
name: 'Template',
path: 'template'
}, {
name: 'Expression',
path: 'expression'
}, {
name: 'Nodata',
path: 'nodata'
}, {
name: 'Alarm-Dashboard',
path: 'alarm'
}];
export default banner;
|
import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import Home from './Home';
import CreateAccount from './CreateAccount';
import Error from './Error';
import Navigation from './Navigation';
import Login from './Login';
// Bootstrap Core CSS
import '.././css/VendSpec/vendor/bootstrap/css/bootstrap.min.css';
//Custom Fonts
import ".././css/VendSpec/vendor/fontawesome-free/css/all.min.css";
//import "https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic";
import ".././css/VendSpec/vendor/simple-line-icons/css/simple-line-icons.css";
//Custom CSS
import ".././css/VendSpec/css/style.min.css";
import ".././css/VendSpec/css/custom.css";
class App extends React.Component{
constructor(props){
super(props);
this.loggedin = true;
this.state = { loggedin: this.loggedin };
this.divVisible = this.divVisible.bind(this);
}
divVisible = () => {
const {loggedin} = this.state;
this.setState({loggedin : !loggedin})
}
render(){
return(
<Router>
<Navigation />
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/createAccount" component={CreateAccount} />
<Route exact component={Error}/>
</Router>
);
}
}
export default App;
|
import React from "react";
/*
pegar os dados da api -- endpoint para buscar.
*/
export const TokenPost = () => {
const [username, setUsername] = React.useState("");
const [password, setPassword] = React.useState("");
//exibir na tela
const [token, setToken] = React.useState("");
function handleSubmit(e) {
e.preventDefault();
//por padrão o fetch é um get, pra ser um post, deve-se passar as informações dps da vírgula
fetch("https://dogsapi.origamid.dev/json/jwt-auth/v1/token", {
method: "POST",
//só coloca o header pra n dar erro
headers: {
"Content-type": "application/json",
},
//aq a gente passa o objeto com os dados
//esse método pega qualquer objeto e converte numa string
body: JSON.stringify({
username,
password,
}),
})
.then((resp) => {
console.log(resp);
return resp.json();
})
.then((json) => {
console.log(json);
setToken(json.token)
return json;
});
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
placeholder="insiria o seu nome"
onChange={({ target }) => setUsername(target.value)}
/>
<input
type="text"
value={password}
placeholder="insiria a senha"
onChange={({ target }) => setPassword(target.value)}
/>
<button>Enviar</button>
<p>{token}</p>
</form>
);
};
|
import dotenv from 'dotenv'
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import authRouter from './routes/auth';
import registerRouter from './routes/register';
import userRouter from './routes/user';
import staffRouter from './routes/staff';
import { requireAuthentication } from './helpers/functions'
import CrossDomain from './routes/crossDomain'
const env = dotenv.config({path: '.env.local'});
if (env.error) {
throw env.error
}
console.log('ENV LOADED:', env.parsed);
const app = express();
const port = process.env.PORT || 5656;
// Connecting to the database
const dbAddr = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}`;
mongoose.set('useCreateIndex', true);
const db = mongoose.connect(dbAddr, { useNewUrlParser: true })
.then(res => console.log("CONNECTED to MongoDB"))
.catch((err) => console.log("CAN'T CONNECT to MongoDB"));
// setting body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(CrossDomain);
// API routes
app.use('/auth', authRouter);
app.use('/register', registerRouter);
app.all('/api/*', requireAuthentication);
app.use('/api/user', userRouter);
app.use('/api/staff', staffRouter);
// Running the server
app.listen(port, () => {
console.log(`API RUNS ON: http://localhost:${port}`);
})
|
var table = document.getElementById('listContainer_databody')
var names_List = [
'LastName, FirstName 1',
'LastName, FirstName 2',
'LastName, FirstName 3',
'LastName, FirstName 4',
'LastName, FirstName 5'
]
var i=0
for (var row_c = 0, num_r = table.rows.length; row_c < num_r; row_c++) {
var row = table.rows[row_c]
for (var col_c = 0, num_c = row.cells.length; col_c < num_c ; col_c++) {
if (col_c == 1) {
var textToSearch = (row.cells[col_c].innerHTML).toString()
var currentName = textToSearch.substr(0, textToSearch.indexOf(' <input'))
if(currentName === names_List[i]) {
var firstCell = row.cells[0]
var checkBox = firstCell.children[0].children[0]
checkBox.click()
i++
}
}
}
}
document.getElementById('bottom_Submit').click();
|
const items = require('../models/items');
module.exports = {
addItems(req, res){
console.log('test masuk', req.body)
items.create({
item_name: req.body.name,
item_img: req.body.img,
item_price: req.body.price,
})
.then(function(response){
res.status(200).json({
message: 'success',
response: response,
})
})
.catch(function(err){
res.status(500).json({
message: err,
})
})
},
updateItems(req, res){
items.bulkWrite([{
updateOne: {
filter: {
'_id': req.params.id,
},
update: {
item_name: req.body.name,
item_img: req.body.img,
item_price: req.body.price,
}
}
}])
.then(function(response){
res.status(200).json({
message: 'success update data',
response: response
})
})
.catch(function(err){
res.status(500).json({
message: 'Something went wrong when updating the data!',
err: err
})
})
},
deleteItems(req, res){
items.bulkWrite([{
deleteOne:{
filter:{
'_id': req.params.id
}
}
}])
.then(function(result){
res.status(200).json({
message: 'Success delete data',
result: result
})
})
.catch(function(err){
res.status(500).json({
message: 'Something went wrong deleting item data!',
err: err,
})
})
},
getItems(req, res){
items.find({})
.then(function(itemData){
res.status(200).json({
message: 'Successfully get all items',
data: itemData
})
})
.catch(function(err){
res.status(500).json({
message: err
})
})
},
uploadImg(req, res){
res.json({
message: 'Successfully upload',
link: req.file.cloudStoragePublicUrl
})
}
} |
$(document).ready(function(){
});
function warningMsg(title, msg){
popupAlert({
isClose:false,
title:title,
msg: msg,
mainClass: 'mfp-slide-bottom',
popAlertBtn:
[
{
"text" : "Close",
"cb": function()
{
$.magnificPopup.close();
}
}
]
});
}
function loadServer(url, data, callback){
$.ajax({
cache : false,
url : url,
dataType : 'json',
type : 'post',
async : true,
data : data,
success : function( result ){
callback(result);
}
});
}
function showLoading(){
$(".loading").show();
}
function hideLoading(){
$(".loading").hide();
}
/*** Detail page ***/
/******************************
Copy lang button function
******************************/
function copyLang(from_lang, to_lang, no){
if (confirm(js_lang[from_lang] + " > " + js_lang[to_lang] + "?")){
if (lang_fields[no] != undefined){
for (i=0; i<lang_fields[no].length;i++){
field_name = lang_fields[no][i];
from_field_name = field_name + "_" + from_lang;
to_field_name = field_name + "_" + to_lang;
from_field_obj = $("#"+from_field_name);
to_field_obj = $("#"+to_field_name);
if (from_field_obj.length > 0 && to_field_obj.length > 0){
if (from_field_obj.is('select')){
to_field_obj.val(from_field_obj.val());
}else if (from_field_obj.is('textarea')){
if (CKEDITOR.instances[from_field_name] != undefined){
CKEDITOR.instances[to_field_name].setData(CKEDITOR.instances[from_field_name].getData());
}else{
to_field_obj.val(from_field_obj.val());
}
}else if (from_field_obj.is('input')){
if (from_field_obj.attr("type") == "checkbox"){
to_field_obj.prop('checked', from_field_obj.prop('checked'));
}else{
to_field_obj.val(from_field_obj.val());
}
}
}
}
}
warningMsg(js_lang["action"], js_lang["copy_success"]);
}
}
/*** Detail page ***/
/******************************
Resize Image
******************************/
function detectUploadPhoto(pID)
{
var _id = pID;
var _this = $('.rowUploadPhoto[data-id="'+_id+'"]');
var _img = _this.find('img');
var _imgWidth = _img.outerWidth(true);
var _imgHeight = _img.outerHeight(true);
if(_imgWidth > _imgHeight){
_img.removeClass('landscript').removeClass('vertical').addClass('landscript');
}else
{
_img.removeClass('landscript').removeClass('vertical').addClass('vertical');
}
}
/*** popup ***/
/******************************
POPUP
******************************/
function closePop(pTargetArray)
{
if(typeof pTargetArray == "undefined")
{
pTargetArray = new Array();
pTargetArray.push($('.popClose'));
}
var _targetArray = pTargetArray;
for(_i=0; _i<_targetArray.length; _i++)
{
_targetArray[_i].off().on('click',function(){
$.magnificPopup.close();
});
}
}
function popup(pTarget, config)
{
var _settings =
{
items:{
src: pTarget,
type: 'inline'
},
showCloseBtn: false,
closeOnBgClick: true,
mainClass: 'mfp-zoom-in',
fixedContentPos : true,
fixedBgPos : true,
removalDelay: 600,
closeMarkup : '<button title="%title%" class="mfp-close"></button>'
};
$.extend(_settings, config);
$.magnificPopup.open(_settings);
}
function popupAlert(setting, config)
{
var _preSet =
{
target : $('.alertPop'),
targetTitle : $('.alertPop .popAlertTitle h2'),
targetText : $('.alertPop .popAlertMessage p'),
targetBtn : $('.alertPop .popAlertBtnWrapper'),
title: "Title",
msg : "Text in here.",
isClose: false,
popAlertBtn:
[
{
"text" : "textA",
"cb": function()
{
alert("action for btnA");
}
},
{
"text" : "textB",
"cb": function()
{
alert("action for btnA");
}
}
]
}
//console.log(_preSet.popAlertBtn[1].callback);
//_preSet.popAlertBtn_a.callback();
$.extend(_preSet, setting);
var _settings =
{
mainClass: 'mfp-slide-bottom',
closeOnBgClick: _preSet.isClose,
callbacks:
{
open: function(){
_preSet.targetTitle.html(_preSet.title);
_preSet.targetText.html(_preSet.msg);
for(_i=0; _i<_preSet.popAlertBtn.length; _i++)
{
if(_i == _preSet.popAlertBtn.length-1)
{
_preSet.targetBtn.append('<button data-id="popBtn_'+_i+'" class="last" type="button" name="button">'+_preSet.popAlertBtn[_i].text+'</button>');
}else
{
_preSet.targetBtn.append('<button data-id="popBtn_'+_i+'" type="button" name="button">'+_preSet.popAlertBtn[_i].text+'</button>');
}
}
$('button[data-id="popBtn_0"]').on('click', function(){
_preSet.popAlertBtn[0].cb();
});
$('button[data-id="popBtn_1"]').on('click', function(){
_preSet.popAlertBtn[1].cb();
});
},
close: function(){
_preSet.targetTitle.html('');
_preSet.targetText.html('');
_preSet.targetBtn.html('');
}
}
};
$.extend(_settings, config);
popup(_preSet.target, _settings);
}
|
import { axisBottom, axisLeft } from 'd3-axis/src/axis';
const yAxis = (parent, {
yScale, tickCount, fontFamily, unxkcdify, stroke,
}) => {
parent
.append('g')
.call(
axisLeft(yScale)
.tickSize(1)
.tickPadding(10)
.ticks(tickCount, 's'),
);
parent.selectAll('.domain')
.attr('filter', !unxkcdify ? 'url(#xkcdify)' : null)
.style('stroke', stroke);
parent.selectAll('.tick > text')
.style('font-family', fontFamily)
.style('font-size', '16')
.style('fill', stroke);
};
const xAxis = (parent, {
xScale, tickCount, moveDown, fontFamily, unxkcdify, stroke,
}) => {
parent
.append('g')
.attr('transform', `translate(0,${moveDown})`)
.call(
axisBottom(xScale)
.tickSize(0)
.tickPadding(6)
.ticks(tickCount),
);
parent.selectAll('.domain')
.attr('filter', !unxkcdify ? 'url(#xkcdify)' : null)
.style('stroke', stroke);
parent.selectAll('.tick > text')
.style('font-family', fontFamily)
.style('font-size', '16')
.style('fill', stroke);
};
export default {
xAxis, yAxis,
};
|
import Script from '../../core/script';
import letterStandard from '../letterStandard/letterStandard';
class SpawnerScript extends Script {
constructor() {
super();
this.spawnSpeed = 20;
this.deltaSpawnSpeed = 60000 / this.spawnSpeed;
this.nextSpawn = Date.now() + 1200;
}
update() {
if (this.nextSpawn < Date.now()) {
this.nextSpawn = Date.now() + this.deltaSpawnSpeed;
let letter = this.newObject(letterStandard(5));
letter.setPosition(1000, 800);
letter.render.setZIndex(50);
let spawnLetter = new CustomEvent('spawnLetter',
{'detail': {
'letter': letter
}
});
document.dispatchEvent(spawnLetter);
}
}
}
export default SpawnerScript;
|
import Api from '@/config/api'
import Tool from './tool.js'
import { Loading, MessageBox } from 'element-ui'
/**
* 生产环境代码
*/
const Prod = {}
/**
* [请求:初始数据]
*/
Prod.A_submitDividingGanttSummary = function (state, commit) {
const { item_id = '2c9f10b676d559730176d68dbdcb018c', plant_order_id = '2c9f10b676d559730176daa5e0cf03b2' } = JSON.parse(localStorage.getItem('NOVA_orderItemNodeFrom') || '{}')
const name = '初始数据'
const obj = { item_id, type: 3, plant_order_id }
const suc = function (res) {
const { data, msg, status } = res
if (String(status) === '0') {
// eslint-disable-next-line
MessageBox({ title: '数据异常', message: msg, type: 'warning', closeOnClickModal: false, closeOnPressEscape: false, callback() { dg.close() } })
} else {
// console.log('初始数据 ----- ', res)
// localStorage.setItem('提报工厂甘特表', JSON.stringify(res))
//
const { ganttTemplate, itemSummaryItemData, itemSummaryDataList, nodeData, startEndDateMap, divdingData, p_item_gantt_id } = data
const { returnTopData, order_time, deliver_date, qcArr } = Tool.returnTopData(itemSummaryItemData)
state.ganttTemplate = ganttTemplate || [] // 模板信息
state.itemSummaryItemData = returnTopData // 顶部数据
state.order_time = order_time // 下单时间
state.deliver_date = deliver_date // 交货日期
state.nodeData = Tool.concatNodeData({}, nodeData) || {} // 表头信息
state.startEndDateMap = startEndDateMap || {} // 基础节点日期
state.itemSummaryDataList = itemSummaryDataList || [] // 旧数据
state.divdingData = divdingData // 新数据
state.qcArr = qcArr // QC岗位人员信息
state.p_item_gantt_id = p_item_gantt_id // 主线甘特表id
//
/** 复制:新模板数据 **/
state.copyNewData = Tool.copyNewTemplateData(divdingData.nodeTempleteDetail)
/** 返回:表格数据 **/
commit('returnTableData')
}
}
const err = function () {
// eslint-disable-next-line
MessageBox({ title: '加载失败,请重试', message: '', type: 'warning', closeOnClickModal: false, closeOnPressEscape: false, callback() { dg.close() } })
}
Api({ name, obj, suc, err, loading: '数据加载中...' })
}
/**
* [请求:模板明细]
*/
Prod.A_getNodeTempleteDetail = function (state, commit) {
const { activeTemplateId } = state
/* 发起请求 */
const name = '模板明细'
const obj = { node_template_id: activeTemplateId }
const suc = function (res) {
const { nodeData } = state
/** 合并:表头信息 **/
state.nodeData = Tool.concatNodeData(nodeData, res.nodeData)
/** 覆盖:新数据 **/
state.divdingData.nodeTempleteDetail = Tool.newDataAddAttr(res.nodeTempleteDetailList)
/** 复制:新模板数据 **/
state.copyNewData = Tool.copyNewTemplateData(res.nodeTempleteDetailList)
/** 返回:表格数据 **/
commit('returnTableData')
}
const err = function () {
MessageBox({ title: '加载失败,请重试', message: '', type: 'warning', closeOnClickModal: false, closeOnPressEscape: false })
}
Api({ name, obj, suc, err, loading: '加载模板中...' })
}
/**
* [请求:提报]
*/
Prod.A_savePlantMterialGanttNode = function (state, getters, audit_status) {
const { activeTemplateId, startEndDateMap, p_item_gantt_id } = state
const { tableList } = getters
const { dataList, errorArr } = Tool.returnSubmitData(tableList, startEndDateMap, audit_status, p_item_gantt_id)
const { ganttType = 3, item_id = '2c915e107466aec50174674e8fb20000' } = JSON.parse(localStorage.getItem('NOVA_orderItemNodeFrom') || '{}')
if (errorArr.length) {
MessageBox.alert(`${errorArr.join('')}`, '请完善后再提交', {
dangerouslyUseHTMLString: true,
confirmButtonText: '确定'
})
} else {
/* 发起请求 */
const name = '提报'
const obj = { item_id, node_template_id: activeTemplateId, ganttType, dataList: JSON.stringify(dataList) }
const suc = function (res) {
Loading.service({ text: String(audit_status) === '1' ? '暂存成功' : '提交成功', spinner: 'el-icon-circle-check' })
setTimeout(() => {
// eslint-disable-next-line
dg.close()
}, 1000)
}
const err = function () {
MessageBox({ title: '提交失败,请重试', message: '', type: 'warning', closeOnClickModal: false, closeOnPressEscape: false })
}
Api({ name, obj, suc, err, loading: '提交中...' })
}
}
export default Prod
|
import { default as passport } from 'koa-passport'
export function init(app) { return app.use(passport.session()) }
|
angular.module('jobzz')
.controller('RegisterEmployeeCtrl', ['$scope', '$rootScope', '$http', '$location', 'intervalDateForCalendarsService',
function ($scope, $rootScope, $http, $location, intervalDateForCalendarsService) {
var dates = intervalDateForCalendarsService.getDates();
$scope.error = false;
$scope.errorMessage = "";
$scope.minDate = dates.minDate;
$scope.maxDate = dates.maxDate;
$scope.minDateExp = dates.minDateExp;
$scope.maxDateExp = dates.maxDateExp;
(function () {
var req = {
method: 'GET',
dataType: 'json',
url: '/register/get/jobs',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
$http(req).then(function (response) {
$scope.jobs = response.data.jobs;
});
})();
$scope.newAccount = function () {
if ($scope.employee.password === $scope.employee.repeatPassword) {
var req = {
method: 'POST',
dataType: 'json',
url: '/register/employee',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: $scope.employee
};
$http(req).then(function (response) {
if (response.data.isCreated) {
$rootScope.isCreated = true;
$location.path('/login').replace();
} else {
$scope.error = true;
$scope.errorMessage = $scope.employee.email + " already exist !";
}
}, function () {
$scope.error = true;
$scope.errorMessage = "A problem has happened during recording. Please try again.";
});
}
};
}]); |
function multiply(a, b){
return a*b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n){
return square(n, n);
}
printSquare(5);
//--------------------------
function foo(){
return foo();
}
foo();
//--------------------------
//Diagram
setTimeout(function(){
console.log('Here');
}, 500);
console.log('THere');
|
import { startGame } from './index'
class Hangman {
constructor(word, amountOfGuesses) {
this.word = word.toLowerCase().split('')
this.amountOfGuesses = amountOfGuesses
this.guessedLetters = []
this.status = 'playing'
}
get puzzle() {
let puzzle = ''
this.word.forEach(letter => {
if (this.guessedLetters.includes(letter) || letter === ' ') {
puzzle += letter
} else {
puzzle += '*'
}
})
return puzzle
}
guessLetter(guessedLetter) {
let guess = guessedLetter.toLowerCase()
const uniqueGuess = !this.guessedLetters.includes(guess)
const wrongGuess = !this.word.includes(guess)
if (this.status !== 'playing') {
return
}
if (uniqueGuess) {
this.guessedLetters = [...this.guessedLetters, guessedLetter]
}
if (uniqueGuess && wrongGuess) {
this.amountOfGuesses--
}
this.statusRecalculation()
}
get statusMessage() {
let status = this.status
if (status === 'playing') {
return `Guesses left: ${this.amountOfGuesses}`
} else if (status === 'failed') {
return `Nice try! The word was "${this.word.join('')}"`
} else if (status === 'finished') {
return 'Great work, you guessed the word'
}
}
display() {
let puzzle = this.puzzle.split('')
const body = document.querySelector('body')
const divElement = document.createElement('div')
const wordElement = document.createElement('div')
let messageElement = document.createElement('p')
const resetButton = document.createElement('button')
body.innerHTML = ''
body.appendChild(divElement)
wordElement.id = 'puzzle'
wordElement.className = 'puzzle'
puzzle.forEach((letter) => {
const letterEl = document.createElement('span')
letterEl.textContent = letter
wordElement.appendChild(letterEl)
})
divElement.appendChild(wordElement)
messageElement.id = 'guesses'
messageElement.textContent = this.statusMessage
divElement.appendChild(messageElement)
resetButton.className = 'button'
resetButton.textContent = 'Reset'
divElement.appendChild(resetButton)
resetButton.addEventListener('click', startGame)
}
statusRecalculation() {
let finished = true
let guesses = this.amountOfGuesses
this.word.forEach(letter => {
if (this.guessedLetters.includes(letter) || letter === ' ') {
} else {
finished = false
}
if (guesses === 0) {
this.status = 'failed'
} else if (finished) {
this.status = 'finished'
} else {
this.status = 'playing'
}
})
}
}
export { Hangman as default } |
/*jshint multistr: true */
var colorPickerCss = '\
@charset "utf-8";\
/*\
Copyright (c) 2010, Yahoo! Inc. All rights reserved.\
Code licensed under the BSD License:\
http://developer.yahoo.com/yui/license.html\
version: 3.1.1\
build: 47\
*/\
html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:\'\';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}\
\
/* clearfix */\
\
.fbox {\
zoom: 100%;\
}\
.fbox:after {\
content: "";\
clear: both;\
height: 0;\
display: block;\
visibility: hidden;\
}\
\
/* test */\
canvas {\
//margin-top:0;\
margin:0 !important;\
}\
\
/* tools */\
#toolstage {\
margin:auto;\
position:absolute;\
top:0;right:0;bottom:0;left:0;\
background-color:#ccc;\
height:100%;\
padding-right:166p;\
}\
\
#canvas_wrapper {\
position:relative;\
height:100%;\
}\
\
#sighting {\
position:absolute;\
margin:auto auto;\
top:0;right:0;bottom:0;left:0;\
width:5px;height:5px;\
}\
\
#sighting .hor {\
width:5px;height:1px;\
position:absolute;top:2px;left:0;\
background-color:#000000;\
}\
\
#sighting .ver {\
width:1px;height:5px;\
position:absolute;top:0px;left:2px;\
background-color:#000000;\
}\
\
#tools {\
position:absolute;\
bottom:10px;\
margin:0 auto;\
left:0px;\
right:0px;\
height:40px;\
width:240px;\
background:transparent;\
}\
\
#tools li.tools_base {\
display:block;\
width:36px;\
height:36px;\
margin:0;\
border:2px solid #666666;\
background-color:#525252;\
float:left;\
}\
\
#tools li.tools_base:hover {\
border:2px solid #ffaa00;\
background-color:#666666;\
}\
\
#tools li.tools_base.selected {\
border:2px solid #ffaa00;\
}\
\
#tool01>div {\
background-image:url("./files/images/tools01.png");\
background-position:0 0;\
}\
\
#tool02>div {\
background-image:url("./files/images/tools01.png");\
background-position:-36px 0px;\
}\
\
#tool03>div {\
background-image:url("./files/images/tools01.png");\
background-position:-72px 0px;\
}\
\
#tool04>div {\
background-image:url("./files/images/tools01.png");\
background-position:-108px 0px;\
}\
\
#tool05>div {\
background-image:url("./files/images/tools01.png");\
background-position:-144px 0px;\
}\
\
#tool06>div {\
background-image:url("./files/images/tools01.png");\
background-position:-180px 0px;\
}\
\
#tools li div.tools {\
display:block;\
margin:0;\
width:36px;\
height:36px;\
}\
\
#tools li.tools_base.selected {\
border-color:#ffaa00;\
}\
\
#cps {\
position:absolute;\
margin:0;\
left:0px;\
top:162px;\
height:80px;\
width:160px;\
padding: 0 3px 0 3px;\
background:transparent;\
}\
\
#cps li.tools_cp_base {\
display:block;\
width:36px;\
height:36px;\
margin:0;\
border:2px solid #666666;\
background:url("./files/images/cp_bg.gif") 0 0 repeat;\
float:left;\
}\
\
#cps li div.tools_cp {\
display:block;\
margin:0;\
width:36px;\
height:36px;\
background-color:#ffffff;\
}\
\
#cps li.tools_cp_base.selected {\
border-color:#ffaa00;\
}\
#panels {\
width:166px;\
background-color:#666;\
position:absolute;\
right:0;top:0;\
height:100%;\
}\
';
// Global variable which will be an interface for PlayCanvas
var colorPicker = {};
colorPicker.activeColor = [255, 255, 255, 255];
// playcanvasにどのツールがセレクトされたかを渡すためのグローバル変数
var selectedTool;
colorPicker.selectedTool = null;
// Create style element and append to head element
var style = document.createElement('style');
document.head.appendChild(style);
// Get asset from registry by id
style.innerHTML = colorPickerCss;
// set html elements
// canvas要素をターゲットに使うため取得
var canvas = $('#application-canvas');
// 消しゴムやマジック選択などのツール類定義
var tools = '<ul id="tools" class="fbox"><li class="tools_base" id="tool01" data-toolname="paint"><div class="tools"></div></li><li class="tools_base" id="tool02" data-toolname="addbox"><div class="tools"></div></li><li class="tools_base" id="tool03" data-toolname="erase"><div class="tools"></div></li><li class="tools_base" id="tool04" data-toolname="magickselect"><div class="tools"></div></li><li class="tools_base" id="tool05" data-toolname="spuit"><div class="tools"></div></li><li class="tools_base" id="tool06" data-toolname="rangeselect"><div class="tools"></div></li></ul>';
// 照準をツール類と一緒にしておく
tools += '<div id="sighting"><div class="hor"></div><div class="ver"></div></div>';
// カラーピッカーの色ボックスを定義
var cps = '<div id="panels"><ul id="cps" class="fbox"><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li><li class="tools_cp_base"><div class="tools_cp"></div></li></ul></div>';
// canvasの既存position指定を変更し外側を追従させたいdivでくるむ
canvas.css('position','relative').wrap( '<div id="toolstage" class="fbox"><div id="canvas_wrapper"></div></div>' );
// ツールと照準をDOMに追加
$('#canvas_wrapper').append(tools);
// 右側のツールランにdiv#panelsを追加し、カラーピッカーボックスも追加
$('#toolstage').append(cps);
resetScreenSize();
// ツール類がクリックされたら.selectedを付与してツール名を変数に格納
$('.tools').click(function(e) {
$('li.tools_base').removeClass('selected');
$(this).parent().addClass('selected');
colorPicker.selectedTool = $(this).parent().data('toolname');
//console.log(colorPicker.selectedTool);
});
// カラーボックスがクリックされたら.selectedをつけてカラーの値を変数に格納
$('.tools_cp').click(function(e) {
$('li.tools_cp_base').removeClass('selected');
$(this).parent().addClass('selected');
getMyColor($(this));
});
// カラーピッカーを生成(クリック前から生成するように変更予定)
$('.tools_cp').colorPicker({
renderCallback: function($elm, toggled) {
getMyColor($elm);
}
});
// run after window resize
var timer = false;
$(window).resize(function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = setTimeout(function() {
resetScreenSize();
}, 200);
});
function getMyColor(elm) {
var myColorCode = elm.css('background-color');
//console.log(myColorCode);
var arrColorCode = myColorCode.replace(/rgba\(/g,'').replace(/rgb\(/g,'').replace(/\)/g,'').replace(/ /g,'').split(',');
//console.log(arrColorCode);
if ( arrColorCode.length < 4 ) { arrColorCode[3] = 255; } else { arrColorCode[3] = Math.round( Number(arrColorCode[3]) * 255 ) ; }
arrColorCode[0] = Number(arrColorCode[0]);
arrColorCode[1] = Number(arrColorCode[1]);
arrColorCode[2] = Number(arrColorCode[2]);
//arrColorCode[3] = Number(arrColorCode[3]);
colorPicker.activeColor = arrColorCode;
//console.log(colorPicker.activeColor);
}
function resetScreenSize() {
$('#toolstage').css({
height: "100%",
width: $(document).height() / 480 * 640 + 166
});
$('#canvas_wrapper').css({
height: "100%",
width: $(document).height() / 480 * 640
});
//console.log($('canvas').width());
}
|
import React, { useState, useEffect } from "react";
import {
View,
Text,
Button,
StyleSheet,
Modal,
TextInput,
Image,
Alert,
} from "react-native";
import { useColorScheme } from "react-native-appearance";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useTheme } from "@react-navigation/native";
import { color } from "react-native-reanimated";
import { getChannels, storeChannels } from "../hooks/useChannels";
const EditChannelModal = ({ navigation }) => {
const channel = navigation.state.params.item;
const [title, setTitle] = useState(channel.title);
const [uri, setUri] = useState(channel.uri);
const [video_url, setVideo_url] = useState(channel.video_url);
const [channels, setChannels] = useState([]);
const { colors } = useTheme();
useEffect(() => {
getChannels().then((data) => {
setChannels(data);
});
}, []);
return (
<View
style={[
styles.view,
{ color: colors.text, backgroundColor: colors.card, marginTop: 10 },
]}
>
<Image
style={[styles.img]}
source={{
url: `https://s2.googleusercontent.com/s2/favicons?domain=${channel.uri}`,
}}
/>
<Text style={[styles.title, { color: colors.text }]}>{title}</Text>
<Text style={[styles.sub, { color: colors.text }]}>Title</Text>
<CustomInput value={title} onChangeText={setTitle} theme={colors} />
<Text style={[styles.sub, { color: colors.text }]}>Website url</Text>
<CustomInput value={uri} onChangeText={setUri} theme={colors} />
<Text style={[styles.sub, { color: colors.text }]}>Video url</Text>
<CustomInput
value={video_url}
onChangeText={setVideo_url}
theme={colors}
/>
<Button
style={{ width: 50, height: 30, margin: 10, alignSelf: "center" }}
title="Save"
onPress={() => {
let index = getIndex(channel, channels);
channels[index].title = title;
channels[index].uri = uri;
channels[index].video_url = video_url;
setChannels([...channels]);
storeChannels(channels)
.catch(() =>
Alert.alert("Something went wrong", "Could not edit channel")
)
.then(() =>
Alert.alert("Channel saved", "Channel saved succesfully")
);
navigation.navigate("Home");
}}
/>
</View>
);
};
const CustomInput = (props) => {
const { theme } = props;
return (
<View style={{ height: 45, margin: 3 }}>
<TextInput
{...props}
clearButtonMode="while-editing"
keyboardType="default"
returnKeyType="default"
autoCapitalize="none"
autoCorrect={false}
style={[
styles.input,
{ color: theme.text, backgroundColor: theme.background },
]}
/>
</View>
);
};
const getIndex = (item, cha) => {
let index = cha.findIndex((elem) => {
if (elem.uri === item.uri) return true;
});
return index;
};
EditChannelModal.navigationOptions = () => ({
mode: "modal",
title: "Channel",
headerLeft: () => null,
headerShown: true,
gestureEnabled: false,
});
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
},
view: {
margin: 10,
padding: 5,
borderRadius: 14,
},
img: {
width: 24,
height: 24,
alignSelf: "center",
margin: 10,
},
title: {
fontSize: 20,
alignSelf: "center",
padding: 5,
margin: 5,
},
sub: {
fontSize: 16,
padding: 5,
margin: 3,
},
input: {
flex: 1,
height: 40,
padding: 5,
margin: 5,
borderRadius: 8,
},
});
export default EditChannelModal;
|
import _regeneratorRuntime from 'babel-runtime/regenerator';
import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator';
import * as RxDatabase from './RxDatabase';
import * as RxSchema from './RxSchema';
import * as QueryChangeDetector from './QueryChangeDetector';
import PouchDB from './PouchDB';
/**
* create a database
* @param {string} prefix as databaseName for the storage (this can be the foldername)
* @param {Object} storageEngine any leveldown instance
* @param {String} password if the database contains encrypted fields
* @param {boolean} multiInstance if true, multiInstance-handling will be done
* @return {Promise<Database>}
*/
export var create = function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(args) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', RxDatabase.create(args));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function create(_x) {
return _ref.apply(this, arguments);
};
}();
export function plugin(mod) {
if (typeof mod === 'object' && mod['default']) mod = mod['default'];
PouchDB.plugin(mod);
}
export { RxSchema, PouchDB, QueryChangeDetector, RxDatabase }; |
/*!
* News - Hacker news and reddit in the CLI.
*
* Veselin Todorov <hi@vesln.com>
* MIT License.
*/
/**
* Module dependencies.
*/
var Redr = require('redr');
var optimist = require('optimist');
var path = require('path');
/**
* Readers.
*
* @type {Object}
*/
var readers = new Redr(path.join(__dirname, 'readers')).load();
/**
* Formatter.
*
* @type {Function}
*/
var Formatter = require('./formatter');
/**
* Default reader.
*
* @type {String}
*/
var defaults = 'hackernews';
/**
* Expose the start function.
*/
module.exports = function() {
/**
* Argv.
*
* @type {Object}
*/
var argv = optimist.argv;
/**
* The reader.
*
* @type {String}
*/
var reader = new readers.get[argv._[0] || defaults];
reader.get(function(err, data) {
if (err) throw err;
var formatter = new Formatter(data);
formatter.format(function(out) {
console.log(out);
})
});
}; |
tinymce.PluginManager.add('ninethemeShortcodes', function(ed, url) {
// Add a button that opens a window
ed.addButton('ninetheme_button', {
type: 'splitbutton',
text: '',
icon: 'emoticons',
tooltip: 'Ninetheme Shortcodes',
menu: [
{
text: 'Slider Item',
onclick: function() {
ed.insertContent('[appy_slider addclass=\"slide-current\" title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]\
[appy_slider title=\"your title\" img=\"image url\"]');
}
},
{
text: 'Services',
onclick: function() {
ed.insertContent('[services_container]\
[services_item title=\"your title\" context="Your Description" bckgrd="Item background" icon=\"iconimgurl\" serviceslink=\"linkhere\" serviceslinktitle=\"linktexthere\"]\
[services_item title=\"your title\" context="Your Description" bckgrd="Item background" icon=\"iconimgurl\" serviceslink=\"linkhere\" serviceslinktitle=\"linktexthere\"]\
[services_item title=\"your title\" context="Your Description" bckgrd="Item background" icon=\"iconimgurl\" serviceslink=\"linkhere\" serviceslinktitle=\"linktexthere\"]\
[services_item title=\"your title\" context="Your Description" bckgrd="Item background" icon=\"iconimgurl\" serviceslink=\"linkhere\" serviceslinktitle=\"linktexthere\"]\
[/services_container]');
}
},
{
text: 'Testiominal',
onclick: function() {
ed.insertContent('[testiominal_container]\
[testifirst_item classactive=\"active\" title=\"your title\" testid="test1" img=\"testiominalimgurl\" ]\
[testifirst_item title=\"your title\" testid="test2" img=\"testiominalimgurl\" ]\
[testifirst_item title=\"your title\" testid="test3" img=\"testiominalimgurl\" ]\
[testifirst_item title=\"your title\" testid="test4" img=\"testiominalimgurl\" ]\
[/testiominal_container]\
[testisecond_item testid="test1" display="block" usercontentx=\"user reviews\" name=\"customer name\" link="customerlink" linkname="customerlinkname" ]\
[testisecond_item testid="test2" display="none" usercontentx=\"user reviews\" name=\"customer name\" link="customerlink" linkname="customerlinkname" ]\
[testisecond_item testid="test3" display="none" usercontentx=\"user reviews\" name=\"customer name\" link="customerlink" linkname="customerlinkname" ]\
[testisecond_item testid="test4" display="none" usercontentx=\"user reviews\" name=\"customer name\" link="customerlink" linkname="customerlinkname" ]');
}
},
{
text: 'Download Section',
onclick: function() {
ed.insertContent('[download_container]\
[download_section logolink=\"Link to logo\" logoalt=\"Logo alt\" title=\"Download Popup Title\" downloadcontentx=\"Download Content\" downloadextracontentx=\"Download Extra Content\" button=\"Download it\"]\
[download_contact]\[/download_contact]
[download_social sociallink=\"Social link here\" socialicon=\"facebook\"]\
[download_social sociallink=\"Social link here\" socialicon=\"twitter\"]\
[download_social sociallink=\"Social link here\" socialicon=\"google\"]\
[download_social sociallink=\"Social link here\" socialicon=\"instagram\"]\
[download_copyright title=\"Site title\" copyright=\"Site copyright\"]\
[/download_container]');
}
},
{
text: 'Download Popup',
onclick: function() {
ed.insertContent('[download_popup title=\"Download Popup Title\" downloadcontentx=\"Download Popup Content\" link=\"Download Popup Link\" linkname=\"Download Popup Link Text\"]');
}
},
{
text: 'Buttons',
menu: [
{
text: 'Button With Icon',
onclick: function() {
ed.insertContent('[button context=\"Download CV\" icon=\"download\" link=\"#\"]');
}
},
{
text: 'Button More',
onclick: function() {
ed.insertContent('[button_more context=\"Show More\" link=\"#\"]');
}
},
]
}
],
});
}); |
module.exports.getAll = function (req, res) {
return res.status(200).json({ status: 'Test getAll' });
}
module.exports.create = function (req, res) {
res.status(200).json({ status: 'Test create' });
} |
define(function () {
var hash = {};
return {
getUniqueId: function () {
return Math.ceil(Math.random() * Math.pow(2, 53));
},
byId: function (id) {
return hash[id];
},
add: function (widget) {
hash[widget.id] = widget;
},
remove: function (id) {
if (hash[id]) {
delete hash[id];
}
},
findWidgets: function (root) {
var widgets = [];
function getChildrenHelper(root) {
for (var node = root.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 1) {
var widgetId = node.getAttribute("data-kb-widget-id");
if (widgetId) {
var widget = hash[widgetId];
if (widget && widgets.indexOf(widget) == -1) {
widgets.push(widget);
}
}else{
getChildrenHelper(node);
}
}
}
}
getChildrenHelper(root);
return widgets;
}
}
});
|
$(function(){
$(".win-subject").on('click', '.j-open .title', function(event) {
event.preventDefault();
var $this = $(this),$tip = $this.closest(".j-open");
if($tip.hasClass("open")){
$tip.removeClass("open");
}else{
$tip.addClass("open");
}
});
})
function setProgress(num){
$(".j-progress i").width(num);
$(".j-progress .num").html(num);
} |
/*
**********************************************************************
* Copyright 2014
* United Services Automobile Association
* All Rights Reserved
*
* File: hs_site_catalyst.js
**********************************************************************
* Target Chg Date Name Description
* ======== ======== =============== ================================
* 11-04-2015 Liz Donaldson Added new events
* 10-01-2014 Esteban Martinez Site Catalyst
**********************************************************************
*/
/**
* @fileOverview - Create Site Catalyst for WCM/Health
* @author Esteban Martinez
* @version 1.0
*/
/**
* @class USAA.fasg.health.siteCatalyst
* @description: Private self-executing namespace that sets up Site Catalyst.
* @namespace
*/
var USAA = USAA || {};
USAA.fasg = USAA.fasg || {};
USAA.fasg.health = (function() {
var _Event = YAHOO.util.Event;
function setPageDescription(page) {
var preserveName = USAA.ent.digitalData.page.pageDesc;
USAA.ent.digitalData.page.pageDesc += page;
USAA.ent.DigitalAnalytics.pageView();
USAA.ent.digitalData.page.pageDesc = preserveName;
return;
}
var _siteCatalyst = function() {
var ids = ["compare", "compare1", "compare2", "compare3", "help_choose", "tab1", "tab2", "tab3", "medigap_plan_f",
"parta_partb", "parta", "partb", "partd", "expand_all", "older_65", "turn_65", "65_under", "have_coverage", "choices",
"ma_plan", "original", "download", "download1", "video1", "video2", "video3", "video4", "initial", "late", "pers_care_srv",
"calc", "cost", "estimate", "mi_shop_now", "vi_shop_now", "di_shop_now", "waiting", "mmi_quote", "tmi_quote", "compare_tab1",
"compare_tab2", "compare_tab3", "compare_tab3a", "learn_more_explore", "learn_more_high_vol",
"learn_more_tax_penalty", "code_learn_more_tax_penalty"];
_Event.addListener(ids, "click", function() {
setPageDescription(this.id);
});
};
return {
siteCatalyst: _siteCatalyst
};
}());
YAHOO.util.Event.onDOMReady(USAA.fasg.health.siteCatalyst); |
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
//Request a tab for sending needed information
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"windowType": "normal",
"active": true,
"highlighted": true
}, function (tabs) {
for (tab in tabs) {
//Sending Message to content scripts
//console.log('[Background page] sendMessage from the devtools.', message);
chrome.tabs.sendMessage(tabs[tab].id, message);
}
});
});
//Posting back to Devtools
chrome.extension.onMessage.addListener(function (message, sender) {
if (message.from !== 'webpage') return;
//console.log('[Background page] postMessage from the web page.', message);
port.postMessage(message);
});
});
|
const http = require('http')
const fs = require('fs')
const path = require('path')
http.createServer((req, res) => {
const { url, method } = req
if (url === '/' && method === 'GET') {
fs.readFile('./index.html', (err, data) => {
res.statusCode = 200
res.setHeader('Content-type', 'text/html')
res.end(data)
})
} else if (url === '/users' && method === 'GET') {
res.setHeader('Content-type', 'application/json')
res.end(JSON.stringify([{ name: 'tom', age: 20 }]))
} else if (req.headers.accept.indexOf('image/*') != -1 && method === 'GET') {
fs.createReadStream('.' + url).pipe(res)
}
}).listen(3001) |
/*
Given a string and a pattern, find out if the string contains any permutation of the pattern.
Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:
abc
acb
bac
bca
cab
cba
If a string has ‘n’ distinct characters it will have n!n! permutations.
Input: String="oidbcaf", Pattern="abc"
Output: true
Explanation: The string contains "bca" which is a permutation of the given pattern.
Input: String="odicf", Pattern="dc"
Output: false
Explanation: No permutation of the pattern is present in the given string as a substring.
Input: String="bcdxabcdy", Pattern="bcdyabcdx"
Output: true
Explanation: Both the string and the pattern are a permutation of each other.
Input: String="aaacb", Pattern="abc"
Output: true
Explanation: The string contains "acb" which is a permutation of the given pattern.
*/
str = "oidbcaf";
pattern = "abc";
permStr("llabcccrc3bpb5555bac", "abc");
function permStr(str1, str2) {
let hash1 = {};
let hash2 = {};
let isItThere = false;
let j;
for (let z = 0; z < str2.length; ++z) {
if (str2[z] in hash1) {
hash1[str2[z]] += 1;
} else {
hash1[str2[z]] = 1;
}
}
for (let i = 0; i < str1.length; ++i) {
if (str1[i] in hash1) {
hash2 = Object.assign({}, hash1);
for (j = i; j < Math.min(i + str2.length, str1.length); ++j) {
if (!(str1[j] in hash2)) {
i = j;
break;
}
if (str1[j] in hash2) {
hash2[str1[j]] -= 1;
if (hash2[str1[j]] === 0) {
delete hash2[str1[j]];
}
}
if (Object.keys(hash2).length === 0) {
isItThere = true;
i = j;
break;
}
}
}
}
return console.log(isItThere);
}
|
"use strict";
//Creating the constructor function for the animal farm
function Animal(animalType) {
this.animalType = animalType;
}
//Render function for Animals. Able to be used for any animal type.
Animal.prototype.render = function () {
//Getting the elements, creating them, setting to variables to be used later.
let animalDiv = document.createElement('div');
animalDiv.setAttribute('class',`${this.animalType}Object`);
animalDiv.textContent = this.animalType;
let makeAnimalButton = document.querySelector(`#${this.animalType}Section`);
//Appending element to webpage
makeAnimalButton.appendChild(animalDiv);
};
//Setting up the condensed function:
//Getting the element of the buttons
let catButton = document.getElementById('makeCat');
let dogButton = document.getElementById('makeDog');
let sheepButton = document.getElementById('makeSheep');
let horseButton = document.getElementById('makeHorse');
//Creating makeAnimal function
function makeAnimal(animal){
let myAnimal = new Animal (animal);
myAnimal.render();
}
//Calling eachfunction with listeners
catButton.addEventListener('click', ()=>{
let theAnimal = 'Cat';
makeAnimal(theAnimal);
})
dogButton.addEventListener('click', ()=>{
let theAnimal = 'Dog';
makeAnimal(theAnimal);
})
sheepButton.addEventListener('click', ()=>{
let theAnimal = 'Sheep';
makeAnimal(theAnimal);
})
horseButton.addEventListener('click', ()=>{
let theAnimal = 'Horse';
makeAnimal(theAnimal);
}) |
import React, { PureComponent } from 'react';
import events from '../events';
export default class DropdownMenu extends PureComponent {
state = {
open: false,
}
componentDidMount() {
events.subscribe('document_click', this.onDocumentPress);
}
onDocumentPress = (event) => {
// eslint-disable-next-line react/no-find-dom-node
if (this.node && !this.node.contains(event.target) && this.state.open) {
this.close();
event.stopPropagation();
}
}
open = () => {
this.setState({ open: true });
}
close = () => {
this.setState({ open: false });
}
toggle = () => {
if (this.state.open) {
this.close();
} else {
this.open();
}
}
render() {
return (
<div
ref={(node) => { this.node = node; }}
{...this.props}
style={{ display: this.state.open ? 'block' : 'none' }}
>
{this.props.children}
</div>
);
}
}
|
import React from 'react'
import { Link } from 'gatsby'
import styled from 'styled-components'
const MainContainer = styled.div`
display: grid;
grid-template-areas:
'header'
'container'
'footer';
grid
`
const Header = styled.div`
grid-area: header;
min-height: 200px;
`
const Container = styled.div`
grid-area: container;
min-height: 200px;
`
const Footer = styled.div`
grid-area: footer;
min-height: 200px;
`
const Menu = styled.div`
display: flex;
justify-content: flex-start;
`
const MenuItem = styled(Link)`
padding: 10px;
display: flex;
box-shadow: none;
`
class Layout extends React.Component {
render() {
const { children } = this.props
return (
<MainContainer>
<Header>
<Menu>
<MenuItem to="/">Home</MenuItem>
<MenuItem to="countries">Countries</MenuItem>
<MenuItem to="cities">Cities</MenuItem>
<MenuItem to="about">About</MenuItem>
<MenuItem to="contact">Contact</MenuItem>
</Menu>
</Header>
<Container>{children}</Container>
<Footer>
© {new Date().getFullYear()}
{` `}
<a href="https://www.ukpopulation.net">uk population</a>
</Footer>
</MainContainer>
)
}
}
export default Layout
|
define("dragList", ["animate"],
function(_animate){
var _list;
var _dragging = {dragY:0,
dragX:0,
startY:0,
startX:0,
target: false,
dragged: true};
function init(list){
_list = list;
_animate.start(doDragItem);
_animate.pause();
}
function startEdit(){
_list.addClass("edit");
_list.on("touchstart", "img", onTouchStart);
_list.on("mousedown", "img", onMouseDown);
}
function stopEdit(){
_list.removeClass("edit");
_list.off("touchstart", "img", onTouchStart);
_list.off("mousedown", "img", onMouseDown);
_list.off("touchmove", onTouchMove);
_list.off("touchend", onTouchEnd);
_list.off("mousemove", onMouseMove);
_list.off("mouseup", onMouseUp);
var items = [];
$("li", _list).each(function(){
items.push({name: $("span", this).text(), value:0});
});
return items;
}
function isEditing(){
var edit = $(".edit");
return edit.length == 1;
}
function insert(name, value){
_list.append($('<li><span>'+name+'</span><input data-name="'+name+'" type="number" value="'+value+'"></input><img src="gfx/drag.png" class="drag"></img><img src="gfx/trash.png" class="delete"></img></li>'));
}
function onMouseDown(e){
var target = $(this).parent("li");
var x = e.originalEvent.pageX;
var y = e.originalEvent.pageY;
onDragStart(target, x, y);
_list.on("mousemove", onMouseMove);
_list.on("mouseup", onMouseUp);
e.preventDefault();
return false;
}
function onMouseMove(e){
var x = e.originalEvent.pageX;
var y = e.originalEvent.pageY;
onDragMove(x, y);
e.preventDefault();
return false;
}
function onMouseUp(e){
var x = e.originalEvent.pageX;
onDragEnd(x, 0);
_list.off("mousemove", onMouseMove);
_list.off("mouseup", onMouseUp);
e.preventDefault();
return false;
}
function onTouchStart(e){
var target = $(this).parent("li");
var x = e.originalEvent.changedTouches[0].pageX;
var y = e.originalEvent.changedTouches[0].pageY;
onDragStart(target, x, y);
_list.on("touchmove", onTouchMove);
_list.on("touchend", onTouchEnd);
e.preventDefault();
return false;
}
function onTouchMove(e){
var x = e.originalEvent.changedTouches[0].pageX;
var y = e.originalEvent.changedTouches[0].pageY;
onDragMove(x, y);
e.preventDefault();
return false;
}
function onTouchEnd(e){
var x = e.originalEvent.changedTouches[0].pageX;
onDragEnd(x, 0);
_list.off("touchmove", onTouchMove);
_list.off("touchend", onTouchEnd);
e.preventDefault();
return false;
}
function onDragStart(target, x, y){
_dragging.target = target;
_dragging.target.addClass("dragging");
_dragging.startX = x;
_dragging.startY = y;
_dragging.dragX = 0;
_dragging.dragY = 0;
setTransformOnElement("scale(1, 1.1)", _dragging.target);
_animate.unpause();
}
function onDragMove(x, y){
var dx = x - _dragging.startX;
var dy = y - _dragging.startY;
dx = dx > 0 ? 0 : dx;
_dragging.dragX = dx;
_dragging.dragY = dy;
_dragging.hasDragged = false;
}
function doDragItem(tick){
if(_dragging.target === false || _dragging.hasDragged === true) return;
var dx = _dragging.dragX;
var dy = _dragging.dragY;
var inside = true;
var height = _dragging.target.outerHeight();
var width = _dragging.target.outerWidth();
if(dx < -width/2){
dy = 0;
}else{
dx = 0;
if(dy > 0){
if(_dragging.target.next().length == 0){
inside = false;
}else{
var nextElm = _dragging.target;
while(dy > height){
console.log("skip", dy, height);
nextElm = nextElm.next();
_dragging.startY += height;
dy -= height;
}
if(nextElm[0] != _dragging.target[0]){
_dragging.target.insertAfter(nextElm);
}
}
}else if(dy < 0){
if(_dragging.target.prev().length == 0){
inside = false;
}else{
var prevElm = _dragging.target;
while(dy < -height){
prevElm = prevElm.prev();
_dragging.startY -= height;
dy += height;
}
if(prevElm[0] != _dragging.target[0]){
_dragging.target.insertBefore(prevElm);
}
}
}
}
if(inside){
setTransformOnElement("translate("+dx+"px,"+dy+"px) scale(1, 1.1)", _dragging.target);
}else{
setTransformOnElement("scale(1, 1.1)", _dragging.target);
}
_dragging.hasDragged = true;
}
function onDragEnd(x, y){
var dx = x - _dragging.startX;
var width = _dragging.target.outerWidth();
if(dx < -width/2){
_dragging.target.remove();
}else{
_dragging.target.removeClass("dragging");
setTransformOnElement("", _dragging.target);
}
_animate.pause();
_dragging.target = false;
}
function setTransformOnElement(transform, element){
element.css("-webkit-transform", transform);
element.css("OTransform", transform);
element.css("MozTransform", transform);
}
return expose(
init,
startEdit,
stopEdit,
isEditing,
insert);
}); |
export default {
id: 'psybok-vol1',
title: 'PSYBOK volume 1',
date: '2018/04/01',
period: 'avril 2018'
} |
const remote = require('remote');
const ipcRenderer = require('electron').ipcRenderer;
const fs = remote.require('fs');
const path = remote.require('path');
import style from './style.styl';
export default {
template: require('./template.jade')(),
data: function() {
return {
depth: [],
current: {},
filelist: [],
reaction: {
loadingDir: false
}
}
},
filters: {
file2IconName: function(file) {
if (/\.(mp4|mpe?g)$/.test(file.name)) {
return "video_library";
} if (file.type === "directory") {
return "folder";
}
}
},
events: {
'filer-set-dir': "setDir",
'getDir': "getDir",
'filer-add-depth': "addDepth",
},
methods: {
selectItem: function(file) {
if (file.type === 'directory') {
this.$emit('getDir', file);
} else if (file.type === 'file') {
ipcRenderer.send('controller:ipc-bridge', 'filer:select-file', JSON.stringify(file));
}
},
onSelectDepth: function(file, depth) {
this.$data.depth.length = depth;
this.$emit('getDir', file);
},
getDir: function(file) {
this.$data.reaction.loadingDir = true;
if (fs.statSync(file.path).isDirectory()) {
let finder = [];
for(var p of fs.readdirSync(file.path)) {
if (/^\..*/.test(p)) { continue; }
let stats = fs.statSync(path.join(file.path, p));
finder.push({
name: p,
path: path.join(file.path, p),
type: stats.isDirectory() ? 'directory' : 'file'
})
}
this.$emit('filer-set-dir', finder);
this.addDepth(file);
this.$data.reaction.loadingDir = false;
}
},
setDir: function(files) {
this.$set('filelist', files);
},
addDepth: function(file) {
this.$data.depth.push(file);
},
addFilesAll: function() {
this.$dispatch('all', 'files:get', this.$data.filelist);
}
},
ready: function() {
this.getDir({ path: '/Users', name: '/' });
}
}
|
import React from 'react';
import { shallow} from 'enzyme';
import App from '../client/src/components/App.jsx';
import { reviews, stars } from './testDummyData.js';
describe('App', () => {
it('should be defined', () => {
expect(App).toBeDefined();
});
it('should render correctly', () => {
const tree = shallow(
<App name='App test' reviews={reviews} stars={stars[0]}/>
);
expect(tree).toMatchSnapshot();
});
}); |
$(document).ready(function(){
$('.top-notice').delay(1200).fadeOut(500);
$('a.closeBox').on('click', function(e){
e.preventDefault();
var par = $(this).parent();
console.log('sup');
if($(this).hasClass('closeUp')){
par.slideUp();
} else if ($(this).hasClass('closeDown')){
par.slideDown();
} else if ($(this).hasClass('closeLeft')){
par.slideLeft();
} else if ($(this).hasClass('closeRight')){
par.slideRight();
} else {
par.hide();
}
})
}); |
$(document).ready(function () {
var options, init;
OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
OpenLayers.Util.onImageLoadErrorColor = 'transparent';
OpenLayers.Util.onImageLoadError = function () {
this.src = '/Content/Images/sorry.jpg';
this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
};
options = {
wms: 'WMS',
wmslayers: ['poly_landmarks', 'tiger_roads', 'poi'].join(),
controls: [],
projection: 'EPSG:4326',
format: 'image/png',
wmsparams: {
'MAP_TYPE': 'DEF'
}
};
init = function () {
var lon = -73.9529, lat = 40.7723, zoom = 10,
map, sharpmap, click, toolbar, center;
map = new OpenLayers.Map('map', options);
sharpmap = new OpenLayers.Layer.WMS(
'SharpMap WMS',
'/wms.ashx', {
layers: options.wmslayers,
service: options.wms,
version: '1.3.0',
format: options.format,
transparent: true
}, {
isBaseLayer: true,
transparent: true,
visibility: true,
buffer: 0,
singleTile: false,
ratio: 1.5
});
sharpmap.mergeNewParams(options.wmsparams);
map.addLayers([sharpmap]);
click = new OpenLayers.Control.WMSGetFeatureInfo({
url: '/wms.ashx',
title: 'Identify features by clicking',
layers: [sharpmap],
vendorParams: options.wmsparams,
queryVisible: true
});
click.events.register("getfeatureinfo", this, function (evt) {
$('#nodelist').html(evt.text);
});
toolbar = OpenLayers.Class(OpenLayers.Control.NavToolbar, {
initialize: function () {
OpenLayers.Control.NavToolbar.prototype.initialize.apply(this, [options]);
this.addControls([click]);
}
});
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.PanZoom({
position: new OpenLayers.Pixel(2, 10)
}));
map.addControl(new OpenLayers.Control.MousePosition());
map.addControl(new OpenLayers.Control.LoadingPanel());
map.addControl(new toolbar());
center = new OpenLayers.LonLat(lon, lat);
map.setCenter(center, zoom);
};
init();
}); |
import React from "react"
import Image from "../Image/Index"
import Link from "../../components/Link/index";
import swal from 'sweetalert'
import ShortNumber from "short-number"
import Like from "../Like/Index"
import Dislike from "../Dislike/Index"
import axios from "../../axios-orders"
import Timeago from "../Common/Timeago"
import Translate from "../../components/Translate/Index"
class Item extends React.Component {
constructor(props) {
super(props)
let propsData = {...this.props}
this.state = {
channel:propsData.channel,
post: propsData.post,
language:propsData.i18n.language
}
this.delete = this.delete.bind(this)
}
static getDerivedStateFromProps(nextProps, prevState) {
if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){
return null;
}
if(prevState.localUpdate){
return {...prevState,localUpdate:false}
}else if ((nextProps.post && nextProps.post != prevState.post) || nextProps.i18n.language != prevState.language) {
return { post: nextProps.post,language:nextProps.i18n.language }
} else{
return null
}
}
// shouldComponentUpdate(nextProps,nextState){
// if(nextProps.post != this.props.post || nextProps.i18n.language != this.state.language){
// return true
// }
// return false
// }
delete(e) {
e.preventDefault()
swal({
title: Translate(this.props,"Are you sure?"),
text: Translate(this.props,"Once deleted, you will not be able to recover this!"),
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
const formData = new FormData()
formData.append('id', this.state.post.post_id)
formData.append('channel_id', this.state.post.channel_id)
const url = "/post/delete"
axios.post(url, formData)
.then(response => {
if (response.data.error) {
swal("Error", Translate(this.props,"Something went wrong, please try again later", "error"));
} else {
}
}).catch(err => {
swal("Error", Translate(this.props,"Something went wrong, please try again later"), "error");
});
//delete
} else {
}
});
}
render() {
var description = this.state.post.title
if (description.length > 300) {
description = description.substring(0, 300);
}
return (
<React.Fragment>
<div className="communty-content d-flex">
<div className="profileImg">
<Link href="/channel" customParam={`channelId=${this.state.post.channel_custom_url}`} as={`/channel/${this.state.post.channel_custom_url}`}>
<a>
<Image title={this.state.post.channel_name} image={this.state.post.avtar} imageSuffix={this.props.pageInfoData.imageSuffix} />
</a>
</Link>
</div>
<div className="content flex-grow-1">
<div className="postBy">
<div className="authr">
<Link href="/channel" customParam={`channelId=${this.state.post.channel_custom_url}`} as={`/channel/${this.state.post.channel_custom_url}`}>
<a>
{this.state.post.channel_name}
</a>
</Link>
</div>
<div className="pdate">
<Link href="/post" customParam={`postId=${this.state.post.post_id}`} as={`/post/${this.state.post.post_id}`}>
<a><Timeago {...this.props} tile={true}>{this.state.post.creation_date}</Timeago></a>
</Link>
</div>
</div>
{
this.state.channel && (this.state.channel.canEdit || this.state.channel.canDelete) ?
<div className="options">
<div className="LikeDislikeWrap">
<ul className="LikeDislikeList">
<li>
<div className="dropdown TitleRightDropdown">
<a href="#" data-bs-toggle="dropdown"><span className="material-icons" data-icon="more_verti"></span></a>
<ul className="dropdown-menu dropdown-menu-right edit-options">
{
this.state.channel.canEdit ?
<li>
<a href="#" onClick={(e) => this.props.adPost(this.state.post,e)}><span className="material-icons" data-icon="edit"></span>{Translate(this.props, "Edit")}</a>
</li>
: null
}
{
this.state.channel.canDelete ?
<li>
<a onClick={this.delete} href="#"><span className="material-icons" data-icon="delete"></span>{Translate(this.props, "Delete")}</a>
</li>
: null
}
</ul>
</div>
</li>
</ul>
</div>
</div>
: null
}
<div className="text">
{
!this.props.linkify ?
<Link href="/post" customParam={`postId=${this.state.post.post_id}`} as={`/post/${this.state.post.post_id}`}>
<a className="postImg">
<p>{description}</p>
{
this.state.post.image ?
<Image image={this.state.post.image} className="img-fluid" imageSuffix={this.props.pageInfoData.imageSuffix} />
: null
}
</a>
</Link>
:
<React.Fragment>
<p style={{whiteSpace:"pre-line"}} dangerouslySetInnerHTML={{__html:this.props.linkify(this.state.post.title)}}></p>
{
this.state.post.image ?
<Image image={this.state.post.image} className="img-fluid" imageSuffix={this.props.pageInfoData.imageSuffix} />
: null
}
</React.Fragment>
}
</div>
<div className="LikeDislikeWrap">
<ul className="LikeDislikeList">
<li>
<Like icon={true} {...this.props} like_count={this.state.post.like_count} item={this.state.post} type="channel_post" id={this.state.post.post_id} />{" "}
</li>
<li>
<Dislike icon={true} {...this.props} dislike_count={this.state.post.dislike_count} item={this.state.post} type="channel_post" id={this.state.post.post_id} />{" "}
</li>
<li>
<Link href="/post" customParam={`postId=${this.state.post.post_id}`} as={`/post/${this.state.post.post_id}`}>
<a className="community-comment-a">
<span title={this.props.t("Comments")}><span className="material-icons" data-icon="comment"></span> {`${ShortNumber(this.state.post.comment_count ? this.state.post.comment_count : 0)}`}</span>
</a>
</Link>
</li>
</ul>
</div>
</div>
</div>
</React.Fragment>
)
}
}
export default Item; |
import Ember from 'ember';
export default Ember.TextField.extend({
attributeBindings: ['readonly'],
readonly: true,
defaultDateOptions: {
dateFormat: 'dd MM yyyy'
},
didRender() {
let dateOptions = Ember.$.extend({
input: this.$(),
onClose: (p, values, displayValues) => {
if(!Ember.$.isFunction(this.get('changeAction'))) {
return;
}
this.get('changeAction')(this.get('value'));
}
}, this.get('defaultDateOptions'), this.get('dateOptions'));
this.set('calendar', this.get('f7.f7').calendar(dateOptions));
}
});
|
var AWS = require('aws-sdk');
var fs = require('fs');
var config = require('../config.json');
/**
* Push the JSON file to S3
* @see https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html
* @param None
*/
module.exports = function(gulp) {
return async function deployS3(){
//console.log('Starting process')
//console.log(config['aws']['credentials_path'])
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-json-file.html
await AWS.config.loadFromPath(config['aws']['credentials_path']);
// Create S3 service object
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var uploadParams = {Bucket: config['aws']['deploy_bucket'], Key: '', Body: '', ContentType: 'application/json'};
var jsonFile = './app/data/_build.json';
// Configure the file stream and obtain the upload parameters
var fileStream = fs.createReadStream(jsonFile);
fileStream.on('error', function(err) {
console.log('File Error', err);
});
uploadParams.Body = fileStream;
var path = require('path');
uploadParams.Key = config['arc_composer']['content_id']+'.json';
// call S3 to retrieve upload file to specified bucket
await s3.upload(uploadParams, function (err, data) {
if (err) {
console.log("Error", err);
} if (data) {
console.log("Upload Success", data.Location);
}
});
};
};
|
/*
** 1 Remove duplicate from array and output should ne [1,2,5,6,7]
*/
let numbers = [1,2,2,5,5,6,7];
console.log([ ...new Set(numbers)]);
/*
** 2 Difference between let and const
*/
let letAndConst = function() {
{
let let1 = 'let';
var v = 'var';
}
console.log(v);
// console.log(let1);
}
letAndConst();
//O/P var
// ReferenceError: let1 is not defined
// 3 Immediately scope function
let scopeFun = function() {
{
(function(){
let l = 'let';
var v = 'var';
})();
}
// console.log(l);
// console.log(v);
}
scopeFun();
// ReferenceError: l is not defined
// ReferenceError: v is not defined
//4 what will will be O/p ?
console.log(5<6<7);
// true<7 // 1<7 // true
console.log(5>6>7);
// true > 6 // true means 1 false
// 5 what will will be o/p
let a = () => arguments;
// console.log('arguments',a("hi"));
// 6 what will will be o/p
let b = (...n) => {return n};
console.log(b("hi"));
// o/p hi
// 7 what will will be o/p
let x = function(){
return {
mess:'hi'
}
}
console.log('x in function',x());
// o/p {mess: "hi"}
// 8 how to prevent addding property
let profile = {
name:'vikash'
}
profile.age = 3;
console.log(profile);
// use Object.freeze(profile)
// 9 update propery only not to add
Object.seal(profile)
//10 Add property but read only
let profilePor = {
name:'vikash'
}
// Object.defineProperties(profilePor,'age',{
// value:3,
// writable:false
// })
// profilePor.name = 'verma';
// profilePor.age = 14;
// console.log(profilePor);
// 11 why infinte
console.log(Math.max()); // - infinity
//12 get only array from object
// 1.way
let x1 = {
a:1,
b:2
};
const xArr = Object.entries(x1);
console.log("12.get only array from object",xArr);
// 12.get only array from object [ [ 'a', 1 ], [ 'b', 2 ] ]
// 2nd way
const Arrayx = []
for(let i in x1){
Arrayx.push(i);
}
console.log("12.get only array from object",Arrayx);
// 12.get only array from object [ 'a', 'b' ]
// 13 reverse string
let xHi = "hi";
let yHi = "ih";
const reverseStr = (str) =>{
return str.split('').reverse().join('')
}
console.log("13.reverseStr",reverseStr(xHi));
console.log(reverseStr(xHi) === yHi);
// 13.reverseStr ih
// true
// 14 object value
// is this correct
const obj = {
a:1,
b:2,
getA(){
console.log(this.a);
},
getB(){
console.log(this.b);
}
}
// obj.getA().getB();
// no
// correct one is
const objOne = {
a:1,
b:2,
getA(){
console.log(this.a);
return this; // have to return
},
getB(){
console.log(this.b);
}
}
// objOne.getA().getB();
console.log("14",objOne.getA().getB());
// 15 print this
// [1,2].print(); // 1,2
// 1st way
Array.prototype.print = () => {
console.log(`${this[0]} , ${this[1]}`);
}
// 16 reverse string
const aReverse =function(x){
this.x = x;
}
const bReverse =function(x,y){
this.y = y;
}
// const newB = new b('x','y');
// newB.getX();
// newB.getY();
// 17 clone
const objClone = {
a:{
b:{
c:1
}
}
}
const clone = Object.assign({},objClone);
clone.a.b.c = 2;
// console.log(obj.a.b.c);
// 18 reverse string
const aaReverse = [1,2,3,3];
const bbReverse = [2,56,8,7];
const c = aaReverse.concat(bbReverse).sort((aaReverse,bbReverse) => aaReverse>bbReverse );
// 19 reverse string
const objReverse1 = {
x:1,
getX(){
const inner = function() {
console.log(this.x)
}
inner;
}
}
objReverse1.getX();
// 20 reverse string
const objReverse2 = {
x:1,
getX(){
const inner = function() {
console.log(this.x) // bind
}
inner.call(this);
}
}
objReverse2.getX();
|
/*jshint es5:true*/
'use strict';
var fs = require('fs');
var path = require('path');
var task = {
id: 'package-autofile',
author: 'Indigo United',
name: 'Package autofile',
options: {
autofile: {
description: 'The autofile that will be loaded.',
},
'options-intro': {
description: 'The text that is shown before the options.',
default: 'Here\'s a list of the options that this task can take:'
}
},
setup: function (opt, ctx, next) {
opt.task = require(path.resolve(opt.autofile));
opt.__dirname = __dirname;
next();
},
tasks: [
{
description: 'Copy template README.md file',
task: 'cp',
options: {
files: {
'{{__dirname}}/README.md.tpl': 'README.md'
}
}
},
{
description: 'Replace overall info in README.md',
task: 'scaffolding-replace',
options: {
files: 'README.md',
data: {
id: '{{task.id}}',
name: '{{task.name}}',
description: '{{task.description}}',
author: '{{task.author}}',
'options-intro': '{{options-intro}}'
}
}
},
{
description: 'Generate options list',
on: '{{task.options}}',
task: function (opt, ctx, next) {
var options = '';
var def;
for (var optionName in opt.task.options) {
def = opt.task.options[optionName].default;
switch (typeof def) {
case 'string':
def = '"' + def + '"';
break;
case 'boolean':
def = def ? 'true' : 'false';
}
// put option name and possibly flag of mandatory
options += '- `' + (def === undefined ? '*' : '') + optionName + '`';
// put default if it exists
options += (def !== undefined ? ' *(' + opt.task.options[optionName].default + ')*' : '');
// put description
options += ': ' + opt.task.options[optionName].description + '\n';
}
opt.optionsList = options;
next();
}
},
{
description: 'Put options in README.md',
on: '{{task.options}}',
task: 'scaffolding-replace',
options: {
files: 'README.md',
data: {
options: '{{optionsList}}'
}
}
},
{
description: 'Setup package.json with the task info',
task: function (opt, ctx, next) {
if (!fs.existsSync('./package.json')) {
ctx.log.warnln('No "package.json" file found. It\'s good practice to create one.');
return next();
}
var pkg = require(path.resolve('./package.json'));
pkg.name = 'autofile-' + opt.task.id;
pkg.description = opt.task.description;
pkg.author = opt.task.author;
pkg.main = path.basename(opt.autofile);
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, ' '));
next();
}
}
]
};
module.exports = task; |
'use strict';
const gutil = require('gulp-util');
const through = require('through2');
const cheerio = require('cheerio');
const fs = require('fs');
const PLUGIN_NAME = "gulp-replace-src";
var PluginError = gutil.PluginError;
var tools = {
getTimeStamp:function(){/*生成时间戳*/
var d = new Date();
return (d.toISOString().split('T')[0]+d.toTimeString().split(' ')[0]).replace(/[\:\-]/g, '');
},
isType:function(type){/*类型判断*/
return function(o){
return Object.prototype.toString.call(o) === '[object ' + type + ']';
}
}
}
var isString = tools.isType("String"),
isObject = tools.isType("Object"),
isArray = tools.isType("Array");
var DEFAULTS = {
manifest:'',
hash:true,//如果为true,文件名将会替换成添加md5后缀的新文件名,如果不设置,将给地址添加query参数 时间戳?v=20170422112122
basePath:'',//替换之后文件的根路径,如果设置此项,css与js最终发布的根路径都将使用此配置,如果不设置,将使用原来的路径或下面独立的配置
basePathCSS:'', //用于生成的css发布路径
basePathJS:'', //用于生成的js发布路径
inline:false, //是否要嵌入到页面,些配置为true时,标签必须携带 inline 属性,方便针对个别资源inline
rootPath:'', //【必填】替换文件的根路径,如果设置此项,那么css与js的替换文件查找将使用此配置
rootPathCSS:'', //css替换文件的根路径,用于查找css的替换文件
rootPathJS:'', //js替换文件的根路径,用于查找js的替换文件
};
var Plugin = function(options){
if(isObject(options)){
options = Object.assign(DEFAULTS, options);
if(!isObject(options.manifest)){
throw new PluginError(PLUGIN_NAME, 'manifest must be object');
}
if(!options.rootPath && (!options.rootPathCSS && !options.rootPathJS)){
throw new PluginError(PLUGIN_NAME, 'rootPath not be null');
}
}else{
throw new PluginError(PLUGIN_NAME, 'options not be null');
}
return through.obj(function(file, enc, done) {
if (file.isNull()) {
this.push(file);
return done();
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return done();
}
// 处理文件
var content = file.contents.toString();
var $ = cheerio.load(content, {decodeEntities: false});
// 获取css与js的标签
var cssLinks = $('link'), jsLinks = $('script');
cssLinks.each(function(){
processURL($(this), 'css', options, fs);
});
jsLinks.each(function(){
processURL($(this), 'js', options, fs);
});
file.contents = new Buffer($.html());
this.push(file);
done();
});
function processURL($el, type, options, fs){
var manifestKeys = Object.keys(options.manifest);
let attrType = type === 'css' ? 'href' : 'src';
var href = $el.attr(attrType);
var manifestKeyArr = manifestKeys.filter((v)=>{
if(v.indexOf('.'+type)>-1) return v;
});
manifestKeyArr.forEach((v)=>{
if(new RegExp(v).test(href)){
// 判断是否需要inline [用于发布上线]
if(options.inline && $el.attr('inline')===''){
// 读取源文件 转换成 字符串
var content = fs.readFileSync(options.rootPath+v).toString("utf-8");
// 替换
$el.replaceWith(type === 'css' ? `<style>\n${content}\n</style>` :`<script>\n${content}\n</script>` );
}else{
// 是否使用新的发布路径, 是否替换文件名, 是否添加query参数
// 获取新的路径
var newPath = '';
if(options.basePathCSS || options.basePath){
newPath = (options.basePathCSS || options.basePath)+href.substring(href.indexOf(v));
}
// 不使用hash文件名,就添加时间戳参数
if(!options.hash){
var timesp = tools.getTimeStamp();
newPath = newPath.indexOf('?')===-1?(newPath+'?v='+timesp):(newPath+'&v='+timesp);
}else{
newPath = newPath.replace(v, options.manifest[v]);
}
$el.attr(attrType, newPath);
}
}})
}
}
module.exports = Plugin;
|
//Import basic modules
const fs = require('fs')
const path = require('path')
const express = require('express')
//Data
const { accounts, users, writeJSON } = require('./data.js');
const app = express()
//Routes
const accountRoutes = require("./routes/accounts.js")
const servicesRoutes = require("./routes/services.js")
//Setup of static files
app.set('views', path.join(__dirname, './views'))
app.use(express.static(path.join(__dirname, 'public')))
//Views Engine
app.set('view engine', 'ejs')
//Parse Json
app.use(express.json())
//Encode URL data
app.use(express.urlencoded({extended: true}))
///Main Routes -- Summary view
app.get('/', (req,res) => res.render('index', {title: 'Account Summary', accounts: accounts}))
//Profile view
app.get('/profile', (req,res) => res.render('profile', {user: users[0]}))
//Call routes
app.use("/account", accountRoutes)
app.use("/services", servicesRoutes)
//Server
app.listen(3000, () =>{
console.log("Server is running on http://localhost:3000");
}) |
function rangeOfNumbers(startNum, endNum) {
/* If startNum === endNum true, return [startNum] */
return startNum === endNum
? [startNum]
/* If false create an array with startNum and endNum - 1, then combine the arrays */
: rangeOfNumbers(startNum, endNum - 1).concat(endNum);
};
|
import styled from 'styled-components/macro';
export const Card = styled.section`
background-color: var(--color-red);
border-radius: var(--size-s);
padding: var(--size-s);
box-shadow: 2px 2px 2px #222;
border: 1px solid var(--color-golden);
`;
|
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
addons: [
{
name: "@storybook/addon-essentials",
options: {
backgrounds: true,
toolbars: true,
controls: true,
actions: true,
viewport: true,
docs: true,
},
},
"@storybook/addon-links",
"@storybook/addon-a11y",
"themeprovider-storybook/register",
],
};
|
const bin = `node ${process.cwd()}\\bin\\pos-cli.js`;
module.exports = bin;
|
//GLOBALS
var str = JSON.stringify;
$("#random-button").on('click', function(){
generate();
});
$("#button-author").on('click', function(){
window.location.href = "./author.html?a=" + $('#author').attr('data-value');
});
function generate(){
$.get("https://quote-garden.herokuapp.com/api/v3/quotes", function(data){
data_string = JSON.stringify(data);
var total_quotes = data['totalQuotes'];
$.get("https://quote-garden.herokuapp.com/api/v3/quotes?limit=1&page="+ Math.random() * (total_quotes - 0) + 0, function(data){
var quote = data['data'];
document.getElementById("quote-text").innerHTML = str(quote[0]["quoteText"]);
document.getElementById("author").innerHTML = str(quote[0]["quoteAuthor"]).replace(/['"]+/g, '');
$("#author").attr("data-value", str(quote[0]["quoteAuthor"]).replace(/['"]+/g, ''));
document.getElementById("genre").innerHTML = str(quote[0]["quoteGenre"]).replace(/['"]+/g, '');
});
});
}
generate(); |
const merge = require('webpack-merge');
const baseConfig = require('./base.config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(baseConfig, {
entry: {
app: './wrapper/index.jsx',
},
output: {
filename: 'bundle.js',
chunkFilename: '[name].bundle.js',
},
devtool: 'eval-source-map',
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
inline: true,
port: '3001',
overlay: true
}
});
|
const publicRoot = new axios.create({ baseURL: "http://localhost:3000/public"});
const loadPosts = async function() {
let urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('post')) {
loadSinglePost(parseInt(urlParams.get('post')));
return;
}
//get posts
let result = await publicRoot.get('/blog');
let posts = result.data.result.posts;
if (window.localStorage.getItem("jwt") != null) {
let jwt = window.localStorage.getItem("jwt");
const userRoot = new axios.create({ baseURL: "http://localhost:3000/user", headers: {"Authorization": "Bearer " + jwt}});
let result2 = await userRoot.get("/savedPosts")
.catch( function () {
renderPosts(posts, []);
});
let ids = result2.data.result.ids;
if (ids == null) {
renderPosts(posts, []);
}
else {
renderPosts(posts, ids);
}
}
else {
renderPosts(posts, []);
$(".save").remove();
}
$(".save").on("click", savePost);
$(".unsave").on("click", unsavePost);
}
const renderPosts = function (posts, ids) {
for (let i = 0; i < posts.length; i++) {
posts[i].id = i;
$("#posts").append(renderPost(posts[i], ids.includes(i + "")));
}
}
const renderPost = function (post, isSaved) {
let postDiv = document.createElement("div");
postDiv.setAttribute("class", "post");
postDiv.setAttribute("id", post.id);
let postHeader = document.createElement("div");
postHeader.setAttribute("class", "post-header");
postHeader.innerText = post.title;
let postCenter = document.createElement("div");
postCenter.setAttribute("class", "post-center");
postCenter.innerText = post.body;
let postFooter = document.createElement("div");
postFooter.setAttribute("class", "post-footer");
postFooter.innerHTML = "<a href='?post="+post.id+"'>view comments</a>";
let like = document.createElement("input");
like.setAttribute("type", "image");
like.style.height = "12px";
if (isSaved) {
console.log(post.id + " is saved");
like.setAttribute("src", "heart2.png"); like.setAttribute("class", "unsave");
}
else { like.setAttribute("src", "heart.png"); like.setAttribute("class", "save"); }
like.style.margin = "-1px 10px";
postFooter.appendChild(like);
postDiv.appendChild(postHeader);
postDiv.appendChild(postCenter);
postDiv.appendChild(postFooter);
return postDiv;
}
const loadSinglePost = async function(id) {
let result1 = await publicRoot.get('/blog');
let posts = result1.data.result.posts;
$("#posts").append(renderPost(posts[id], false));
$("#undefined").attr("id", id); //whatever
if (window.localStorage.getItem("jwt") == null) {
let commentsDiv = document.createElement("div");
commentsDiv.setAttribute("class", "comments");
let hiddenComments = document.createElement("div");
hiddenComments.setAttribute("class", "comment-title");
hiddenComments.innerHTML= "<a href=login.html>Log in</a> to view comments.";
commentsDiv.appendChild(hiddenComments);
$(".post-footer").replaceWith(commentsDiv);
return;
}
let jwt = window.localStorage.getItem("jwt");
const privateRoot = new axios.create({ baseURL: "http://localhost:3000/private", headers: {"Authorization": "Bearer " + jwt}});
let result2 = await privateRoot.get('/blogComments', {}
).catch(function(error) {
console.log('Error fetching user data:', error);
return;
});
let comments = result2.data.result.comments.filter(comment => comment.parentID == id);
$(".post-footer").replaceWith(renderCommentsSection(comments));
$("#post-comment").on("click", postComment);
}
const renderCommentsSection = function (comments) {
let commentsDiv = document.createElement("div");
commentsDiv.setAttribute("class", "comments");
if (window.localStorage.getItem("jwt") == null) {
let hiddenComments = document.createElement("div");
hiddenComments.setAttribute("class", "comment-title");
hiddenComments.innerHTML= "<a href=login.html>Log in</a> to view comments.";
commentsDiv.appendChild(hiddenComments);
return commentsDiv;
}
commentsDiv.appendChild(renderCommentBox());
let commentTitle = document.createElement("div");
commentTitle.setAttribute("class", "comment-title");
commentTitle.innerText = comments.length + " comments";
commentsDiv.appendChild(commentTitle);
for (let i = comments.length-1; i >= 0; i--) {
commentsDiv.appendChild(renderComment(comments[i]));
}
return commentsDiv;
}
const renderComment = function (comment) {
let commentDiv = document.createElement("div");
commentDiv.setAttribute("class", "comment");
let commentHeader = document.createElement("div");
commentHeader.setAttribute("class", "comment-header");
commentHeader.innerText = comment.author;
let commentCenter = document.createElement("div");
commentCenter.setAttribute("class", "comment-center");
commentCenter.innerText = comment.body;
let commentFooter = document.createElement("div");
commentFooter.setAttribute("class", "comment-footer");
commentFooter.innerText = comment.signature + " ";
let date = document.createElement ("span");
date.setAttribute("class", "date");
date.innerText = comment.date;
commentFooter.appendChild(date);
commentDiv.appendChild(commentHeader);
commentDiv.appendChild(commentCenter);
commentDiv.appendChild(document.createElement("hr"));
commentDiv.appendChild(commentFooter);
return commentDiv;
}
const renderCommentBox = function() {
let commentBoxDiv = document.createElement("div");
commentBoxDiv.setAttribute("class", "content");
let commentForm = document.createElement("form");
commentForm.setAttribute("id", "comment-form");
let textbox = document.createElement("input");
textbox.setAttribute("id", "comment-box");
textbox.setAttribute("class", "textarea");
textbox.setAttribute("type", "textarea");
textbox.setAttribute("name", "comment-box");
textbox.setAttribute("placeholder", "Write a comment!");
let field = document.createElement("div");
field.setAttribute("class", "field");
let control = document.createElement("div");
control.setAttribute("class", "control");
let button = document.createElement("button");
button.setAttribute("id", "post-comment");
button.setAttribute("type", "submit");
button.innerText = "Post Comment";
let message = document.createElement("p");
message.setAttribute("id", "message");
control.appendChild(button);
field.appendChild(control);
commentForm.appendChild(textbox);
commentForm.appendChild(field);
commentForm.appendChild(message);
commentBoxDiv.appendChild(commentForm);
return commentBoxDiv;
}
const getDateTime = async function() {
let timeresponse = await axios({
method: 'GET',
url: "https://world-time2.p.rapidapi.com/ip",
headers: {
"x-rapidapi-host": "world-time2.p.rapidapi.com",
"x-rapidapi-key": "c3adc3c5f6mshf17a6cac61ab8cbp13e587jsn3be1d3df306f"
}
});
let time = timeresponse.data;
let day = "";
switch (time.day_of_week) {
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday"; break;
case 7: day = "Sunday"; break;
}
let dateDay = time.datetime.slice(5,7);
let dateYear = time.datetime.slice(0,4);
let dateMonth = time.datetime.slice(8, 10);
return (day + ", " + dateMonth + "/" + dateDay + "/" + dateYear);
}
const postComment = async function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$("#message").html('');
let body = document.getElementById("comment-box").value;
if (body == "") {
$("#message").html('<span class="has-text-danger">Comment cannot be empty.</span>');
return;
}
let jwt = window.localStorage.getItem("jwt");
let response = await axios({
method: 'GET',
url: "http://localhost:3000/account/status",
headers: { "Authorization": "Bearer " + jwt }
}).catch(function(error) {
console.log('Error fetching user data:', error);
return;
});
let username = response.data.user.name;
let signature = response.data.user.data.signature;
let urlParams = new URLSearchParams(window.location.search);
let id = parseInt(urlParams.get("post"));
let date = await getDateTime();
const privateRoot = new axios.create({ baseURL: "http://localhost:3000/private", headers: {"Authorization": "Bearer " + jwt}});
await privateRoot.post('/blogComments/comments', {
data: {
parentID: id,
author: username,
body: body,
signature: signature,
date: date
},
type: "merge"
});
window.location.reload();
}
const savePost = async function(event) {
event.preventDefault();
event.stopImmediatePropagation();
let postID = event.target.closest(".post").id;
let jwt = window.localStorage.getItem("jwt");
const userRoot = new axios.create({ baseURL: "http://localhost:3000/user", headers: {"Authorization": "Bearer " + jwt}});
await userRoot.post("/savedPosts/ids", {
data: postID,
type: "merge"
});
window.location.reload();
}
const unsavePost = async function(event) {
event.preventDefault();
event.stopImmediatePropagation();
let postID = event.target.closest(".post").id;
let jwt = window.localStorage.getItem("jwt");
const userRoot = new axios.create({ baseURL: "http://localhost:3000/user", headers: {"Authorization": "Bearer " + jwt}});
let result = await userRoot.get("/savedPosts");
let ids = result.data.result.ids;
let index = ids.indexOf(postID);
if (index >= 0) {
ids.splice(index, 1);
}
await userRoot.post("/savedPosts", {
data: {
ids: ids
}
});
window.location.reload();
}
$(function() { loadPosts(); }); |
import React, { Component } from "react";
import "../styles/slider_switch.css";
class Slider extends Component {
onClick = () => {
this.props.onClick();
}
render() {
const {status, connected} = this.props.device;
return (
<div onClick={this.onClick} className={"switch " + (status==="on" ? "active":"") + (!connected?"disabled":"")} >
<span className="slider" />
</div>
);
}
}
export default Slider;
|
const state = [{
href: "https://www.bushblade.co.uk/",
text: 'Bushblade Knives'
},
{
href: "http://www.louadamsphotography.com/",
text: 'Lou Adams Photography'
},
{
href: "http://www.westyorkshirebushcraft.co.uk/",
text: 'West Yorkshire Bushcraft'
}
]
const render = () => state.reduce((str, site) => (str += `
<li>
<a href="${ site.href }">
<span class="icon">
<i class="fa-lg fas fa-external-link-square-alt" aria-hidden="true"></i>
</span>${ site.text }</a>
</li>
`), '')
module.exports = {render} |
'use strict'
require('../../../../../../asset/css/buttons.css')
require('./view.css')
require('../../../../../../asset/js/xxt.ui.schema.js')
require('./_asset/ui.round.js')
window.moduleAngularModules = ['round.ui.enroll', 'schema.ui.xxt']
var ngApp = require('./main.js')
ngApp.factory('Record', [
'http2',
'tmsLocation',
function (http2, LS) {
var Record, _ins
Record = function (oApp) {
var data = {} // 初始化空数据,优化加载体验
oApp.dynaDataSchemas.forEach(function (schema) {
data[schema.id] = ''
})
this.current = {
enroll_at: 0,
data: data,
}
}
Record.prototype.remove = function (record) {
var url
url = LS.j('record/remove', 'site', 'app')
url += '&ek=' + record.enroll_key
return http2.get(url)
}
return {
ins: function (oApp) {
if (_ins) {
return _ins
}
_ins = new Record(oApp)
return _ins
},
}
},
])
ngApp.controller('ctrlRecord', [
'$scope',
'$parse',
'$sce',
function ($scope, $parse, $sce) {
$scope.value2Label = function (schemaId) {
var val, oRecord
if (schemaId && $scope.Record) {
oRecord = $scope.Record.current
if (oRecord && oRecord.data) {
val = $parse(schemaId)(oRecord.data)
return val ? $sce.trustAsHtml(val) : ''
}
}
return ''
}
$scope.score2Html = function (schemaId) {
var oSchema, val, oRecord, label
if ($scope.Record) {
if ((oSchema = $scope.app._schemasById[schemaId])) {
label = ''
oRecord = $scope.Record.current
if (oRecord && oRecord.data && oRecord.data[schemaId]) {
val = oRecord.data[schemaId]
if (oSchema.ops && oSchema.ops.length) {
oSchema.ops.forEach(function (op, index) {
label +=
'<div>' + op.l + ': ' + (val[op.v] ? val[op.v] : 0) + '</div>'
})
}
}
return $sce.trustAsHtml(label)
}
}
return ''
}
},
])
ngApp.controller('ctrlView', [
'$scope',
'$parse',
'tmsLocation',
'http2',
'noticebox',
'Record',
'picviewer',
'$timeout',
'tmsSchema',
'enlRound',
'$uibModal',
function (
$scope,
$parse,
LS,
http2,
noticebox,
Record,
picviewer,
$timeout,
tmsSchema,
enlRound,
$uibModal
) {
function fnHidePageActions() {
var domActs
if ((domActs = document.querySelectorAll('[wrap=button]'))) {
angular.forEach(domActs, function (domAct) {
domAct.style.display = 'none'
})
}
}
function fnGetRecord(ek) {
if (ek) {
return http2.get(LS.j('record/get', 'site', 'app') + '&ek=' + ek)
} else {
return http2.get(LS.j('record/get', 'site', 'app', 'ek', 'rid'))
}
}
function fnGetRecordByRound(oRound) {
return http2.get(LS.j('record/get', 'site', 'app') + '&rid=' + oRound.rid)
}
function fnProcessData(oRecord) {
var oRecData, originalValue, afterValue
oRecData = oRecord.data
if (oRecData && Object.keys(oRecData).length) {
_oApp.dynaDataSchemas.forEach(function (oSchema) {
originalValue = $parse(oSchema.id)(oRecData)
if (originalValue) {
switch (oSchema.type) {
case 'longtext':
afterValue = tmsSchema.txtSubstitute(originalValue)
break
case 'single':
if (oSchema.ops && oSchema.ops.length) {
for (var i = oSchema.ops.length - 1; i >= 0; i--) {
if (originalValue === oSchema.ops[i].v) {
afterValue = oSchema.ops[i].l
}
}
}
break
case 'multiple':
originalValue = originalValue.split(',')
if (oSchema.ops && oSchema.ops.length) {
afterValue = []
oSchema.ops.forEach(function (op) {
originalValue.indexOf(op.v) !== -1 && afterValue.push(op.l)
})
afterValue = afterValue.length ? afterValue.join(',') : '[空]'
}
break
case 'url':
originalValue._text = tmsSchema.urlSubstitute(originalValue)
break
default:
afterValue = originalValue
}
}
$parse(oSchema.id).assign(
oRecData,
afterValue ||
originalValue ||
(/image|file|voice|multitext/.test(oSchema.type) ? '' : '[空]')
)
afterValue = undefined
})
}
}
function fnDisableActions() {
var domActs
if ((domActs = document.querySelectorAll('button[ng-click]'))) {
angular.forEach(domActs, function (domAct) {
var ngClick = domAct.getAttribute('ng-click')
if (
ngClick.indexOf('editRecord') === 0 ||
ngClick.indexOf('removeRecord') === 0
) {
domAct.style.display = 'none'
}
})
}
}
/**
* 控制轮次题目的可见性
*/
function fnToggleRoundSchemas(dataSchemas, oRecordData) {
dataSchemas.forEach(function (oSchema) {
var domSchema
domSchema = document.querySelector(
'[wrap=value][schema="' + oSchema.id + '"]'
)
if (
domSchema &&
oSchema.hideByRoundPurpose &&
oSchema.hideByRoundPurpose.length
) {
var bVisible
bVisible = true
if (
oSchema.hideByRoundPurpose.indexOf(
$scope.Record.current.round.purpose
) !== -1
) {
bVisible = false
}
oSchema._visible = bVisible
domSchema.classList.toggle('hide', !bVisible)
}
})
}
/**
* 控制关联题目的可见性
*/
function fnToggleAssocSchemas(dataSchemas, oRecordData) {
dataSchemas.forEach((oSchema) => {
let domSchema
domSchema = document.querySelector(
'[wrap=value][schema="' + oSchema.id + '"]'
)
if (
domSchema &&
oSchema.visibility &&
oSchema.visibility.rules &&
oSchema.visibility.rules.length
) {
let bVisible = tmsSchema.getSchemaVisible(oSchema, oRecordData)
domSchema.classList.toggle('hide', !bVisible)
oSchema.visibility.visible = bVisible
}
})
}
/* 显示题目的分数 */
function fnShowSchemaScore(oScore) {
_aScoreSchemas.forEach(function (oSchema) {
var domSchema, domScore
domSchema = document.querySelector(
'[wrap=value][schema="' + oSchema.id + '"]'
)
if (domSchema) {
for (var i = 0; i < domSchema.children.length; i++) {
if (domSchema.children[i].classList.contains('schema-score')) {
domScore = domSchema.children[i]
break
}
}
if (!domScore) {
domScore = document.createElement('div')
domScore.classList.add('schema-score')
domSchema.appendChild(domScore)
}
if (oScore) {
domScore.innerText = oScore[oSchema.id] || 0
} else {
domScore.innerText = '[空]'
}
}
})
}
/* 显示题目的分数 */
function fnShowSchemaBaseline(oBaseline) {
if (oBaseline) {
var domSchema, domBaseline
for (var schemaId in oBaseline.data) {
domSchema = document.querySelector(
'[wrap=value][schema="' + schemaId + '"]'
)
domBaseline = null
if (domSchema) {
for (var i = 0; i < domSchema.children.length; i++) {
if (domSchema.children[i].classList.contains('schema-baseline')) {
domBaseline = domSchema.children[i]
break
}
}
if (!domBaseline) {
domBaseline = document.createElement('div')
domBaseline.classList.add('schema-baseline')
domSchema.appendChild(domBaseline)
}
domBaseline.innerText = oBaseline.data[schemaId]
}
}
} else {
/*清空目标值*/
var domBaselines, domBaseline
domBaselines = document.querySelectorAll(
'[wrap=value] .schema-baseline'
)
for (var i = 0; i < domBaselines.length; i++) {
domBaseline = domBaselines[i]
domBaseline.parentNode.removeChild(domBaseline)
}
}
}
/* 根据获得的记录设置页面状态 */
function fnSetPageByRecord(rsp) {
var oRecord, oOriginalData
$scope.Record.current = oRecord = rsp.data
oRecord.data = oOriginalData = rsp.data.data
? angular.copy(rsp.data.data)
: {}
if (oRecord.enroll_at === undefined) oRecord.enroll_at = 0
/* 设置轮次题目的可见性 */
fnToggleRoundSchemas(_oApp.dynaDataSchemas, oOriginalData)
/* 设置关联题目的可见性 */
fnToggleAssocSchemas(_oApp.dynaDataSchemas, oOriginalData)
/* 将数据转换为可直接显示的形式 */
fnProcessData(oRecord)
/* 显示题目的分数 */
if (_aScoreSchemas.length) {
fnShowSchemaScore(oRecord.score)
}
/* disable actions */
if (
_oApp.scenarioConfig.can_cowork &&
_oApp.scenarioConfig.can_cowork !== 'Y'
) {
if ($scope.user.uid !== oRecord.userid) {
fnDisableActions()
}
}
/* 检查是否可以提交数据 */
// 设置按钮初始状态
var submitActs = []
if (_oPage.actSchemas && _oPage.actSchemas.length) {
_oPage.actSchemas.forEach(function (a) {
if (a.name === 'editRecord' || a.name === 'removeRecord') {
a.disabled = false
submitActs.push(a)
}
})
}
// 检查轮次时间
if (oRecord.round) {
if (oRecord.round.start_at > 0) {
if (oRecord.round.start_at * 1000 > new Date() * 1) {
noticebox.warn(
'活动轮次【' +
oRecord.round.title +
'】还没开始,不能提交、修改、保存或删除填写记录!'
)
submitActs.forEach(function (a) {
a.disabled = true
})
}
}
if (oRecord.round.end_at > 0) {
if (oRecord.round.end_at * 1000 < new Date() * 1) {
noticebox.warn(
'活动轮次【' +
oRecord.round.title +
'】已结束,不能提交、修改、保存或删除填写记录!'
)
submitActs.forEach(function (a) {
a.disabled = true
})
}
}
}
// 检查白名单
if (
_oApp.entryRule &&
_oApp.entryRule.wl &&
_oApp.entryRule.wl.submit &&
_oApp.entryRule.wl.submit.group
) {
if ($scope.user.group_id != _oApp.entryRule.wl.submit.group) {
_oPage.actSchemas.forEach((a) => {
if (a.name === 'editRecord' || a.name === 'removeRecord') {
a.disabled = true
}
})
}
}
$timeout(function () {
var imgs
if ((imgs = document.querySelectorAll('.data img'))) {
picviewer.init(imgs)
}
})
/* 设置页面分享信息 */
$scope.setSnsShare(oRecord, null, null, (sharelink) => {
$scope.sharelink = sharelink
})
/* 同轮次的其他记录 */
if (parseInt(_oApp.count_limit) !== 1) {
http2
.post(LS.j('record/list', 'site', 'app') + '&sketch=Y', {
record: {
rid: oRecord.round.rid,
},
})
.then(function (rsp) {
var records
if ((records = rsp.data.records)) {
$scope.recordsOfRound = {
records: records,
page: {
size: 1,
total: rsp.data.total,
},
shift: function () {
fnGetRecord(records[this.page.at - 1].enroll_key).then(
fnSetPageByRecord
)
},
}
for (var i = 0, l = records.length; i < l; i++) {
if (records[i].enroll_key === oRecord.enroll_key) {
$scope.recordsOfRound.page.at = i + 1
break
}
}
}
})
} else {
$scope.recordsOfRound = {
records: [],
page: {
size: 1,
total: 0,
},
}
}
/* 目标轮次记录(判断的逻辑需要,是可以直接设置目标轮次的) */
if (_oApp.roundCron && _oApp.roundCron.length) {
if (['C', 'S'].indexOf(oRecord.round.purpose) !== -1) {
http2
.get(
LS.j('record/baseline', 'site', 'app') +
'&rid=' +
oRecord.round.rid
)
.then(function (rsp) {
if (rsp.data) {
/* 显示题目的目标值 */
fnShowSchemaBaseline(rsp.data)
}
})
} else {
/* 清除显示题目的目标值 */
fnShowSchemaBaseline(false)
}
}
}
var _oApp, _oPage, _aScoreSchemas
$scope.gotoHome = function () {
location.href =
'/rest/site/fe/matter/enroll?site=' +
_oApp.siteid +
'&app=' +
_oApp.id +
'&page=repos'
}
$scope.addRecord = function (event, page) {
if (page) {
$scope.gotoPage(event, page, null, $scope.Record.current.round.rid, 'Y')
} else {
for (var i in $scope.app.pages) {
var oPage = $scope.app.pages[i]
if (oPage.type === 'I') {
$scope.gotoPage(
event,
oPage.name,
null,
$scope.Record.current.round.rid,
'Y'
)
break
}
}
}
}
$scope.editRecord = function (event, page) {
if ($scope.app.scenarioConfig) {
if ($scope.app.scenarioConfig.can_cowork !== 'Y') {
if ($scope.user.uid !== $scope.Record.current.userid) {
noticebox.warn('不允许修改他人提交的数据')
return
}
}
}
if (!page) {
for (var i in $scope.app.pages) {
var oPage = $scope.app.pages[i]
if (oPage.type === 'I') {
page = oPage.name
break
}
}
}
$scope.gotoPage(event, page, $scope.Record.current.enroll_key)
}
$scope.removeRecord = function (event, page) {
if (
$scope.app.scenarioConfig.can_cowork &&
$scope.app.scenarioConfig.can_cowork !== 'Y'
) {
if ($scope.user.uid !== $scope.Record.current.userid) {
noticebox.warn('不允许删除他人提交的数据')
return
}
}
noticebox.confirm('删除记录,确定?').then(function () {
$scope.Record.remove($scope.Record.current).then(function (data) {
page && $scope.gotoPage(event, page)
})
})
}
$scope.shiftRound = function (oRound) {
fnGetRecordByRound(oRound).then(fnSetPageByRecord)
}
$scope.shareQrcode = function () {
if ($scope.sharelink) {
$uibModal.open({
templateUrl: 'shareQrcode.html',
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
$scope2.qrcode =
'/rest/site/fe/matter/enroll/qrcode?site=' +
$scope.app.siteid +
'&url=' +
encodeURIComponent($scope.sharelink)
$scope2.cancel = function () {
$mi.dismiss()
}
},
],
backdrop: 'static',
})
}
}
$scope.doAction = function (event, oAction) {
switch (oAction.name) {
case 'addRecord':
$scope.addRecord(event, oAction.next)
break
case 'editRecord':
$scope.editRecord(event, oAction.next)
break
case 'removeRecord':
$scope.removeRecord(event, oAction.next)
break
case 'gotoPage':
$scope.gotoPage(event, oAction.next)
break
case 'closeWindow':
$scope.closeWindow()
break
case 'shareQrcode':
$scope.shareQrcode()
}
}
$scope.$on('xxt.app.enroll.ready', function (event, params) {
var facRound
/* 不再支持在页面中直接显示按钮 */
fnHidePageActions()
_oApp = params.app
_oPage = params.page
_aScoreSchemas = []
_oApp.dynaDataSchemas.forEach(function (oSchema) {
if (
oSchema.requireScore === 'Y' &&
oSchema.format === 'number' &&
oSchema.type === 'shorttext'
) {
_aScoreSchemas.push(oSchema)
}
})
$scope.Record = Record.ins(_oApp)
/* 活动轮次列表 */
if (_oApp.roundCron && _oApp.roundCron.length) {
facRound = new enlRound(_oApp)
facRound.list().then((oResult) => {
$scope.rounds = oResult.rounds
})
} else $scope.rounds = []
fnGetRecord().then(fnSetPageByRecord)
/*设置页面导航*/
$scope.setPopNav(['votes', 'repos', 'rank', 'kanban', 'event'], 'view')
/* 记录页面访问日志 */
if (
!_oApp.scenarioConfig.close_log_access ||
_oApp.scenarioConfig.close_log_access !== 'Y'
)
$scope.logAccess()
})
},
])
|
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
CropSwap.Routers.App = (function(_super) {
__extends(App, _super);
function App() {
_ref = App.__super__.constructor.apply(this, arguments);
return _ref;
}
App.prototype.initialize = function() {
return this.bind("all", this.triggerRouteChange);
};
App.prototype.routes = {
'': 'home',
'home': 'home',
'search': 'search',
'offer': 'offer',
'account': 'account',
'login': 'login'
};
App.prototype.home = function() {
var view;
view = new CropSwap.Views.Home();
return $('.wrapper').html(view.render().el);
};
App.prototype.search = function() {
var view;
view = new CropSwap.Views.Search();
return $('.wrapper').html(view.render().el);
};
App.prototype.offer = function() {
var view;
if (CropSwap.is_logged_in()) {
view = new CropSwap.Views.Offer();
return $('.wrapper').html(view.render().el);
} else {
return routeTo('login');
}
};
App.prototype.account = function() {
var view;
if (CropSwap.is_logged_in()) {
view = new CropSwap.Views.Account();
return $('.wrapper').html(view.render().el);
} else {
return routeTo('login');
}
};
App.prototype.login = function() {
var view;
view = new CropSwap.Views.Login();
return $('.wrapper').html(view.render().el);
};
App.prototype.triggerRouteChange = function(event) {
if (/^route:/.test(event)) {
console.log("route change event: " + event);
this.trigger('change');
return $(".nav-collapse.collapse").removeClass("show");
}
};
return App;
})(Backbone.Router);
}).call(this);
|
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
const Experience = () => {
return (
<div className="experience">
<h3>Experience</h3>
<div className="exp-1">
<h4>Developpeur Full stack jS / React</h4>
<h5>2020-2021</h5>
<p>
Développer des applications Web avec React js.<br />
Développer des API avec node et express js.<br />
Créer et structurer des bases de données avec Mongo DB.<br />
Rédiger un cahier des charges technique. <br />
Élaborer des chartes graphiques.<br />
Agile méthode scrum</p>
</div>
<div className="exp-2">
<h4>Developpeur Integrateur web</h4>
<h5>2017-2019</h5>
<p> Développer des interfaces utilisateur avec JavaScript<br />
Mise en forme des pages web responsive avec Bootstrap.<br />
Utilistation de Git et Agilité en méthode Scrum. </p>
</div>
<div className="exp-3">
<h4>Chef d'équipe supply chaine</h4>
<h5>2013-2015</h5>
<p>
Planifier l’activité du personnel.<br />
Organiser l’arrivage.<br />
Gérer la réception et les expéditions.<br />
Suivre et gérer la préparation des commandes.<br />
Traiter des litiges et les dysfonctionnements.<br />
</p>
</div>
</div>
);
};
export default Experience; |
var mongoose = require('mongoose');
var Promise = require('bluebird');
Promise.promisifyAll(mongoose);
var adminUserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
password: String
}, { versionKey: false });
var AdminUser = mongoose.model('AdminUser', adminUserSchema);
module.exports = AdminUser; |
define(['require', 'mschemaService', 'matterSchema'], function (require) {
'use strict';
var ngApp = angular.module('app', ['ngRoute', 'ui.bootstrap', 'ui.tms', 'ui.xxt', 'http.ui.xxt', 'tinymce.ui.xxt', 'notice.ui.xxt', 'schema.ui.xxt', 'service.matter', 'service.mschema', 'schema.matter', 'protect.ui.xxt']);
ngApp.constant('CstApp', {
alertMsg: {
'schema.duplicated': '不允许重复添加登记项',
},
});
ngApp.config(['$controllerProvider', '$routeProvider', '$locationProvider', '$compileProvider', 'srvSiteProvider', 'srvMschemaProvider', 'srvMschemaNoticeProvider', function ($controllerProvider, $routeProvider, $locationProvider, $compileProvider, srvSiteProvider, srvMschemaProvider, srvMschemaNoticeProvider) {
var RouteParam = function (name, baseURL) {
!baseURL && (baseURL = '/views/default/pl/fe/site/mschema/');
this.templateUrl = baseURL + name + '.html?_=' + (new Date * 1);
this.controller = 'ctrl' + name[0].toUpperCase() + name.substr(1);
this.reloadOnSearch = false;
this.resolve = {
load: function ($q) {
var defer = $q.defer();
require([baseURL + name + '.js'], function () {
defer.resolve();
});
return defer.promise;
}
};
};
$locationProvider.html5Mode(true);
ngApp.provider = {
controller: $controllerProvider.register,
directive: $compileProvider.directive
};
$routeProvider
.when('/rest/pl/fe/site/mschema/main', new RouteParam('main'))
.when('/rest/pl/fe/site/mschema/extattr', new RouteParam('extattr'))
.when('/rest/pl/fe/site/mschema/notice', new RouteParam('notice'))
.otherwise(new RouteParam('main'));
var siteId = location.search.match(/site=([^&]*)/)[1];
srvSiteProvider.config(siteId);
srvMschemaProvider.config(siteId);
}]);
ngApp.controller('ctrlMschema', ['$scope', '$location', 'http2', 'srvSite', 'srvMschema', function ($scope, $location, http2, srvSite, srvMschema) {
function shiftAttr(oSchema) {
oSchema.attrs = {
mobile: oSchema.attr_mobile.split(''),
email: oSchema.attr_email.split(''),
name: oSchema.attr_name.split('')
};
}
$scope.schemas = [];
$scope.$on('$locationChangeSuccess', function (event, currentRoute) {
var subView = currentRoute.match(/([^\/]+?)\?/);
$scope.subView = subView[1] === 'mschema' ? 'main' : subView[1];
switch ($scope.subView) {
case 'main':
$scope.opened = 'edit';
break;
case 'notice':
$scope.opened = 'other';
break;
default:
$scope.opened = '';
}
});
$scope.switchTo = function (subView, hash) {
var url = '/rest/pl/fe/site/mschema/' + subView;
$location.path(url).hash(hash || '');
};
$scope.chooseSchema = function (oSchema) {
$scope.choosedSchema = oSchema;
};
$scope.addSchema = function () {
var url = '/rest/pl/fe/site/member/schema/create?site=' + $scope.site.id;
http2.post(url, {}).then(function (rsp) {
shiftAttr(rsp.data);
$scope.schemas.push(rsp.data);
});
};
$scope.delSchema = function () {
var url, schema;
if (window.confirm('确认删除通讯录?')) {
schema = $scope.choosedSchema;
url = '/rest/pl/fe/site/member/schema/delete?site=' + $scope.site.id + '&id=' + schema.id;
http2.get(url).then(function (rsp) {
var i = $scope.schemas.indexOf(schema);
$scope.schemas.splice(i, 1);
$scope.choosedSchema = null;
});
}
};
srvSite.get().then(function (oSite) {
var entryMschemaId;
$scope.site = oSite;
srvSite.snsList().then(function (data) {
$scope.sns = data;
});
if (location.hash) {
$scope.entryMschemaId = entryMschemaId = location.hash.substr(1);
srvMschema.get(entryMschemaId).then(function (oMschema) {
shiftAttr(oMschema);
$scope.schemas = [oMschema];
$scope.chooseSchema(oMschema);
});
$scope.bOnlyone = true;
} else {
srvMschema.list('N').then(function (schemas) {
schemas.forEach(function (schema) {
shiftAttr(schema);
$scope.schemas.push(schema);
});
if ($scope.schemas.length === 0) {
$scope.schemas.push({
type: 'inner',
valid: 'N',
attrs: {
mobile: ['0', '0', '0', '0', '0', '0', '0'],
email: ['0', '0', '0', '0', '0', '0', '0'],
name: ['0', '0', '0', '0', '0', '0', '0']
}
});
}
$scope.chooseSchema(schemas[0]);
});
$scope.bOnlyone = false;
}
});
}]);
/***/
require(['domReady!'], function (document) {
angular.bootstrap(document, ["app"]);
});
/***/
return ngApp;
}); |
import React from 'react';
import { Text, View, StyleSheet} from 'react-native';
class MenuBar extends React.Component {
render(){
return (
<View style={styles.main_container}>
<View style={styles.title_view}>
<Text style={styles.title_text}> Teach'rs Favoris </Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
main_container : {
flex: 1,
backgroundColor:'blue',
marginTop:-50
},
title_view : {
flex : 1,
color: 'white',
alignItems: 'center',
justifyContent : 'flex-end'
},
title_text : {
color : 'white',
fontSize : 20,
marginBottom : 20,
}
})
export default MenuBar |
import React, { Component } from "react";
class Footer extends Component {
render() {
return (
<footer id="site_footer" className="footer">
<div class="container-fluid m-0 p-0">
<div class="row no-gutters mx-5">
<div class="col-12 col-lg-auto px-lg-5 mx-lg-5">
<h6 class="mt-3 footer-title collapsed">CUSTOMER SERVICE</h6>
<ul class="mobile-collapse list-unstyled">
<li>
<a href="#" class="footer-link text-white">
Shipping information
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
Refund
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
FAQs
</a>
</li>
</ul>
</div>
<div class="col-12 col-lg-auto px-lg-4 mx-lg-5">
<h6 class="mt-3 footer-title collapsed">NEWS AND EVENTS</h6>
<ul class="mobile-collapse list-unstyled">
<li>
<a href="#" class="footer-link text-white">
Press
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
Events
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
Testimonials
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
Recipes
</a>
</li>
</ul>
</div>
<div class="col-12 col-lg-auto px-lg-5 mx-lg-5">
<h6 class="mt-3 footer-title collapsed">PAY SECURELY</h6>
<ul class="mobile-collapse list-unstyled">
<li>
<a href="#" class="footer-link text-white">
PAY U
</a>
</li>
<li>
<a href="#" class="footer-link text-white">
PAYPAL
</a>
</li>
</ul>
</div>
<div class="col-12 col-lg-auto px-lg-5 mx-lg-5">
<ul class="mobile-collapse list-unstyled"></ul>
</div>
<div class="sign-up col-12 col-lg-auto">
<h6 class="mt-3 footer-title collapsed">
<b>Sign up to our news letter</b>
</h6>
<ul class="mobile-collapse list-unstyled">
<span>
<li class="footer-text">
signup for our mails and choc-full
</li>
<li class="footer-text">
of new arrivals and special offers.
</li>
</span>
<button
className="btn btn-danger text-center px-2 mt-2 mx-auto"
onClick={e => this.sendData(e)}
>
Subscribe now
</button>
</ul>
</div>
</div>
<div class="row">
<div class="col-12 mt-4">
<div class="text-center">
<span class="footer-text">
Smoor©2019 | All Rights Reserved.
</span>
</div>
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;
|
/**
* Created by pm on 17-10-12.
*/
import * as TYPES from './Types';
import {fetchData} from '../utils/FetchUtils';
import {createAction} from 'redux-actions';
const api = 'https://api.douban.com/v2/movie/in_theaters';
/*export let fetchList = createAction(TYPES.FETCH_MOVE_LIST, (start = 0, count = 2) => {
return fetch(`${api}?start=${start}&count=${count}`)
.then((response) => response.text())
.then((responseText) => {
const json = JSON.parse(responseText);
return json.subjects;
}).then((data) => {
for (let i = 0; i++;i<data.length){
console.log(data[i].title);
}
return data
})
.catch((error) => {
console.error(error);
});
});*/
//action 是一个用于描述已发生事件的普通对象。
const moveAction = (movie) => {
return {
type:TYPES.FETCH_MOVE_LIST,
movie,
};
};
export function fetchList(start=0,count=6) {
return fetchData(start,count,moveAction)(api);
}
export function fetchMore(start=0,count=6) {
return fetchData(start,count,moveAction)(api)
}
|
import childProcess from 'child_process';
import cb from './callback';
export default () => {
// npm init
childProcess.exec('npm init -y', (error, stdout, stderr) => {
cb(error, { stdout, stderr, message: 'Инициализирован: npm'} );
});
// git init
childProcess.exec('git init', (error, stdout, stderr) => {
cb(error, { stdout, stderr, message: "Инициализирован: git" });
});
// npm install --save-dev @babel/core @babel/node @babel/cli @babel/preset-env
childProcess.exec('npm install --save-dev @babel/core @babel/node @babel/cli @babel/preset-env', (error, stdout, stderr) => {
cb(error, { stdout, stderr, message: "Добавленны зависимости: babel"});
});
// npm install --save-dev eslint
childProcess.exec('npm install --save-dev eslint', (error, stdout, stderr) => {
cb(error, { stdout, stderr, message: "Добавленна зависимость: eslint" });
});
}; |
export const PATH_BASE = 'http://localhost:8080'; |
import { useEffect, useReducer, useState} from "react";
import "./App.css";
import { reducer ,getGrade} from "./reducer";
import Axios from "axios"
require('dotenv').config()
function App() {
const initialState = {
data: []
};
const [state, dispatch] = useReducer(reducer, initialState);
const getData = ()=>{
Axios.get('https://student-grade-api.herokuapp.com/api/v1/student').then((res)=>dispatch({type:'set',payload:res.data.students}))
}
useEffect(()=>{
getData()
},[])
const [data, setData] = useState({ id:"",name: "", score: 0, grade: "" });
const [isEdit,setIsEdit] =useState(false)
const [isSuccess,setIsSuccess] = useState({add:false,edit:false,delete:false})
const [isShow,setIsShow]=useState(false)
const handleChange = (e) => {
e.preventDefault();
const name = e.target.name;
const value = e.target.value;
setData({ ...data, [name]: value });
};
const handleAdd = (e) => {
e.preventDefault();
const { name, score } = data;
if (name && score) {
const newData = {
id:'643'+(Math.floor(Math.random()*(10000-1000+1))+1000).toString()+'21',
name,
score,
grade:getGrade(score)
};
Axios.post('https://student-grade-api.herokuapp.com/api/v1/student',newData).then((res)=>console.log(res))
dispatch({ type: "add", payload: newData });
setData({ id:"", name: "", score: 0, grade: "" });
setIsSuccess({add:true,edit:false,delete:false})
successAction()
}
};
const handleEdit = (e)=>{
e.preventDefault()
const {name,score,id} = data
if(name && score){
const newData = {
name,score,id,grade:getGrade(score)
}
Axios.patch(`https://student-grade-api.herokuapp.com/api/v1/student/${id}`,newData).then((res)=>console.log(res))
dispatch({type:'edit', payload:newData})
setData({ id:"", name: "", score: 0, grade: "" });
setIsEdit(false)
setIsSuccess({add:false,edit:true,delete:false})
successAction()
}
}
const successAction = ()=>{
setTimeout(()=>{
setIsSuccess({add:false,edit:false,delete:false})
},3000)
}
const sortByScore = (array) => {
return array.sort((a, b) => {
return b.score - a.score;
});
};
sortByScore(state.data);
return (
<div>
<div className="container mt-4">
<h1 align="center">Student Grade</h1>
<form>
<div className="container">
<div className="mb-3">
<label htmlFor="name" className="form-label">
Name :
</label>
<input
key="name"
type="text"
className="form-control"
value={data.name}
onChange={handleChange}
name="name"
></input>
</div>
<div className="mb-3">
<label htmlFor="score" className="form-label">
Score :
</label>
<input
key="score"
type="number"
className="form-control"
min="0"
max="200"
value={data.score}
name="score"
onChange={handleChange}
></input>
</div>
{!isEdit && <button className="btn btn-primary" onClick={handleAdd}>
Add
</button>}
{isEdit && <button className='btn btn-warning' onClick={handleEdit}>Edit</button>}
<button className="btn btn-secondary mx-2" onClick={(e)=>{
e.preventDefault()
setIsShow(!isShow)}}>
Show/Hide
</button>
</div>
</form>
{isSuccess.add && <p className="mt-4 mx-3 alert alert-success text-success">เพิ่มข้อมูลสำเร็จ</p> }
{isSuccess.delete && <p className="mt-4 mx-3 alert alert-danger text-danger">ลบข้อมูลสำเร็จ</p>}
{isSuccess.edit && <p className="mt-4 mx-3 alert alert-warning text-warning">แก้ไขข้อมูลสำเร็จ</p>}
<hr></hr>
{isShow &&
<div>
<h1 align="center">Student Ranking</h1>
<div>
<h6 align="right">Total :{state.data.length} | Max : {state.data.length===0?0:Math.max(...state.data.map(e=>e.score))} | Min : {state.data.length===0?0:Math.min(...state.data.map(e=>e.score))} | Mean : {state.data.length===0?0:(state.data.reduce((total,num)=>total+Number.parseFloat(num.score),0)/state.data.length).toFixed(2)}</h6>
</div>
<div className="table-responsive">
<table className="table align-middle">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Score</th>
<th scope="col">Grade</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
{state.data.map((e, i) => {
return (
<tbody key={i}>
<tr>
<th scope="row">{i + 1}</th>
<td >{e.id}</td>
<td>{e.name}</td>
<td>{parseInt(e.score)}</td>
<td>{e.grade}</td>
<td>
<button
className="btn btn-warning"
onClick={() => {
setData({name:e.name,score:e.score,id:e.id})
setIsEdit(true)
}}
>
Edit
</button>
</td>
<td>
<button
className="btn btn-danger"
onClick={() =>{
Axios.delete(`https://student-grade-api.herokuapp.com/api/v1/student/${e.id}`)
dispatch({ type: "delete", payload: e.id })
setData({ id:"",name: "", score: 0, grade: "" })
setIsEdit(false)
setIsSuccess({add:false,edit:false,delete:true})
successAction()
}
}
>
Delete
</button>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
</div>
}
</div>
</div>
);
}
export default App;
|
import React, {Component} from 'react';
import {Text, StyleSheet, View, TouchableOpacity} from 'react-native';
import FormNumber from '../../components/Form/FormNumber';
import FormPassword from '../../components/Form/FormPassword';
import LoadingIndicator from '../../components/LoadingIndicator';
import {Formik} from 'formik';
import * as Yup from 'yup';
import {connect} from 'react-redux';
import {login} from '../../redux/actions/auth';
import {showMessage} from '../../helpers/showMessage';
const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/;
const validationSchema = Yup.object().shape({
password: Yup.string()
.min(5, '*Password must have at least 5 characters')
.max(50, '*Password must be less than 50 characters')
.required('*Password is required'),
phoneNumber: Yup.string()
.matches(phoneRegExp, 'Phone number is not valid')
.required('*Phone number is required'),
});
class SignIn extends Component {
state = {
loading: false,
};
login = async (values) => {
this.setState({loading: true});
const {phoneNumber, password} = values;
await this.props.login(phoneNumber, password);
if (this.props.auth.token) {
this.setState({loading: false});
showMessage(this.props.auth.message, 'success');
this.props.navigation.replace('MainApp');
} else {
this.setState({loading: false});
showMessage(this.props.auth.errorMsg);
}
};
render() {
return (
<View style={styles.container}>
<Formik
initialValues={{
phoneNumber: '',
password: '',
}}
validationSchema={validationSchema}
onSubmit={(values) => this.login(values)}>
{({
handleChange,
handleBlur,
handleSubmit,
values,
errors,
isValid,
touched,
}) => (
<>
<TouchableOpacity onPress={handleSubmit}>
<Text style={styles.next}>Next</Text>
</TouchableOpacity>
<View style={styles.row}>
<Text style={styles.title}>Sign In</Text>
<Text style={styles.subTitle}>
Let's start your chat to {'\n'} build relationships
</Text>
<FormNumber
label="Phone Number"
placeholder="Your phone number"
onChange={handleChange('phoneNumber')}
onBlur={handleBlur('phoneNumber')}
value={values.phoneNumber}
/>
{errors.phoneNumber && touched.phoneNumber ? (
<Text style={styles.textError}>{errors.phoneNumber}</Text>
) : null}
<View style={styles.gap} />
<FormPassword
label="Password"
placeholder="Your password"
onChange={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
/>
{errors.password && touched.password ? (
<Text style={styles.textError}>{errors.password}</Text>
) : null}
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('ForgotPassword')
}>
<Text style={styles.textForgot}>Forgot Password?</Text>
</TouchableOpacity>
</View>
</>
)}
</Formik>
{this.state.loading && <LoadingIndicator />}
</View>
);
}
}
const mapStateToProps = (state) => ({
auth: state.auth,
});
const mapDispatchToProps = {login};
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000000',
padding: 20,
},
next: {
fontSize: 18,
fontFamily: 'Poppins-Medium',
color: '#ffffff',
textAlign: 'right',
},
row: {
flex: 1,
justifyContent: 'center',
},
title: {
fontSize: 28,
fontFamily: 'Poppins-Regular',
color: '#ffffff',
textAlign: 'center',
},
subTitle: {
fontSize: 16,
fontFamily: 'Poppins-Regular',
color: '#ffffff',
textAlign: 'center',
marginTop: 20,
marginBottom: 30,
},
gap: {
height: 15,
},
textForgot: {
fontSize: 14,
fontFamily: 'Poppins-Regular',
color: '#ffffff',
textAlign: 'right',
marginTop: 15,
},
textError: {
fontSize: 12,
color: 'red',
},
});
|
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles({
root: {
maxWidth: 170,
margin: '40px 0',
borderRadius: 20,
background: 'transparent',
overflow: 'visible',
},
media: {
mixBlendMode: 'multiply',
marginTop: '-40px',
width: '100%',
height: '100%',
borderRadius: '50%',
border: '1px solid #999'
},
actions: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: 0,
},
cardActions: {
'&:hover': {
background: 'transparent',
borderRadius: 20
}
}
});
export default useStyles |
import React from 'react';
import {Link} from 'react-router-dom';
import * as _ from 'lodash';
import moment from 'moment';
import './style.css';
import {getAllCourseFutureExames} from '../../../services/mock-exam';
export default class ExamHomeComponent extends React.Component{
state={
isError:false,
message:'Please wait while we are loading current exam list...',
todayExamList:[],
upcomingExamList:[],
}
componentDidMount = ()=>{
window.scroll(0,0);
getAllCourseFutureExames(this.props.courseId)
.then(data =>{
let examList = data.examList;
if(!examList || !examList.length){
this.setState({isError:false, message:'Currently we have not scheduled any exam. Our experts are working to prepare the exam for you.'});
return;
}
let todayExamList=[];
let upcomingExamList=[];
let dayStart = moment().startOf('day');
let dayEnd = moment().endOf('day');
_.forEach(examList, exam =>{
if(moment(exam.startDateTime).isBetween(dayStart,dayEnd)){
todayExamList.push(exam);
}else if(moment(exam.startDateTime).isAfter(dayEnd)){
upcomingExamList.push(exam);
}
examList = null;
});
this.setState({isError:false, message:'',
upcomingExamList:upcomingExamList,
todayExamList:todayExamList,
});
})
.catch(error =>{
this.setState({isError:true, message:'Error while loading exams.'});
});
this.setState({isError:false,message:'Please wait while loading exams...'});
}
render (){
let {todayExamList} = this.state;
let {upcomingExamList} = this.state;
if((Array.isArray(todayExamList) && todayExamList.length )
|| (Array.isArray(upcomingExamList) && upcomingExamList.length) ){
return <div className="container-fluid exam-home-container">
<div className="row">
<div> <button className="btn btn-primary" onClick={this.props.history.goBack}><span className="text-style">Back</span></button></div>
</div>
{ (Array.isArray(todayExamList) && todayExamList.length )?
<div className="container-fluid today-exam-container ">
<div className="row ">
<div className="flex-grow-1 text-center"><span className="text-style">Today's Exam</span>
</div>
</div>
<hr className="divider"/>
{
todayExamList.map((exam,index)=>{
return <div key={index} className="row ">
<div className="flex-grow-1">
<div className="container">
<div><span className="text-style">
{exam.name}
</span></div>
</div>
</div>
<div className="flex-grow-1"><span className="text-style">Start Time:{moment(exam.startDateTime).format('DD/MM/YYYY hh:mm A')}</span></div>
{moment().isAfter(moment(exam.startDateTime))?
<Link
to={
{
pathname:`${this.props.match.url}/start/`+exam.id,
state:{exam:exam}
}}
>
<span className="text-style" >Start</span>
</Link>:''}
</div>;
})
}
</div> :''}
{ (Array.isArray(upcomingExamList) && upcomingExamList.length )?
<div className="container-fluid upcoming-exam-container ">
<div className="row justify-content-center">
<div><span className="text-style">Up-Coming Exams</span></div>
</div>
<hr className="divider"/>
{
upcomingExamList.map((exam,index)=>{
return <div key={index} className="row ">
<div className="flex-grow-1">
<div className="container">
<div><span className="text-style">
{exam.name}
</span></div>
</div>
</div>
<div className="flex-grow-1"><span className="text-style">Start Time:{moment(exam.startDateTime).format('DD/MM/YYYY hh:mm A')}</span></div>
</div>;
})
}
</div> :''}
</div> ;
}else{
return <div className="container-fluid exam-home-container">
<div className="row">
<div> <button className="btn btn-primary" onClick={this.props.history.goBack}><span className="text-style">Back</span></button></div>
<div className="flex-grow-1 text-center">{this.state.message} </div>
</div>
</div>;
}
}
}; |
let squares = document.getElementsByClassName('square')
let squaresArray = Array.from(squares).forEach( e => console.log(e))
console.log(squaresArray)
console.log(squares)
/*let squaresArray = Array.from(squares.entries())
for(let i = 0; i < squares.length; i++){
squaresArray.push(squares[i])
}
console.log(squaresArray)*/
function changeBorder(element){
console.log(element)
element.border[radius] = '100px'
element.mozBorderRadius = '100px'
element.webkitBorderRadius = '100px'
} |
const merge = require('webpack-merge');
const baseConfig = require('./config/webpack.base');
const environment = process.env.NODE_ENV || 'local';
module.exports = merge(
baseConfig,
require('./config/webpack.' + environment)
)
|
import React from 'react'
import PropTypes from 'prop-types'
import BackButton from './BackButton'
const Toolbar = (props) => {
const {children, title, backTo} = props
return (
<div className="d-flex mb-2 mt-2">
<div className="form-inline">
<h4>
{backTo &&
<BackButton className="mr-2" backTo={backTo} />
}
{title}
</h4>
</div>
<div className="col pr-0">
<div className="form-inline justify-content-end">
{React.Children.map(children, (child, index) => {
if (child) return <span className="ml-2" key={index}>{child}</span>
return null
})}
</div>
</div>
</div>
)
}
Toolbar.propTypes = {
children: PropTypes.any,
title: PropTypes.any,
backTo: PropTypes.string
}
export default Toolbar
|
export const QUIZ_TYPE = {
OPTIONS: 'options',
SCALE: 'scale',
TWO_COLUMNS: 'twoColumns'
};
|
import autoprefixer from 'autoprefixer';
import tailwind from 'tailwindcss';
import tailwindConfig from './tailwind.config.js';
export default {
plugins: [tailwind(tailwindConfig), autoprefixer],
}; |
// Initializes the `user` service on path `/user`
const hooks = require('./user.hooks');
const CreateUserService = require('./customServices/createUser/user.create.service');
const CreateUserHooks = require('./customServices/createUser/user.create.hooks');
const LoginUserService = require('./customServices/loginUser/user.login.service');
const LoginUserHooks = require('./customServices/loginUser/user.login.hooks');
module.exports = function () {
const app = this;
app.use('/user/create', CreateUserService);
app.service('user/create').hooks(CreateUserHooks);
app.use('/user/login', LoginUserService);
app.service('user/login').hooks(LoginUserHooks);
};
|
import ModalWrapper from './ModalWrapper.vue';
import BaseModal from './BaseModal.vue';
function install(Vue) {
if (install.installed) return;
install.installed = true;
Vue.component('v-modal-wrapper', ModalWrapper);
Vue.component('v-modal-base', BaseModal);
}
export default { install };
export { ModalWrapper, BaseModal };
|
console.log('This would be the main JS file.');
var downloads = document.getElementById("downloads");
downloads.parentNode.removeChild(downloads);
var headerContainer = document.getElementById("a-title").parentNode;
for (var child of headerContainer.children)
{
if (child.tagName == "H2")
{
child.remove();
break;
}
}
|
import React from 'react';
const Loader = require('halogen/PulseLoader');
import './Loader.scss';
export default ({ color, size, margin, display }) => {
console.log('display: ',display);
if (!display) { return (<span></span>); }
return (
<div className="loader">
<Loader color={color} size={size} margin={margin} />
</div>
);
};
|
import { expect } from 'chai';
import { renderComponent } from '../setup';
import { favoritesList, currentCity } from '../mocks';
import FavoritesBar from '../../src/components/FavoritesBar';
import FavoriteCity from '../../src/components/FavoriteCity';
describe('<FavoritesBar /> component', () => {
let wrapper, defaultProps;
beforeEach(() => {
defaultProps = {
favorites: favoritesList,
currentCity: currentCity,
deleteFavorite: () => {},
selectFavorite: () => {}
};
wrapper = renderComponent(FavoritesBar, defaultProps);
});
it('Has list of citys', () => {
expect(wrapper.find('.list-group')).to.have.length(1);
});
it('Render all citys', () => {
expect(wrapper.find(FavoriteCity)).to.have.length( favoritesList.length );
});
it('Mark current city', () => {
expect(wrapper.find(FavoriteCity).at(0).prop('current')).to.be.true;
expect(wrapper.find(FavoriteCity).at(1).prop('current')).not.be.true;
expect(wrapper.find(FavoriteCity).at(2).prop('current')).not.be.true;
});
it('If favorites list is empty, show message', () => {
defaultProps.favorites = [];
wrapper = renderComponent(FavoritesBar, defaultProps);
expect(wrapper.text()).to.contain('Save your favorites places');
expect(wrapper.find(FavoriteCity)).to.have.length(0);
});
});
|
import Ember from 'ember';
import pagedArray from 'ember-cli-pagination/computed/paged-array';
export default Ember.Mixin.create({
sortProperties: ['createdAt:desc'],
semesterNames: Ember.computed.alias('semesters.@each.name'),
uniqueSemesters: Ember.computed.uniq('semesterNames'),
sortedGrades: Ember.computed.sort('grades', 'sortProperties'),
filteredGrades: Ember.computed.oneWay('sortedGrades'),
names: Ember.computed.alias('courses.@each.name'),
uniqueNames: Ember.computed.uniq('names'),
selectedSemester: null,
selectedCourse: null,
gradesDidChange: function(){
var grades = this.get('sortedGrades');
var selectedSemester = this.get('selectedSemester');
var selectedCourse = this.get('selectedCourse');
if( selectedCourse || selectedSemester) {
this.set('page', 1)
}
if(selectedSemester && selectedCourse) {
this.set('filteredGrades', grades.filterBy("course.semester", selectedSemester).
filterBy('course.name', selectedCourse));
} else if (selectedSemester) {
this.set('filteredGrades', grades.filterBy("course.semester", selectedSemester));
} else if (selectedCourse) {
this.set('filteredGrades', grades.filterBy("course.name", selectedCourse));
} else {
this.set('filteredGrades', grades);
}
}.observes('sortedGrades', 'sortedGrades.[]', 'selectedSemester', 'selectedCourse'),
// setup our query params
queryParams: ["page", "perPage"],
// set default values, can cause problems if left out
// if value matches default, it won't display in the URL
page: 1,
perPage: 10,
// can be called anything, I've called it pagedContent
// remember to iterate over pagedContent in your template
pagedGradeContent: pagedArray('filteredGrades', {pageBinding: "page", perPageBinding: "perPage"}),
// binding the property on the paged array
// to a property on the controller
totalPagesBinding: "pagedGradeContent.totalPages"
});
|
import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { resetCounter } from '../../actions/index';
import * as skin from './skin';
const Count = styled.span`${skin.Count}`;
const renderHistory = (history, i) => <Count key={i}>{history}</Count>;
const BackButton = styled(Link)`${skin.BackButton}`;
const List = ({ history, resetCounter }) => {
return (
<Fragment>
<BackButton onClick={() => resetCounter()} to='/'>Back to home </BackButton>
{history.length > 0 ?
history.map(renderHistory) :
'There is nothing in the history'
}
</Fragment>
);
}
List.propTypes = {
history: PropTypes.array.isRequired,
resetCounter: PropTypes.func.isRequired,
}
const mapStateToProps = state => {
const { history } = state.counter
return {
history
}
}
const mapDispatchToProps = {
resetCounter
}
export default connect(mapStateToProps, mapDispatchToProps)(List);
|
/**
* Created by MACHENIKE on 2017/2/19.
*/
import * as types from '../actionTypes.js'
const initialState = {
products:{
type:'all',
products:[]
},
list:{
type:'list',
products:[]
},
}
const getProduct = (state = initialState,action = {}) => {
let i = 0;
switch (action.type){
case types.GET_PRODUCTS:
console.log(action.products)
state.products.products = action.products;
return Object.assign([],state,{
products:{
type:'all',
products:state.products.products
}});
break;
case types.GET_LIST:
state.list.products = action.products;
return Object.assign([],state);
break;
case types.ADD_PRODUCTS:
let l = state.products.products.length;
for(;i<l;i++){
if(state.products.products[i].id==action.id){
if(state.products.products[i].num>0){
state.products.products[i].num -=1;
let i1 = 0,l1 = state.list.products.length,s =true;
if(l1>0){
for(;i1<l1;i1++){
if(state.list.products[i1].id==action.id){
s = false
state.list.products[i1].num +=1;
break
}
}
if(s){
state.list.products.push(Object.assign({},state.products.products[i],{num:1}))
}
}else{
state.list.products.push(Object.assign({},state.products.products[i],{num:1}))
}
}else{
alert('库存不足')
}
}
}
return Object.assign([],state,{
products:{
type:'all',
products:state.products.products
},
list:{
type:'list',
products:state.list.products
}
});
break;
case types.REMOVE_PRODUCTS:
let listLength = state.list.products.length;
for(;i<listLength;i++){
if(state.list.products[i].id==action.id){
if(state.list.products[i].num>1){
state.list.products[i].num -=1;
}else{
state.list.products.splice(i,1);
}
let listLength1 = 0,productsLength = state.products.products.length;
for(;listLength1<productsLength;listLength1++){
if(state.products.products[listLength1].id==action.id){
state.products.products[listLength1].num +=1;
break
}
}
break
}
}
return Object.assign([],state,{
products:{
type:'all',
products:state.products.products
},
list:{
type:'list',
products:state.list.products
}
});
break;
default: return state
}
}
export default getProduct |
import React from 'react'
import { Form, Row, Col, DatePicker } from 'antd'
const FormItem = Form.Item;
const formItemLayout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
class BenefitHeader extends React.Component {
state = {
startValue: null,
endValue: null,
endOpen: false,
}
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
console.log(values);
this.props.onSubmit(err, values);
});
}
/********开始、结束日期关联***********/
disabledStartDate = (startValue) => {
const endValue = this.state.endValue;
if (!startValue || !endValue) {
return false;
}
return startValue.valueOf() > endValue.valueOf();
}
disabledEndDate = (endValue) => {
const startValue = this.state.startValue;
if (!endValue || !startValue) {
return false;
}
return endValue.valueOf() <= startValue.valueOf();
}
onChange = (field, value) => {
this.setState({
[field]: value,
});
}
onStartChange = (value) => {
this.onChange('startValue', value);
}
onEndChange = (value) => {
this.onChange('endValue', value);
}
handleStartOpenChange = (open) => {
if (!open) {
this.setState({ endOpen: true });
}
}
handleEndOpenChange = (open) => {
this.setState({ endOpen: open });
}
/********开始、结束日期关联*********/
render(){
const { endOpen } = this.state;
const { getFieldDecorator } = this.props.form;
return (
<Form onSubmit={this.handleSubmit}>
<Row gutter={16}>
<Col span={12}>
<FormItem {...formItemLayout} label={`开始日期`}>
{getFieldDecorator(`startTime`,{
rules: [{ required: true, message: '请输入开始日期', }]
})(
<DatePicker disabledDate={this.disabledStartDate}
format="YYYY-MM-DD"
placeholder="开始日期"
onChange={this.onStartChange}
onOpenChange={this.handleStartOpenChange}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`结束日期`}>
{getFieldDecorator(`endTime`,{ rules: [{ required: true, message: '请输入开始日期', }] })(
<DatePicker disabledDate={this.disabledEndDate}
format="YYYY-MM-DD"
placeholder="结束日期"
onChange={this.onEndChange}
open={endOpen}
onOpenChange={this.handleEndOpenChange}
/>
)}
</FormItem>
</Col>
</Row>
</Form>
)
}
}
BenefitHeader = Form.create()(BenefitHeader)
export default BenefitHeader
|
function iterator(arr) {
var position = 0;
return {
hasNext: function() {
return position < arr.length;
},
getNext: function() {
return arr[position++];
}
};
}
(function() {
var i = iterator([5, 7, 9]);
while (i.hasNext()) {
console.log(i.getNext());
}
})();
|
export const theme = {
breakpoints: [850],
spaces: ["8px", "14px", "20px", "28px", "34px", "68px", "88px", "126px", "164px", "316px"],
borderWidths: ["1px", "1.5px", "2px"],
borderRadius: "2px",
fontSizes: ["14px", "16px", "18px"],
color: {
text: "#33475b",
primary: "#7c99b6",
title: "#374a5e",
background: "#ffffff",
lightHighlight: "#f5f8fad8",
light: "#f5=> tf8fa",
gray: "#cbd6e2",
lightGray: "#dfe3eb",
lightGray1: "#d1dbe6",
},
transition: {
duration: "0.8s",
rotations: ["-90deg", "-180deg", "-270deg"],
},
};
|
X.define("modules.contract.contractEdit",["adapter.webuploader","model.contractModel","common.layer"],function (webuploader,contractModel,layer) {
//初始化视图对象
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.contract.tpl.contractEdit
});
//初始化控制器
var ctrl = X.controller.newOne({
view: view
});
ctrl.rendering = function () {
//渲染页面
var addContractFunction = function(data){
return view.render(data,function () {
ctrl.vmaddContract = ctrl.getViewModel(ctrl.view.el.find(".js-addContractForm"),{meta: {"contractAttachmentList": {size: 30,type:7,downloadType:4,showExplain:true,explainMaxlength:20,filePicker:".filePicker",filePickerLabel:"添加合同附件"}},data:data});
ctrl.vmaddContract.initControl();
//合同表单验证
ctrl.validate = {
rules: {
salesman: {
isChinese: true,
rangelength: [2,4]
},
customerName: {
required: true,
isChineseNumber:true,
rangelength: [6,50]
},
contractName: {
required: true,
isContractName: true
}
},
messages: {
salesman: {
isChinese: "请输入2-4个汉字",
rangelength: "请输入2-4个汉字"
},
customerName: {
required: "请输入6-50个汉字或数字组合",
isChineseNumber:"请输入6-50个汉字或数字组合",
rangelength: "请输入6-50个汉字或数字组合"
},
contractName: {
required: "请输入1-50个字符",
isContractName: "该合同名称已注册"
}
},
onkeyup: false,
onfocusout: function (element) {
var elem = $(element);
elem.valid();
},
success: function(value,element){
},
errorPlacement: function (error, element) {
var errorWrap = element.parent().find(".js-error");
errorWrap.html("");
error.appendTo(errorWrap);
}
};
if(_para["contractId"]){
ctrl.validate.rules.contractName.isContractName = false;
ctrl.addEvent("change", ".js-contractName", "checkFun");
ctrl.checkFun =function(){
if (ctrl.view.el.find(".js-contractName").val() == data.contractName){
ctrl.validate.rules.contractName.isContractName = false;
}else{
ctrl.validate.rules.contractName.isContractName = true;
}
};
}
ctrl.view.el.find(".js-addContractForm").validate(ctrl.validate);
});
};
var callback = function(result){
var data = result.data[0];
addContractFunction(data);
};
if(_para["contractId"]){
//编辑合同
ctrl.getContractData(callback);
}else{
//创建合同
addContractFunction({});
}
};
//获取合同信息
ctrl.getContractData = function(callback){
var data = {
contractId:_para["contractId"]
};
contractModel.getContract(data,callback);
};
//提交合同信息
ctrl.submitInfo = function (){
ctrl.publicMethod();
};
//保存合同信息
ctrl.saveInfo = function (){
ctrl.publicMethod(true);
};
ctrl.publicMethod = function (save){
if(ctrl.vmaddContract.getValue("contractAttachmentList").contractAttachmentList.length){
if(ctrl.view.el.find(".js-addContractForm").valid()){
ctrl.publicMethodSubmitSave(save);
}
}else{
var wrapAttachError = ctrl.view.el.find(".js-attachError");
if(!wrapAttachError.html()){
var error = '<label class="error">附件不能为空</label>';
$(error).appendTo(wrapAttachError);
}
}
};
ctrl.publicMethodSubmit = function(contnet,num){
var data = ctrl.vmaddContract.collectData();
data.contractStatus = num;
var callback = function(result){
var submitCallback;
if(result.statusCode == 2000000){
submitCallback = function (index){
layer.closeIt(index);
X.router.back();
};
layer.successBtn(contnet,"提示",submitCallback);
}else{
submitCallback = function (index){
layer.closeIt(index);
X.publish(X.CONSTANTS.channel.menuCall,{m:"contract.contractList"});
};
layer.successBtn(result.message,"提示",submitCallback);
}
};
if(_para["contractId"]){
data.contractId = _para["contractId"];
//编辑合同
contractModel.changeContract(data,callback);
}else{
//创建合同
contractModel.addContract(data,callback);
}
};
ctrl.publicMethodSubmitSave = function(save){
if(save){
//保存合同信息
ctrl.publicMethodSubmit("保存成功",0);
}else{
//提交合同信息
var layerCallback = function (index){
ctrl.publicMethodSubmit("提交成功",1);
layer.closeIt(index);
};
layer.successConfirm("确定提交此合同信息?",layerCallback,"提示");
}
};
//最大输入100个字符
ctrl.maxNumber = function (event){
var value = $(this.that).val();
if (value.length >= 100 && event.keyCode !== 8 && event.keyCode !== 37 && event.keyCode !== 38 &&
event.keyCode !== 39 && event.keyCode !== 40 && event.keyCode !== 46) {
event.returnValue = false;
}
};
ctrl.addEvent("click", ".js-submit", "submitInfo");
ctrl.addEvent("click", ".js-preservation", "saveInfo");
ctrl.addEvent("keydown", ".js-contractRemark", "maxNumber");
var _para;
ctrl.load = function(para){
para = para || {};
_para = para ;
ctrl.rendering();
};
return ctrl;
}); |
import React from "react";
const List = ({ list, remove }) => (
<>
{list.map((el) => (
<div key={el.id} className="card mt-4 p-2 hov">
<div className="list">
<div>{el.title}</div>
<div className="del">
<div
className={`mx-5 ${el.type === "pos" ? "pos" : "neg"}`}
>{`${el.price.toLocaleString().replace(/,/g, " ")} HUF`}</div>
<button onClick={() => remove(el)} className="btn btn-secondary">
Törlés
</button>
</div>
</div>
</div>
))}
</>
);
export default List;
|
"use realm";
const UL = {
tag: 'ul',
menu: true,
inline: true,
icon: 'unordered-list',
hint: 'Bulleted list',
toBBCode: function(root) {
while (root.find('ul').length > 0) {
root.find('ul').each(function(index, element) {
$(element).replaceWith('[ul]' + $(element).html() + '[/ul]');
});
}
},
cmd: function() {
this.execCommand('insertunorderedlist');
},
toProduction: function(item) {
return '<ul>'
}
}
export UL;
|
import { combineReducers } from "redux"
import programs from "./programs"
const rootReducer = combineReducers({
programs,
})
export default rootReducer
|
import {
rhythm,
scale
} from '../../lib/traits'
export default {
root: {
padding: rhythm(1),
textAlign: 'center',
fontSize: scale(2)
}
}
|
//cho tai tai lieu xong
$(document).ready(function(){
sukien();
});
function sukien(){
$('#show').click(function(){
$('#image').show(800,function(){
$('#image').hide(800);
});
});
$('#hide').click(function(){
$('#image').hide(800,function(){
$('#image').show(800);
});
});
$('#change').click(function(){
$('#image').toggle(800);
});
$('#sl').click(function(){
// $('#image').slideDown(1000);
$( "#image" ).slideDown(800);
});
$('#sl1').click(function(){
$('#image').slideUp(800);
});
$('#sl2').click(function(){
$('#image').slideToggle(800);
});
$('#fadein').click(function(){
$('#image').fadeIn(8000);
})
$('#fadeout').click(function(){
$('#image').fadeOut(8000);
})
$('#fadetoggle').click(function(){
$('#image').fadeToggle(500);
})
} |
const _ = require('lodash')
const getPopupPosition = (x, y, popupHeight) => {
let popupPosition = ''
const popupWidth = 500
// Header height + popup above pin
const fromTop = 80
// too high
if (y < (popupHeight + fromTop)) {
popupPosition = popupPosition + 'top '
}
// too right
if ((window.innerWidth - x) < popupWidth / 2) {
popupPosition = popupPosition + 'right'
}
// too left
if (x < popupWidth / 2) {
popupPosition = popupPosition + 'left'
}
return popupPosition
}
const createWebString = (text) => {
if (text.length > 50) {
text = text.substring(0, 50)
}
text = text.replace(/\s/g, '-')
text = encodeURIComponent(text)
return text
}
const randId = () => {
return Math.random().toString(36).substr(2, 5)
}
const validateFields = (f, mode) => {
let errors = {}
if (mode === 'login' || mode === 'signup') {
if (_.isEmpty(f.password)) {
errors['password'] = "Password can't be blank"
} else if (f.password.length < 6) {
errors['password'] = 'Please use at least 6 characters'
}
}
if (mode === 'signup') {
if (_.isEmpty(f.passwordConfirm)) {
errors['password'] = 'Please confirm your password'
} else if (f.password !== f.passwordConfirm) {
errors['password'] = "Passwords don't match"
}
}
if (mode === 'update' && !_.isEmpty(f.password)) {
if (f.password.length < 6) {
errors['password'] = 'Please use at least 6 characters'
} else if (f.password !== f.passwordConfirm) {
errors['password'] = "Passwords don't match"
}
}
if (mode === 'signin' || mode === 'update') {
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if (_.isEmpty(f.email)) {
errors['email'] = "Email can't be blank"
} else if (!f.email.match(re)) {
errors['email'] = 'Not a valid email'
}
}
return errors
}
const sanitizePinTitle = (text) => {
return text.replace(/[^\w\s!.,:'&()$\-\"]/gi, '')
}
module.exports = {
getPopupPosition: getPopupPosition,
sanitizePinTitle: sanitizePinTitle,
createWebString: createWebString,
randId: randId,
validateFields: validateFields
}
|
var widgetConfig = {
title: 'Reeds Ideal Hearts and Arrows diamond',
pages: [
{
title: 'Summary',
code: 'summary'
},
{
title: 'Hearts & Arrows',
code: 'hna'
},
{
title: 'Loupe',
code: 'loupe'
},
{
title: 'Inscription',
code: 'loupeInscription'
},
{
title: 'Cut',
code: 'cut'
}
]
};
|
/**
* Draw question card with provided data
* @param {Object} cardContent - card data (question, options, img, ID...) to draw
* @param {number} cardContent.id
* @param {string} cardContent.question
* @param {string[]} cardContent.options
* @param {string} [cardContent.img]
* @param {number} cardContent.numberPerGroup
* @param {number} cardContent.group
* @param {number} [cardContent.chosenOption]
* @return {void} Nothing
*/
// group, numberpergroup, img, question
function drawCard({ group, numberPerGroup, img, question, options, cardId }) {
// Create meta-element
const metaElement = document.getElementById('question-id')
metaElement.innerHTML = '';
metaElement.textContent =
`Г${group}, В${numberPerGroup}`;
// Create img element
document.getElementById('image-container').innerHTML = '';
if (img) {
const imageElement = document.createElement('img');
imageElement.src = 'app/content/' + cardContent.img;
document.getElementById('image-container').appendChild(imageElement);
}
// Create question element
const questionElement = document.getElementById('question-text');
questionElement.innerHTML = '';
questionElement.textContent = question;
// create options
const { isAnswered,
isfirstAnswerCorrect,
correctAnswer,
firstselectedOption } = getCardAnswerHistory(cardId, allCards)
if (isAnswered) {
if (isfirstAnswerCorrect) {
drawOptions({
'options': options,
'cardId': cardId,
'correctId': correctAnswer - 1
})
} else if (!isfirstAnswerCorrect) {
drawOptions({
'options': options,
'cardId': cardId,
'correctId': correctAnswer - 1,
'wrongId': firstselectedOption
})
}
} else if (!isAnswered) {
drawOptions({
'options': options,
'cardId': cardId
})
}
};
function drawOptions({ cardId, options, correctId = null, wrongId = null, isButtonDisabled = true }) {
const nextUnansweredButton = document.getElementById('next-unanswered-button');
const optionsContainerElement = document.getElementById('options-container');
if (isButtonDisabled) {
nextUnansweredButton.classList.add('disabled')
} else if (!isButtonDisabled) {
nextUnansweredButton.addEventListener('click', nextButtonListener);
nextUnansweredButton.classList.remove('disabled');
};
optionsContainerElement.innerHTML = '';
options.forEach((option, optionIndex) => {
const optionElement = document.createElement('div');
optionElement.textContent = option;
optionElement.classList.add('singleOption', 'disable-hover');
optionElement.id = `option-${optionIndex}`;
optionsContainerElement.appendChild(optionElement);
if (correctId === null) {
optionElement.classList.remove('disable-hover');
const optionListener = function () {
// console.log(`answer - ${cardContent.answer}, chosenOption - ${optionIndex}`)
// TODO remove reload from answerCard
const { correctId, wrongId } = answerCard(cardId, optionIndex, answeredCards = getAnsweredCards(), allCards)
drawOptions({
'options': options,
isButtonDisabled: false,
'wrongId': wrongId,
'correctId': correctId
})
}
optionElement.addEventListener('click', optionListener);
}
});
if (correctId !== null) {
const correctOptionElement = document.getElementById(`option-${correctId}`)
correctOptionElement.classList.add('correct');
};
if (wrongId !== null) {
const wrongOptionElement = document.getElementById(`option-${wrongId}`)
wrongOptionElement.classList.add('error');
}
}
function nextButtonListener() {
const nextCardId = getNextUnansweredId(allCards, getAnsweredCards())
if (nextCardId) {
drawNewPage(nextCardId, allCards, answeredCards = getAnsweredCards())
} else throw console.error(`Wrong card ID: ${nextCardId}`);
}
/**
*
* @param {Object<number, boolean|null>} cardsStateList
* @param {number} openedCardId
* @param {object} allCards
*/
function drawTabList(groupList, selectedGroup, openedCardId) {
document.getElementById('group-bar').innerHTML = '';
for (let groupNumber of groupList) {
const groupLinkElement = document.createElement('div');
groupLinkElement.textContent = groupNumber;
groupLinkElement.classList.add('group-link', 'tab', 'active');
groupLinkElement.setAttribute('data-tabs', `group-${groupNumber}`);
document.getElementById('group-bar').appendChild(groupLinkElement);
if (groupNumber !== selectedGroup) {
const groupTabListener = function () {
drawCardList(getGroupCardStateList(groupNumber, allCards, answeredCards = getAnsweredCards()), openedCardId)
drawTabList(getAllGroupList(allCards), groupNumber, openedCardId)
}
groupLinkElement.classList.remove('active')
groupLinkElement.addEventListener('click', groupTabListener);
}
}
}
// 203 : {isCorrect: false, group: 2, numberPerGroup: 72}
function drawCardList(cardsStateList, openedCardId) {
document.getElementById('card-list-container').innerHTML = '';
for (let cardId in cardsStateList) {
cardId = parseInt(cardId)
const cardLinkElement = document.createElement('div');
cardLinkElement.textContent = cardsStateList[cardId]['numberPerGroup'];
cardLinkElement.classList.add('card-link', `card-${cardId}`);
cardLinkElement.addEventListener('click', function () {
drawNewPage(cardId, allCards, answeredCards = getAnsweredCards())
});
if (cardsStateList[cardId]['isCorrect'] === true) { cardLinkElement.classList.add('correct') }
else if (cardsStateList[cardId]['isCorrect'] === false) { cardLinkElement.classList.add('wrong') }
console.log(`cardId: ${typeof (cardId)} openedCardId: ${typeof (openedCardId)}`)
if (openedCardId === cardId) {
console.log(`currently selected card: ${cardId}`)
cardLinkElement.classList.add('current')
cardLinkElement.classList.remove('correct', 'wrong')
}
document.getElementById('card-list-container').appendChild(cardLinkElement);
}
}
function answerCard(cardId, optionId, answeredCards = getAnsweredCards(), allCards) {
return logAnswer(cardId, optionId, answeredCards, allCards)
}
function drawNewPage(cardId, allCards, answeredCards = getAnsweredCards(), groupList = getAllGroupList()) {
// if cardId null, draw emptystate "all question being answered"
drawCard(cardContent = getContentForCard(cardId, allCards, answeredCards))
const selectedGroup = getCardGroup(cardId, allCards)
drawTabList(groupList, selectedGroup, cardId)
const cardsStateList = getGroupCardStateList(selectedGroup, allCards, answeredCards)
drawCardList(cardsStateList, openedCardId = cardId)
saveState(cardId, 'currentCardAll')
}
|
import React from 'react';
import {Container, Row, Col, Image} from 'react-bootstrap';
import SocialIcons from "../commons/social-icons";
import './footer.css';
const Footer = ({conf}) => {
return (
<div id={"location"} className={"black-section"}>
<div className={"section footer"}>
<Container>
<Row>
<Col sm={4}>
<div>
<Image fluid src={require('./images/new_logo_grey.svg')}/>
</div>
</Col>
<Col sm={8}>
<SocialIcons addStyle={{float: 'left', color: 'white'}}/>
</Col>
</Row>
<Row className={"align-items-end justify-content-center"}>
<Col sm={4} xs={12}>
<div className={"phone-info footer"}>
<span>{conf.phoneText}</span>
</div>
<div className={"other-info"}>
<span>{conf.email}</span>
</div>
<div className={"other-info"}>
<span>Адрес: { conf.address.city }, { conf.address.address }</span>
</div>
</Col>
<Col sm={5} xs={12}>
<div className={"other-info"}>
<span>️<i className={"fa fa-copyright"}/> 2019 Петровград недвижимость</span>
</div>
<div className={"other-info"}>
<span>
График работы:
</span>
</div>
<div className={"other-info"}>
<span>
понедельник-пятница 10:00–19:00
</span>
</div>
<div className={"other-info"}>
<span>
суббота 11:00–18:00, воскресенье — выходной
</span>
</div>
</Col>
<Col sm={3} xs={12}>
<div className={"other-info"}>
<span>Пользовательское соглашение</span>
</div>
</Col>
</Row>
</Container>
</div>
</div>
);
};
export default Footer; |
import { GraphQLObjectType, GraphQLString, GraphQLID } from 'graphql'
import organizationType from './organization'
import { HostEnum } from './enums'
const image = new GraphQLObjectType({
name: 'image',
fields: () => ({
id: {
type: GraphQLID
},
title: {
type: GraphQLString
},
host: {
type: HostEnum
},
description: {
type: GraphQLString
},
localId: {
type: GraphQLString
},
organization: {
type: organizationType,
async resolve(src) {
try {
return await src.getOrganization()
} catch (ex) {
console.error(ex)
}
}
},
format: {
type: GraphQLString
},
captionCredit: {
type: GraphQLString
}
})
})
export default image
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.