text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import { render} from 'react-dom';
import InvoiceTmp from '../../src';
import styled from 'styled-components';
const Container = styled.div`
margin: 60px auto;
width:720px;
padding: 30px 60px;
box-shadow: 10px 10px 5px #888888;
background: #f9f9f9;
`;
const App = () => <Container><InvoiceTmp/></Container>;
render(<App />, document.getElementById("root"));
|
function selectRegion(){
var id_region = $('select[name="region"]').val();
if(!id_region){
$('div[name="selectDataRegion"]').html('');
}
else {
$.ajax({
type: "GET",
url: "../region_selector",
data: {'id_region': id_region},
dataType: "json",
success: function(city_list) {
var html = '';
$.each(city_list, function (i, d){
html += '<option value="' + d + '">' + d + '</option>';
});
$("#city").html(html);
}
});
};
};
function EmailCheck(val) {
var re = /^[\w-\.]+@[\w-]+\.[a-z]{2,4}$/i;
var valid = re.test(val);
if (valid) output = 'black';
else output = 'red';
document.getElementById('email').style.color = output;
}
function PhoneCheck(val) {
var re = /^\d[\d\(\)\ -]{4,14}\d$/;
var valid = re.test(val);
if (valid) output = 'black';
else output = 'red';
document.getElementById('phone').style.color = output;
}
function SubmitCorrectData()
{
var phone_col = document.getElementById('phone').style.color;
var email_col = document.getElementById('email').style.color;
if ((phone_col == 'black' && email_col =='black')) return true;
else
{
alert("Данные телефона или почты неверно введены. Проверьте правильность ввода.");
return false;
}
}
|
import React, { useContext, useEffect, useState } from 'react';
import OrderStatus from './OrderStatus';
import { useLocation } from "react-router-dom"
import io from 'socket.io-client'
import {SweetOrderStatusUpdated} from '../../../SweetAlert'
import api from '../../../utils/api';
import Loader from '../../../components/Loader';
import { Context } from '../../../utils/context';
const Order = () => {
const { state } = useLocation()
const [data=state, {}] = useContext(Context)
const [isLoading, setIsLoading] = useState(true)
const [order, setOrder] = useState([])
const [activeStep,setActiveStep] = useState(0);
const order_status = {
"order_placed" : 0,
"order_confirm" : 1,
"order_prepare" : 2,
"order_out" : 3,
"order_deliverd": 4
}
const getSteps =
[
'Order Placed Succesfully',
'Order Confirm By Speedyfood',
'Preparing Food',
'Your Order Is Out For Delivery',
'Order Deliverd Successfully'
]
useEffect(() => {
const getOrders = async () => {
const res = await api.post('/singleorder',{email:data.user?.email,id:state?.id})
setIsLoading(false)
setOrder(res.data)
setActiveStep(order_status[res.data.status])
}
getOrders()
const socket = io(`http://localhost:5000/`,{
withCredentials: true
})
// const socket = io(`${process.env.REACT_APP_ENDPOINT}`,{
// withCredentials: true
// })
socket.on("connect",() => {
socket.emit('join',`order_${state.id}`)
socket.on('orderUpdated',(data) => {
setActiveStep(order_status[data.status])
SweetOrderStatusUpdated(getSteps[order_status[data.status]])
})
})
return () => {
socket.off()
}
},[activeStep,state?.id])
if(isLoading) return <Loader />
return (
<section className="mt-3 md:mt-10">
<div className="md:mx-36 order grid grid-cols-1 md:gap-12 md:grid-cols-2">
<div className="">
<h1 className="text-center font-bold text-xl text-gray-700 my-4">Items</h1>
{
order?.items?.map((item) => {
return (
<div key={item.id} className="flex items-center justify-center p-2 md:ml-4 border-gray-200 border-b-2 md:py-4">
<img className="w-24" src={item.image} alt="" />
<div className="flex-1 item-name ml-2 md:ml-4">
<h1 className="text-sm md:text-lg">{item.title}</h1>
</div>
<div className="flex-1 align-middle ml-2 md:ml-0">
<span className="text-base md:text-lg inline-block">{item.qty} Pcs</span>
</div>
<span className="font-bold text-base md:text-lg">{item.price} Rs</span>
</div>
)
})
}
</div>
<div className="mx-auto md:col-span-1">
<h1 className="text-center font-bold text-xl text-gray-700 my-4">Order Status</h1>
<OrderStatus status={activeStep} />
</div>
</div>
</section>
);
}
export default Order
|
module.exports = {
"_embedded" : {
"permissions" : [ {
"status" : null,
"created" : "2020-05-08T06:29:53.793Z",
"lastModified" : "2020-05-08T06:29:53.793Z",
"isDeleted" : false,
"name" : "create",
"entity" : "casts",
"code" : "CREATE_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f5"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f5"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.796Z",
"lastModified" : "2020-05-08T06:29:53.796Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "casts",
"code" : "DELETE_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fa"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fa"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.796Z",
"lastModified" : "2020-05-08T06:29:53.796Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "casts",
"code" : "EDIT_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f9"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f9"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.795Z",
"lastModified" : "2020-05-08T06:29:53.795Z",
"isDeleted" : false,
"name" : "view",
"entity" : "casts",
"code" : "VIEW_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f8"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f8"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.794Z",
"lastModified" : "2020-05-08T06:29:53.794Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "casts",
"code" : "DEACTIVATE_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f7"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f7"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.793Z",
"lastModified" : "2020-05-08T06:29:53.793Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "casts",
"code" : "ACTIVATE_CAST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f6"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f6"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.813Z",
"lastModified" : "2020-05-08T06:29:53.813Z",
"isDeleted" : false,
"name" : "create",
"entity" : "catalogs",
"code" : "CREATE_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30f"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30f"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.817Z",
"lastModified" : "2020-05-08T06:29:53.817Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "catalogs",
"code" : "DEACTIVATE_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f314"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f314"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.816Z",
"lastModified" : "2020-05-08T06:29:53.816Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "catalogs",
"code" : "ACTIVATE_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f313"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f313"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.816Z",
"lastModified" : "2020-05-08T06:29:53.816Z",
"isDeleted" : false,
"name" : "view",
"entity" : "catalogs",
"code" : "VIEW_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f312"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f312"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.815Z",
"lastModified" : "2020-05-08T06:29:53.815Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "catalogs",
"code" : "DELETE_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f311"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f311"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.814Z",
"lastModified" : "2020-05-08T06:29:53.814Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "catalogs",
"code" : "EDIT_CATALOG",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f310"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f310"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.788Z",
"lastModified" : "2020-05-08T06:29:53.788Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "categories",
"code" : "ACTIVATE_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f0"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f0"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.792Z",
"lastModified" : "2020-05-08T06:29:53.792Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "categories",
"code" : "DELETE_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f4"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f4"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.791Z",
"lastModified" : "2020-05-08T06:29:53.791Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "categories",
"code" : "EDIT_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f3"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f3"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.790Z",
"lastModified" : "2020-05-08T06:29:53.790Z",
"isDeleted" : false,
"name" : "view",
"entity" : "categories",
"code" : "VIEW_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f2"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f2"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.789Z",
"lastModified" : "2020-05-08T06:29:53.789Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "categories",
"code" : "DEACTIVATE_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f1"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2f1"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.787Z",
"lastModified" : "2020-05-08T06:29:53.787Z",
"isDeleted" : false,
"name" : "create",
"entity" : "categories",
"code" : "CREATE_CATEGORY",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ef"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ef"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.781Z",
"lastModified" : "2020-05-08T06:29:53.781Z",
"isDeleted" : false,
"name" : "view",
"entity" : "channels",
"code" : "VIEW_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e9"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e9"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.786Z",
"lastModified" : "2020-05-08T06:29:53.786Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "channels",
"code" : "RETRIEVE_BCM_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ee"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ee"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.785Z",
"lastModified" : "2020-05-08T06:29:53.785Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "channels",
"code" : "DELETE_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ed"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ed"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.784Z",
"lastModified" : "2020-05-08T06:29:53.784Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "channels",
"code" : "EDIT_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ec"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ec"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.783Z",
"lastModified" : "2020-05-08T06:29:53.783Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "channels",
"code" : "DEACTIVATE_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2eb"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2eb"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.782Z",
"lastModified" : "2020-05-08T06:29:53.782Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "channels",
"code" : "ACTIVATE_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ea"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ea"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.780Z",
"lastModified" : "2020-05-08T06:29:53.780Z",
"isDeleted" : false,
"name" : "create",
"entity" : "channels",
"code" : "CREATE_CHANNEL",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e8"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e8"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.769Z",
"lastModified" : "2020-05-08T06:29:53.769Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "clips",
"code" : "DEACTIVATE_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2de"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2de"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.773Z",
"lastModified" : "2020-05-08T06:29:53.773Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "clips",
"code" : "DELETE_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e1"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e1"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.772Z",
"lastModified" : "2020-05-08T06:29:53.772Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "clips",
"code" : "EDIT_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e0"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e0"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.767Z",
"lastModified" : "2020-05-08T06:29:53.767Z",
"isDeleted" : false,
"name" : "create",
"entity" : "clips",
"code" : "CREATE_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2dc"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2dc"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.768Z",
"lastModified" : "2020-05-08T06:29:53.768Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "clips",
"code" : "ACTIVATE_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2dd"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2dd"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.770Z",
"lastModified" : "2020-05-08T06:29:53.770Z",
"isDeleted" : false,
"name" : "view",
"entity" : "clips",
"code" : "VIEW_CLIP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2df"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2df"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.823Z",
"lastModified" : "2020-05-08T06:29:53.823Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "configuration",
"code" : "DELETE_CONFIGURATION",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31c"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31c"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.821Z",
"lastModified" : "2020-05-08T06:29:53.821Z",
"isDeleted" : false,
"name" : "create",
"entity" : "configuration",
"code" : "CREATE_CONFIGURATION",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f319"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f319"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.822Z",
"lastModified" : "2020-05-08T06:29:53.822Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "configuration",
"code" : "EDIT_CONFIGURATION",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31a"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31a"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.823Z",
"lastModified" : "2020-05-08T06:29:53.823Z",
"isDeleted" : false,
"name" : "view",
"entity" : "configuration",
"code" : "VIEW_CONFIGURATION",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31b"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f31b"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.800Z",
"lastModified" : "2020-05-08T06:29:53.800Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "contracts",
"code" : "EDIT_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ff"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ff"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.800Z",
"lastModified" : "2020-05-08T06:29:53.800Z",
"isDeleted" : false,
"name" : "view",
"entity" : "contracts",
"code" : "VIEW_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fe"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fe"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.797Z",
"lastModified" : "2020-05-08T06:29:53.797Z",
"isDeleted" : false,
"name" : "create",
"entity" : "contracts",
"code" : "CREATE_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fb"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fb"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.798Z",
"lastModified" : "2020-05-08T06:29:53.798Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "contracts",
"code" : "ACTIVATE_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fc"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fc"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.799Z",
"lastModified" : "2020-05-08T06:29:53.799Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "contracts",
"code" : "DEACTIVATE_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fd"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2fd"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.802Z",
"lastModified" : "2020-05-08T06:29:53.802Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "contracts",
"code" : "DELETE_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f301"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f301"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.802Z",
"lastModified" : "2020-05-08T06:29:53.802Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "contracts",
"code" : "RETRIEVE_BCM_CONTRACT",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f300"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f300"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.762Z",
"lastModified" : "2020-05-08T06:29:53.762Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "episodes",
"code" : "DEACTIVATE_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d7"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d7"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.760Z",
"lastModified" : "2020-05-08T06:29:53.760Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "episodes",
"code" : "ACTIVATE_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d6"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d6"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.759Z",
"lastModified" : "2020-05-08T06:29:53.759Z",
"isDeleted" : false,
"name" : "view",
"entity" : "episodes",
"code" : "VIEW_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d5"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d5"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.758Z",
"lastModified" : "2020-05-08T06:29:53.758Z",
"isDeleted" : false,
"name" : "create",
"entity" : "episodes",
"code" : "CREATE_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d4"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d4"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.765Z",
"lastModified" : "2020-05-08T06:29:53.765Z",
"isDeleted" : false,
"name" : "approve",
"entity" : "episodes",
"code" : "APPROVE_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2da"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2da"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.766Z",
"lastModified" : "2020-05-08T06:29:53.766Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "episodes",
"code" : "RETRIEVE_BCM_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2db"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2db"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.764Z",
"lastModified" : "2020-05-08T06:29:53.764Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "episodes",
"code" : "DELETE_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d9"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d9"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.763Z",
"lastModified" : "2020-05-08T06:29:53.763Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "episodes",
"code" : "EDIT_EPISODE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d8"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d8"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.807Z",
"lastModified" : "2020-05-08T06:29:53.807Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "licensors",
"code" : "EDIT_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f306"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f306"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.806Z",
"lastModified" : "2020-05-08T06:29:53.806Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "licensors",
"code" : "DEACTIVATE_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f305"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f305"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.805Z",
"lastModified" : "2020-05-08T06:29:53.805Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "licensors",
"code" : "ACTIVATE_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f304"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f304"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.804Z",
"lastModified" : "2020-05-08T06:29:53.804Z",
"isDeleted" : false,
"name" : "view",
"entity" : "licensors",
"code" : "VIEW_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f303"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f303"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.803Z",
"lastModified" : "2020-05-08T06:29:53.803Z",
"isDeleted" : false,
"name" : "create",
"entity" : "licensors",
"code" : "CREATE_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f302"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f302"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.808Z",
"lastModified" : "2020-05-08T06:29:53.808Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "licensors",
"code" : "DELETE_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f308"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f308"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.808Z",
"lastModified" : "2020-05-08T06:29:53.808Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "licensors",
"code" : "RETRIEVE_BCM_LICENSOR",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f307"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f307"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.775Z",
"lastModified" : "2020-05-08T06:29:53.775Z",
"isDeleted" : false,
"name" : "view",
"entity" : "playlists",
"code" : "VIEW_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e3"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e3"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.776Z",
"lastModified" : "2020-05-08T06:29:53.776Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "playlists",
"code" : "ACTIVATE_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e4"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e4"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.777Z",
"lastModified" : "2020-05-08T06:29:53.777Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "playlists",
"code" : "DEACTIVATE_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e5"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e5"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.778Z",
"lastModified" : "2020-05-08T06:29:53.778Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "playlists",
"code" : "EDIT_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e6"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e6"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.779Z",
"lastModified" : "2020-05-08T06:29:53.779Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "playlists",
"code" : "DELETE_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e7"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e7"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.774Z",
"lastModified" : "2020-05-08T06:29:53.774Z",
"isDeleted" : false,
"name" : "create",
"entity" : "playlists",
"code" : "CREATE_PLAYLIST",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e2"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2e2"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.809Z",
"lastModified" : "2020-05-08T06:29:53.809Z",
"isDeleted" : false,
"name" : "create",
"entity" : "schedules",
"code" : "CREATE_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f309"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f309"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.810Z",
"lastModified" : "2020-05-08T06:29:53.810Z",
"isDeleted" : false,
"name" : "view",
"entity" : "schedules",
"code" : "VIEW_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30a"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30a"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.811Z",
"lastModified" : "2020-05-08T06:29:53.811Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "schedules",
"code" : "EDIT_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30b"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30b"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.811Z",
"lastModified" : "2020-05-08T06:29:53.811Z",
"isDeleted" : false,
"name" : "schedules",
"entity" : "schedules",
"code" : "SCHEDULE_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30c"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30c"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.812Z",
"lastModified" : "2020-05-08T06:29:53.812Z",
"isDeleted" : false,
"name" : "remove",
"entity" : "schedules",
"code" : "REMOVE_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30d"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30d"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.813Z",
"lastModified" : "2020-05-08T06:29:53.813Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "schedules",
"code" : "DELETE_SCHEDULE",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30e"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f30e"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.757Z",
"lastModified" : "2020-05-08T06:29:53.757Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "seasons",
"code" : "RETRIEVE_BCM_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d3"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d3"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.756Z",
"lastModified" : "2020-05-08T06:29:53.756Z",
"isDeleted" : false,
"name" : "edit_view_contract",
"entity" : "seasons",
"code" : "EDIT_VIEW_CONTRACT_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d2"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d2"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.746Z",
"lastModified" : "2020-05-08T06:29:53.746Z",
"isDeleted" : false,
"name" : "create",
"entity" : "seasons",
"code" : "CREATE_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ca"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ca"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.755Z",
"lastModified" : "2020-05-08T06:29:53.755Z",
"isDeleted" : false,
"name" : "edit_approval",
"entity" : "seasons",
"code" : "EDIT_APPROVAL_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d1"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d1"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.753Z",
"lastModified" : "2020-05-08T06:29:53.753Z",
"isDeleted" : false,
"name" : "approve",
"entity" : "seasons",
"code" : "APPROVE_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d0"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2d0"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.747Z",
"lastModified" : "2020-05-08T06:29:53.747Z",
"isDeleted" : false,
"name" : "view",
"entity" : "seasons",
"code" : "VIEW_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cb"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cb"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.748Z",
"lastModified" : "2020-05-08T06:29:53.748Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "seasons",
"code" : "ACTIVATE_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cc"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cc"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.749Z",
"lastModified" : "2020-05-08T06:29:53.749Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "seasons",
"code" : "DEACTIVATE_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cd"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cd"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.751Z",
"lastModified" : "2020-05-08T06:29:53.751Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "seasons",
"code" : "EDIT_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ce"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2ce"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.752Z",
"lastModified" : "2020-05-08T06:29:53.752Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "seasons",
"code" : "DELETE_SEASON",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cf"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2cf"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.742Z",
"lastModified" : "2020-05-08T06:29:53.742Z",
"isDeleted" : false,
"name" : "edit_approval",
"entity" : "shows",
"code" : "EDIT_APPROVAL_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c7"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c7"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.744Z",
"lastModified" : "2020-05-08T06:29:53.744Z",
"isDeleted" : false,
"name" : "edit_view_contract",
"entity" : "shows",
"code" : "EDIT_VIEW_CONTRACT_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c9"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c9"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.741Z",
"lastModified" : "2020-05-08T06:29:53.741Z",
"isDeleted" : false,
"name" : "approve",
"entity" : "shows",
"code" : "APPROVE_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c6"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c6"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.740Z",
"lastModified" : "2020-05-08T06:29:53.740Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "shows",
"code" : "DELETE_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c5"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c5"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.738Z",
"lastModified" : "2020-05-08T06:29:53.738Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "shows",
"code" : "EDIT_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c4"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c4"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.737Z",
"lastModified" : "2020-05-08T06:29:53.737Z",
"isDeleted" : false,
"name" : "deactive",
"entity" : "shows",
"code" : "DEACTIVATE_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c3"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c3"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.736Z",
"lastModified" : "2020-05-08T06:29:53.736Z",
"isDeleted" : false,
"name" : "activate",
"entity" : "shows",
"code" : "ACTIVATE_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c2"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c2"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.734Z",
"lastModified" : "2020-05-08T06:29:53.734Z",
"isDeleted" : false,
"name" : "view",
"entity" : "shows",
"code" : "VIEW_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c1"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c1"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.724Z",
"lastModified" : "2020-05-08T06:29:53.724Z",
"isDeleted" : false,
"name" : "create",
"entity" : "shows",
"code" : "CREATE_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c0"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c0"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.743Z",
"lastModified" : "2020-05-08T06:29:53.743Z",
"isDeleted" : false,
"name" : "retrieve_bcm",
"entity" : "shows",
"code" : "RETRIEVE_BCM_SHOW",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c8"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f2c8"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.818Z",
"lastModified" : "2020-05-08T06:29:53.818Z",
"isDeleted" : false,
"name" : "create",
"entity" : "usergroups",
"code" : "CREATE_USERGROUP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f315"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f315"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.819Z",
"lastModified" : "2020-05-08T06:29:53.819Z",
"isDeleted" : false,
"name" : "edit",
"entity" : "usergroups",
"code" : "EDIT_USERGROUP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f316"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f316"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.819Z",
"lastModified" : "2020-05-08T06:29:53.819Z",
"isDeleted" : false,
"name" : "view",
"entity" : "usergroups",
"code" : "VIEW_USERGROUP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f317"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f317"
}
}
}, {
"status" : null,
"created" : "2020-05-08T06:29:53.820Z",
"lastModified" : "2020-05-08T06:29:53.820Z",
"isDeleted" : false,
"name" : "delete",
"entity" : "usergroups",
"code" : "DELETE_USERGROUP",
"endpoints" : null,
"_links" : {
"self" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f318"
},
"permissionEntity" : {
"href" : "http://pyco-bo-api-dev-701675839.us-east-1.elb.amazonaws.com/bo-auth/permissions/5eb4fc61b6ed2a4b7414f318"
}
}
} ]
},
"page" : {
"size" : 1000,
"totalElements" : 93,
"totalPages" : 1,
"number" : 0
}
}
|
import React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';
import {Route, Router, Switch} from 'react-router';
import {connect} from 'react-redux';
import {Badge} from 'reactstrap';
import Menu from '../components/general/Menu';
import Start from '../components/views/Start';
import RepoListView from '../components/views/repos/RepoListView';
import RepoArchiveListView from '../components/views/repos/RepoArchiveListView';
import ArchiveView from '../components/views/archives/ArchiveView';
import ConfigurationPage from '../components/views/config/ConfigurationPage';
import RestServices from '../components/views/develop/RestServices';
import JobMonitorView from '../components/views/jobs/JobMonitorView';
import {getRestServiceUrl, isDevelopmentMode} from '../utilities/global';
import LogPage from '../components/views/logging/LogPage';
import Footer from '../components/views/footer/Footer';
import {loadVersion} from '../actions';
import {getTranslation} from '../utilities/i18n';
import ConfigureRepoPage from '../components/views/repos/ConfigureRepoPage';
class WebApp extends React.Component {
history = createBrowserHistory();
componentDidMount = () => {
this.props.loadVersion();
this.interval = setInterval(() => this.fetchSystemInfo(), 5000);
};
fetchSystemInfo = () => {
fetch(getRestServiceUrl('system/info'), {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(json => {
this.setState({
systemInfo: json
});
})
.catch();
};
render() {
let jobsBadge = '';
const statistics = (this.state && this.state.systemInfo) ? this.state.systemInfo.queueStatistics : null;
if (statistics && statistics.numberOfRunningAndQueuedJobs > 0) {
jobsBadge = <Badge color="danger" pill>{statistics.numberOfRunningAndQueuedJobs}</Badge>;
}
let configurationBadge = '';
if (this.state && this.state.systemInfo && !this.state.systemInfo.configurationOK) {
configurationBadge = <Badge color="danger" pill>!</Badge>;
}
let routes = [
['Start', '/', Start],
['Repositories', '/repos', RepoListView],
['Job monitor', '/jobmonitor', JobMonitorView, {badge: jobsBadge}],
[getTranslation('logviewer'), '/logging', LogPage],
[getTranslation('configuration'), '/config', ConfigurationPage, {badge: configurationBadge}]
];
if (isDevelopmentMode()) {
routes.push(['Rest services', '/restServices', RestServices]);
}
return (
<Router history={this.history}>
<div>
<Menu routes={routes}/>
<div className={'container main-view'}>
<Switch>
{
routes.map((route, index) => (
<Route
key={index}
path={route[1]}
component={route[2]}
exact
/>
))
}
<Route path={'/repoArchives/:id/:displayName'} component={RepoArchiveListView} />
<Route path={'/archives/:repoId/:archiveId/'} component={ArchiveView} />
<Route path={'/repo/configure'} component={ConfigureRepoPage} />
</Switch>
</div>
<Footer versionInfo={this.props.version}/>
</div>
</Router>
);
}
}
const mapStateToProps = state => ({
version: state.version
});
const actions = {
loadVersion
};
export default connect(mapStateToProps, actions)(WebApp);
|
const initialState = {
currentPage: '',
currentTab: 0,
currentEditTab: 0,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
alert: null,
time: Date.now(),
commissioningData: null,
fetchingCommissioningData: false,
currentTracker: null,
currentTrackerInfo: null,
xbeeResponse: [],
controlledTrackers: [],
editedTrackers: [],
SPAParameters: null,
stowAngles: null,
sendingSPAParameters: false,
sendingStowAngles: false,
gettingSPAParameters: false,
gettingStowAngles: false,
addingTrackers: false,
sensors: [],
responseQueue: [],
listen: false,
windSense: {
speed: null,
direction: null
},
floodSense: null,
snowSense: null,
wifiList: [],
sensorEvents: {
wind: 'disconnected',
snow: 'disconnected',
flood: 'disconnected'
},
roverStatus: {},
windLimits: {
speedLimits : {
upperSpeedLimit: '',
lowerSpeedLimit: ''
},
breachParameters : {
minBreachTime: '',
maxBreachTime: '',
maxBreachCount: ''
}
},
floodLimits: {
maxFloodLevel: '',
movingAveragePeriod: ''
},
snowLimits: {
maxSnowLevel: '',
movingAveragePeriod: '',
rowHeight: '',
rowWidth: '',
stepSize: ''
},
gettingFloodLimits: false,
settingFloodLimits: false,
gettingSnowLimits: false,
settingSnowLimits: false,
gettingWindLimits: false,
settingWindLimits: false,
PANID: '',
bqEnabled: false,
currentWifi: '',
zoneID: '',
heartBeatInterval: '',
heartBeatMaxMessages: '',
heartBeatEnabled: false,
powerRequestTimePeriod: '',
statusRequestTimePeriod: '',
logList: [],
enableEthernet: false,
staticIP: '',
connected: false
}
const difference = (a1, a2) => {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
export function app(state, action) {
if (typeof state === 'undefined') {
return initialState
}
switch (action.type) {
case 'CONNECTED':
return {
...state,
connected: true
}
case 'DISCONNECTED':
return {
...state,
connected: false
}
case 'GET_ETHERNET_SETTINGS_SUCCESS':
return {
...state,
enableEthernet: action.json.message.dhcpStatus,
staticIP: action.json.message.staticIP === null ? '' : action.json.message.staticIP
}
case 'GET_LOGS_LIST_SUCCESS':
return {
...state,
logList: action.json.message
}
case 'GET_REQUEST_FREQUENCY_SUCCESS':
return {
...state,
powerRequestTimePeriod: action.json.message.powerRequestTimePeriod,
statusRequestTimePeriod: action.json.message.statusRequestTimePeriod
}
case 'GET_HEARTBEAT_SETTINGS_SUCCESS':
return {
...state,
heartBeatInterval: action.json.message.interval,
heartBeatMaxMessages: action.json.message.maxMsgs,
heartBeatEnabled: Boolean(action.json.message.enabled)
}
case 'GET_ZONE_ID_SUCCESS':
return {
...state,
zoneID: action.json.message
}
case 'GET_WIFI_SUCCESS':
return {
...state,
currentWifi: action.json.message
}
case 'GET_BQ_SUCCESS':
return {
...state,
bqEnabled: action.json
}
case 'ui/xbee/panid':
return {
...state,
PANID: action.json.panID
}
case 'SET_SNOW_LIMITS_REQUEST':
return {
...state,
settingSnowLimits: true
}
case 'SET_FLOOD_LIMITS_REQUEST':
return {
...state,
settingFloodLimits: true
}
case 'SET_WIND_LIMITS_REQUEST':
return {
...state,
settingWindLimits: true
}
case 'SET_SNOW_LIMITS_SUCCESS':
return {
...state,
settingSnowLimits: false
}
case 'SET_FLOOD_LIMITS_SUCCESS':
return {
...state,
settingFloodLimits: false
}
case 'SET_WIND_LIMITS_SUCCESS':
return {
...state,
settingWindLimits: false
}
case 'GET_SNOW_LIMITS_REQUEST':
return {
...state,
gettingSnowLimits: true
}
case 'GET_FLOOD_LIMITS_REQUEST':
return {
...state,
gettingFloodLimits: true
}
case 'GET_WIND_LIMITS_REQUEST':
return {
...state,
gettingWindLimits: true
}
case 'GET_SNOW_LIMITS_SUCCESS':
return {
...state,
snowLimits: action.json.message,
gettingSnowLimits: false
}
case 'GET_FLOOD_LIMITS_SUCCESS':
return {
...state,
floodLimits: action.json.message,
gettingFloodLimits: false
}
case 'GET_WIND_LIMITS_SUCCESS':
return {
...state,
windLimits: action.json.message,
gettingWindLimits: false
}
case 'changeEvent/rover':
return {
...state,
roverStatus: {...state.roverStatus, [action.json.DID]: action.json.state}
}
case 'SCAN_WIFI_SUCCESS':
return {
...state,
wifiList: action.json.message
}
case 'sensorReadings/wind':
return {
...state,
windSense: action.json
}
case 'sensorReadings/flood':
return {
...state,
floodSense: action.json.reading
}
case 'sensorReadings/snow':
return {
...state,
snowSense: action.json.reading
}
case 'time':
return {
...state,
time: action.json.time
}
case 'SET_CURRENT_TRACKER':
return {
...state,
currentTracker: action.deviceID
}
case 'SET_RESPONSE_LISTENER':
return {
...state,
listen: true
}
case 'SEND_SPA_PARAMETERS_REQUEST':
return {
...state,
sendingSPAParameters: true,
responseQueue: []
}
case 'SEND_STOW_ANGLES_REQUEST':
return {
...state,
sendingStowAngles: true,
responseQueue: []
}
case 'ui/rover/response/multiple':
if(state.listen) {
if(state.editedTrackers.length === state.responseQueue.length + 1) {
return {
...state,
responseQueue: [...state.responseQueue, action.json],
listen: false
}
}
return {
...state,
responseQueue: [...state.responseQueue, action.json]
}
} else {
return {
...state
}
}
case 'GET_SENSORS_SUCCESS':
let temp = {
wind: 'disconnected',
snow: 'disconnected',
flood: 'disconnected'
}
action.json.message.map(s => {
temp[s.type] = s.status
})
return {
...state,
sensors: action.json.message,
sensorEvents: temp
}
case 'REMOVE_SENSOR_SUCCESS':
alert(`Removed Sensor of type: ${action.type} and model no: ${action.model} successfully`)
return {
...state,
sensorEvents: {...state.sensorEvents, [action.type]: 'disconnected'}/*
alert: {
type: 'success',
message: 'Removed Sensor Successfully'
} */
}
case 'ADD_SENSORS_SUCCESS':
alert('Added Sensor Successfully')
return {
...state,/*
alert: {
type: 'success',
message: 'Added Sensor Successfully'
} */
}
case 'CHANGE_PAGE':
return {
...state,
currentPage: action.page,
responseQueue: [],
commandQueue: []
}
case 'CHANGE_TAB':
return {
...state,
currentTab: action.value.value,
responseQueue: [],
commandQueue: []
}
case 'CHANGE_EDIT_TAB':
return {
...state,
currentEditTab: action.value.value,
responseQueue: [],
commandQueue: []
}
case 'CLEAR_ALERT':
return {
...state,
alert: null
}
case 'GET_COMMISSIONING_DATA_REQUEST':
return {
...state,
fetchingCommissioningData: true
}
case 'GET_COMMISSIONING_DATA_SUCCESS':
if(action.json.message === null || action.json.message.length === 0) {
return {
...state,
fetchingCommissioningData: false,
currentPage: state.currentPage === '' ? 'Dashboard' : state.currentPage,
commissioningData: null
}
} else {
let newRoverStatus = {...state.roverStatus}
action.json.message.map(r => {
newRoverStatus[r.deviceID] = 'online'
})
return {
...state,
fetchingCommissioningData: false,
currentPage: state.currentPage === '' ? 'Dashboard' : state.currentPage,
commissioningData: action.json.message.sort((a, b) => a.deviceID - b.deviceID),
currentTracker: action.json.message[0].deviceID,
roverStatus: newRoverStatus
}
}
case 'GET_COMMISSIONING_DATA_FAILURE':
alert('Error loading commissioning data')
return {
...state,
fetchingCommissioningData: false,
currentPage: state.currentPage === '' ? 'Dashboard' : state.currentPage,/*
alert: {
type: 'error',
message: 'Error loading commissioning data'
} */
}
case 'GET_TIMEZONE_SUCCESS':
if(action.json.timeZone !== null) {
return {
...state,
timeZone: action.json.timeZone
}
} else {
return state
}
case 'GET_TIMEZONE_FAILURE':
alert('Error getting timezone')
return {
...state,/*
alert: {
type: 'error',
message: 'Error getting timezone'
} */
}
case 'SCAN':
return {
...state,
currentPage: 'Row Controller',
currentTab: 1
}
case 'GET_CURRENT_TRACKER_INFO_REQUEST':
return {
...state
}
case 'GET_CURRENT_TRACKER_INFO_SUCCESS':
return {
...state,
currentTrackerInfo: action.json.message
}
case 'GET_CURRENT_TRACKER_INFO_FAILURE':
//alert('Error getting current tracker info')
return {
...state,/*
alert: {
type: 'error',
message: 'Error getting current tracker info'
} */
}
case 'DISCOVER_SUCCESS':
alert('Started Scanning')
return {
...state,
xbeeResponse: [],/*
alert: {
type: 'success',
message: 'Started Scanning'
} */
}
case 'DISCOVER_FAILURE':
alert('Error Starting Scan')
return {
...state,/*
alert: {
type: 'error',
message: 'Error starting scan'
} */
}
case 'ui/rover/scan':
let a = null
if(state.commissioningData === null) {
if(state.xbeeResponse.filter(r => action.json.macID === r.macID).length === 0) {
a = [...state.xbeeResponse, action.json]
} else {
a = state.xbeeResponse
}
} else {
let b = state.commissioningData.filter(r => action.json.macID === r.macID)
if(b.length === 0) {
if(state.xbeeResponse.filter(r => action.json.macID === r.macID).length === 0) {
a = [...state.xbeeResponse, action.json]
} else {
a = [...state.xbeeResponse]
}
} else {
a = [...state.xbeeResponse]
}
}
return {
...state,
xbeeResponse: a
}
case 'ADD_TRACKERS_REQUEST':
return {
...state,
addingTrackers: true
}
case 'ADD_TRACKERS_SUCCESS':
alert('Tracker(s) added')
const newXbeeResponse = difference(state.xbeeResponse, action.devices)
return {
...state,
xbeeResponse: newXbeeResponse,
addingTrackers: false,/*
alert: {
type: 'success',
message: 'Tracker(s) added'
} */
}
case 'ADD_TRACKERS_FAILURE':
alert('Error adding trackers')
return {
...state,
addingTrackers: false,/*
alert: {
type: 'error',
message: 'Error adding trackers'
} */
}
case 'SET_EDITED_TRACKERS':
return {
...state,
editedTrackers: action.trackers
}
case 'SET_CONTROLLED_TRACKERS':
return {
...state,
controlledTrackers: action.trackers
}
case 'ui/rover/spa':
return {
...state,
SPAParameters: {...state.SPAParameters, [action.json.DID]: action.json},
gettingSPAParameters: false
}
case 'ui/rover/stowangles':
return {
...state,
stowAngles: {...state.stowAngles, [action.json.DID]: action.json},
gettingStowAngles: false
}
case 'GET_STOW_ANGLES_REQUEST':
return {
...state,
gettingStowAngles: true
}
case 'GET_STOW_ANGLES_FAILURE':
alert('Error getting stow angles')
return {
...state,
gettingStowAngles: false,/*
alert: {
type: 'error',
message: 'Error getting stow angles'
} */
}
case 'GET_SPA_PARAMETERS_REQUEST':
return {
...state,
gettingSPAParameters: true
}
case 'GET_SPA_PARAMETERS_FAILURE':
alert('Error getting SPA parameters')
return {
...state,
gettingSPAParameters: false,/*
alert: {
type: 'error',
message: 'Error getting SPA parameters'
} */
}
case 'SEND_SPA_PARAMETERS_FAILURE':
alert('Error setting SPA parameters')
return {
...state,
sendingSPAParameters: false,/*
alert: {
type: 'error',
message: 'Error setting SPA parameters'
} */
}
case 'SEND_SPA_PARAMETERS_SUCCESS':
return {
...state,
sendingSPAParameters: false
}
case 'SEND_STOW_ANGLES_FAILURE':
alert('Error setting stow angles')
return {
...state,
sendingStowAngles: false,/*
alert: {
type: 'error',
message: 'Error setting stow angles'
} */
}
case 'SEND_STOW_ANGLES_SUCCESS':
return {
...state,
sendingStowAngles: false
}
default:
return state
}
}
|
function Missile(x, y, angle, damage) {
this.pos = createVector(x, y);
this.vel = p5.Vector.fromAngle(PI / 2 + angle);
this.r = 8;
this.damage = damage;
this.dead = false;
this.health = 50;
this.speed = 6;
this.lifeLength = 0;
this.update = function() {
if (this.lifeLength > 30) { // Make it wait some time before flying
this.pos.x += -this.vel.x*this.speed;
this.pos.y += -this.vel.y*this.speed;
this.released = true;
}
if (!player.dead) {
this.vel = p5.Vector.fromAngle(PI / 2 + this.targetAngle); // Set velocity towards player
}
this.targetAngle = PI / 2 + atan2(player.pos.y-this.pos.y, player.pos.x-this.pos.x); // Set angle in the opposite direction of travel to fire particles
if (this.pos.x < 0 || this.pos.x > width ||this.pos.y < 0 || this.pos.y > height) {
this.explode();
}
fires.push(new Fire(this.pos.x, this.pos.y, 5, 10, this.targetAngle)); // Spawn fire particles
this.lifeLength ++;
}
this.show = function() {
push();
stroke(255, 0, 0, 50);
if (!player.dead) {
line(this.pos.x, this.pos.y, player.pos.x, player.pos.y); // Laser that point to player
}
translate(this.pos.x, this.pos.y);
rotate(this.targetAngle);
stroke(0);
fill(255);
rect(0, 0, 5, 15); // Actuall missile
if (debug.collider) {
noFill();
ellipse(0, 0, this.r); // Collider sphere
}
pop();
}
this.explode = function() {
explosions.push(new Explosion(this.pos.x, this.pos.y)); // Spawn explosion effect
this.dead = true; // And kill the missile
}
}
|
'use strict';
var $ = require('jquery');
var ItemView = require('./views/ItemView');
var ItemModel = require('./models/ItemModel');
|
async function loaded() {
const first = await import('./examples_exports/async_import/first.js');
const second = await import('./examples_exports/async_import/second.js');
console.log(first.first_export());
console.log(second.second_export());
}
loaded();
|
var matriks1 = [1,2,3];
var matriks2 = [3,4,5];
var hasil_1 = matriks1[0] + matriks2[0];
var hasil_2 = matriks1[1] + matriks2[1];
var hasil_3 = matriks1[2] + matriks2[2];
console.log(matriks1[0], matriks1[1], matriks1[2]);
console.log(matriks2[0], matriks2[1], matriks2[2]);
console.log("Hasil :");
console.log(hasil_1, hasil_2, hasil_3);
|
class Flipper {
constructor(front, back) {
this.front = front
this.back = back
this.rect_x = 0.0
this.rect_size = 0.0
this.flip_speed = 300.0 * (width / 1000.0);
}
draw(g) {
imageMode(CORNER);
let edge_x = this.rect_x - this.rect_size / 2.0
if (edge_x < 0) edge_x = 0
if (edge_x > width) edge_x = width
if (g) {
if (this.rect_size < width)
g.image(this.front, 0, 0)
if (this.rect_size >= 1.0)
g.image(this.back, edge_x, 0, this.rect_size, height, edge_x, 0, this.rect_size, height)
} else {
if (this.rect_size < width)
image(this.front, 0, 0)
if (this.rect_size >= 1.0)
image(this.back, edge_x, 0, this.rect_size, height, edge_x, 0, this.rect_size, height)
}
}
flip(x, y) {
this.rect_x = x
this.rect_size += this.flip_speed
if (this.rect_size > width) this.rect_size = width
}
unflip(x, y) {
this.rect_x = x
this.rect_size -= this.flip_speed
if (this.rect_size < 0) this.rect_size = 0
}
}
|
/* eslint-disable import/no-cycle */
import { format } from 'date-fns';
import { lightBackground } from './displayEffects';
import { renderLists, renderListContent } from './renderDom';
import { removeBox } from './renderPopUpBox';
const toDoFactory = (toDos,
list,
notes,
id,
active = false) => ({
toDos, list, notes, id, active,
});
/* eslint-disable import/no-mutable-exports */
export let toDoArray = [];
/* eslint-enable import/no-mutable-exports */
toDoArray.push(toDoFactory([{
title: 'Create the functionality and the front end part',
dueDate: '02/03/2021',
done: false,
priority: false,
},
{
title: 'use webpack to compile the code',
dueDate: '10/03/2021',
done: false,
priority: true,
}], 'Microverse', 'Microverse wants student to create a todo App', '1609618397810', true));
export const getInput = (id) => document.getElementById(id).value;
toDoArray = JSON.parse(localStorage.getItem('toDoArray') || '[]');
export const addNewToDo = () => {
let date = '';
if (getInput('box-date') !== '') {
date = format(new Date(getInput('box-date')), 'dd/MM/yyyy');
}
/* eslint-disable no-console */
for (let i = 0; i < toDoArray.length; i += 1) {
if (toDoArray[i].active === true) {
toDoArray[i].toDos
.push({
title: getInput('box-title-input'),
dueDate: date,
done: false,
priority: document.querySelector('#box-prio-checkbox').checked,
});
renderListContent();
lightBackground();
removeBox();
}
}
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
date = '';
};
/* eslint-enable no-console */
export const setActiveList = (targetListId) => {
toDoArray.forEach(list => {
list.active = false;
if (list.id === targetListId) {
list.active = true;
}
});
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
};
export const addNewList = () => {
setActiveList();
/* eslint-disable no-restricted-globals */
toDoArray.push(toDoFactory([''].splice(0, length),
getInput('list-name-input'),
getInput('box-notes-input'),
Date.now().toString(),
true));
removeBox();
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
/* eslint-enable no-restricted-globals */
};
export const removeList = (val) => {
toDoArray.forEach((list, index) => {
if (list.id === val.value) {
toDoArray.splice(index, 1);
if (toDoArray.length !== 0) {
toDoArray[0].active = true;
}
renderLists();
renderListContent();
removeBox();
}
});
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
};
export const editList = (val, listInfo) => {
toDoArray.forEach((list) => {
if (list.id === val.value) {
list.list = listInfo.children[1].value;
list.notes = listInfo.children[3].value;
renderLists();
removeBox();
}
});
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
};
export const toggleToDoStatus = (val, name) => {
toDoArray.forEach(td => {
for (let i = 0; i < td.toDos.length; i += 1) {
if (td.toDos[i].title === name && td.id === val) {
if (td.toDos[i].done === false) {
td.toDos[i].done = true;
} else {
td.toDos[i].done = false;
}
}
}
});
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
};
export const removeToDo = (val) => {
toDoArray.forEach(list => {
if (list.id === val.firstChild.getAttribute('value')) {
list.toDos.forEach((todo, index) => {
if (todo.title === val.firstChild.textContent) {
list.toDos.splice(index, 1);
renderListContent();
}
});
}
});
localStorage.setItem('toDoArray', JSON.stringify(toDoArray));
};
/* eslint-enable import/no-cycle */
|
var express = require('express');
var app = express();
var port = 5000;
app.get('/',function (req,res) {
res.send('hello word');
});
app.listen(port, function (err) {
console.log('running server on port', port);
});
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { StatusBar, SectionList } from 'react-native';
import { TabRouter } from 'react-navigation';
import { connect } from 'react-redux';
import ParallaxScroll from '@monterosa/react-native-parallax-scroll';
import { Kitsu } from 'kitsu/config/api';
import { defaultCover } from 'kitsu/constants/app';
import { listBackPurple } from 'kitsu/constants/colors';
import { TabBar, TabBarLink } from 'kitsu/screens/Profiles/components/TabBar';
import { SceneHeader } from 'kitsu/screens/Profiles/components/SceneHeader';
import { SceneLoader } from 'kitsu/components/SceneLoader';
import { SceneContainer } from 'kitsu/screens/Profiles/components/SceneContainer';
import { MaskedImage } from 'kitsu/screens/Profiles/components/MaskedImage';
import { CustomHeader } from 'kitsu/screens/Profiles/components/CustomHeader';
import Summary from 'kitsu/screens/Profiles/ProfilePages/pages/Summary';
import { coverImageHeight } from 'kitsu/screens/Profiles/constants';
// There's no way to Report Profiles at the moment in the API.
const MORE_BUTTON_OPTIONS = ['Block', /* 'Report Profile', */ 'Nevermind'];
const tabPage = name => ({ key: name.toLowerCase(), label: name, screen: name });
const TAB_ITEMS = [
tabPage('Summary'),
tabPage('About'),
tabPage('Library'),
tabPage('Groups'),
tabPage('Reactions'),
];
/* eslint-disable global-require */
const TabRoutes = TabRouter({
Summary: { screen: Summary },
About: { getScreen: () => require('./pages/About').About },
Library: { getScreen: () => require('./pages/Library').Library },
Groups: { getScreen: () => require('./pages/Groups').Groups },
Reactions: { getScreen: () => require('./pages/Reactions').Reactions },
}, {
initialRouteName: 'Summary',
});
class ProfilePage extends PureComponent {
static navigationOptions = {
header: null,
}
static propTypes = {
navigation: PropTypes.object.isRequired,
userId: PropTypes.number,
currentUser: PropTypes.object.isRequired,
}
static defaultProps = {
userId: null,
}
state = {
active: 'Summary',
loading: true,
error: null,
profile: null,
feed: null,
}
componentWillMount() {
const userId = this.props.userId || (this.props.navigation.state.params || {}).userId;
if (!userId) {
this.setState({
loading: false,
error: 'Missing userId in component.',
});
return;
}
this.loadUserData(userId);
}
onMoreButtonOptionsSelected = async (button) => {
if (button === 'Block') {
await Kitsu.create('blocks', {
blocked: { id: this.props.userId },
user: { id: this.props.currentUser.id },
});
} else if (button === 'Report Profile') {
// There's no current way to report users from the site.
// Once there is, the API call goes here.
}
}
setActiveTab = (tab) => {
this.setState({ active: tab });
}
goBack = () => {
this.props.navigation.goBack();
}
loadUserData = async (userId) => {
try {
const users = await Kitsu.findAll('users', {
filter: {
id: userId,
},
fields: {
users: 'waifuOrHusbando,gender,location,birthday,createdAt,followersCount,followingCount,coverImage,avatar,about,name,waifu',
},
include: 'waifu',
});
if (users.length < 1) {
console.log(`Could not locate user with ID ${userId}.`);
this.setState({
loading: false,
error: 'Could not find that user.',
});
return;
}
this.setState({
loading: false,
profile: users[0],
});
} catch (error) {
console.log('Error loading user: ', error);
this.setState({
loading: false,
error,
});
}
}
handleFollowing = () => {}
renderTabNav = () => (
<TabBar>
{TAB_ITEMS.map(tabItem => (
<TabBarLink
key={tabItem.key}
label={tabItem.label}
isActive={this.state.active === tabItem.screen}
onPress={() => this.setActiveTab(tabItem.screen)}
/>
))}
</TabBar>
);
renderTabScene = () => {
const TabScene = TabRoutes.getComponentForRouteName(this.state.active);
const userId = this.props.userId || (this.props.navigation.state.params || {}).userId;
const { navigation } = this.props;
return (
<TabScene
key="tabScene"
setActiveTab={tab => this.setActiveTab(tab)}
userId={userId}
navigation={navigation}
currentUser={this.props.currentUser}
profile={this.state.profile}
/>
);
}
render() {
const { error, loading, profile } = this.state;
if (loading) {
return (
<SceneContainer>
<SceneLoader />
</SceneContainer>
);
}
if (error) {
// Return error state.
return null;
}
return (
<SceneContainer>
<StatusBar barStyle="light-content" />
<ParallaxScroll
style={{ flex: 1 }}
headerHeight={60}
isHeaderFixed
parallaxHeight={coverImageHeight}
renderParallaxBackground={() => (
<MaskedImage
maskedTop
maskedBottom
source={{ uri: (profile.coverImage && profile.coverImage.large) || defaultCover }}
/>
)}
renderHeader={() => (
<CustomHeader
leftButtonAction={this.goBack}
leftButtonTitle="Back"
/>
)}
headerFixedBackgroundColor={listBackPurple}
>
<SceneHeader
variant="profile"
title={profile.name}
description={profile.about}
posterImage={profile.avatar && profile.avatar.large}
followersCount={profile.followersCount}
followingCount={profile.followingCount}
moreButtonOptions={MORE_BUTTON_OPTIONS}
onFollowButtonPress={this.handleFollowing}
onMoreButtonOptionsSelected={this.onMoreButtonOptionsSelected}
/>
<SectionList
style={{ flex: 1 }}
stickySectionHeadersEnabled
renderSectionHeader={({ section }) => section.title}
renderItem={({ item }) => item}
sections={[
{ data: [this.renderTabScene()], title: this.renderTabNav() },
]}
/>
</ParallaxScroll>
</SceneContainer>
);
}
}
const mapStateToProps = ({ user }) => {
const { currentUser } = user;
return { currentUser };
};
export default connect(mapStateToProps)(ProfilePage);
|
import React, { Component } from 'react';
import Carousels from '../components/Carousels';
import SearchHostel from '../components/SearchHostel';
import HostelList from '../components/HostelList';
export default class Home extends Component {
render() {
return (
<>
<div className="mb-5">
<Carousels />
<div className="container" style={{ marginTop: '-4rem' }}>
<SearchHostel />
<HostelList/>
</div>
</div>
</>
)
}
}
|
'use strict';
// var button = document.getElementById('submit')
// button.addEventListener("click", addDataToPage)
var container = document.querySelector('section');
function doRequest(callback) {
var x = new XMLHttpRequest();
x.open('GET', 'http://localhost:8080/');
x.onload = function() {
var data = JSON.parse(x.responseText).posts;
callback(data);
};
x.send();
}
function handleData(data){
console.log(data);
data.forEach(function(element) {
let blah = document.createElement('div');
blah.innerHTML = element.title;
container.appendChild(blah);
let url = document.createElement('a');
url.setAttribute('href', element.url);
url.innerHTML = element.url;
container.appendChild(url);
console.log(element.url);
});
};
doRequest(handleData)
// function addDataToPage() {
// console.log("click event");
// var submit = document.getElementById('submit').value;
// if (location !== "") {
// getData(location, handleData);
// }
// }
|
/**
* Created by pi on 8/25/16.
*/
var fs = require('fs');
var logfile = 'OPCUAlog-2.txt';
var wstream = fs.createWriteStream(logfile);
module.exports = function(logType, data, i18n) {
var time = new Date().toLocaleString();
// new Date().toISOString().
// replace(/T/, ' '). // replace T with a space
// replace(/\..+/, '');
var log = time
+ ': [' + logType +']: ' + data + '\n';
wstream.write(log);
console.log(log);
}
|
/*eslint-disable semi */
const fs = require('fs')
arguments = process.argv.splice(2)
const print = require('./plugins/helper').print
let tfwords = null
let tffreqs = null
function load_plugins() {
let config = require('./config.json')
words_plugin = config.words
frequencies_plugin = config.frequencies
tfwords = require(words_plugin)
tffreqs = require(frequencies_plugin)
}
load_plugins()
res = tffreqs.top25(tfwords.extract_words(arguments[0]))
print(res)
|
console.clear();
const keep_alive = require('./keep_alive');
const config = require('./config.json');
require('dotenv');
const { token } = require('./config');
const dbd = require('dbd.js');
const bot = new dbd.Bot({
token: process.env.DISCORD_BOT,
prefix: 'prefix'
});
bot.onMessage();
const fs = require('fs');
const folders = fs.readdirSync('./commands/');
for (const files of folders) {
const folder = fs
.readdirSync(`./commands/${files}/`)
.filter(file => file.endsWith('.js'));
for (const commands of folder) {
const command = require(`./commands/${files}/${commands}`);
bot.command({
name: command.name,
code: command.code
});
}
}
bot.status({
text: 'YOUR BOT Watching You',
type: 'PLAYING',
status: 'online',
time: 12
});
bot.status({
text: 'My Prefix $getServerVar[prefix]',
type: 'WATCHING',
status: 'online',
time: 12
});
bot.variables({
prefix: 'your prefix',
wchan: '',
lchan: '',
ticketchannel: '',
rch: '',
rmsg: 'Congrats {user.tag}🎉, you leveled up to level {level}',
lvl: '0',
exp: '0',
rexp: '40',
rsystem: '0',
ccmd: '',
modmail: '',
giveaway: '',
cdes: '',
autorole: '',
autorolestate: 'on/off'
});
const username = `$username[$authorID]`;
const discrim = `$discriminator[$authorID]`;
const members = `$membersCount`;
const guild = `$serverName`;
const avatar = `$replaceText[$userAvatar[$authorID];webp;png]`;
const background = `https://cdn.discordapp.com/attachments/821606929720934423/829209279151210566/images.jpeg`;
bot.joinCommand({
channel: '$getServerVar[wchan]',
code: `$djseval[(async() =>{const Discord = require('discord.js')
const canvas = require('discord-canvas'),
welcomeCanvas = new canvas.Welcome();
let image = await welcomeCanvas
.setUsername("${username}")
.setDiscriminator("${discrim}")
.setMemberCount("${members}")
.setGuildName("${guild}")
.setAvatar("${avatar}")
.setColor("border", "#8015EA")
.setColor("username-box", "#8015EA")
.setColor("discriminator-box", "#8015EA")
.setColor("message-box", "#8015EA")
.setColor("title", "#8015EA")
.setColor("avatar", "#8015EA")
.setBackground("${background}")
.setText("message", "Welcome to {server}")
.toAttachment();
let attachment = new Discord.MessageAttachment(image.toBuffer(), "welcome.png");
message.channel.send(attachment);
})()]`
});
bot.leaveCommand({
channel: '$getServerVar[lchan]',
code: `$djseval[(async() =>{const Discord = require('discord.js')
const canvas = require('discord-canvas'),
welcomeCanvas = new canvas.Welcome();
let image = await welcomeCanvas
.setUsername("${username}")
.setDiscriminator("${discrim}")
.setMemberCount("${members}")
.setGuildName("${guild}")
.setAvatar("${avatar}")
.setColor("border", "#8015EA")
.setColor("username-box", "#8015EA")
.setColor("discriminator-box", "#8015EA")
.setColor("message-box", "#8015EA")
.setColor("title", "#8015EA")
.setColor("avatar", "#8015EA")
.setBackground("${background}")
.setText("message", "Leaving from {server}")
.setText("title", "Goodbye")
.toAttachment();
let attachment = new Discord.MessageAttachment(image.toBuffer(), "welcome.png");
message.channel.send(attachment);
})()]`
});
bot.onLeave();
bot.onJoined();
bot.botJoinCommand({
channel: '818723065448890399',
code: `
$title[New Server!]
$addField[SERVER NAME;$serverName]
$addField[TOTAL MEMBERS;$membersCount]
$addField[OWNER;\`$userTag[$ownerID]\`]
$color[GREEN]
`
});
bot.onGuildJoin();
bot.command({
name: 'ticket-setup',
code: `
$awaitMessages[$authorID;30s;everything;tsp2;Command has been cancelled]
$sendMessage[**Which Category Do you want to make For Ticket System.
Provide the Category ID.
This Command will be cancelled after** \`30 seconds\`.;no]
$onlyPerms[admin;You Dont Have Prem To Use this Command{delete:10s}]
$suppressErrors[]`
});
bot.awaitedCommand({
name: 'tsp2',
code: `
**Successfully Setuped Ticket Channel!📫**
$setServerVar[ticketchannel;$message]
$onlyIf[$channelExists[$message]==true;Provided Category Doesn't Exist{delete:10s}]
$onlyIf[$isNumber[$message]==true;Please provide Category ID{delete:10s}]`
});
bot.command({
name: 'ticket',
code: `
$newTicket[ticket-$username[$authorID];{title:Ticket opened!}{description:Hello, <@$authorID>. Here is your ticket!:tickets: Please give the information about your problem or feedback.
}{footer:Use close to *close your ticket};$getServerVar[ticketchannel];no;<@$authorID>, I failed to create your ticket! Try again]
$sendMessage[Ticket Successfully opened! Hello, <@$authorID>. Go to **$toLowercase[#$username$discriminator]** to describe your issue!;Something went wrong]`
});
bot.command({
name: 'close',
code: `
$closeTicket[This is not a ticket]
$onlyIf[$checkContains[$channelName;ticket]==true;{description:This command can only be used in ticket channel!} {color:RED} {delete:10s}]
$suppressErrors`
});
bot.command({
name: 'say',
code: `
$deletecommand
$message
`
});
bot.command({
name: '<@828631576530518026>',
code: `$title[Bot Name]
$description[**Hi $username my prefix is** \`$getServerVar[prefix]\`
**You can type** \`$getServerVar[prefix]help\` **for more info**
[**Invite-Me**\\](https://discord.com/api/oauth2/authorize?client_id=828631576530518026&permissions=8&scope=bot) | [**Support-Server**\\](https://discord.gg/kEPV3WFsnj)]
$color[RANDOM]`,
nonPrefixed: true
});
bot.command({
name: '<@!828631576530518026>',
code: `$title[Bot Name]
$description[**Hi $username my prefix is** \`$getServerVar[prefix]\`
**You can type** \`$getServerVar[prefix]help\` **for more info**
[**Invite-Me**\\](https://discord.com/api/oauth2/authorize?client_id=828631576530518026&permissions=8&scope=bot) | [**Support-Server**\\](https://discord.gg/kEPV3WFsnj)]
$color[RANDOM]`,
nonPrefixed: true
});
bot.command({
name: 'ann',
code: `
$title[ $serverName • ANNOUNCEMENT]
$description[$message]
$image[https://cdn.discordapp.com/attachments/783319872230129674/784371198188453909/Tw.gif]
$footer[Announced: $username]
$addTimestamp
$thumbnail[$serverIcon]
$deletecommand
$onlyPerms[admin;only Admin Command if u use again u will kicked from server]`
});
bot.command({
name: 'setrank',
usage: 'setrank <channel>',
description: 'settings the levelup channel',
code: `$description[Rank channel has been set up to <#$mentionedChannels[1;yes]>]
$color[01ff00]
$setServerVar[rch;$mentionedChannels[1;yes]]
$setServerVar[rsystem;1]
$onlyBotPerms[mentioneveryone;{description:I dont have permission \`MENTION_EVERYONE\`}{color:ff2050}]
$onlyPerms[manageserver;{description:You need \`MANAGE_SERVER\` permission}{color:ff2050}]
$cooldown[5s;Please wait **%time%**]`
});
bot.command({
name: 'resetrank',
usage: 'resetrank',
description: 'reset the levelup channel',
code: `$description[Rank channel has been reseted <#$mentionedChannels[1;yes]>]
$color[01ff00]
$setServerVar[rch;]
$setServerVar[rmsg;$getVar[rmsg]]
$setServerVar[rsystem;0]
$onlyIf[$getServerVar[rsystem]>=1;{description:Leveling system is __disabled__ on this server}{color:ff2050}]
$onlyBotPerms[mentioneveryone;{description:I dont have permission \`MENTION_EVERYONE\`}{color:ff2050}]
$onlyPerms[manageserver;{description:You need \`MANAGE_SERVER\` permission}{color:ff2050}]
$cooldown[5s;Please wait **%time%**]`
});
bot.command({
name: '$alwaysExecute',
code: `$useChannel[$getServerVar[rch]]
$replaceText[$replaceText[$replaceText[$replaceText[$getServerVar[rmsg];{user.tag};$userTag];{user.mention};<@$authorID>];{level};$getUserVar[lvl]];{exp};$getUserVar[exp]]
$setUserVar[lvl;$sum[$getUserVar[lvl];1]]
$setUserVar[rexp;$multi[$getUserVar[rexp];2]]
$onlyIf[$getUserVar[exp]>=$getUserVar[rexp];]
$onlyForServers[$guildID;]`
});
bot.command({
name: '$alwaysExecute',
code: `$setUserVar[exp;$sum[$getUserVar[exp];$random[1;4]]]
$onlyIf[$getServerVar[rsystem]>=1;]
$onlyForServers[$guildID;]`
});
bot.awaitedCommand({
name: 'errorrank',
code: `$setServerVar[rch;]
$onlyForServers[$guildID;]`
});
bot.command({
name: 'setrankmsg',
usage: 'setrankmsg <message>',
description: 'message for the leveled up',
code: `$description[You have been setted the message to:
\`$message\`]
$color[01ff00]
$setServerVar[rmsg;$message]
$onlyIf[$message!=;You can also use this variables:
\`\`\`
{user.tag} = $userTag
{user.mention} = <@$authorID>
{level} = 1
{exp} = 25
\`\`\`
Current msg is:
\`$getServerVar[rmsg]\`]
$onlyBotPerms[mentioneveryone;managemessages;{description:I need permission \`MANAGE_MESSAGES\`/\`MENTION_EVERYONE\`}{color:ff2050}]
$onlyPerms[manageserver;{description:You need \`MANAGE_SERVER\` permission}{color:ff2050}]
$cooldown[5s;Please wait **%time%**]`
});
bot.command({
name: 'rank',
aliases: ['level'],
usage: 'rank (user)',
description: 'see the current level and exp',
code: `$image[https://vacefron.nl/api/rankcard?username=$replaceText[$username[$mentioned[1;yes]]; ;+;-1]&avatar=$userAvatar[$mentioned[1;yes]]?size=4096&level=$getUserVar[lvl;$mentioned[1;yes]]&rank=¤txp=$getUserVar[exp;$mentioned[1;yes]]&nextlevelxp=$getUserVar[rexp;$mentioned[1;yes]]&previouslevelxp=0&custombg=https://cdn.discordapp.com/attachments/793071150614970388/794565647760752650/20210101_205624.jpg&xpcolor=ffffff&isboosting=true]
$onlyIf[$getServerVar[rsystem]>=1;{description:Leveling system is __disabled__}{color:ff2050}]
$cooldown[5s;]`
});
bot.command({
name: 'set-modmail',
code: `
$title[✅ | Task complete]
$description[The modmail channel has been changed to <#$findChannel[$message]>]
$color[RANDOM]
$addTimestamp
$setServerVar[modmail;$findChannel[$message]]
$onlyPerms[admin;You need \`ADMIN\` permision]
$argsCheck[1;Put a valid channel]
`
});
bot.command({
name: 'modmail',
code: `$color[RANDOM]
$useChannel[$getServerVar[modmail]]
$description[<@$authorID> $message]
$title[$username\`($authorID)\` sent modmail - to respond type \`<Prefix>\`mreply @user message>]
$addCmdReactions[📨]
$deletecommandIn[30s]
$cooldown[1m;⛔ Modmail is on cooldown.]
$onlyIf[$getServerVar[modmail]!=;The modmail channel has not been set]
`
});
bot.command({
name: 'mreply',
code: `$title[Modmail Reply]
$dm[$mentioned[1]]
$color[RANDOM]
$description[You've received a new reply to your modmail.
$message]
$addCmdReactions[📦]
$onlyPerms[admin;Only Users with \`ADMIN\` perms can use this]
$suppressErrors[Make sure to mention an user]`
});
bot.command({
name: 'giveaway',
code: `
$editMessage[$getServerVar[giveaway];{title:Giveaway Finished 🎉}{description:Prize: \`$replaceText[$message;$message[1] ;;-1]\`
Hosted By: **$userTag[$authorID]**
Winner: $replaceText[$replaceText[$checkCondition[$getTextSplitLength==1];true;None, there were not enough participants.];false;<@$randomText[$joinSplitText[;]]>.]}{color:RANDOM}{footer:Giveaway Finished.:$authorAvatar}]
$channelSendMessage[$channelID;$replaceText[$replaceText[$checkCondition[$getTextSplitLength==1];true;There were not enough participants.];false;The winner of the prize: **$replaceText[$message;$message[1];;-1]** is: <@$randomText[$joinSplitText[;]]>, Congratulations!]]
$textSplit[$replaceText[$getReactions[$channelID;$getServerVar[giveaway];🎉;id];$clientID,;];,]
$wait[$message[1]]
$setServerVar[giveaway;$sendMessage[{title:React with 🎉 to participate!.}{description:Prize: \`$replaceText[$message;$message[1] ;;-1]\`
Hosted By: **$userTag[$authorID]**
Time: **$message[1]**}{timestamp}{color:RED}{reactions:🎉};yes]]
$onlyIf[$message[2]!=;{title:Looking For Arguments}{description:You have not put any prize to draw.Follow This Format:
\`\`\`
- $getServerVar[prefix]giveaway <time> <prize>.\`\`\`
- \`Arguments with<> are required \`
- }{color:ORANGE}]
- $onlyIf[$isNumber[$replaceText[$replaceText[$replaceText[$replaceText[$message[1];s;];m;];h;];d;]]!=false;{title:Invalid Format}{description:The time format you just entered is invalid Follow this example:
- \`\`\`
- 1s Is 1 second
- 1m Is 1 minute
- 1h Is 1 hour
- 1d Is 1 day
- \`\`\`}{color:RED}]
$onlyPerms[admin;{title:No Permission}{description:You Dont Have \`ADMINISTRATOR\` Permission To Use This Command.}{color:RED}]
`
});
bot.command({
name: 'warn',
code: `
$dm[$mentioned[1]]
$title[Warn]
$description[You Got Warn By $username
Reason : $message]
$footer[Warned By $username]
$onlyPerms[admin;You Dont Have The Warn Perms]`
});
bot.command({
name: 'add-cmd',
code: `
$setservervar[ccmd;$replacetext[$replacetext[$checkcondition[$getservervar[ccmd]!=];false;$tolowercase[$message[1]]/];true;$getservervar[ccmd]$tolowercase[$message[1]]/]]
$setservervar[cdes;$getservervar[cdes]$messageslice[1;10]/]
Successfully added $replacetext[$replacetext[\`$tolowercase[$message[1]]\`;#right_click#;>];#left_click#;<] to the commands list, type \`$getservervar[prefix]cmd-list\` to see all available commands
$onlyif[$findtextsplitindex[$tolowercase[$message[1]]]==0;{description:Command \`$tolowercase[$message[1]]\` is available in the command list}{color:ff2050}]
$textsplit[$getservervar[ccmd];/]
$onlyif[$checkcontains[$message;#RIGHT#;#LEFT#;#RIGHT_BRACKET#;#LEFT_BRACKET#;/]==false;{description:Please don't use it \`symbol\` for trigger and response}{color:ff2050}]
$argscheck[>2;{description:Correct use \n\`\`\`\n$getservervar[prefix]add-cmd <trigger> <response>\n\`\`\`}{color:ff2050}]
$onlyperms[manageserver;{description:You have no permissions for \`MANAGE_SERVER\`}{color:ff2050}{timestamp}]
`
});
bot.command({
name: 'del-cmd',
code: `
$setservervar[ccmd;$replacetext[$getservervar[ccmd];$advancedtextsplit[$getservervar[ccmd];/;$findtextsplitindex[$tolowercase[$message]]]/;]]
$setservervar[cdes;$replacetext[$getservervar[cdes];$advancedtextsplit[$getservervar[cdes];/;$findtextsplitindex[$tolowercase[$message]]]/;]]
Successfully cleared command $replacetext[$replacetext[\`$tolowercase[$message[1]]\`;#right_click#;>];#left_click#;<]
$onlyif[$findtextsplitindex[$tolowercase[$message]]!=0;{description:Command \`$tolowercase[$message]\` not available in the command list}{color:ff2050}]
$textsplit[$getservervar[ccmd];/]
$onlyif[$checkcontains[$message;#RIGHT#;#LEFT#;#RIGHT_BRACKET#;#LEFT_BRACKET#;/]==false;{description:Please don't use it \`symbol\` for trigger and response}{color:ff2050}]
$argscheck[>1;{description:Correct use \n\`\`\`\n$getservervar[prefix]del-cmd <trigger>\n\`\`\`}{color:ff2050}]
$onlyperms[manageserver;{description:You have no permissions for \`MANAGE_SERVER\`}{color:ff2050}{timestamp}]
`
});
bot.command({
name: 'cmd-list',
code: `
$title[**__Custom Commands__**]
$color[RANDOM]
$thumbnail[$servericon]
$description[\`$replacetext[$replacetext[$replacetext[$getservervar[ccmd];#right_click#;>];#left_click#;<];/;, ]\`]
$addtimestamp
$onlyif[$gettextsplitlength>=2;{description:There are no custom commands on the server \`$servername\`}{color:ff2050}]
$textsplit[$getservervar[ccmd];/]
`
});
bot.command({
name: '$alwaysExecute',
code: `
$advancedtextsplit[$getservervar[cdes];/;$findtextsplitindex[$tolowercase[$message]]]
$onlyif[$findtextsplitindex[$tolowercase[$message]]!=0;]
$onlyif[$isbot[$authorid]==false;]
$textsplit[$getservervar[ccmd];/]
`
});
bot.command({
name: 'autorole',
code: `$deletecommand
$argsCheck[>1;Please Mention a role]
$setServerVar[autorole;$mentionedRoles[1]]
$onlyPerms[Only admins can access this command]
$title[ROLES]
$description[Auto-role has been updated to <@&$mentionedRoles[1]>]
$footer[MAGIC]
$color[RANDOM]`
});
bot.command({
name: 'autoroleon',
code: `
$onlyIf[$getServerVar[autorole]>0;You need to Setup the Autoroles First!]
$setServerVar[autorolestate;on]
$title[Success!]
$description[Autorole has been enabled!]
$color[$random[15;99999]]`
});
bot.joinCommand({
channel: '$getServerVar[wchan]',
code: `
$onlyIf[$getServerVar[autorole]>0;]
$giveRole[$getServerVar[autorole];$authorID]`
});
bot.command({
name: 'autoroleoff',
code: `
$onlyIf[$getServerVar[autorole]>0;You need to Setup the Autoroles First!]
$setServerVar[autorolestate;off]
$title[Success!]
$description[Autrole has been disabled!]
$color[$random[15;99999]]
`
})
|
// pages/index/index.js
import {
me,
xmini,
xPage,
mapState,
storage,
mapActions
} from '../../config/xmini';
import api from '../../api/index';
import dealData from '../../utils/dealData';
// console.warn('=====index.js api', api);
import {
mapTo,
pullList,
} from '../../utils/index';
import mixins from '../../utils/mixins';
import { urlMap, getUrlType } from '../../utils/urlMap';
import CountManger from '../../utils/CountManger';
import { formatCountDown,formatDate } from '../../utils/dateUtil';
import { clone } from '../../utils/index';
import formatNum from '../../utils/formatNum';
let windowWidth;
const app = getApp();
xPage({
...mixins,
...dealData,
...pullList,
/**
* 页面的初始数据
*/
oldE: {},
hasOldE: false,
_data: {
collectionTipTimeoutTag: false,
collectionTipTimeout: null, // 收藏弹窗的滑动隐藏计时器
},
data: {
isLoading: true,
collectionTip: true, // 收藏提示弹窗
banner: {},
showFooter: false,
listMode: 'card',
list: [],
shareInfo: true,
showBackTop: false,
lowerThreshold: 300,
pullLoading: true,
couponList: [],
showCouponTip: false,
showFavorite: false,
activeShow: true,
couponShow: true,
modules: [], // 首页模块
newMsg: {},
...mapState({
newMsg: state => state.msg.newMsg,
logged: state => state.user.logged,
// userInfo: state => state.user.userInfo,
}),
killTime:{}
},
// ...mapActions(['startPollingMsg', 'stopPollingMsg']),
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (query) {
console.warn('============index.js onLoad', this)
this.onPageInit(query);
this.shareJump();
this.initData();
// const that = this;
// app.onSubscribeEvent(this, 'KHOT_SEARCH_WORDS', (res) => {
// const { hotSearch } = app.getData();
// that.setData({
// hotSearch: hotSearch || {},
// });
// });
// const { hotSearch } = app.getData();
// windowWidth = wx.getSystemInfoSync().windowWidth;
// this.setData({
// lowerThreshold: wx.getSystemInfoSync().screenHeight / 2,
// hotSearch: hotSearch || {},
// });
// this.refresh();
},
onShow() {
this.updatadSpmPage(); // 新增更新spm 三段中的 page
// console.log('========', this.selectComponent('#dwd-page'));
this.onMessage();
this.getServiceConfig();
// this.startPollingMsg();
// this.dealCountDown('item','1563246799');
},
onReachBottom() {
this.onScrollToLower();
},
onUnload() {
this.clearCountDown();
app.offSubscribeEvent('KHOT_SEARCH_WORDS', this.getPageName);
this.closeTip();
// this.stopPollingMsg();
},
onHide() {
this.clearCountDown();
// this.stopPollingMsg();
this.closeTip();
// 隐藏弹窗
this.selectComponent('#dwd-page-index').closePopup();
},
gotoTest() {
this.forward('test')
},
initData() {
const that = this;
app.onSubscribeEvent(this, 'KHOT_SEARCH_WORDS', (res) => {
const { hotSearch } = app.getData();
that.setData({
hotSearch: hotSearch || {},
});
});
const { hotSearch } = app.getData();
windowWidth = wx.getSystemInfoSync().windowWidth;
this.setData({
lowerThreshold: wx.getSystemInfoSync().screenHeight / 2,
hotSearch: hotSearch || {},
});
this.refresh();
},
refresh() {
this.getIndex();
this.initPullList();
this.pullModel = api.getCoupleListV1;
},
// 页面滑动监听
scrpllIndex(e){
if (this.data.collectionTip && !this._data.collectionTipTimeoutTag){
this._data.collectionTipTimeoutTag = true;
clearTimeout(this._data.collectionTipTimeout);
this._data.collectionTipTimeout = setTimeout(() => {
this.setData({
collectionTip: false,
})
}, 3000)
}
},
onAuthSuccess() {
console.log('授权成功喽')
},
// 获取首页广告模块数据
getIndex() {
this.setData({
isLoading: true,
})
api.getIndex({
scope: this,
weights: 1,
}, (res) => {
wx.hideLoading();
wx.stopPullDownRefresh()
const { info = {} } = res.data;
const newModules = this.getModules(res);
// console.log(this.data.list, 'item list');
// console.log('newModules', newModules);
// this.dealCountDown(list)
this.setData({
isLoading: false,
modules: newModules,
floats: info.floats || [],
}, () => {
//
});
// console.log(this.data.timestamp,'times moduleItem');
// 主动触发加载事件
this.onScrollToLower();
}, (err) => {
wx.stopPullDownRefresh()
});
},
onShowAll(data){
const { index,id,status } = data;
const moduleIndex = this.data.modules.findIndex((item,index) => {return item.id == id});
console.log(this.data, 'index data', moduleIndex);
this.setData ({
[`modules[${moduleIndex}].list[${index}].showupArrow`]: !status
})
},
dealList(list) {
return mapTo(list, (item,index) => {
return {
...item,
tags: (item.tags || []).splice(0, 2),
market_price: (item.market_price / 100).toFixed(2),
price: this.productPrice((item.price / 100).toFixed(2)),
member_price:(item.member_price / 100).toFixed(2),
link: item.link,
expired_date_text: item.expired_date_text_two,
// 添加统计信息
'piwikName':'c_pdr2',
'piwikData':{
index,
pinActivitiesId:item.biz_id,
},
};
});
},
//处理秒杀场次
dealTimeOpt(startTime,endTime,serveTime){
// console.log(startTime, 'deal moduleItem');
let remainTime = endTime - serveTime;
let mStatus = formatDate(startTime,'YM') == formatDate(serveTime,'YM');//是否跨月
if(!mStatus){
return formatDate(startTime,'m月d日')
}
if(remainTime > 0){
let day = Math.abs(formatNum((serveTime - startTime) * 1000).day);
switch (day){
case 0:
return formatDate(startTime,'h')+`点场`;
case 1:
return `明天`+formatDate(startTime,'h')+`点`;
// case 2:
// return formatDate(startTime,'M日H点');
default:
return formatDate(startTime,'d日h点');
}
// console.log(formatNum(remainTime).day,'time moduleItem');
}else{
// remainTime = (serveTime - startTime) * 1000;
// console.log(formatNum(remainTime),'moduleItem day');
return 'end';
}
},
afterPullData() {
//console.log('length', this.data.list.length);
// this.startCountDown();
},
startCountDown() {
const that = this;
const { list = [], diffTime } = that.data;
if (!list.length) return;
const countDownOptions = {
times: 1000,
dataList: list,
set() {
this.localEndTime = (this.data.endTime * 1000) + diffTime;
const leftTime = this.localEndTime - Date.now();
const isStartCountdown = leftTime > 0 && leftTime < (this.data.showCountDownLimit * 1000);
if (isStartCountdown) {
this.start();
}
that.setData({
[`list[${this.index}].isSetCountDown`]: true,
});
},
callback() {
const leftTime = this.localEndTime - Date.now();
if (leftTime > 0) {
const format = leftTime > 86400000 ? 'd天 H:F:S' : 'H:F:S';
const info = formatCountDown(leftTime, format);
that.setData({
[`list[${this.index}]`]: Object.assign({}, that.data.list[this.index], { countDownInfo: info }),
});
} else {
that.setData({
[`list[${this.index}]`]: Object.assign({}, that.data.list[this.index], { countDownInfo: null }),
});
this.clear();
}
},
};
if (!this.countManger) {
this.countManger = new CountManger(countDownOptions);
} else {
this.countManger.add(countDownOptions);
}
},
clearCountDown() {
const that = this;
// if (this.countManger) {
// this.countManger.clear(function() {
// // 不要使用箭头函数
// that.setData({
// [`list[${this.index}].isSetCountDown`]: false,
// });
// });
// }
},
onTapNext(e) { //暂停使用,走afterFormIdSubmit
this.setOldE(e);
},
// 去地址选择页面
// onLocationPage(e){ //暂停使用,走afterFormIdSubmit
// this.setOldE(e);
// },
onDetailPage(e){ //暂停使用,走afterFormIdSubmit
this.setOldE(e);
},
// 搜索
onSearch(e) { //暂停使用,走afterFormIdSubmit
xmini.piwikEvent('c_schbox');
this.setOldE(e);
},
setOldE(e) {
if (e) {
this.oldE = clone(e);
this.hasOldE = true; //阻止点击空白地区跳转
}
},
calculateModuleHeight(width, height){
if(!width || width == 0){
width = windowWidth;
}
return Math.round(height / width * windowWidth);
},
calculateModuleMargin(margin = 0){
return Math.round(windowWidth / 375 * margin);
},
onUrlPage(e) { //覆盖mixins中的方法,并存下e,在发送formId后重新调用
this.setOldE(e);
},
afterFormIdSubmit() { //formId提交之后调用,注意给页面、组件的事件view上加data-form-type
const oldE = this.oldE || {};
if (this.hasOldE && oldE.currentTarget && oldE.currentTarget.dataset) {
const { formType } = oldE.currentTarget.dataset;
if (formType == 'onUrlPage') {
mixins.onUrlPage.call(this, oldE);
} else if (formType == 'search') {
this.forward('search');
} else if (formType == 'cardRecPin') {
const {
id,
index,
canBought,
} = oldE.currentTarget.dataset;
if(canBought){
xmini.piwikEvent('推荐商品', {
index: (index && index + 1) || 0,
id: id,
})
this.forward('detail', {
id,
});
}
} else if (formType == 'card') {
const {
id,
online,
instock,
index,
} = oldE.currentTarget.dataset;
xmini.piwikEvent('首页点击列表', {
index: (index && index + 1) || 0,
id: id,
})
if (online && instock) {
this.forward('detail', {
id,
});
}
}
this.hasOldE = false;
}
},
getServiceConfig() {
api.getServiceConfig({
isLoading: false
}, res => {
const { list = [] } = res.data;
// console.log(list);
this.setData({
tipList: list.slice(0, 2)
})
// console.log(res);
}, err => {
console.log(err);
return true;
})
},
closeTip() {
const tipList = this.data.tipList || [];
// 只有一个活动
if (tipList.length && tipList.length == 1) {
this.setData({
activeShow: false,
couponShow: false,
})
} else if (tipList.length && tipList.length == 2) {
if (this.data.activeShow) {
this.setData({
activeShow: false,
})
} else {
this.setData({
couponShow: false,
})
}
}
},
closeActiveTip(e) {
const { type } = e.currentTarget.dataset;
switch (type) {
case '1':
this.setData({
activeShow: false,
})
break;
case '2':
this.setData({
couponShow: false,
})
break;
default:
// do nothing
break;
}
},
couponItemClick(e) {
const { couponindex, tipindex, code } = e.currentTarget.dataset;
// console.log(couponindex);
// console.log(tipindex);
this.coderedeem(tipindex, couponindex, code)
},
coderedeem(tipindex, couponindex, code) {
wx.showLoading();
api.couponRedeem({
code,
}, (res) => {
wx.hideLoading();
wx.showToast('领取成功');
this.setData({
[`tipList[${tipindex}].list[${couponindex}].receiveType`]: 2,
})
}, (err) => {
if (err.errno === 510010 || err.errno === 210013) {
// 主动授权
authMixin.userAuthLogin.call(this, {
authType: 'auth_user',
resolve: (res) => {
this.coderedeem(code)
},
reject: (err) => {
console.log(err);
}
})
return true;
} else {
wx.hideLoading();
}
});
},
// 修改弹窗显示隐藏
setCollectionTip(){
this.setData({
collectionTip: !this.data.collectionTip
})
},
//
goLogin(){
const { logged } = this.data;
const pageComponent = this.selectComponent('#dwd-page-index');
if (!logged) {
// 显示登录弹窗
pageComponent.setData({
isShowLoginPopup: true
});
return false
}
},
});
|
function myfunction() {
document.getElementById("demo").innerHTML = "Hello!!! This Is Js Demo.";
}
|
var searchData=
[
['stbi_5fio_5fcallbacks_56',['stbi_io_callbacks',['../structstbi__io__callbacks.html',1,'']]]
];
|
import React, { useState } from 'react';
import { Form, Button, Container, Modal } from 'react-bootstrap';
import { setLocalUser } from '../lib/auth';
import axios from '../lib/axios';
import { useHistory } from 'react-router';
export function Signup({ loginToApp }) {
const history = useHistory();
const [userId, setUserId] = useState(null);
//modal
const [show, setShow] = useState(false);
const handleShow = () => setShow(true);
/**
* controls what happends when signup form submission happens
* prevents default browser behaviour
* makes a request to cart API endpoint to create a new cart entry in Carts table
* sets cartId which will be the usersId to component state
* triggers modal to open which will display the users assigned cartId/userId
*/
const handleSubmit = async (event) => {
event.preventDefault();
const cart = await axios.post('/carts');
setUserId(cart.data.id);
setLocalUser(userId);
handleShow();
};
/**
* logs user in when they sign up
* redirects user to homepage on if login attempt successful
*/
const handleHomepage = async () => {
const loggedIn = await loginToApp(userId);
if (loggedIn) {
history.push('/');
}
};
return (
<>
<Container className="my-auto">
<Form>
<Form.Group className="mb-3" controlId="formUserId">
<Form.Label>Name</Form.Label>
<Form.Control placeholder="Enter your name" />
<Form.Text className="text-muted">Please enter a valid name</Form.Text>
</Form.Group>
<Button variant="primary" type="submit" onClick={handleSubmit}>
Sign Up
</Button>
</Form>
<Modal show={show}>
<Modal.Header closeButton>
<Modal.Title>Welcome user {userId}!</Modal.Title>
</Modal.Header>
<Modal.Body></Modal.Body>
<Modal.Footer>
<Button onClick={handleHomepage}>Go to Homepage</Button>
</Modal.Footer>
</Modal>
</Container>
</>
);
}
|
const http = require('http')
const express = require('express')
const routes = require('./routes')
const logger = require('morgan')
const methodOverride = require('method-override')
const session = require('express-session')
const bodyParser = require('body-parser')
const multer = require('multer')
const errorHandler = require('errorhandler')
const database = require('./Database/database');
const app = express()
const upload = multer({ dest: 'uploads/' });
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
// all environments
database.connectToMongo();
app.set('port', process.env.PORT || 3001)
app.use(logger('dev'))
app.use(methodOverride())
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'uwotm8'
}))
app.use(bodyParser.json());
app.use('/uploads',express.static('./uploads'));
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/api/games', routes);
// error handling middleware should be loaded after the loading the routes
if (app.get('env') === 'development') {
app.use(errorHandler())
}
const server = http.createServer(app)
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'))
})
|
layui.use(['layer'], function(){
var layer = layui.layer;
var layerLoadId = layer.load(2);
$.ajax({
url: '/stu_info/api/checkLogin.action',
method: 'post',
dataType: 'json',
data: {
fun: 'checkLogin'
},
success: function(data){
if(data.err == 0){
if(data.userType == 0){
location.href = '/stu_info/student.html';
}else if(data.userType == 1){
location.href = '/stu_info/admin.html';
}else{
location.href = '/stu_info/login.html';
}
}else{
location.href = '/stu_info/login.html';
}
},
error: function(){
layer.close(layerLoadId);
layer.msg('未知错误', {time: 0});
}
});
});
|
//配置微信jssdk
function wxConfig(configData, openJssdkDebug) {
wx.ready(function () {
wx.checkJsApi({
jsApiList: ["chooseImage"],
success: function (res) {
if (res.checkResult.chooseImage) {
console.log("wx.checkJsApi success");
window.wxConfigReady = true;
document.dispatchEvent(new Event("wxConfigReady"));
}
console.log("wx.checkJsApi result:", res.checkResult);
},
fail: function (res) {
console.log("wx.checkJsApi fail:", res);
}
});
});
wx.error(function (res) {
console.log("wx.config error:", res);
});
wx.config({
debug: openJssdkDebug,
appId: configData.appId,
timestamp: configData.timestamp,
nonceStr: configData.nonceStr,
signature: configData.signature,
jsApiList: [
"checkJsApi",
"onMenuShareTimeline",
"onMenuShareAppMessage",
"onMenuShareQQ",
"onMenuShareWeibo",
"onMenuShareQZone",
"updateAppMessageShareData",
"updateTimelineShareData",
"hideMenuItems",
"showMenuItems",
"hideAllNonBaseMenuItem",
"showAllNonBaseMenuItem",
"translateVoice",
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"onVoicePlayEnd",
"pauseVoice",
"stopVoice",
"uploadVoice",
"downloadVoice",
"chooseImage",
"previewImage",
"uploadImage",
"downloadImage",
"getNetworkType",
"openLocation",
"getLocation",
"hideOptionMenu",
"showOptionMenu",
"closeWindow",
"scanQRCode",
"chooseWXPay",
"openProductSpecificView",
"addCard",
"chooseCard",
"openCard"
]
});
}
//加载jweixin标签,兼容6.7.2微信jssdk1.4.0版本
loadScript("./js/jweixin-1.2.0.js", function () {
//加载配置微信jssdk参数标签
loadScript("https://game.flyh5.cn/game/xiyouji_jssdk/twolevel_autho/share.php?auth_appid=wx1da84b6515b921cd&type=js&isonlyopenid=true", function () {
//配置微信jssdk
wxConfig({
appId: wx_config["appId"],
timestamp: wx_config["timestamp"],
nonceStr: wx_config["nonceStr"],
signature: wx_config["signature"]
}, window.openJssdkDebug)
});
})
//加载script
function loadScript(src, callback) {
var s = document.createElement("script");
s.async = false;
s.src = src;
var evtName = null;
var evtListener = null;
function logic() {
s.parentNode.removeChild(s);
s.removeEventListener(evtName, evtListener, false);
callback && callback();
}
if (!-[1,]) {
evtName = "readystatechange";
evtListener = function () {
(this.readyState == "loaded" || this.readyState == "complete") && logic();
}
} else {
evtName = "load";
evtListener = logic;
}
s.addEventListener(evtName, evtListener, false);
console.log(s);
document.body.appendChild(s);
}
|
import {defaultsDeep, merge, extend, pick, isObject} from 'lodash'
import {sky} from './sky.jsx'
import {Status} from '../app/config'
const XHROpen = XMLHttpRequest.prototype.open
sky.fetchOptions = {
mode: 'cors',
headers: {}
}
extend(sky, {
fetch(url, options) {
return fetch(url, defaultsDeep(options, sky.fetchOptions))
.then(function (r) {
const type = r.headers.get('content-type')
if (type && type.indexOf('json') > 0) {
return r.json()
}
})
},
getContacts(username) {
// return sky.fetch(`https://contacts.skype.com/contacts/v1/users/${username}/contacts`)
return sky.fetch(`https://contacts.skype.com/contacts/v2/users/${username}?delta&reason=default`)
},
getChatConversations() {
return sky.fetch('https://client-s.gateway.messenger.live.com/v1/users/ME/conversations?view=msnp24Equivalent&targetType=Thread')
},
getMembers(chatId) {
return sky.fetch(`https://client-s.gateway.messenger.live.com/v1/threads/19:${chatId}@thread.skype?view=msnp24Equivalent`)
},
/*
invite(username, greeting = '') {
return fetch(`https://contacts.skype.com/contacts/v2/users/${sky.profile.username}/contacts`, {
method: 'POST',
headers: merge(sky.fetchOptions.headers, {
'content-type': 'application/json'
}),
body: JSON.stringify({
mri: '8:' + username,
greeting
})
})
},
*/
removeContact(username) {
const fetch = url => this.fetch(url + username, {
method: 'DELETE'
})
return fetch(`https://contacts.skype.com/contacts/v2/users/${sky.profile.username}/contacts/8:`)
.then(() => fetch('https://client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:'))
}
})
extend(window, {
/*
invite(username, greeting) {
sky.invite(username, greeting)
.then(function ({status}) {
status = 404 === status ? Status.ABSENT : Status.INVITED
sky.send({
type: 'invite',
username,
status
})
})
},
*/
getMembers(chatId) {
sky.getMembers(chatId)
.then(function (r) {
r.type = 'getMembers'
sky.send(r)
})
},
getChatConversations() {
sky.getChatConversations()
.then(function (r) {
r.type = 'getChatConversations'
sky.send(r)
})
},
getContacts(id) {
sky.getContacts(id)
.then(({contacts, groups}) => sky.send({
type: 'getContacts',
id,
contacts,
groups
}))
},
removeContact(username) {
sky.removeContact(username)
.then(() => sky.send({
type: 'contact.remove',
username
}))
},
getPerformance() {
sky.send({
type: 'getPerformance',
memory: pick(performance.memory, 'jsHeapSizeLimit', 'totalJSHeapSize', 'usedJSHeapSize')
})
}
})
let neededHeaders = ['X-Skypetoken', 'RegistrationToken']
window.abcd = {}
XMLHttpRequest.prototype.open = function (method, url, sync) {
const xhr = this
if (neededHeaders) {
this.setRequestHeader = function (key, value) {
if (neededHeaders.indexOf(key) >= 0) {
sky.fetchOptions.headers[key] = value
}
XMLHttpRequest.prototype.setRequestHeader.call(this, key, value)
}
// console.log('url', sky.fetchOptions.headers)
if (neededHeaders.every(h => (h = sky.fetchOptions.headers[h]) && h.length > 0)) {
const headers = merge(sky.fetchOptions.headers, {
Cookie: document.cookie,
'User-Agent': navigator.userAgent
})
sky.send({type: 'token', headers})
sky.profile.headers = headers
neededHeaders = false
// XMLHttpRequest.prototype.open = XHROpen
}
}
const isContacts = 0 === url.indexOf('https://contacts.skype.com/contacts/v2/users/') && url.indexOf('/invites') < 0
if (isContacts && 'GET' === method) {
this.addEventListener('load', function () {
const {contacts, groups} = JSON.parse(this.responseText)
if (contacts instanceof Array) {
sky.send({
type: 'contacts',
contacts,
groups
})
}
else {
console.error('Unknown contacts response', this.responseText)
}
})
}
const isConversations = 0 == url.indexOf('https://client-s.gateway.messenger.live.com/v1/users/ME/conversations')
&& url.indexOf('/messages') < 0
if (isConversations && 'GET' === method) {
this.addEventListener('load', function () {
const {conversations} = JSON.parse(this.responseText)
if (conversations instanceof Array) {
sky.send({
type: 'conversations',
conversations
})
}
else {
console.error('Unknown conversations response', this.responseText)
}
})
}
function getTarget(url) {
return /(8|19):([^@/]+)/.exec(url)
}
const isMessages = url.indexOf('https://client-s.gateway.messenger.live.com/v1/users/ME/conversations/') >= 0
if (isMessages && 'GET' === method) {
this.addEventListener('load', function () {
const r = JSON.parse(this.responseText)
if (isObject(r._metadata) && r.messages instanceof Array) {
const conversation = getTarget(r._metadata.syncState)
if (!conversation) {
return console.error('Invalid conversation', r)
}
const messages = []
let recipient = sky.profile.id
let chat = conversation[2]
for(const m of r.messages) {
if (!m.content) {
continue
}
const target = getTarget(m.from)
if (target) {
const _from = target[2]
const _to = '19' === conversation[1]
? conversation[2]
: (conversation[2] === target[2]
? sky.profile.id || sky.profile.username
: conversation[2])
const message = {
from: _from,
to: _to,
text: m.content.trim(),
created: new Date(+m.id)
}
if (m.version !== m.id && new Date(message.time) !== new Date(+m.version)) {
message.time = new Date(+m.version)
}
messages.push(message)
}
else {
console.error('Invalid message', m)
}
}
if (messages.length > 0) {
sky.send({
type: 'messages',
recipient,
chat,
messages
})
}
else {
console.warn('Empty messages', r)
}
}
else {
console.error('Invalid messages response', r)
}
})
}
// if ('https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints/SELF/subscriptions/0/poll' === url) {
// console.log(url)
// this.send = Function()
// }
if ('https://api.skype.com/users/self/profile' === url && 'GET' === method && !sky.profile && sky.fetchOptions.headers['X-Skypetoken']) {
this.addEventListener('load', function () {
sky.profile = JSON.parse(this.responseText)
sky.profile.v = 1
sky.profile.type = 'profile'
sky.send(sky.profile)
})
}
XHROpen.call(this, method, url, sync)
}
|
/*
======================================================================
NewsBar v1.2 (modified to Forum Images NewsFader 1.0)
Vasil Dinkov's NewsBar v1.2 is modified for use and distribution by
forumimages.com with the author's kind permission.
======================================================================
Forum Images NewsFader 1.0
A Forum Images Production -- http://www.forumimages.us/
Authors: SamG, Daz
License: FI Free to Use and Distribute - Please see the included licenses.html
file before using this software. A copy of the license that applies to this script
can be found on the Forum Images site should it not be included;
http://www.forumimages.us/terms.html
======================================================================
*/
// Variables for news items
var defaultNews = 'Welcome to the Our website!';
var newsContent = [
'<a href="http://www.integramod.com/forum/portal.php?page=3">IntegraMOD</a> and <a href="http://www.integramod.com/forum/portal.php?page=4">IM Portal</a> are the two main projects of this site which utilizes the power of the <a href="http://www.phpbb.com">phpBB</a> forum application',
'<a href="http://www.integramod.com/forum/portal.php?page=14">IM Portal</a> is a flexible and powerful portal front end for your <a href="http://www.phpbb.com">phpBB</a> forum with lots of great and advanced features.',
'<a href="http://www.integramod.com/forum/portal.php?page=3">IntegraMOD</a> is a full featured pre-modded version of <a href="http://www.phpbb.com">phpBB</a> forum application with all the great and powerful MODs seamlessly integrated into one superb package.',
'Do NOT forget to read the <a href="rules.php">rules</a> of this site.',
'Please <a href="profile.php?mode=register">register</a> and join the discussions in our <a href="index.php">forums</a>',
'Enjoy, and have a nice day!'
];
// Variables for general configuration
var defaultNewsTimeout = 6;
var newsPopUpFeatures = 'height=320,left=16,menubar,resizable,scrollbars,status,toolbar,top=16,width=560';
var newsPopUpName = 'newsPopUp';
var newsTimeout = 10;
var pauseOnMouseover = true;
// Variables for news fade
var fade = true;
var fadeToDark = true;
var startRed = 255;
var startGreen = 255;
var startBlue = 255;
var endRed = 0;
var endGreen = 0;
var endBlue = 0;
|
async function getResponseFilter() {
if (document.readyState == 'loading') {//при обновлении страницы возвращает значения sessionStorage в 'по умолчанию'
sessionStorage.setItem('filterStoreys', 0)
sessionStorage.setItem('filterArea', 250)
}
let filterStoreys = sessionStorage.getItem('filterStoreys')
let filterArea = sessionStorage.getItem('filterArea')
if (filterStoreys == null) {
filterStoreys = 0
}
if (filterArea == null) {
filterArea = 250
}
let filterAreaStart
if (filterArea == 100) {
filterAreaStart = 0
} else if (filterArea == 150) {
filterAreaStart = 100
} else if (filterArea == 200) {
filterAreaStart = 150
} else if (filterArea == 250) {
filterAreaStart = 0
}
let priceStart = sessionStorage.getItem('priceStart')
let priceEnd = sessionStorage.getItem('priceEnd')
if (priceStart == null) {
priceStart = 0
}
if (priceEnd == null) {
priceEnd = 9999999
}
console.log('http://cloud-desk.ru/DB_Dealers_Domus_Dev/hs/CalcAPI/ProjectsToSite/' + filterStoreys + '/' + filterAreaStart + '/' + filterArea + '/' + priceStart + '/' + priceEnd)
let response = await fetch('http://cloud-desk.ru/DB_Dealers_Domus_Dev/hs/CalcAPI/ProjectsToSite/' + filterStoreys + '/' + filterAreaStart + '/' + filterArea + '/' + priceStart + '/' + priceEnd)
let content = await response.json()
let contentCards = content[1].МассивПроектов
let list = document.querySelector('.gallery-grid')
list.innerHTML = ``// стираем все ячейки и выводим в зависимости от фильтра
contentCards.forEach(item => {
let pictures = item.МассивСсылокНаКартинки
let firstP
let secondP
let thirdP
if (pictures.length == 0) {
firstP = 'https://st4.depositphotos.com/2381417/26959/i/600/depositphotos_269592714-stock-photo-no-thumbnail-image-placeholder-for.jpg'
secondP = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS9E3cZiqQw5v4z-NsSL-h-os1gzakQdeTYeQ&usqp=CAU'
thirdP = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS9E3cZiqQw5v4z-NsSL-h-os1gzakQdeTYeQ&usqp=CAU'
} else {
firstP = pictures[0].СсылкаНаКартинку
secondP = pictures[1]
thirdP = pictures[2]
}
// list.innerHTML = ``
list.innerHTML += `
<div class="grid-item ${item.Этажность} ">
<img src="${firstP}" alt=""
class="grid-item__img" class="btn-primary" data-toggle="modal"
data-target="#exampleModal" onclick = "showAll()">
<div class="grid-content">
<div class="d-name">
<h4 class="name" id="name-1">${item.Наименование}</h4>
</div>
<div class="br"></div>
<div class="item_area">
<p>Площадь:</p>
<div class="n-area">${item.Площадь}</div><span>м²</span>
</div>
<div class='house'>
<div class="house_area">
<p>Длина:</p>
<div class="">${item.Длина}</div >
</div >
<div class="house_area"">
<p>Ширина:</p>
<div class="">${item.Ширина}</div>
</div>
</div>
<div class="house_price">
<p>Цена:</p>
<div class="item_price">${item.Цена}</div><span>₽</span>
</div>
</div>
</div>
`
})
}
getResponseFilter()
|
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect, NavLink } from 'react-router-dom';
import logo from '../images/logo.svg';
import '../scss/App.scss';
import '../scss/markdown.scss';
import Docs from './docs';
import Help from './help';
import Blog from './blog';
import About from './about';
class App extends Component {
renderHeader() {
return (
<header className="header">
<div className="head-box">
<h1 className="h1-logo">
<img src={logo} className="logo" alt="logo" />
<span>React Native</span>
</h1>
<div className="header-nav">
<ul className="top-nav">
<li className="top-nav-item">
<NavLink to='/docs'>文档</NavLink>
</li>
<li className="top-nav-item">
<NavLink to='/help'>社区</NavLink>
</li>
<li className="top-nav-item">
<NavLink to='/blog'>博客</NavLink>
</li>
<li className="top-nav-item">
<NavLink to='/about'>关于我们</NavLink>
</li>
<li className="top-nav-item">
<a target="_blank" rel="noopener noreferrer" href="https://github.com/GoSoin/reactnative.org.cn">Github</a>
</li>
<li className="top-nav-item">
<a target="_blank" rel="noopener noreferrer" href="https://github.com/GoSoin/reactnative.org.cn">React</a>
</li>
</ul>
</div>
</div>
</header>
);
}
renderSubNav() {
return (
<div className="sub-nav-box">
<div className="sub-nav-inner">
<div className="top-sub-nav">
</div>
</div>
</div>
)
}
render() {
return (
<Router>
<div className="app">
{ this.renderHeader() }
{ this.renderSubNav() }
<section>
{/* 路由 */}
<Route exact path={'/docs'} render={()=><Redirect to={'/docs/getting-started'} />} />
<Route exact path={'/docs/:content'} component={Docs} />
<Route path={`/help`} component={Help} />
<Route path={`/blog`} component={Blog} />
<Route path={`/about`} component={About} />
</section>
</div>
</Router>
)
}
};
export default App;
|
export * from '@xmini/x-mini/lib/core/storage';
|
import { useEffect } from 'react';
import { Link as RouterLink, useLocation } from 'react-router-dom';
import PropTypes from 'prop-types';
import {
Avatar,
Box,
Divider,
Drawer,
Hidden,
List,
Typography
} from '@material-ui/core';
import {
Settings as SettingsIcon,
User as UserIcon,
Home
} from 'react-feather';
import NavItem from './NavItem';
import { useAuth } from '../store/auth-context';
import { PermissionEnum } from '../models/user';
const getSidebarItems = (permissionsType) => [
{
href: '/admin/dashboard',
icon: Home,
title: 'בית'
},
{
href: '/admin/account',
icon: UserIcon,
title: 'חשבון',
hide: permissionsType > PermissionEnum.ACCOUNT_ADMIN
},
{
href: '/admin/groups',
icon: SettingsIcon,
title: 'קבוצות'
},
{
href: '/admin/accounts',
icon: UserIcon,
title: 'חשבונות',
hide: permissionsType !== PermissionEnum.SUPER_USER
},
{
href: '/admin/users',
icon: UserIcon,
title: 'משתמשים',
hide: permissionsType > PermissionEnum.ACCOUNT_ADMIN
},
{
href: '/admin/settings',
icon: SettingsIcon,
title: 'הגדרות',
hide: permissionsType > PermissionEnum.ACCOUNT_ADMIN
}
];
const DashboardSidebar = ({ onMobileClose, openMobile }) => {
const location = useLocation();
const { currentUser } = useAuth();
const items = getSidebarItems(currentUser.permission);
useEffect(() => {
if (openMobile && onMobileClose) {
onMobileClose();
}
}, [location.pathname]);
const content = (
<Box
sx={{
display: 'flex',
flexDirection: 'column',
height: '100%'
}}
>
<Box
sx={{
alignItems: 'center',
display: 'flex',
flexDirection: 'column',
p: 2
}}
>
<Avatar
component={RouterLink}
src={currentUser.avatar}
sx={{
cursor: 'pointer',
width: 64,
height: 64
}}
to="/admin/account"
>
{/* {getInitials(`${currentUser.firstName} ${currentUser.lastName}`)} */}
</Avatar>
<Typography
color="textPrimary"
variant="h5"
>
{`${currentUser.firstName} ${currentUser.lastName}`}
</Typography>
</Box>
<Divider />
<Box sx={{ p: 2 }}>
<List>
{items.map((item) => (
<NavItem
href={item.href}
key={item.title}
title={item.title}
icon={item.icon}
hide={item.hide}
/>
))}
</List>
</Box>
</Box>
);
return (
<>
<Hidden lgUp>
<Drawer
anchor="right"
onClose={onMobileClose}
open={openMobile}
variant="temporary"
PaperProps={{
sx: {
width: 256
}
}}
>
{content}
</Drawer>
</Hidden>
<Hidden lgDown>
<Drawer
anchor="right"
open
variant="persistent"
PaperProps={{
sx: {
width: 256,
top: 64,
height: 'calc(100% - 64px)'
}
}}
>
{content}
</Drawer>
</Hidden>
</>
);
};
DashboardSidebar.propTypes = {
onMobileClose: PropTypes.func,
openMobile: PropTypes.bool
};
DashboardSidebar.defaultProps = {
onMobileClose: () => { },
openMobile: false
};
export default DashboardSidebar;
|
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const moment = require('moment')
const gmailEmail = "vladdragonsun@gmail.com";
const gmailPassword = "jhcjhc123";
const mailTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
port: 587,
secure: true
});
const APP_NAME = 'MyPaldip';
const reminderScheduleMinute = 60 // unit is min
admin.initializeApp();
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
let users = [];
// exports.sendTimedEmail = functions.https.onCall((data, context) => {
exports.sendTimedEmail = functions.https.onRequest((req, res) => {
let currTime = moment()
let startTime = moment(currTime).subtract(reminderScheduleMinute, 'minutes')
let records = [
admin.database().ref(`Groups`).once('value'),
admin.database().ref(`StudentGroups`).once('value'),
admin.database().ref(`Users`).once('value'),
admin.database().ref(`QuestionSets`).once('value'),
admin.database().ref(`Questions`).once('value'),
admin.database().ref(`NewAnswers`).once('value'),
admin.database().ref(`LikertAnswer`).once('value'),
admin.database().ref(`Settings/reminderSettings`).once('value'),
];
Promise.all(records).then(snapshots => {
let TeacherGroups = snapshots[0].val();
let StudentGroups = snapshots[1].val();
let Users = snapshots[2].val();
let AllQuestionSets = snapshots[3].val();
let allQuestions = snapshots[4].val()
let Questions = {}
for (questionKey in allQuestions) {
let question = allQuestions[questionKey]
let setKey = question.Set
Questions[setKey] = Questions[setKey] || {}
Questions[setKey][questionKey] = question
}
let Answers = snapshots[5].val();
let LikertAnswers = snapshots[6].val();
let reminderSettings = snapshots[7].val();
let usersInGroup = {}
let emailList = {}
let nameList = {}
for (studentKey in StudentGroups) {
let stGroups = StudentGroups[studentKey]
for (key in stGroups) {
let groupKey = stGroups[key]
usersInGroup[groupKey] = usersInGroup[groupKey] || []
usersInGroup[groupKey].push(studentKey)
}
}
for (teacherKey in TeacherGroups) {
let Groups = TeacherGroups[teacherKey]
for (groupKey in Groups) {
let Group = Groups[groupKey]
let QuestionSets = Group.QuestionSets || {}
let groupUsers = usersInGroup[groupKey] || []
for (qsetKey in QuestionSets) {
let QuestionSet = QuestionSets[qsetKey]
let reminder = QuestionSet.reminder ? QuestionSet.reminder : Group.reminder
if (QuestionSet.deadline === undefined || reminder === undefined) continue // continue if reminder doesn't exist
let reminderTime = moment(QuestionSet.deadline).add(reminder.day1, 'days').add(reminder.hour1, 'hours')
let pastList = []
if (reminderTime.isAfter(startTime) && reminderTime.isBefore(currTime)) {
pastList.push({ day: reminder.day1, hour: reminder.hour1 })
}
if (reminder.count === 2) {
reminderTime = moment(QuestionSet.deadline).add(reminder.day2, 'days').add(reminder.hour2, 'hours')
if (reminderTime.isAfter(startTime) && reminderTime.isBefore(currTime)) {
pastList.push({ day: reminder.day1, hour: reminder.hour1 })
}
}
for (i = 0; i < groupUsers.length; i++) {
studentKey = groupUsers[i]
let questionSetKey = QuestionSet.siblingSetKey ? QuestionSet.siblingSetKey : qsetKey
let qsetQuestions = Questions[questionSetKey] || {}
let inComplete = false
for (questionKey in qsetQuestions) {
if (QuestionSet.LikertType) {
if (!LikertAnswers[questionSetKey] || !LikertAnswers[questionSetKey][studentKey] || !LikertAnswers[questionSetKey][studentKey].answer || !LikertAnswers[questionSetKey][studentKey].answer[questionKey]) {
inComplete = true
break
}
} else {
if (!Answers[questionKey] || !Answers[questionKey].answer || !Answers[questionKey].answer[studentKey]) {
inComplete = true
break
}
}
}
if (inComplete) {
for (pastIndex = 0; pastIndex < pastList.length; pastIndex++) {
pastTime = pastList[pastIndex]
const teacherEmail = Users[teacherKey].ID
const studentEmail = Users[studentKey].ID
// const studentEmail = 'vladdragonsun@gmail.com'
if (emailList[studentEmail] === undefined) {
emailList[studentEmail] = []
nameList[studentEmail] = Users[studentKey].nick_name ? Users[studentKey].nick_name : 'Student'
}
emailList[studentEmail].push({
teacherEmail: teacherEmail,
groupName: Group.groupname,
questionSetName: AllQuestionSets[qsetKey].setname,
deadline: QuestionSet.deadline,
pastTime: pastTime,
})
}
}
}
}
}
}
for (studentEmail in emailList) {
let setList = emailList[studentEmail]
var items = ""
for (var i = 0; i < setList.length; i++) {
items = items + `<div class='list'><p><b>Group Name:</b>${setList[i].groupName}</p><p><b>Questionset Name:</b>${setList[i].questionSetName}</p>` +
`<p><b>Past Time:</b> ${pastTime.day} days ${pastTime.hour} hours</p></div>`
}
const mailOptions = {
from: `"${APP_NAME}" <no-reply@mypaldip.com>`,
to: studentEmail,
subject: 'Timed Reminder'
};
let content = reminderSettings.headerContent
let regex = new RegExp('<Student>', 'g');
content = content.replace(regex, nameList[studentEmail]);
mailOptions.html = `<!doctype html><html><head><meta name="viewport" content="width=device-width" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Timed Reminder</title>
<style>
body {background-color: #d8dad9;} .container { background-color: white; width: 80%; margin: 0px auto;border-radius: 6px;padding: 20px;}
.header { text-align: center; } .list { border-bottom: solid 1px #c3c3c3; width: 600px; margin: 0px 0px 20px 40px; }
.list>p>b { display: inline-block; width: 150px; } pre{font-size: 16px;}
</style></head>
<body><div class="container">
<h1 class="header">${reminderSettings.title}</h1>
<div class="content">
<pre>${content}</pre>
<br />
${items}
</div> </div></div> </body></html>`;
mailTransport.sendMail(mailOptions)
}
return res.send(emailList)
}).catch(error => {
res.send(error)
})
});
exports.getUsers = functions.https.onCall((data, context) => {
users = [];
return listAllUsers();
});
function listAllUsers(nextPageToken) {
// List batch of users, 1000 at a time.
return admin.auth().listUsers(1000, nextPageToken)
.then((listUsersResult) => {
listUsersResult.users.forEach((userRecord) => {
users.push(userRecord);
});
if (listUsersResult.pageToken) {
return listAllUsers(listUsersResult.pageToken)
} else {
return users;
}
})
.catch((error) => {
return ({ error: error });
});
}
// Start listing users from the beginning, 1000 at a time.
exports.sendEmail = functions.https.onCall((data, context) => {
// async function sendEmail(adminEmail, teacherEmail) {
const { adminEmail, teacherEmail, createTime } = data;
const mailOptions = {
from: `"${APP_NAME}" <no-reply@mypaldip.com>`,
to: adminEmail,
};
mailOptions.subject = "New teacher added!";
mailOptions.html = `<h1> Approve Request</h1>
<h2>Dear Manager!</h2>
<p>New teacher added!<p>
<p>Teacher Email:  <b>${teacherEmail}</b></p>
<p>Create Time:  <b>${createTime}</b></p>
<p>Please approve his account.</p>
<p>Thanks.</p>`;
return mailTransport.sendMail(mailOptions).then(() => {
return { result: 'success' }
});
});
exports.sendAproveEmail = functions.https.onCall((data, context) => {
// async function sendEmail(adminEmail, teacherEmail) {
const { adminEmail, teacherEmail } = data;
const mailOptions = {
from: `"${APP_NAME}" <no-reply@mypaldip.com>`,
to: teacherEmail,
};
mailOptions.subject = "Account has been approved!";
// const title = (state == 'approved') ? "<h1>Account has been approved!</h1>" : "<h1>Account has been disapproved!</h1>";
// "Your teacher account has now been approved. You can now login using your email and password at www.mypaldip.com and begin creating question sets and groups.
// You can access the manual at bit.ly/PaLDIPManual ."
// mailOptions.html = `<h1>Your teacher account has now been approved!</h1>
// <p>You can now login using your email and password at <a href='www.mypaldip.com'>www.mypaldip.com</a> and begin creating question sets and groups.<p>
// <p>You can access the manual at <a href='http://bit.ly/PaLDIPManual'>here</a>.</p>
// <p>Regards.</p>
// <p><b>mypaldip</b> Manager.</p>
// `;
mailOptions.html = `<h1>Your teacher account has now been approved!</h1>
<p>You can now login using your email and password at www.mypaldip.com and begin creating question sets and groups.<p>
<p>You can access the manual at http://bit.ly/PaLDIPManual.</p>
<p>Regards.</p>
<p><b>mypaldip</b> Manager.</p>
`;
return mailTransport.sendMail(mailOptions).then(() => {
return { result: 'success' }
});
});
exports.sendReminderEmail = functions.https.onCall((data, context) => {
const { studentList, emailTemplate } = data;
studentList.forEach(student => {
const { email, name } = student
let emailContent = emailTemplate
var regex = new RegExp('<Student>', 'g');
emailContent = emailContent.replace(regex, name);
mailOptions = {
from: `"${APP_NAME}" <no-reply@mypaldip.com>`,
to: email,
};
mailOptions.subject = "Answer Request Reminder";
mailOptions.html = `<h1>Answer Request</h1>
<pre style="font-size:18px;">`+ emailContent + `</pre>`;
mailTransport.sendMail(mailOptions)
});
return { result: 'success', sendCount: studentList.length }
});
|
/*eslint-env node*/
module.exports = {
extends: ['./lib/eslint'],
rules: {
'no-undef': 0,
},
};
|
import React, { useContext } from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import Spinner from '../../../atoms/Spinner/Spinner';
import NamespaceJoinBox from '../components/NamespaceJoinBox';
import * as Styles from '../styles/multiStepStyles';
import { NamespaceControllerContext } from '../context/NamespaceControllerContext';
const StyledWrapper = styled.div`
width: 100%;
height: 100%;
padding: 4rem;
overflow-y: scroll;
position: relative;
`;
const FoundNamespacesWrapper = styled.section`
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-y: scroll;
`;
const StyledHeading = styled.h1`
font-size: 36px;
font-family: ${({ theme }) => theme.font.family.avanti};
color: #222;
margin-bottom: 2rem;
`;
const StyledParagraph = styled.p`
color: #222;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
`;
const FoundNamespacesPage = ({ isSearching, searchedNamespaces }) => {
const { changePage } = useContext(NamespaceControllerContext);
return (
<StyledWrapper>
{isSearching ? (
<Spinner />
) : (
<>
<StyledHeading>Servers: </StyledHeading>
<FoundNamespacesWrapper>
{searchedNamespaces.length !== 0 ? (
<>
{searchedNamespaces.map(item => (
<NamespaceJoinBox namespace={item} key={item._id} />
))}
</>
) : (
<StyledParagraph>Servers not found</StyledParagraph>
)}
</FoundNamespacesWrapper>
</>
)}
<Styles.BackParagraph onClick={() => changePage(2)}>GO BACK</Styles.BackParagraph>
</StyledWrapper>
);
};
const mapStateToProps = ({ namespaceReducer: { isSearching, searchedNamespaces, namespaceError } }) => {
return { isSearching, searchedNamespaces, namespaceError };
};
export default connect(mapStateToProps)(FoundNamespacesPage);
|
function SpeakerRenderProps(props) {
const speakers = [
{ imageSrc: "spekaer-1124", name: "Douglas Crockford" },
{ imageSrc: "spekaer-1530", name: "Tamara Bakr" },
{ imageSrc: "spekaer-10803", name: "Eugene Chuvyrov" },
];
return props.children({
speakers: speakers,
});
}
export default SpeakerRenderProps;
|
// import Joi from 'joi';
// import Boom from 'boom';
// import {
// Task
// } from 'models';
// export const getAllTasks = {
// method: 'GET',
// path: '/tasks',
// handler: (request, reply) => {
// Task.findAll()
// .then((tasks) => {
// reply(tasks);
// });
// }
// };
// export const getTask = {
// method: 'GET',
// path: '/tasks/{taskId}',
// handler: (request, reply) => {
// const taskId = request.params.taskId;
// Task.findOne({
// where: {
// id: taskId
// }
// })
// .then((task) => {
// reply(task);
// });
// }
// };
// export const createTask = {
// method: 'POST',
// path: '/tasks',
// config: {
// validate: {
// payload: {
// requirements: Joi.string(),
// deliverables: Joi.string(),
// status: Joi.string(),
// tstart: Joi.date(),
// tend: Joi.date(),
// tdue: Joi.date(),
// tcompletion: Joi.date(),
// uidsupervisor: Joi.string(),
// uidoperator: Joi.string(),
// uidauditor: Joi.string(),
// mid: Joi.string(),
// oid: Joi.string()
// }
// }
// },
// handler: (request, reply) => {
// const payload = request.payload;
// Task.create(payload).then((task) => {
// reply(task);
// });
// }
// };
// export const updateTask = {
// method: 'PUT',
// path: '/tasks/{taskId}',
// config: {
// validate: {
// payload: {
// requirements: Joi.string(),
// deliverables: Joi.string(),
// status: Joi.string(),
// tstart: Joi.date(),
// tend: Joi.date(),
// tdue: Joi.date(),
// tcompletion: Joi.date(),
// uidsupervisor: Joi.string(),
// uidoperator: Joi.string(),
// uidauditor: Joi.string(),
// mid: Joi.string(),
// oid: Joi.string()
// }
// }
// },
// handler: (request, reply) => {
// const taskId = request.params.taskId;
// const payload = request.payload;
// Task.update(payload, {
// where: {
// id: taskId
// }
// })
// .then((task) => {
// reply(task);
// });
// }
// };
// export const deleteTask = {
// method: 'DELETE',
// path: '/tasks/{taskId}',
// handler: (request, reply) => {
// const taskId = request.params.taskId;
// Task.destroy({
// where: {
// id: taskId
// }
// })
// .then((task) => {
// reply(task);
// });
// }
// };
//
export const genSuccessRes = (props, values) => {
return genRes('success', props, values)
}
export const genErrRes = (props, values) => {
return genRes('error', props, values)
}
let genRes = (status, props, values) => {
if ((props instanceof Array) && (values instanceof Array)){
if (props.length != values.length){
throw new Error('2 arrays must have the same number of elements')
}
let result = {
status: status,
response: {}
}
for(let i = 0; i < props.length; i++){
if (props[i] in result.response){
throw new Error('Duplicate keys for genRes')
}
else {
result.response[props[i]] = values[i]
}
}
return JSON.parse(JSON.stringify(result))
}
else{
throw new Error('Invalid type for genRes')
}
}
|
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
const rst = [];
function atomic(leftArr, arr) {
if (arr.length === 1) {
return rst.push(leftArr.concat([arr[0]]));
}
for (let i = 0; i < arr.length; i++) {
atomic(leftArr.concat(arr[i]), arr.filter(item => item !== arr[i]));
}
}
atomic([], nums);
return rst;
};
module.exports = permute;
|
import React, { Component } from 'react';
import InlineSVG from 'svg-inline-react';
import classnames from 'classnames';
import AppActions from '../../actions/AppActions';
const svgMap = {
one: require('../../../images/icons/player-repeat-one.svg'),
all: require('../../../images/icons/player-repeat.svg'),
default: require('../../../images/icons/player-repeat.svg'),
};
/*
|--------------------------------------------------------------------------
| RepeatButton
|--------------------------------------------------------------------------
*/
export default class ButtonRepeat extends Component {
static propTypes = {
repeat: React.PropTypes.string,
}
constructor(props) {
super(props);
this.toggleRepeat = this.toggleRepeat.bind(this);
}
render() {
const svg = svgMap[this.props.repeat] || svgMap.default;
const buttonClasses = classnames('button repeat',{
active: this.props.repeat === 'one' || this.props.repeat === 'all',
});
const svgClasses = classnames('icon', {
'repeat-one': this.props.repeat === 'one',
'repeat': this.props.repeat !== 'one',
});
return (
<button className={ buttonClasses } onClick={ this.toggleRepeat }>
<InlineSVG src={ svg } className={ svgClasses } />
</button>
);
}
toggleRepeat() {
let repeat = 'none';
switch(this.props.repeat) {
case 'none':
repeat = 'all';
break;
case 'all':
repeat = 'one';
break;
case 'one':
repeat = 'none';
break;
}
AppActions.player.repeat(repeat);
}
}
|
var chatController = require("./chatController");
module.exports = function (io){
/**
* @api {ON} connect A. Connecting to socket
* @apiVersion 0.1.0
* @apiName Socket connect
* @apiGroup Chat
* @apiDescription Connecting to socket will require some data that will be appended in the url as query (e.g. http://socket_url:3000?id=(user_id)&tag=(device tag))
*
* @apiParam {String} id User id
* @apiParam {String} tag device tag
*/
io.on('connect', function (socket){
var handshake = socket.handshake.query;
if(handshake.id && handshake.tag){
chatController.connect({
id: handshake.id ? handshake.id : "",
tag: handshake.tag ? handshake.tag : "",
socketId: socket.id ? socket.id : ""
});
}else{
socket.disconnect();
console.log("DISCONNETED");
return;
}
/**
* @api {emit} startChat B. Starting chat with another user
* @apiVersion 0.1.0
* @apiName Socket start
* @apiGroup Chat
*
* @apiParam {Array} users Array of users id
* @apiSuccess {Boolean} error=false Value will be true/false
* @apiSuccess {String} chatHead Conversation Id
* @apiSuccessExample Acknowledgement:
* {
* error: false,
* chatHead: 10
* }
*
* @apiError error=true
*/
socket.on('startChat', function (data, ack){
chatController.startChat(data, function (resp){
if(resp.chatHead)
socket.join(resp.chatHead);
ack(resp);
})
});
/**
* @api {emit} sendMessage C. Send message to chatmate
* @apiVersion 0.1.0
* @apiName Socket send
* @apiGroup Chat
*
* @apiDescription This will send messages to user chatmate
*
* @apiParam {JSON} -JsonObject/NSDictionary- data type
* @apiParam {String} JsonObject.chatHead id(chatHead) you got from EMIT 'startChat' or in INBOX
* @apiParam {String} JsonObject.name Sender name
* @apiParam {String} JsonObject.message Sender message
* @apiParam {String} JsonObject.to Receiver id
* @apiParam {String} JsonObject.from Sender id
*
*
* @apiSuccess {JSON} -JsonObject/NSDictionary- data type
* @apiSuccess {String} JsonObject.chatHead id(chatHead) you got from EMIT 'startChat' or in INBOX
* @apiSuccess {String} JsonObject.name Sender name
* @apiSuccess {String} JsonObject.message Sender message
* @apiSuccess {String} JsonObject.to Receiver id
* @apiSuccess {String} JsonObject.from Sender id
*
* @apiSuccessExample Acknowledgement:
* {
* chatHead: 10,
* name: 'sample name'
* message: 'sample message'
* to: 2
* from: 1
* }
*
* @apiErrorExample Acknowledgement:
* {
* error: true,
* message: 'Sending failed'
* }
*
*/
socket.on('sendMessage', function (data, ack){
chatController.saveMessage(socket, data, function (resp){
ack(resp);
})
});
/**
* @api {on} newMessage D. Receive message
* @apiVersion 0.1.0
* @apiName Socket receive
* @apiGroup Chat
*
* @apiDescription This will listen and receive messages from user chatmate
*
* @apiSuccess {JSON} -JsonObject/NSDictionary- data type
* @apiSuccess {String} JsonObject.chatHead id(chatHead) you got from EMIT 'startChat' or in INBOX
* @apiSuccess {String} JsonObject.name Sender name
* @apiSuccess {String} JsonObject.message Sender message
* @apiSuccess {String} JsonObject.to Receiver id
* @apiSuccess {String} JsonObject.from Sender id
*
* @apiSuccessExample Acknowledgement:
* {
* chatHead: 10,
* name: 'sample name'
* message: 'sample message'
* to: 2
* from: 1
* }
*
*/
/**
* @api {emit} getMessages E. Get messages
* @apiVersion 0.1.0
* @apiName Socket get
* @apiGroup Chat
*
* @apiDescription This will return the messages for specific chatHead ID
*
* @apiParam {JSON} -JsonObject/NSDictionary- data type
* @apiParam {String} a.chatHead chatHead id
* @apiParam {String} [a.last_message_id] required if fetching another set of messages in a specific chatHead id
*
* @apiSuccess {JSON} messages Container of messages
* @apiSuccess {Array} messages.-JsonArray- data type -- array of messages
* @apiSuccess {JSON} messages.JsonArray.-JsonObject- data type per array
* @apiSuccess {String} messages.JsonArray.JsonObject.chatHead id(chatHead) you got from EMIT 'startChat' or in INBOX
* @apiSuccess {String} messages.JsonArray.JsonObject.name Sender name
* @apiSuccess {String} messages.JsonArray.JsonObject.message Sender message
* @apiSuccess {String} messages.JsonArray.JsonObject.to Receiver id
* @apiSuccess {String} messages.JsonArray.JsonObject.from Sender id
* @apiSuccess {Date} messages.JsonArray.JsonObject.created date
*
* @apiSuccess {Boolean} hasNext indicator if there's more messages to fetch
*
* @apiSuccessExample Acknowledgement:
* {
* messages: [
* {
* chatHead: 10,
* name: 'sample name'
* message: 'sample message'
* to: 1,
* from: 2
* },
* {
* chatHead: 10,
* name: 'sample name'
* message: 'sample message'
* to: 1,
* from: 2
* }
* ],
* hasNext: true/false
*}
*
* @apiErrorExample Acknowledgement:
* {
* error: true,
* message: 'Sending failed'
* }
*
*/
socket.on('getMessages', function (data, ack){
chatController.getMessages(data, function (resp){
ack(resp);
})
});
/**
* @api {emit} markAsRead F. Mark as read
* @apiVersion 0.1.0
* @apiName Socket mark
* @apiGroup Chat
*
* @apiDescription Marking messages as read to appear read/seen
*
* @apiParam {String} id last message id of chatmate message
* @apiParam {String} chatMateId chatmate ID
* @apiSuccess {Boolean} error=false Value will be true/false
* @apiSuccessExample Acknowledgement:
* {
* error: false
* }
*
*/
socket.on('markAsRead', function (data, ack){
chatController.markAsRead(data, function(resp){
ack(resp);
})
});
/**
* @api {emit} getUserInbox G. Get user inbox
* @apiVersion 0.1.0
* @apiName Socket get inbox
* @apiGroup Chat
*
* @apiDescription This return user converstions
*
* @apiParam {JSON} -JsonObject/NSDictionary- data type
* @apiParam {String} a.id user id
*
* @apiSuccess {Array} -JsonArray- data type -- array of conversation
* @apiSuccess {JSON} JsonArray.-JsonObject- data type per array
* @apiSuccess {String} JsonArray.JsonObject.chatHead id(chatHead) you got from EMIT 'startChat' or in INBOX
* @apiSuccess {String} JsonArray.JsonObject.name Sender name
* @apiSuccess {String} JsonArray.JsonObject.message Sender message
* @apiSuccess {String} JsonArray.JsonObject.to Receiver id
* @apiSuccess {String} JsonArray.JsonObject.from Sender id
* @apiSuccess {Date} JsonArray.JsonObject.created date
*
* @apiSuccess {Boolean} hasNext indicator if there's more messages to fetch
*
* @apiSuccessExample Acknowledgement:
* [
* {
* id: 10,
* user_1: 1
* user_2: 2
* created: '2016-06-19T02:13:52.000Z',
* last_message: {
* id: 60,
* chatHead: 10,
* name: 'sample name'
* message: 'sample message',
* to: 1,
* from: 2,
* created: '2016-06-20T08:55:00.000Z',
* status: 'unread'
* }
* }
* ]
*
* @apiError {Array} Empty It will return empry array
* @apiErrorExample Acknowledgement:
* []
*/
socket.on('getUserInbox', function (data, ack){
chatController.getUserInbox(data, function(resp){
ack(resp);
})
});
/**
* @api {emit} leave_chat H. Leaving chat page
* @apiVersion 0.1.0
* @apiName Socket leave
* @apiGroup Chat
*
* @apiDescription This will stop socket from listening in newMessages from a specific chatroom/page
*
* @apiParam {JsonObject} -JsonObject- data type
* @apiParam {String} JsonObject.chatHead chatHead id
*/
socket.on('leave_chat', function (data){
socket.leave(data.chatHead);
console.log(socket.id + " leaving room " + data.chatHead);
});
/**
* @api {emit} Typing I. Typing status
* @apiVersion 0.1.0
* @apiName Socket typing
* @apiGroup Chat
*
* @apiDescription This will inform other user that their chatmate is typing
*
* @apiParam {JsonObject} -JsonObject- data type
* @apiParam {String} JsonObject.chatHead chatHead id
* @apiParam {Boolean} JsonObject.isTyping true/false
*/
socket.on('typing', function (data){
socket.broadcats.to(data.chatHead).emit('isTyping', { isTyping: data.isTyping });
});
/**
* @api {emit} Logout J. Logout user
* @apiVersion 0.1.0
* @apiName Socket logout
* @apiGroup Chat
*
* @apiDescription This will logout and remove user socket session
*
* @apiParam {JsonObject} -JsonObject- Just pass an empty jsonObject/NSDictionary
*/
socket.on("logout", function (data, ack){
chatController.deleteTag({
id: handshake.id ? handshake.id : "",
tag : handshake.tag ? handshake.tag : ""
}, function (resp){
ack(resp);
})
});
/**
* @api {emit} registerEvent A. Register event to start chatting
* @apiVersion 0.1.0
* @apiName Socket register event
* @apiGroup Event
*
* @apiParam {String} event_id Event id
* @apiParam {String} user_id Id of user who owns the event
* @apiSuccess {Boolean} error=false Value will be true/false
* @apiSuccess {String} chatHead Conversation Id
* @apiSuccessExample Acknowledgement:
* {
* error: false,
* eventChat: 10
* }
*
* @apiError error=true
*/
socket.on('registerEvent', function (data, ack){
chatController.registerEventForChat(data, function (resp){
if(resp.eventChat)
socket.join(resp.eventChat);
ack(resp);
})
});
/**
* @api {emit} addUserToEvent B. Register user to event to enable chat with other users
* @apiVersion 0.1.0
* @apiName Socket add user
* @apiGroup Event
*
* @apiParam {String} user_id Id of user that joined the event
* @apiParam {String} eventChat_id Id of event user want to join
* @apiSuccess {Boolean} error=false Value will be true/false
* @apiSuccess {String} message Success response
* @apiSuccessExample Acknowledgement:
* {
* error: false,
* message: "success"
* }
*
* @apiError error=true
*/
socket.on('addUserToEvent', function (data, ack){
chatController.addUserToEvent(data, function (resp){
ack(resp);
});
});
/**
* @api {emit} getEventMessages C. Get messages on a specific event
* @apiVersion 0.1.0
* @apiName Socket get msg event
* @apiGroup Event
*
* @apiDescription This will return the messages for specific event
*
* @apiParam {JSON} -JsonObject/NSDictionary- data type
* @apiParam {String} a.eventChat_id id from EMIT 'registerEvent
* @apiParam {String} [a.last_message_id] required if fetching another set of messages in a specific event
*
* @apiSuccess {JSON} messages Container of messages
* @apiSuccess {Array} messages.-JsonArray- data type -- array of messages
* @apiSuccess {JSON} messages.JsonArray.-JsonObject- data type per array
* @apiSuccess {String} messages.JsonArray.JsonObject.eventChat_id id(eventChat_id) you got from EMIT 'registerEvent'
* @apiSuccess {String} messages.JsonArray.JsonObject.name Sender name
* @apiSuccess {String} messages.JsonArray.JsonObject.message Sender message
* @apiSuccess {String} messages.JsonArray.JsonObject.image Sender image
* @apiSuccess {String} messages.JsonArray.JsonObject.from Sender id
* @apiSuccess {Date} messages.JsonArray.JsonObject.created date
*
* @apiSuccess {Boolean} hasNext indicator if there's more messages to fetch
*
* @apiSuccessExample Acknowledgement:
* {
* messages: [
* {
* eventChat_id: 10,
* name: 'sample name'
* message: 'sample message'
* image: 'sample image',
* from: 2,
* created: '2016-06-20T08:55:00.000Z',
* },
* {
* eventChat_id: 10,
* name: 'sample name'
* message: 'sample message'
* image: 'sample image'
* from: 2,
* created: '2016-06-20T08:55:00.000Z',
* }
* ],
* hasNext: true/false
* }
*
* @apiErrorExample Acknowledgement:
* {
* error: true,
* message: 'Sending failed'
* }
*
*/
socket.on('getEventMessages', function (data, ack){
chatController.getEventMessages(data, function(resp){
ack(resp);
})
});
/**
* @api {emit} sendMessageToEvent D. Send message to an event
* @apiVersion 0.1.0
* @apiName Socket send to event
* @apiGroup Event
*
* @apiDescription This will send messages to event chat room
*
* @apiParam {JSON} -JsonObject/NSDictionary- data type
* @apiParam {String} JsonObject.eventChat_id id(eventChat)
* @apiParam {String} JsonObject.name Sender name
* @apiParam {String} JsonObject.message Sender message
* @apiParam {String} JsonObject.image Sender image
* @apiParam {String} JsonObject.from Sender id
* @apiParam {String} [JsonObjecy.file] file URL
*
*
* @apiSuccess {JSON} -JsonObject/NSDictionary- data type
* @apiSuccess {String} JsonObject.eventChat_id id(eventChat_id) you got from EMIT 'registerEvent'
* @apiSuccess {String} JsonObject.name Sender name
* @apiSuccess {String} JsonObject.message Sender message
* @apiSuccess {String} JsonObject.image Sender image
* @apiSuccess {String} JsonObject.from Sender id
* @apiSuccess {String} [JsonObjecy.file] file URL
*
* @apiSuccessExample Acknowledgement:
* {
* eventChat_id: 10,
* name: 'sample name'
* message: 'sample message'
* image: 'sample image'
* from: 1
* }
*
* @apiErrorExample Acknowledgement:
* {
* error: true,
* message: 'Sending failed'
* }
*
*/
socket.on('sendMessageToEvent', function (data, ack){
chatController.sendMessageToEvent(socket, data, function (resp){
ack(resp);
})
});
/**
* @api {emit} joinEvent E. Join in event chatroom to receive messages
* @apiVersion 0.1.0
* @apiName Socket joinEvent
* @apiGroup Event
*
* @apiDescription This will join user in event chatroom
*
* @apiParam {JsonObject} -JsonObject- data type
* @apiParam {String} JsonObject.eventChat eventChat id
* @apiParam {String} [JsonObject.eventId] event id -- in case eventChat id is not obtained
*/
socket.on('joinEvent', function(data, ack){
if(!data.eventChat){
chatController.getEventChatIdByEventId(data, function(resp){
if(resp.eventChat){
socket.join(resp.eventChat);
}else {
ack(resp);
}
})
}else{
socket.join(data.eventChat);
ack({error: false, message: "success"});
}
});
/**
* @api {emit} leaveEvent F. Leave in event chatroom to stop receiving messages
* @apiVersion 0.1.0
* @apiName Socket leaveEvent
* @apiGroup Event
*
* @apiDescription This will leave user in event chatroom
*
* @apiParam {JsonObject} -JsonObject- data type
* @apiParam {String} JsonObject.eventChat eventChat id
*/
socket.on('leaveEvent', function(data){
socket.leave(data.eventChat);
console.log(socket.id + " leaving event " + data.eventChat);
});
socket.on('offline', function(data){
console.log("offline", data);
chatController.logout({
id: data.id ? data.id : "",
tag: data.tag ? data.tag : "",
socketId: socket.id ? socket.id : ""
})
});
socket.on('reconnect', function (data){
chatController.connect({
id: data.id ? data.id : "",
tag: data.tag ? data.tag : "",
socketId: socket.id ? socket.id : ""
});
});
socket.on('disconnect', function (){
console.log("disconnect", handshake);
chatController.logout({
id: handshake.id ? handshake.id : "",
tag: handshake.tag ? handshake.tag : "",
socketId: socket.id ? socket.id : ""
})
});
});
};
|
var fs = require('fs')
var path = require('path')
var filetype = process.argv[3]
fs.readdir(process.argv[2], 'utf8', function processafter(error, data){
if (error) return console.error(error)
data.forEach(function (item) {
if(path.extname(item) == ('.' + filetype)) {
console.log(item)
}
})
})
|
import React from 'react';
import {CardText, CardSubtitle, CardTitle, CardBody, CardImg, Col, Card} from 'reactstrap'
import './Producto.css';
import FichaProduto from './FichaProducto';
class Producto extends React.Component {
render(){
return(
<Col sm= '4'>
<Card className= 'Card' body outline color= 'primary'>
<CardImg src= {this.props.imagen}/>
<CardBody>
<CardTitle>{this.props.titulo}</CardTitle>
<CardSubtitle><b>Valor:</b>{this.props.precio}</CardSubtitle>
<CardText>{this.props.descripcion}</CardText>
<FichaProduto props= {this.props}/>
</CardBody>
</Card>
</Col>
);
}
};
export default Producto;
|
import React from 'react';
const Footer = props => {
({Icon} = Telescope.components);
return (
<footer className="footer container">
<div className="footer-item">
© {new Date().getFullYear()} <a href="http://aftersync.com/" target="_blank" className="footer-item_link">AfterSync</a>
</div>
<div className="footer-item">
<a href="https://www.facebook.com/TopBINews/" target="_blank" className="footer-item_link"><Icon name="facebook"/></a>
<a href="http://twitter.com/TopBINews" target="_blank" className="footer-item_link"><Icon name="twitter"/></a>
<a href="https://google.com/+TopBiNews" target="_blank" className="footer-item_link"><Icon name="googleplus"/></a>
</div>
</footer>
)
}
module.exports = Footer;
|
import ExpoPixi from 'expo-pixi';
export default async context => {
//http://pixijs.io/examples/#/basics/basic.js
const app = ExpoPixi.application({
context,
});
app.stage.interactive = true;
// create a spine boy
const spineBoy = await ExpoPixi.spineAsync({
json: require('../../assets/pixi/spineboy.json'),
atlas: require('../../assets/pixi/spineboy.atlas'),
assetProvider: {
'spineboy.png': require('../../assets/pixi/spineboy.png'),
},
});
// set the position
spineBoy.x = app.renderer.width / 2;
spineBoy.y = app.renderer.height;
spineBoy.scale.set(1.5);
// set up the mixes!
spineBoy.stateData.setMix('walk', 'jump', 0.2);
spineBoy.stateData.setMix('jump', 'walk', 0.4);
// play animation
spineBoy.state.setAnimation(0, 'walk', true);
app.stage.addChild(spineBoy);
global.document.addEventListener('touchstart', function() {
spineBoy.state.setAnimation(0, 'jump', false);
spineBoy.state.addAnimation(0, 'walk', true, 0);
});
};
|
'use strict';
define(['app'], function (app) {
var scbBranchController = function ($rootScope, $scope, $log, $timeout, $route,$routeParams, _, messageService,
dashboardService, constantService, navigationService, localStorageService,
configurationService,scbBranchService) {
var userInfo, promis;
$scope.saveScbBranch=function(scbBranch){
userInfo = localStorageService.getValue(constantService.userInfoCookieStoreKey);
$scope.scbBranchObj = scbBranch;
$scope.scbBranchObj.loginBean = userInfo;
$scope.scbBranchObj.operation = constantService.Save;
promis = scbBranchService.postObject($scope.scbBranchObj);
promis.then(function(data) {
if (!data.success) {
messageService.showMessage(constantService.Danger,data.message);
return;
}
messageService.showMessage(constantService.Success,data.message);
$scope.scbBranch= {};
});
};
var getScbBranchByID = function() {
userInfo = localStorageService.getValue(constantService.userInfoCookieStoreKey);
var Obj = {
operation : constantService.GetByOId,
loginBean : userInfo
};
Obj.oid = $routeParams.oid;
promis =scbBranchService.postObject(Obj);
debugger;
promis.then(function(data) {
if (!data.success) {
messageService.showMessage(constantService.Danger, 'Unable to load branch');
return;
}
$scope.scbBranch = data.data;
});
};
var init = function () {
if ($routeParams.oid == undefined || $routeParams.oid == null || $routeParams.oid.length == 0) {
return;
}
getScbBranchByID();
};
init();
};
app.register.controller('scbBranchController', ['$rootScope', '$scope', '$log', '$timeout', '$route','$routeParams', '_',
'messageService', 'dashboardService', 'constantService', 'navigationService',
'localStorageService','configurationService','scbBranchService', scbBranchController]);
});
|
const _id=Symbol('id');
const _email=Symbol("email")
const _phone=Symbol("phone")
const _alternativePhone=Symbol("alternative Phone")
const _address=Symbol('address')
class Contact{
constructor(id,email,phone,address){
this[_id]=id || null
this[_alternativePhone]=null
this[_email]=email || null
this[_phone]=phone || null
this[_address]=address || null
}
get contactId(){
return this[_id]
}
get email(){
return this[_email]
}
get phone(){
return this[_phone]
}
get alternativePhone(){
return this[_alternativePhone]
}
get address(){
return this[_address]
}
set email(value){
this[_email]=value;
}
set phone(value){
this[_phone]=phone
}
set alternativePhone(value){
this[_alternativePhone]=phone
}
set address(value){
this[_address]=value;
}
toString(){
return ` ContactId:${this[_id]}
email:${this[_email]}
phone:${this[_phone]}
alternativePhone:${this[_alternativePhone]}
address:${this[_address]}
`.trim()
}
}
module.exports=Contact
|
import React, { Component } from "react";
import "./TaskForm.css";
import {connect} from "react-redux";
import * as actions from "../../actions/index";
class TaskForm extends Component {
constructor(props) {
super(props);
this.state = {
Date: null,
category: "",
title: "",
content: "",
};
}
handleChange = (event)=>{
var target = event.target;
var name = target.name;
var value = target.value;
this.setState({
[name]: value
});
this.props.SaveDatatoStore(this.state)
};
render() {
var { Date, category, title, content } = this.state;
return (
<div className="menu-right-new">
<h1>Add Note</h1>
<form>
<div className="menu-right-main-new">
<b>Add Title Note</b>
<input
type="text"
name="title"
placeholder="Enter a title"
onChange={e => {
this.handleChange(e);
}}
value={title || ""}
></input>
</div>
<div className="menu-right-main-new">
<b>Add Date Note</b>
<input
type="date"
name="Date"
onChange={e => {
this.handleChange(e);
}}
value={Date || ""}
></input>
</div>
<div className="menu-right-main-new">
<b>Add Category Note</b>
<input
type="text"
name="category"
placeholder="Enter the category"
onChange={e => {
this.handleChange(e);
}}
value={category || ""}
></input>
</div>
<div className="menu-right-main-new">
<b>Add Content Note</b>
<textarea
type="text"
name="content"
onChange={e => {
this.handleChange(e);
}}
value={content || ""}
></textarea>
</div>
</form>
</div>
);
}
}
const mapStateToProps = state => {
return {
};
};
const mapDispatchToProps = (dispatch, props) => {
return {
SaveDatatoStore: dataAdd => {
dispatch(actions.actSaveDatatoStore(dataAdd));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TaskForm);
|
import questions from './_questions.json'
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
export default class {
list;
stopped;
lastQuestionId;
constructor() {
const questionsList = questions.slice();
shuffle(questionsList);
this.list = questionsList;
this.lastQuestionId = -1;
this.stopped = false;
}
stop() {
this.stopped = true;
}
getNextQuestion() {
// TODO: implement it
if (this.stopped || this.lastQuestionId >= this.list.length) {
return null;
}
return this.list[++this.lastQuestionId];
}
};
|
//
//var app = document.getElementById("app");
////ReactDOM.render(React.createElement(TextAreaCounter, {
//// defaultValue: "Hello World!"
////}), app);
//ReactDOM.render(
// <div>
// <TextAreaCounter defaultValue="Hello World!"/>
// </div>,
// app);
|
import React, { useState } from 'react'
import './KillersPresenter.css'
import { List } from '../List/List'
import { Pagination } from '@material-ui/lab'
import { Title } from '../Titles/Title/Title'
import { OrderSwitch } from '../Switch/OrderSwitch'
import { ThemeContext } from '../../contexts/theme-context'
export const ListKillers = (props) => {
const { killersOrdered, handleOrder, dark } = props
const [orderChecked, setOrderChecked] = useState(false)
const [currentPage, setCurrentPage] = useState(1)
const [charactersPerPage] = useState(4)
const indexOfLastcharacter = currentPage * charactersPerPage
const indexOfFirstcharacter = indexOfLastcharacter - charactersPerPage
const currentPosts = killersOrdered.slice(
indexOfFirstcharacter,
indexOfLastcharacter
)
const indexPages = parseInt(killersOrdered.length / charactersPerPage) + 1
const onChangePage = (e, newPage) => {
setCurrentPage(newPage)
}
const switchOrder = () => {
setOrderChecked(!orderChecked)
handleOrder(orderChecked ? 'desc' : 'asc')
}
return (
<>
{currentPosts &&
currentPage &&
indexPages &&
killersOrdered.length !== 0 && (
<>
<div className="pagination">
<Pagination
className={dark ? 'dark' : 'root'}
page={currentPage}
count={indexPages}
onChange={onChangePage}
/>
<OrderSwitch
{...props}
checked={orderChecked}
handleSwitch={() => switchOrder()}
/>
</div>
{currentPosts.map((killersOrdered) => {
return (
<List
name={`${killersOrdered.name}`}
description={`(${killersOrdered.count})`}
key={killersOrdered.name}
id={killersOrdered.name}
type="/killer/"
isList={true}
></List>
)
})}
</>
)}
</>
)
}
export const KillersPresenter = (props) => {
const { dark, theme } = React.useContext(ThemeContext)
return (
<>
<Title theme={theme} title="Killers"></Title>
<ListKillers {...props} theme={theme} dark={dark} />
</>
)
}
|
$(document).ready(function() {
// Esconde a div qual deve ser mostrada apenas quando os dados do formulário são trazidos do back-end
$('#botoesFormularioCarregado').hide();
// Esconde os botões de pesquisar, quais devem aparecer apenas ao selecionar o campo pertinente
$('.input-group-append').hide();
// Validação de campos destinados apenas a valores numéricos
$('.numerico').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
// Pesquisar por alternativa para a solução abaixo
// Mostra e Esconde os botões de pesquisar
$('#cpf').focus(function() {
$('#buscarPorCpf').show(200);
});
$('#cpf').focusout(function() {
$('#buscarPorCpf').hide(400);
});
$('#id').focus(function() {
$('#buscarPorId').show(200);
});
$('#id').focusout(function() {
$('#buscarPorId').hide(400);
});
$('#nome').focus(function() {
$('#buscarPorNome').show(200);
});
$('#nome').focusout(function() {
$('#buscarPorNome').hide(400);
});
});
function incluirCliente() {
if (validarCamposNecessarios()) {
$.ajax({
url: '../api/clientes',
type: 'POST',
data: JSON.stringify(coletarDadosFormulario()),
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function () {
console.log("cliente cadastrado com sucesso")
},
error: function() {
console.log("erro ao cadastrar cliente");
}
});
}
}
function buscarPorId(){
var dados = {
id: $('#id').val()
}
$.ajax({
url: '../api/clientes/',
type: 'GET',
data: dados,
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function(dados) {
atualizarCampos(dados);
console.log("contato trazido com sucesso");
},
error: function(){
console.log("erro ao buscar id");
}
});
}
function buscarPorCpf() {
var dados = {
cpf: $('#cpf').val()
}
$.ajax({
url: '../api/clientes/',
type: 'GET',
data: dados,
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function(dados) {
atualizarCampos(dados);
console.log("contato trazido com sucesso");
},
error: function(){
console.log("erro ao buscar cpf");
}
});
}
function buscarPorNome(callback) {
var dados = {
nome: $('#nome').val()
}
$.ajax({
url: '../api/clientes/',
type: 'GET',
data: dados,
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function(dados) {
console.log("contatos trazidos com sucesso");
callback(dados);
},
error: function(){
console.log("erro ao buscar clientes");
}
});
}
function excluirCliente() {
$.ajax({
url: '../api/clientes',
type: 'DELETE',
data: JSON.stringify(coletarDadosFormulario()),
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function () {
console.log("excluído com sucesso");
},
error: function () {
console.log("erro ao excluir cliente");
}
})
}
function modificarCliente() {
if (validarCamposNecessarios()) {
$.ajax({
url: '../api/clientes',
type: 'PATCH',
data: JSON.stringify(coletarDadosFormulario()),
contentType: 'application/json; charset="utf-8"',
dataType: 'json',
success: function () {
console.log("alterado com sucesso");
},
error: function () {
console.log("erro ao alterar cliente");
}
});
}
}
function validarCamposNecessarios() {
if (($('#cpf').val().length == 11) || $('#cpf').val().length == 14) {
if (($('#nome').val().length > 5)) {
return true;
} else {
$('#nome').focus();
$('#nome').select();
}
} else {
$('#cpf').focus();
$('#cpf').select();
return false;
};
}
function exibirModalBuscaPorNome() {
$('#modal').load("clientes/modalBuscarCliente", function() {
$('#modal').modal();
});
}
function limparFormulario() {
$('#id').val("");
$('#cpf').val("");
$('#nome').val("");
$('#apelido').val("");
$('#telefoneprincipal').val("");
$('#telefonesecundario').val("");
$('#email').val("");
$('#cep').val("");
$('#cidade').val("");
$('#uf').val("");
$('#endereco').val("");
$('#complemento').val("");
$('#bairro').val("");
mostrarBotoesFormularioLimpo();
}
function coletarDadosFormulario() {
var dados = {
cpf: $('#cpf').val(),
id: $('#id').val(),
nome: $('#nome').val(),
apelido: $('#apelido').val(),
telefonePrincipal: $('#telefoneprincipal').val(),
telefoneSecundario: $('#telefonesecundario').val(),
email: $('#email').val(),
cep: $('#cep').val(),
cidade: $('#cidade').val(),
uf: $('#uf').val(),
endereco: $('#endereco').val(),
complemento: $('#complemento').val(),
bairro: $('#bairro').val()
};
return dados;
}
function atualizarCampos(dados) {
$('#id').val(dados.id);
$('#cpf').val(dados.cpf);
$('#nome').val(dados.nome);
$('#apelido').val(dados.apelido);
$('#telefoneprincipal').val(dados.telefonePrincipal);
$('#telefonesecundario').val(dados.telefoneSecundario);
$('#email').val(dados.email);
$('#cep').val(dados.cep);
$('#cidade').val(dados.cidade);
$('#uf').val(dados.uf);
$('#endereco').val(dados.endereco);
$('#complemento').val(dados.complemento);
$('#bairro').val(dados.bairro);
mostrarBotoesFormularioCarregado();
}
function mostrarBotoesFormularioLimpo() {
$('#botoesFormularioLimpo').show();
$('#botoesFormularioCarregado').hide();
}
function mostrarBotoesFormularioCarregado() {
$('#botoesFormularioLimpo').hide();
$('#botoesFormularioCarregado').show();
}
|
;var getRequire = (function(){
return function getRequire(a){
return function atomRequire(m){
return require(deps[a][m])
}
}
})();
(function start (entryAtomName, ATOMS) {
console.log("Starting with", entryAtomName, ATOMS);
Object.keys(ATOMS).map(function (i) {
if (ATOMS[i].value) ATOMS[i].value = require('observ')(ATOMS[i].value);
})
// TODO more intelligently figure out the current script
// document.currentScript used to work, why is it returning null now
var container = document.getElementsByTagName("script")[0].parentElement;
container._etude = {};
container._etude.atom = function(key) { return ATOMS[key] }
container._etude.tree = null;
var installAtom = require('tree').installAtom.bind(null, ATOMS, evaluateAtom);
function getTreeHere (atom) {
if (container._etude.tree) return container._etude.tree;
var tree = {};
Object.keys(ATOMS).map(installAtom.bind(null, tree));
container._etude.tree = tree;
console.log(tree);
return tree;
}
evaluateAtom(ATOMS[entryAtomName]);
connectSocket();
function evaluateAtom (atom) {
var val = require('vm').runInNewContext(
atom.compiled, makeContext(atom.name));
if (atom.value) {
atom.value.set(val)
} else {
atom.value = require('observ')(val);
updateDeps(atom);
}
return val;
}
function updateDeps (atom) {}
function makeContext (atomName) {
var name = translate(atomName)
, atom = ATOMS[name];
var context =
{ _: getTreeHere(atom)
, watch: watchAtomValue
, assoc: require('wisp/sequence.js').assoc
, console: console // TODO remove
, container: container
, conj: require('wisp/sequence.js').conj
, isEqual: require('wisp/runtime.js').isEqual
, log: function () { console.log.apply(console, arguments) }
, require: getRequire(atomName)
, setTimeout: setTimeout
, clearTimeout: clearTimeout
, WebSocket: WebSocket
, XMLHttpRequest: XMLHttpRequest };
return context;
};
function watchAtomValue (key, cb) { // TODO with macro
ATOMS[key].value(cb);
}
function translate (word) {
// TODO import whole wisp
return word.replace(/(-[a-zA-Z])/g,
function (x) { return x[1].toUpperCase() })
}
function connectSocket () {
var socket = new WebSocket('ws://' + window.location.host + '/socket');
socket.onmessage = function (evt) {
var data =
JSON.parse(evt.data)
, atom =
(data.arg && data.arg.name)
? ATOMS[translate(data.arg.name)]
: null;
if (data.event === "atom.updated.source") {
atom.source = data.arg.source;
}
else if (data.event === "atom.updated.compiled") {
atom.compiled = data.arg.compiled;
if (atom.value) {
evaluateAtom(atom);
}
}
else console.log(data);
}
return socket;
}
})("%ENTRY%", %NOTIONS%);
|
// console.log('fred')
const input1 = document.querySelector('#input1')
const input2 = document.querySelector('#input2')
function setCard(){
const card = document.getElementById(input1.value)
console.log(card)
card.style.color = input2.value
}
|
import { getNotificationFromDB } from '../../../database/dal/firebase/chatNotificationDal';
export const getNotification = () => {
return (dispatch) => {
getNotificationFromDB(dispatch);
}
}
|
function Header() {
return (
<nav className="p-2 border-b-2">
<div>
<h2 className="text-lg">Felix Shop</h2>
</div>
</nav>
)
}
export default Header
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
/**
* The Breadcrumb component.
*
* @version 1.0.0
* @author [Himanshu Dixit]
*/
class Breadcrumb extends Component {
render() {
// Using tailwing font family, font weight, font size and color.
let tailwindcss = `
text-primary
text-sm
no-underline
hover:underline
`;
// If additional tailwind classes are passed, add to styles.
if (this.props.additionalTailwindClasses) {
tailwindcss += ' ' + this.props.additionalTailwindClasses;
}
const length = this.props.data.length;
return this.props.data.map((data, i)=>{
if (length === i + 1) {
return <span className="text-xs"><a href={data.link} target={this.props.target} className={tailwindcss}
style={this.props.additionalStyle}
onClick={this.props.click}>{data.text}</a></span>;
} else {
return <span className={tailwindcss+" text-xs"}>
<a href={data.link} target={this.props.target} className={tailwindcss}
style={this.props.additionalStyle}
onClick={this.props.click}>{data.text} </a> > {" "}
</span>;
}
});
}
}
Breadcrumb.defaultProps = {
target: '_self',
};
Breadcrumb.propTypes = {
target: PropTypes.oneOf(['_blank', '_self']),
/**
* URI of the page.
*/
data: PropTypes.any,
/**
* Additional styling you want to pass to heading, not recommend.
*/
additionalTailwindClasses: PropTypes.string,
/**
* Additional styling you want to pass to heading, not recommend.
*/
additionalStyle: PropTypes.string,
/**
* Gets called when the user clicks on the button
*/
click: PropTypes.func,
};
export default Breadcrumb;
|
import {
combineReducers
} from 'redux'
import home from './home'
export default combineReducers({
home
})
|
import { Container } from "./styles";
function Button({ name, ...rest }) {
return (
<Container background={"var(--cor-destaque)"} type="submit" {...rest}>
{name}
</Container>
);
}
export default Button;
|
ig.module(
'game.entities.player'
)
.requires(
'plusplus.abstractities.player',
'game.entities.abilities.fireball-caster',
'game.entities.abilities.axe',
'game.entities.inventory',
'game.common.weapon-manager'
)
.defines(function () {
EntityPlayer = ig.Player.extend({
size: {
x: 16,
y: 20
},
offset: {
x: 17,
y: 22
},
collides: ig.Entity.COLLIDES.ACTIVE,
type: ig.Entity.TYPE.A,
animSheet: new ig.AnimationSheet(ig.CONFIG.PATH_TO_CHARACTERS + 'player_v1.png', 50, 50),
animFrameTime: 0.1,
animInit: 'idleDown',
animSettings: {
idleDown: {
sequence: [0],
frameTime: 1
},
idleUp: {
sequence: [7],
frameTime: 1
},
idleRight: {
sequence: [14],
frameTime: 1
},
idleLeft: {
sequence: [21],
frameTime: 1
},
moveDown: {
sequence: [0, 1, 0, 2]
},
moveUp: {
sequence: [7, 8, 7, 9]
},
moveRight: {
sequence: [14, 15, 14, 16]
},
moveLeft: {
sequence: [21, 22, 21, 23]
},
meleeDown: {
sequence: [3]
},
meleeUp: {
sequence: [4]
},
meleeRight: {
sequence: [5]
},
meleeLeft: {
sequence: [6]
},
shootDown: {
sequence: [10]
},
shootUp: {
sequence: [11]
},
shootRight: {
sequence: [12]
},
shootLeft: {
sequence: [13]
}
},
// The possible states this entity can be in
states: {
DEFAULT: 1,
IN_INVENTORY: 2
},
// The current state for this entity
state: null,
maxVelGrounded: {
x: 250,
y: 250
},
speed: {
x: 10000,
y: 10000
},
// Whether the entity is allowed to move
movementAllowed: true,
// Store the inventory entity for the player
inventory: null,
// Health and MAGIC!!!
health: 50,
energy: 50,
energyMax: 50,
regenHealth: false,
regen: true,
regenRateEnergy: 1,
regenDelay: 0.8,
persistent: true,
activeWeapon: null,
activeWeaponIndex: 0,
weapons: [
'axe',
'fireball'
],
initProperties: function () {
this.parent();
// Set the entity's default state
this.state = this.states.DEFAULT;
// Spawn the inventory at 0, 0 and store it, but only if we're not in Weltmeister
if (!ig.global.wm) {
this.inventory = ig.game.spawnEntity(EntityInventory);
// Set inventory position to the center of the screen
this.inventory.pos.x = (ig.system.width - this.inventory.size.x) / 2;
this.inventory.pos.y = (ig.system.height - this.inventory.size.y) / 2;
}
// Store the player entity globally for performance and ease of reference
ig.global.player = this;
// Shoot fireballs and swing axes like a pro
this.axe = new ig.EntityAxe(this);
this.fireball = new ig.FireballCaster(this);
this.activeWeapon = this[this.weapons[this.activeWeaponIndex]];
this.abilities.addDescendants([this.fireball, this.axe]);
},
spawn: function () {
this.parent();
// Face right
this.facing = {x: 1, y: 0};
},
updateChanges: function () {
this.parent();
// Check for button presses and activate the appropriate animation
this.handleButtons();
},
draw: function () {
if (!ig.global.wm) {
// Set the inventory's visibility based on whether we're in Weltmeister and the
// player is trying to access the inventory
this.inventory.isVisible = this.state == this.states.IN_INVENTORY;
}
this.parent();
},
handleButtons: function () {
// Don't move the player if he's not allowed to (e.g. we're in a menu)
if (!this.movementAllowed) {
return;
}
if (ig.input.pressed('switchWeapon')) {
this.activeWeaponIndex++;
if (!this.weapons[this.activeWeaponIndex]) {
this.activeWeaponIndex = !this.weapons[this.activeWeaponIndex] ? 0 : this.activeWeaponIndex;
}
this.activeWeapon = this[this.weapons[this.activeWeaponIndex]];
}
if (ig.input.pressed('attack')) {
var shootX, shootY;
if (this.facing.x !== 0) {
if (this.facing.x > 0) {
shootX = this.pos.x + this.size.x;
} else {
shootX = this.pos.x;
}
} else {
shootX = this.pos.x + this.size.x * 0.5;
}
if (this.facing.y !== 0) {
if (this.facing.y > 0) {
shootY = this.pos.y + this.size.y;
} else {
shootY = this.pos.y;
}
} else {
shootY = this.pos.y + this.size.y * 0.5;
}
this.activeWeapon.execute({x: shootX, y: shootY});
}
/** Inventory/Menu Navigation **/
if (ig.input.pressed('inventory')) {
// If we're already in the inventory menu, close the menu
if (this.state == this.states.IN_INVENTORY) {
this.movementAllowed = true;
this.state = this.states.DEFAULT;
}
// Otherwise, bring up the inventory menu
else {
this.movementAllowed = false;
this.state = this.states.IN_INVENTORY;
}
// If trying to access inventory, use the keys to navigate the menu
//if @state == @states.IN_INVENTORY
// Check for keypresses to navigate
}
}
});
});
|
import axios from "axios";
import { getTeachersFromDBBasedOnCategory } from '../../../database/dal/firebase/studentDal';
export const getTeachersBasedOnCateogy = (selectedSubject) => {
return (dispatch) => {
getTeachersFromDBBasedOnCategory(dispatch,selectedSubject);
}
}
export const zipRequestDispatch = (zipcode) => {
return (dispatch) => {
axios({
// url: 'https://www.zipcodeapi.com/rest/smSkfHWKkUriOnIvrOfvpwrXKktOzw0r7Zrt3rOGZwTLUmMMyJjdux1FZhpcc3iA/radius.json/' + zipcode + '/5/km',
// url: 'http://localhost:8282/curl/?zipcode='+zipcode,
url: 'http://mplegalfirm.com/curl/?zipcode='+zipcode,
}).then((res) => {
dispatch({type:'SET', res: res.data})
}).catch(err => {
console.error(err)
})
}
}
|
/* Client-side JS logic goes here
* jQuery is already loaded */
// function to parse the date into amount of time passed
function parseHumanDate(timeCreated) {
var created = new Date(timeCreated);
var seconds = Math.floor((Date.now() - created) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
if(interval < 2) {
return interval + ' year ago';
} else {
return interval + ' years ago';
}
}
interval = Math.floor(seconds / 2592000);
if (interval >= 1) {
if(interval < 2) {
return interval + ' month ago';
} else {
return interval + ' months ago';
}
}
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
if(interval < 2) {
return interval + ' hour ago';
} else {
return interval + ' hours ago';
}
}
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
if(interval < 2) {
return interval + ' hour ago';
} else {
return interval + ' hours ago';
}
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
if(interval < 2) {
return interval + ' minute ago';
} else {
return interval + ' minutes ago';
}
}
return Math.floor(seconds) + ' seconds ago';
}
$(document).ready(function() {
//function to create the HTML container in which tweets will be rendered
const createTweetElement = function (tweet) {
const $tweet = $("<article>").addClass("tweet");
const $header = $("<header>");
$header.append($("<img>").attr("src",tweet.user.avatars.small));
$header.append($("<h2>").text(tweet.user.name));
$header.append($("<p>").addClass("twitter-handle").text(tweet.user.handle));
$tweet.append($header);
$tweet.append($("<p>").text(tweet.content.text));
const $footer = $("<footer>");
$footer.append($("<p>").text(parseHumanDate(tweet.created_at)));
const $div = $("<div>").attr('id', "hover-content");
$div.append($("<i class='fa fa-flag' aria-hidden='true'></i>"));
$div.append($("<i class='fa fa-retweet' aria-hidden='true'></i>"));
$div.append($("<i class='fa fa-heart' aria-hidden='true'></i>"));
$footer.append($div);
$tweet.append($footer);
return $tweet;
};
// function to render the tweets into the above container created
const renderTweets = function(tweets) {
const $tweetsContainer = $("#all-tweets");
for (var tweet of tweets) {
createTweetElement(tweet).prependTo($tweetsContainer);
}
return $tweetsContainer;
}
// function to update the tweets when a new one is posted (need to empty
// container and add them again with the new one)
const updateTweets = function(tweets) {
const $tweetsContainer = $("#all-tweets");
$tweetsContainer.empty();
for (var tweet of tweets) {
createTweetElement(tweet).prependTo($tweetsContainer);
}
return $tweetsContainer;
}
//function to load the tweets to the page using ajax request
function loadTweets() {
$.ajax({
url: '/tweets/',
method: 'GET',
success: renderTweets
});
}
loadTweets();
//function to submit new tweets, checking for empty string and character count
$(".new-tweet form").submit(function(event) {
event.preventDefault();
if(!$('textarea').val() || $('textarea').val().trim() == "") {
alert("I'm sure you can think of something to say!");
return;
}
if($(".counter").text() < 0) {
alert("Woah, keep it shorter than 140 characters!");
return;
}
$.post("/tweets", $(this).serialize(), function() {
$.get("/tweets", updateTweets);
});
$("form").trigger("reset");
$(".counter").text(140);
});
//function to slide toggle the tweet box upon clicking compose button
//then focus on text box when tweet box
$(".compose-button").click(function(){
$(".new-tweet").slideToggle(function () {
$(".new-tweet").find("textarea").focus();
});
return false;
});
});
|
import React, { useState, useContext } from "react";
import { NotesContext } from "../context/NotesContext";
import Note from "./Note";
import "./styles/NoteCard.css";
import { AiOutlinePlus, AiFillCloseCircle, AiFillDelete } from "react-icons/ai";
import axios from "../utils/axios";
export default function NoteCard(props) {
const { state, dispatch, getAllNotes } = useContext(NotesContext);
const [noteCard, setNoteCard] = useState("");
const [toggleForm, setToggleForm] = useState(false);
const deleteEntireNote = async () => {
try {
await axios.delete(`/api/notes/${props.note._id}`);
getAllNotes();
} catch (err) {
console.log("Err");
}
};
const addNoteCard = async (ev) => {
try {
ev.preventDefault();
const topic = await axios.post(`/api/notes/${props.note._id}`, {
note: noteCard,
});
dispatch({ type: "ADD_NOTE_CARD", payload: topic.data });
setNoteCard("");
} catch (err) {
console.log("Err");
}
};
const renderForm = () => {
return (
<div>
<form className="toggleForm" onSubmit={addNoteCard}>
<textarea
value={noteCard}
rows={3}
onChange={(ev) => setNoteCard(ev.target.value)}
placeholder="Add a new topic...."
></textarea>
<div className="toggleControls">
<div>
<button type="submit" class="btn bluebtn">
Add Notes
</button>
</div>
<div onClick={() => setToggleForm(false)} className="toggleIcon">
<AiFillCloseCircle
className="icon"
style={{ color: "#026aa7" }}
/>
</div>
</div>
</form>
</div>
);
};
return (
<div className="noteCard">
<div className="note_title">
<div>
<h3>{props?.note.title}</h3>
</div>
<div
style={{ fontSize: 18, cursor: "pointer" }}
onClick={deleteEntireNote}
>
<AiFillDelete />
</div>
</div>
<div className="note_cards">
{props.note.noteCards?.map((noteCard) => {
return (
<Note
eachNote={noteCard}
key={noteCard._id}
noteId={props.note._id}
/>
);
})}
</div>
{toggleForm ? (
renderForm()
) : (
<div class="note_add" onClick={() => setToggleForm(true)}>
<AiOutlinePlus />
Add new Note
</div>
)}
</div>
);
}
|
// https://docs.google.com/presentation/d/1gxpZ07j0m7cxJARJpKocu-bVQx5vPO9fWmU62_wcbfM/edit#slide=id.g1fdeb5d75d_0_8
// Important concepts
//
// - Let and Const
let person = "Mark"
// constructor function is new to JS - classes are just syntactic sugar for
// functions put on prototypes
// all the components you create are inheriting from React.Component
//arrow functions
function multiply(a,b) {
return a * b;
}
let multiply2 = (a,b) => a * b; //implicit return
let multiply3 = (a,b) => {
return a * b;
}
// object.assign and destructuring
// object.assign merges objects from right to left
Object.assign({},
{firstName: "Tim", lastName: "Schoppik"},
{lastName: "Garcia"});
// firstName: "Tim", lastName: "Garcia"}
names = Object.assign({},
{firstName: "Tim", lastName: "Schoppik"},
{lastName: "Garcia"});
var newObj = {
...names,
favoriteFood: 'pizza'
}
// {firstName: "Tim", lastName: "Garcia", favoriteFood: "pizza"}
var {firstName, lastName} = newObj
firstName // "Tim"
lastName // "Garcia"
let upperCaseFirstLetter = word => `${word[0].toUpperCase()}${word.slice(1)}`;
// let upperCaseWords = sentence => {
// var words = sentence.split(" ");
// for(let i = 0; i < words.length; i++){
// words[i] = upperCaseFirstLetter(words[i])
// }
// return words
var upperCaseWords = s => s.split(" ").map(upperCaseFirstLetter).join(" ");
console.log(upperCaseWords("code example to refactor"));
// Code Example To Refactor
// Functional Programming - pure functions
var myObj = {id: 53};
function addName(obj, name){
return Object.assign({}, obj, {name}) //{name: name}
}
var res = addName(myObj, "Tim")
//
|
import React, { Component } from "react";
import TableRow from "@material-ui/core/TableRow";
import TableCell from "@material-ui/core/TableCell";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import Button from "@material-ui/core/Button";
import API from "../utils/API";
import DashboardTable from "../components/DashboardTable";
import SingleRecipe from "../components/SingleRecipe";
import Title from "../components/Title";
import Navbar from "../components/Navbar/index";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Switch from "@material-ui/core/Switch";
import Firebase from "../config/Firebase";
import Swal from "sweetalert2";
let styles = function() {
if (window.innerWidth < 768) {
return midStyles;
} else {
return maxStyles;
}
};
let midStyles = {
crossout: {
textDecoration: "line-through",
display: "inline"
},
none: {
display: "inline"
},
smallCardsWr: {
width: "100%",
display: "flex"
},
cardList: {
width: "93%",
margin: "30px 30px",
overflow: "scroll",
height: "400px",
display: "flex",
flexDirection: "column-reverse"
},
card: {
width: "50%",
margin: "30px 30px",
padding: "20px",
color: "grey",
fontSize: "20px"
},
SubmitForm: {
width: "82%",
margin: "30px 30px",
display: "flex",
flexFlow: "column",
padding: "30px"
},
wrapper: {
display: "flex",
flexFlow: "column",
width: "100%",
alignItems: "center",
fontFamily: "Dosis"
},
i: {
fontSize: "30px",
marginRight: "5px",
color: "rgb(62, 65, 64)"
},
header: {
textAlign: "center",
color: "rgb(62, 65, 64)",
fontFamily: "Dosis"
},
leftAlignFix: {
textAlign: "left",
color: "rgb(62, 65, 64)",
fontFamily: "Dosis"
},
textWr: {
width: "90%",
color: "grey",
textAlign: "center",
borderBottom: "1px solid #8080801f",
padding: "20px"
},
textWrFix: {
width: "90%",
color: "grey",
textAlign: "left!important",
borderBottom: "1px solid #8080801f",
padding: "20px"
},
list: {
display: "flex"
}
};
let maxStyles = {
crossout: {
textDecoration: "line-through",
display: "inline"
},
none: {
display: "inline"
},
textfield: {
margin: "5px 10px 20px 0"
},
SubmitForm: {
display: "flex",
flexFlow: "column",
width: "20%",
padding: "20px",
margin: "30px 30px",
alignItems: "center"
},
header: {
textAlign: "center",
color: "rgb(62, 65, 64)",
fontFamily: "Dosis"
},
card: {
minWidth: "10%",
height: "164px",
margin: "30px 30px",
padding: "20px",
textAlign: "center",
color: "grey",
fontSize: "20px"
},
cardList: {
height: "400px",
width: "60%",
minWidth: "300px",
margin: "30px 30px",
padding: "20px",
overflow: "scroll",
display: "flex"
},
wrapper: {
display: "flex",
width: "100%",
fontFamily: "Dosis",
maxWidth: "1360px"
},
smallCardsWr: {
width: "30%"
},
i: {
fontSize: "30px",
marginRight: "5px",
color: "rgb(62, 65, 64)"
},
textWrFix: {
width: "30%",
color: "grey",
marginLeft: "80px",
textAlign: "left",
borderLeft: "1px solid #8080801f",
paddingLeft: "20px"
},
list: {
width: "350px",
display: "flex"
}
};
class Dashboard extends Component {
state = {
favorites: [],
monday: {},
tuesday: {},
wednesday: {},
thursday: {},
friday: {},
saturday: {},
sunday: {},
time: 0,
meals: 0,
ingredients: {},
clicked: "",
currentUser: "",
phone: "",
email: "",
notes: "",
type: true,
scrollTo: false,
db: false
};
constructor(props) {
super(props);
this.mealRef = React.createRef();
}
componentDidUpdate() {
if (this.state.scrollTo) {
window.scrollTo({
left: 0,
top: this.mealRef.current.offsetTop,
behavior: "smooth"
});
this.setState({ scrollTo: false });
}
}
componentDidMount() {
Firebase.auth().onAuthStateChanged(user => {
if (user && !Firebase.auth().currentUser.isAnonymous) {
this.setState({
currentUser: user.email
});
this.getAll(user.email);
}
});
window.onresize = function() {
this.forceUpdate();
}.bind(this);
}
getTime(data) {
let time = 0;
for (let day in data) {
for (let meal in data[day]) {
if (data[day][meal].time) {
time += parseInt(data[day][meal].time);
}
}
}
let hours = Math.floor(time / 60);
let minutes = time % 60;
let total = hours + " hr " + minutes + " min";
return total;
}
getMeals(data) {
let count = 0;
for (let day in data) {
for (let meal in data[day]) {
if (data[day][meal].label) {
count++;
}
}
}
return count;
}
getIngredients(data) {
let obj = {};
for (let day in data) {
for (let meal in data[day]) {
data[day][meal].ingredients.forEach(item => {
if (item in obj) {
item += " (x2)";
}
obj[item] = false;
});
}
}
return obj;
}
getAll(user) {
API.getDBRecipes(user)
.then(res => {
this.setState({
favorites: res.data.favorites,
monday: res.data.weeklymenu.monday,
tuesday: res.data.weeklymenu.tuesday,
wednesday: res.data.weeklymenu.wednesday,
thursday: res.data.weeklymenu.thursday,
friday: res.data.weeklymenu.friday,
saturday: res.data.weeklymenu.saturday,
sunday: res.data.weeklymenu.sunday,
time: this.getTime(res.data.weeklymenu),
meals: this.getMeals(res.data.weeklymenu),
ingredients: this.getIngredients(res.data.weeklymenu),
db: true
});
})
.catch(err => console.log(err));
}
clicked(meal) {
this.setState({
clicked: meal,
scrollTo: true
});
}
ingredientChecked(item) {
let ingredientProperty = { ...this.state.ingredients };
if (ingredientProperty[item]) {
ingredientProperty[item] = false;
} else {
ingredientProperty[item] = true;
}
this.setState({ ingredients: ingredientProperty });
}
handleInputChange = event => {
const name = event.target.name;
const value = event.target.value;
var reg = new RegExp("^[0-9]+$");
if (name === "phone" && value.match(reg) && value.length < 11) {
this.setState({
[name]: value
});
}
if (name === "notes") {
this.setState({
[name]: value
});
}
if (name === "email") {
this.setState({
[name]: value
});
}
};
handleFormSubmit = event => {
event.preventDefault();
var emailReg = /^(([^<>()\[\]\\.,;:\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,}))$/;
let listArr = Object.keys(this.state.ingredients)
.sort()
.filter(item => {
if (!this.state.ingredients[item]) {
return item;
}
});
let text =
"This is your shopping list: \n- " +
listArr.join("\n- ") +
"\n" +
"Additional notes:\n" +
this.state.notes;
if (this.state.type) {
if (this.state.phone.length !== 10) {
Swal.fire({
type: "error",
title: "Oops...",
text: "Check your phone number"
});
} else {
API.sendSMS(this.state.phone, text).then(res => {
if (res.data) {
Swal.fire({
type: "success",
title: "Your message has been sent!"
});
}
});
}
} else {
if (emailReg.test(this.state.email)) {
API.sendEmail(this.state.email, text).then(res => {
if (res.data) {
Swal.fire({
type: "success",
title: "Your email message has been sent!"
});
}
});
} else {
Swal.fire({
type: "error",
title: "Oops...",
text: "Check your email"
});
}
}
};
handleSwitch = event => {
this.setState({ type: event.target.checked });
};
render() {
return (
<>
<Navbar />
<Title title="Recipedia Dashboard"> Recipedia Dashboard</Title>
{/* <h1 style={styles().header}>Recipedia Dashboard</h1> */}
{this.state.db ? (
<DashboardTable
monday={this.state.monday}
tuesday={this.state.tuesday}
wednesday={this.state.wednesday}
thursday={this.state.thursday}
friday={this.state.friday}
saturday={this.state.saturday}
sunday={this.state.sunday}
clickedMeal={this.clicked.bind(this)}
currentUser={this.state.currentUser}
mealRemoved={() => this.getAll(this.state.currentUser)}
/>
) : (
""
)}
<div style={styles().wrapper}>
<div style={styles().smallCardsWr}>
<Paper style={styles().card}>
<h5>
Total Meal Prep Time:
<p>
<span>
<i style={styles().i} class="fas fa-clock" />
</span>
{this.state.time ? this.state.time : "0 hr 0 min"}
</p>
</h5>
</Paper>
<Paper style={styles().card}>
<h5>
Total Weekly Meals
<p>
<span>
<i style={styles().i} class="fas fa-hamburger" />
</span>
{this.state.meals ? this.state.meals : "0"}
</p>
</h5>
</Paper>
</div>
<Paper style={styles().cardList}>
<ul>
{Object.keys(this.state.ingredients)
.sort()
.map(item => {
return (
<TableRow>
<TableCell style={styles().list} padding="checkbox">
<Checkbox
key={item}
checked={this.state.ingredients[item]}
onChange={() => this.ingredientChecked(item)}
/>
<p
style={
this.state.ingredients[item]
? styles().crossout
: styles().none
}
>
{item}
</p>
</TableCell>
</TableRow>
);
})}
</ul>
<div style={styles().textWrFix}>
<h4 style={styles().leftAlignFix}>Total Ingredient List</h4>
<p>
Here you can customize your shopping list, check items that you
have in your pantry
</p>
</div>
</Paper>
<Paper style={styles().SubmitForm}>
<h4 style={styles().header}>
Share your shopping list with others via phone or email
</h4>
<FormControlLabel
control={
<Switch
checked={this.state.type}
onChange={this.handleSwitch}
value="type"
/>
}
label={this.state.type ? "Phone" : "Email"}
/>
{this.state.type ? (
<TextField
style={styles().textfield}
id="outlined-uncontrolled"
label="Phone"
placeholder="(000)-000-00-00"
margin="normal"
variant="outlined"
name="phone"
value={this.state.phone}
onChange={this.handleInputChange}
/>
) : (
<TextField
style={styles().textfield}
id="outlined-uncontrolled"
label="Email"
placeholder="example@example.com"
margin="normal"
variant="outlined"
name="email"
value={this.state.email}
onChange={this.handleInputChange}
/>
)}
<TextField
style={styles().textfield}
id="outlined-multiline-flexible"
label="Notes"
multiline
rowsMax="4"
value={this.state.notes}
name="notes"
onChange={this.handleInputChange}
margin="normal"
variant="outlined"
/>
<Button variant="outlined" onClick={this.handleFormSubmit}>
Send my list
</Button>
</Paper>
</div>
<div ref={this.mealRef} />
{this.state.clicked ? <SingleRecipe meal={this.state.clicked} /> : ""}
</>
);
}
}
export default Dashboard;
|
import React from 'react';
import { Header, Footer, SearchBox } from './../../components';
import styles from './Layout.scss';
import utils from './../../stylesheets/utils/flexbox.scss';
export default function Layout({ routes, onChange }) {
return (
<div className={utils.flexboxSticky}>
<Header />
<main className={utils.flex1}>
<div className={styles.wrapper}>
<div className={styles.searchBoxContainer}>
<SearchBox
classesInput={styles.searchBox}
placeholder="Search Users"
onChange={onChange}
/>
</div>
</div>
{routes}
</main>
<Footer />
</div>
);
}
|
import { Link } from 'react-router-dom';
import React, { useState, useEffect, Component } from 'react';
import axios from 'axios'
import './Profile.css'
import "bootstrap/dist/css/bootstrap.min.css";
import Modal from 'react-bootstrap/Modal';
import './modal.css'
const Profile = (props) => {
const [show, setShow] = useState(false);
const [artifacts, setArtifacts] = useState([])
const [artifact, setArtifact] = useState({
name: "",
description: "",
imageurl: "",
})
const [error, setError] = useState(null);
useEffect(() => {
axios.get(`${process.env.REACT_APP_SERVER_URL}/profile`)
.then(response => {
if (response.status === 200) {
setArtifacts(response.data)
} else {
setError(response.statusText)
}
console.log(response.data)
})
.catch(err => {
console.log(err)
setError(err.message)
})
}, [])
const handleClose = () => setShow(false);
const handleShow = (e) => {
console.log(e.target.id)
setShow(true);
// axios.get(`${process.env.REACT_APP_SERVER_URL}/profile`)
// .then(response => {
// if (response.status === 200) {
// setArtifact(
// {name:}
// )
// } else {
// setError(response.statusText)
// }
// console.log(response.data)
// })
// .catch(err => {
// console.log(err)
// setError(err.message)
// })
}
let userData = props.user
?
<div>
</div>
: <h4>Loading...</h4>
let errorDiv = () => {
return (
<div className="text-center pt-4"><h3>Please <Link to='/login'>login</Link> to view this page</h3></div>
)
}
let individualArtifact = () => {
return (
<div>
<h3>{artifact.name}</h3>
<p>{artifact.description}</p>
<img className="modalImage" src={artifact.imageurl} />
</div>
)
}
let artifactList = artifacts.length < 1 ?
<h3>There are no favorited artifacts</h3> :
artifacts.map((artifact) => (
<div className="imageRow">
<ul className="test">
<li>
<h3>{artifact.name}</h3>
<img className="savedArtifacts" src={artifact.imageurl} alt="Saved artifacts" onClick={handleShow} />
</li>
</ul>
</div>
))
return (
<div className="profileBackground">
<div className="container center-align topBar">
<div className="modalWindow">
<Modal show={show} className='modalContent'>
<Modal.Body>
<div class="closeButton">
<button class="closeModal" onClick={handleClose} >×</button>
</div>
{individualArtifact}
{/* {artifactList} */}
<h3>{artifacts.name}</h3>
<p>{artifacts.description}</p>
<img className="modalImage" src={artifacts.imageurl} />
<form>
<input type="hidden" name="name" value={artifacts.name}></input>
<input type="hidden" name="description" value={artifacts.description}></input>
<input type="hidden" name="imageurl" value={artifacts.imageurl}></input>
</form>
</Modal.Body>
</Modal>
</div>
{props.user ? userData : errorDiv()}
{artifactList}
</div>
</div>
)
};
export default Profile;
|
var webpackConfig = require('./webpack.config.js');
// Prep webpack config for prod
webpackConfig.output.filename = '[name].[hash].js';
webpackConfig.port = null
// Gruntfile.js
module.exports = function (grunt) {
// load all grunt tasks matching the ['grunt-*', '@*/grunt-*'] patterns
require('load-grunt-tasks')(grunt);
//Config
grunt.initConfig({
clean: ["target/webroot/*"],
webpack: {
index: webpackConfig
}
});
//Tasks
grunt.registerTask('build', [
'clean',
'webpack'
]);
grunt.registerTask('release', ['build']);
grunt.registerTask('snapshot', ['build']);
}
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ParallaxComponent from 'react-parallax-component';
import background from './icons/background.jpg';
class App extends Component {
render() {
return (
<ParallaxComponent
speed="0.003"
width="300"
top="40%"
left="100"
>
<div>
<div className="Test">
<p>ddsfgsdd</p>
</div>
</div>
</ParallaxComponent>
);
}
}
export default App;
|
import React from 'react';
import PropTypes from 'prop-types';
import Icon from '../../atoms/icon';
export const FullscreenImage = (props) => {
return (
<div className="fixed h-full w-full mx-auto bg-nero z-40 max-w-600px" style={{ touchAction: 'none' }}>
<div className="fixed top-0 py-3 px-3 z-100" onClick={props.onClick}>
<Icon name="arrow-left" size="medium" color="white" />
</div>
<div>
<div
className="top-1/2 fixed flex w-full max-w-600px"
style={{ transform: 'translateY(-50%)' }}
>
<img
draggable={false}
src={props.image_url}
alt={props.image_title}
className={'w-auto mx-auto object-cover' }
/>
</div>
</div>
</div>
)
}
FullscreenImage.propTypes = {
image_url: PropTypes.string,
image_title: PropTypes.string,
onClick: PropTypes.func
}
export default FullscreenImage
|
'use strict';
var EE = require('events').EventEmitter
, cluster = require('cluster')
, serverErrorHandler = require('../server-error-handler')
, propagateEvents = require('../propagate-events')
, killTimeout = 30000;
function inspect(obj, depth) {
console.error(require('util').inspect(obj, false, depth || 5, true));
}
var dynamicDedupe = require('dynamic-dedupe');
var browserify = require('browserify');
var startPages = require('./start');
(function startWorker() {
var opts;
try {
if (!process.env.appup_pages_worker_opts) throw new Error('appup_pages_worker_opts missing');
opts = JSON.parse(process.env.appup_pages_worker_opts);
} catch (e) {
console.error(e);
inspect(process.env.appup_pages_worker_opts)
return;
}
// ensure to turn dedupe on BEFORE requiring the entry
if (opts.dedupe) dynamicDedupe.activate();
var apiServerInfo = { host: opts.apiHost, port: opts.apiPort };
var pagesPort = opts.pagesPort;
var entry = opts.entry;
var config = opts.config ? require(opts.config) : {};
var bfy = config.initBrowserify ? config.initBrowserify(browserify) : browserify();
var bundleOpts = config.bundleOpts || { insertGlobals: true, debug: true };
var initPages = config.initPages || function () {};
var postInitPages = config.postInitPages || function () {};
var events = config.events || null;
var send500 = config.pagesSend500; // domain-middleware has default for this
var localEvents = new EE();
propagateEvents(localEvents, events);
bfy.require(entry, { entry: true });
var onServerError = serverErrorHandler(cluster, events, killTimeout)
, onFatalError = onServerError.bind(null, true)
, onNonFatalError = onServerError.bind(null, false)
startPages(
{ bfy : bfy
, bundleOpts : bundleOpts
, customInit : initPages
, customPostInit : postInitPages
, port : pagesPort
, apiServerInfo : apiServerInfo
, watchdir : opts.watchdir
, events : localEvents
, send500 : send500
}
, function (err, address) {
var port = address.port;
var msg = 'pages server listening: http://localhost:' + port;
localEvents.emit('info', msg);
localEvents.on('server-error', onNonFatalError);
localEvents.on('fatal-error', onFatalError);
}
);
})();
|
import React from 'react'
import SundayForm from '../Components/Sunday/Form'
const Sunday = () => {
return (
<>
<SundayForm/>
</>
)
}
export default Sunday
|
const config = {
MONGO_URL: 'mongodb://mongo:27017/netflix_help_desk',
PORT: process.env.PORT || 8883
};
module.exports = config;
|
import fetch from 'node-fetch';
async function fetchPlayerCounts(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == "SUCCESS") {
var totalPlayers = 0
var snapshot = json.snapshot
var teamInfos = snapshot.teamInfo
totalPlayers += (["0"] in teamInfos ? count(teamInfos["0"].players) : 0)
totalPlayers += (["1"] in teamInfos ? count(teamInfos["1"].players) : 0)
totalPlayers += (["2"] in teamInfos ? count(teamInfos["2"].players) : 0)
totalPlayers += (["3"] in teamInfos ? count(teamInfos["3"].players) : 0)
totalPlayers += (["4"] in teamInfos ? count(teamInfos["4"].players) : 0)
return totalPlayers
}
else {
throw new Exception(`Invalid fetch status`)
}
});
}
async function fetchPlayerCounts_team_1(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == "SUCCESS") {
var totalPlayers = 0
var snapshot = json.snapshot
var teamInfos = snapshot.teamInfo
totalPlayers += (["1"] in teamInfos ? count(teamInfos["1"].players) : 0)
return totalPlayers
}
else {
throw new Exception(`Invalid fetch status`)
}
});
}
async function fetchPlayerCounts_team_2(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == "SUCCESS") {
var totalPlayers = 0
var snapshot = json.snapshot
var teamInfos = snapshot.teamInfo
totalPlayers += (["2"] in teamInfos ? count(teamInfos["2"].players) : 0)
return totalPlayers
}
else {
throw new Exception(`Invalid fetch status`)
}
});
}
async function fetchMaps(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
let rawMap = json.snapshot.currentMap.split('/');
let Map = rawMap[3];
const maps = {
MP_Abandoned: 'Zavod 311',
MP_Damage: 'Lancang Dam',
MP_Flooded: 'Flood Zone',
MP_Journey: 'Golmud Railway',
MP_Naval: 'Paracel Storm',
MP_Prison: 'Operation Locker',
MP_Resort: 'Hainan Resort',
MP_Siege: 'Siege of Shanghai',
MP_TheDish: 'Rogue Transmission',
MP_Tremors: 'Dawnbreaker',
XP1_001: 'Silk Road',
XP1_002: 'Altai Range',
XP1_003: 'Guilin Peaks',
XP1_004: 'Dragon Pass',
XP0_Caspian: 'Caspian Border 2014',
XP0_Firestorm: 'Operation Firestorm 2014',
XP0_Metro: 'Operation Metro 2014',
XP0_Oman: 'Gulf of Oman 2014',
XP2_001: 'Lost Islands',
XP2_002: 'Nansha Strike',
XP2_003: 'Wavebreaker',
XP2_004: 'Operation Mortar',
XP3_MarketPl: 'Pearl Market',
XP3_Prpganda: 'Propaganda',
XP3_UrbanGdn: 'Lumpini Garden',
XP3_WtrFront: 'Sunken Dragon',
XP4_Arctic: 'Operation Whiteout',
XP4_SubBase: 'Hammerhead',
XP4_Titan: 'Hangar 21',
XP4_WalkerFactory: 'Giants of Karelia',
XP5_Night_01: 'Zavod: Graveyard Shift',
XP6_CMP: 'Operation Outbreak',
XP7_Valley: 'Dragon Valley 2015'
};
return maps[Map]
} else {
throw new Exception(`Invalid fetch status`);
}
});
}
async function fetchMax(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
const maxp = json.snapshot.maxPlayers
return maxp;
} else {
throw new Exception(`Invalid fetch status`);
}
});
}
async function fetchMode(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(res => res.json())
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
let modes = json.snapshot.gameMode
const fixed = {
ConquestLarge: 'Conquest Large',
ConquestSmall: 'Conquest Small',
Domination: 'Domination',
Elimination: 'Defuse',
Obliteration: 'Obliteration',
RushLarge: 'Rush',
SquadDeathMatch: 'Squad Deathmatch',
TeamDeathMatch: 'Team Deathmatch',
SquadObliteration: 'Squad Obliteration',
GunMaster: 'Gun Master',
};
return fixed[modes]
}
else {
throw new Exception(`Invalid fetch status`);
}
});
}
async function fetchInfo_1(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(response => response.data)
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
let totalPlayers_1;
let snapshot = json.snapshot.teamInfo;
totalPlayers_1 = (snapshot["1"].players);
let result = [];
for (const key in totalPlayers_1) {
let kills = totalPlayers_1[key].kills;
let deaths = totalPlayers_1[key].deaths;
let scores = totalPlayers_1[key].score;
let name = totalPlayers_1[key].name;
result.push(scores, kills, deaths, name);
}
return result
}
else {
throw new Exception(`Invalid fetch status`);
}
})
}
async function fetchInfo_2(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(response => response.data)
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
let totalPlayers_2;
let snapshot = json.snapshot.teamInfo;
totalPlayers_2 = (snapshot["2"].players);
let result = [];
for (const key in totalPlayers_2) {
let kills = totalPlayers_2[key].kills;
let deaths = totalPlayers_2[key].deaths;
let scores = totalPlayers_2[key].score;
let name = totalPlayers_2[key].name;
result.push(scores, kills, deaths, name);
}
return result
}
else {
throw new Exception(`Invalid fetch status`);
}
})
}
async function queue(guid) {
return fetch(`https://keeper.battlelog.com/snapshot/${guid}`)
.then(response => response.data)
.then(json => {
if (json.snapshot.status == 'SUCCESS') {
let queue = json.snapshot.waitingPlayers;
return queue;
} else {
throw new Exception(`Invalid fetch status`);
}
});
}
function count(obj, ignoreNull) {
if (!obj) return 0;
var c = 0;
for (var _i in obj) {
if (ignoreNull) {
if (obj[_i] === null || obj[_i] === undefined) continue;
c++;
} else {
c++;
}
}
return c;
}
module.exports = { // for another file
fetchPlayerCounts: fetchPlayerCounts,
fetchMaps: fetchMaps,
fetchMode: fetchMode,
fetchMax: fetchMax,
fetchInfo_1: fetchInfo_1,
fetchInfo_2: fetchInfo_2,
fetchPlayerCounts_team_1: fetchPlayerCounts_team_1,
fetchPlayerCounts_team_2: fetchPlayerCounts_team_2,
queue: queue
};
|
import { getProjects } from "..";
/**
* @function fetchProjectById
* @param {string} projectIdQuery
* @returns {Project}
*/
const fetchProjectById = (projectIdQuery) => {
const projects = getProjects();
for (let i = 0; i < projects.length; i++) {
const project = projects[i];
if (project.id === projectIdQuery) {
return project;
}
}
};
export default fetchProjectById;
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Gender = sequelize.define('Gender', {
Id: {
primaryKey: true,
autoIncrement: true,
type: DataTypes.INTEGER,
},
Name: DataTypes.STRING
}, {});
Gender.associate = function (models) {
Gender.hasOne(models.User, { foreignKey: 'Gender' });
Gender.belongsToMany(models.Language, { through: models.GenderTranslation, foreignKey: 'Gender' });
};
return Gender;
};
|
import React, { useEffect, useContext, useCallback } from "react";
import queryString from "query-string";
import { useHistory, useLocation } from "react-router-dom";
import { discordSignup } from "../../api/discordApi";
import { UserContext } from "../../context/user/UserContext";
import { ErrorContext } from "../../context/error/ErrorContext";
import { StyledDiscordDiv } from "./StyledDiscord";
const DiscordSignup = () => {
const { setError } = useContext(ErrorContext);
const { setUser } = useContext(UserContext);
const history = useHistory();
const location = useLocation();
const values = queryString.parse(location.search);
const state = values.state;
const code = values.code;
const postDiscordSignup = useCallback(async () => {
const user = await discordSignup(code, state);
if (user.error) {
setUser(null);
setError(user.error);
if (user.error === "User credentials already in use. Please log in.") {
history.push("/login");
} else {
history.push("/signup");
}
} else if (user.data.id) {
setUser(user.data);
history.push("/challenge");
}
}, []);
useEffect(() => {
postDiscordSignup();
}, [postDiscordSignup]);
return <StyledDiscordDiv></StyledDiscordDiv>;
};
export default DiscordSignup;
|
import React, {Component} from 'react';
import {Modal, Radio, Table, Input, Icon, Button, Popconfirm,Form,Checkbox,message, Row, Col, DatePicker, TimePicker,Divider, Select } from 'antd';
import {Link} from 'react-router';
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
import moment from 'moment';
const { MonthPicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const monthFormat = 'YYYY/MM';
const Option = Select.Option;
import Record from './Record';
import './css/supervision.css';
function handleChange(value) {
console.log(`selected ${value}`);
}
//form表单初始布局
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 16 },
};
const formTailLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8, offset: 4 },
};
//const { getFieldDecorator } = this.props.form;
class PerForm_compile extends Component{
constructor(props){
super(props);
this.state = {
ModalText: 'Content of the modal',
confirmLoading: false, //加载状态
value:1,
checkNick: false,
names:'',
stateFunEdit:null,
modalKey:0,
visible:false,
steps:null,
num1:null,
data:null,
num:1,
dataSource:[],
columns:null,
cascadeLeft:[],
datas: [],
cities: {},
secondCity: [],
cascadeLeft:[],
}
this.visible=false;
this.aName='';
this.aSort=0;
this.tableData=null;
this.arr2=[];
this.login = true;
this.data=null;
this.cascadeLeft=[];
this.auditGroup={};
this.datas=[{
key: 1,
dept:'',
NAME:'',
labor:'',
remark:'',
}];
this.columns = [{
title: '部门',
dataIndex: 'dept',
key: 'dept',
width:'160px',
render: (text, record) => {
// console.log(record)
const provinceOptions = this.state.cascadeLeft.map(province => <Option key={province.EAF_ID1} value={JSON.stringify(province)}>{province.EAF_NAME}</Option>);
return (
<div style={{float:'left'}}>
<Select defaultValue={record.dept} style={{ width: 160 }} onChange={(e)=>this.handleProvinceChange(e,record.EAF_ID)}>
{provinceOptions}
</Select>
</div>
)
}
}, {
title: '姓名',
dataIndex:'NAME',
key: 'NAME',
width:'110px',
render: (text, record) => {
// console.log(record)
// console.log(text)
const { getFieldDecorator } = this.props.form;
console.log(this.state.cities);
const cityOptions = this.state.cities[record.EAF_ID]&&this.state.cities[record.EAF_ID].map(city => <Option key={city.EAF_ID} value={JSON.stringify(city)}>{city.EAF_NAME}</Option>);
return (
<div id="nameItem">
<FormItem label="">
{getFieldDecorator('peoples'+record.EAF_ID, {
rules: [{
required: false,
message: '',
}],
initialValue:record.NAME
})(
<Select style={{ width: 110 }} onChange={(e)=>this.onSecondCityChange(e,record.EAF_ID)}>
{cityOptions}
</Select>
)}
</FormItem>
</div>
)
}
}, {
title: '分工',
dataIndex: 'labor',
key: 'labor',
width:'35%',
render: (text, record) => {
return(
<TextArea defaultValue={record.labor} autosize autosize={{ minRows: 1, maxRows: 6 }} onBlur={(e)=>this.handleEdit(e,record,'labor')}/>
)
},
}, {
title: '备注',
dataIndex: 'remark',
key: 'remark',
width:'25%',
render: (text, record) => {
return(
<TextArea defaultValue={record.remark} autosize autosize={{ minRows: 1, maxRows: 6 }} onBlur={(e)=>this.handleEdit(e,record,'remark')}/>
)
},
}
];
}
GetUrlParam=(paraName) =>{
var url = document.location.toString();
var arrObj = url.split("?");
if (arrObj.length > 1) {
var arrPara = arrObj[1].split("&");
var arr;
for (var i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split("=");
if (arr != null && arr[0] == paraName) {
return arr[1];
}
}
return "";
}
else {
return "";
}
}
componentDidMount = () =>{
const addrCont = JSON.parse(localStorage.obj);
console.log(addrCont);
const that = this;
ajax({
url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.selectAuditGroupAndMember&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}",
dataType:"json",
success:function(res){
console.log(res);
that.setState({cascadeLeft:res.rows});
that.cascadeLeft=res.rows;
},
error: function (res) {
message.error(res.EAF_ERROR);
}
})
var obj={};
obj.eaf_id=addrCont?addrCont.EAF_ID:"";
var url="/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.inspactionFormAgainDispaly&eaf_id=E1DC78B90A7B4EE4A2E19F58CE90B715&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}";
ajax({
url:url,
// data:{"eaf_id":addrCont?addrCont.EAF_ID:null},
data:{"eaf_id":JSON.stringify(obj)},
success:function(res){
console.log(res);
if(res){
if(res.EAF_ERROR){
message.error(res.EAF_ERROR);
return;
}
// const dataSource = res.result.detail?res.result.detail:'';
let dataSource=[];
res.result.detail.map((item,index) => {
dataSource.push({
dept:item.DEPT,
NAME:item.NAME,
labor:item.LABOR,
remark:item.REMARK,
EAF_ID:item.EAF_ID,
DEPT_ID:item.DEPT_ID,
USER_ID:item.USER_ID,
})
})
that.setState({dataSource:dataSource});
console.log(dataSource)
}
},
error:function(res){
message.error(res.EAF_ERROR)
}
})
}
handleEdit = (e,record,key)=>{
let data = JSON.parse(JSON.stringify(this.state.dataSource));
data.map((item,index)=>{
if(item.NAME == record.NAME){
data[index][key]=e.target.value;
this.setState({dataSource:data})
}
})
console.log(data)
}
//新增分类
showModal = () => {
this.props.showModal();
this.props.clearData();
}
//modal框cacel关闭方法
handleCancel = () => {
console.log('Clicked cancel button');
this.props.showModal();
this.setState({confirmLoading:false});
// this.setState({
// visible: false,
// });
}
onChange = (e) => {
console.log('radio checked', e.target.value);
this.setState({
value: e.target.value,
});
}
handleSubmits = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
console.log("submit's value is :", values);
if (!err) {
const that =this;
console.log('abc');
const prevCont = JSON.parse(localStorage.obj);
console.log(prevCont);
var obj={};
obj.eaf_id = prevCont.EAF_ID;
obj.sup_id=prevCont.SUP_ID;
obj.supplier_code = prevCont.SUPPLIER_CODE;
obj.sup_name = prevCont.SUP_NAME;
obj.address = values.second;
obj.inspection_scope = values.third;
obj.inspection_start_time = values.rangePicker[0].format("YYYY-MM-DD");
obj.inspection_end_time = values.rangePicker[1].format("YYYY-MM-DD");
obj.supervision_purpose = values.note;
console.log(this.state.dataSource);
const datas = this.state.dataSource.map((item,index)=>(
{
eaf_id: item.EAF_ID,
NAME: item.NAME,
dept: item.dept,
dept_id:item.DEPT_ID,
labor:item.labor?item.labor:'',
remark:item.remark?item.remark:'',
user_id:item.USER_ID,
}
))
obj.auditGroup = datas;
console.log(datas);
let url="/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.updateInspaction&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}";
ajax({
url:url,
dataType:"json",
data:{"insertObject":JSON.stringify(obj)},
success:function(res){
console.log(res);
if(res.SUCCESS){
window.location.href='#Supervision';
}
},
error:function(res){
message.error(res.EAF_ERROR)
}
})
}
});
}
checks = () => {
this.props.form.validateFields(
(err) => {
if (!err) {
console.info('success');
}
},
);
}
handleTableData = (data)=>{
this.tableData = check(JSON.stringify(data));
console.log(1111111111111);
console.log(this.tableData)
}
handleReturn = () => {
window.location.href='#Supervision';
}
pushLogin=()=>{
this.login=false;
this.columnss.push({
title: '记录',
dataIndex: 'remeber',
render: text => <a onClick={this.records}><Icon type="form" /></a>,
})
}
saveTabelData = (data,hang,lie)=>{
console.log(data)
this.state.dataSource.map((item,index)=>{
if(item.EAF_ID==hang){
// this.state.dataSource[index].EAF_ID = item.EAF_ID;
if(lie=='dept'){
this.state.dataSource[index][lie]=data.EAF_NAME;
this.state.dataSource[index].DEPT_ID=data.EAF_ID1;
}else if(lie=='NAME'){
this.state.dataSource[index][lie]=data.EAF_NAME;
this.state.dataSource[index].USER_ID = data.EAF_ID;
}else{
this.state.dataSource[index][lie]=data;
}
}
})
console.log(this.state.dataSource)
}
handleProvinceChange = (value,key) => {
console.log(value);
let id = JSON.parse(value).EAF_ID1;
// let name = JSON.parse(value).EAF_NAME;
this.saveTabelData(JSON.parse(value),key,'dept');
const _this = this;
ajax({
url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.selectUserByDeptId&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}",
dataType:"json",
data:{"deptId":id},
success:function(res){
if(res.EAF_ERROR){
message.error(res.EAF_ERROR);
return;
}
console.log(res)
let obj = _this.state.cities;
obj[key] = res.rows;
_this.setState({cities:obj})
_this.props.form.setFieldsValue({
['peoples'+key]: res.rows[0].EAF_NAME,
});
_this.saveTabelData(res.rows[0],key,'NAME');
console.log(res.rows[0])
console.log(_this.state.cities)
},
error: function (res) {
message.error(res.EAF_ERROR);
}
})
}
onSecondCityChange = (value,key) => {
console.log(value);
this.saveTabelData(JSON.parse(value),key,'NAME');
}
render(){
const { getFieldDecorator } = this.props.form;
const funEdit = this.props.funEdit;
const addrCont = JSON.parse(localStorage.obj);
console.log(addrCont)
this.login&&addrCont.steps==3&&this.pushLogin()
var obj={};
return (
<div>
<h1 style={{textAlign:"center",fontWeight:"bolder"}}>中车株洲电机有限公司<br/>供应商监督审核计划</h1>
<FormItem {...formItemLayout} label="供应商名称">
{getFieldDecorator('first', {
initialValue:addrCont?addrCont.SUP_NAME:'',
rules: [{
required: true,
message: '请输入供应商名称',
}],
})(
<Input placeholder="" disabled={true}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="供应商地址">
{getFieldDecorator('second', {
initialValue:addrCont?addrCont.ADDRESS:'',
rules: [{
required: true,
message: '请输入供应商地址',
}],
})(
<TextArea maxLength={500} autosize={{ minRows: 2, maxRows: 6 }} />
)}
</FormItem>
<FormItem {...formItemLayout} label="督察范围">
{getFieldDecorator('third', {
initialValue:addrCont?addrCont.INSPECTION_SCOPE:'',
rules: [{
required: true,
message: '请输入督察范围',
}],
})(
<TextArea maxLength={200} autosize={{ minRows: 2, maxRows: 6 }} />
)}
</FormItem>
<FormItem {...formItemLayout} label="督察时间">
{getFieldDecorator('rangePicker', {
rules: [{ type: 'array', required: true, message: 'Please select time!' }],
initialValue:[moment(addrCont.INSPECTION_START_TIME
, dateFormat), moment(addrCont.INSPECTION_END_TIME, dateFormat)],
})(
<RangePicker
format={dateFormat}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="督察目的">
{getFieldDecorator('note', {
initialValue:addrCont?addrCont.SUPERVISION_PURPOSE:'',
rules: [{
required: true,
message: '请输入督察目的',
}],
})(
<TextArea autosize />
)}
</FormItem>
<FormItem {...formItemLayout} label="经办">
{getFieldDecorator('jb', {
initialValue:addrCont?addrCont.CREATE_USER:'',
rules: [{
required: true,
message: '请输入经办人员',
}],
})(
<Input placeholder="" disabled={addrCont.CREATE_USER?true:false}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="编制部门">
{getFieldDecorator('bzbm', {
initialValue:addrCont?addrCont.CREATE_DEPT:'',
rules: [{
required: true,
message: '请输入编制部门',
}],
})(
<Input placeholder="" disabled={addrCont.CREATE_DEPT?true:false}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="部门审批意见">
{getFieldDecorator('opinion', {
initialValue:addrCont?addrCont.APPROVAL_OPINION:'',
rules: [{
required: true,
message: '请输入部门审批意见',
}],
})(
<TextArea rows={4} disabled={addrCont.APPROVAL_OPINION?true:false}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="时间">
{getFieldDecorator('date', {
rules: [{ type: 'object', required: true, message: '请选择时间' }],
initialValue:moment(addrCont.APPROVAL_TIME, dateFormat),
})(
<DatePicker format={dateFormat} disabled={addrCont.APPROVAL_TIME?true:false} />
)}
</FormItem>
<p className="p-box" style={{ textAlign: 'center',marginBottom:'20' }}>
<lable className="lab" style={{ float: 'none',fontSize: '17px' }}>审核组成员及分工</lable>
</p>
{this.state.dataSource?
<div id="teams">
<FormItem label="">
{getFieldDecorator('teams', {
initialValue: this.props.department ? this.props.department : '',
rules: [{
required: false,
message: '审核组成员及分工不能为空',
}],
})(
<div style={{width:"75%",marginLeft:"10%"}}>
<Table style={{ position: 'relative', zIndex: 2 }} columns={this.columns} pagination={false} dataSource={this.state.dataSource} />
</div>
)}
</FormItem>
</div>
:''}
<div style={{textAlign:'center',marginTop:'20'}}>
<Button type="primary" onClick={this.handleSubmits} id="tg">发起</Button>
<Button type="primary" style={{ marginLeft: '20' }} onClick={this.handleReturn}>返回</Button>
</div>
</div>
)
}
}
const PerForm_compiles = Form.create()(PerForm_compile);
export default PerForm_compiles;
|
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
const dbConnect = require("./config/db");
const PORT = process.env.PORT || 5000;
const NODE_ENV = process.env.NODE_ENV || "DEV";
const app = express();
// middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
if (NODE_ENV === "DEV") {
app.use(logger("dev"));
}
//routes
const noteRoutes = require("./routes/notes");
app.use("/api/notes", noteRoutes);
// Server Connection
app.listen(PORT, () => {
console.log(`Server listening to PORT ${PORT}`);
});
// DB Connection
dbConnect();
|
var isMatch = function (s, p) {
// TOP-Down Memoization
return dfs(0, 0, s, p);
};
function dfs(i, j, s, p) {
if (i >= s.length && j >= p.length) {
return true;
}
if (j >= s.length) {
return false;
}
let match = i < s.length && (s[i] === p[j] || p[j] === '.');
if (j + 1 < p.length && p[j + 1] === '*') {
// branch
// don't use * (0 repeat), so stay on string and increase j
// let branch1 = dfs(i, j + 2, s, p);
// use star (1 or N repeat), re-use star(*), don't increase j
// let branch2 = dfs(i + 1, j, s, p);
return dfs(i, j + 2, s, p) || (match && dfs(i + 1, j, s, p));
}
if (match) {
return dfs(i + 1, j + 1, s, p);
}
return false;
}
console.log(isMatch('aaaaa', 'a*a*a*'));
console.log(isMatch('aaaa', 'a*'));
console.log(isMatch('aaaa', 'a*a*'));
console.log(isMatch('mississippi', 'mis*is*p*'));
console.log(isMatch('mississippi', 'mis*is*ip*i'));
|
var promptLength = 0;
var socket;
var editor;
// broken backslash
var specialChar = {190 : '.', 188 : ',', 191 : '/', 220 : '\\', 222 : '\''};
var shiftSpecialChar = {190 : '>', 188 : '<', 191 : '?', 220 : '|', 222 : '\"'};
var shiftNumberKeys = {48 : ')', 49 : '!', 50 : '@', 51 : '#', 52 : '$', 53 : '%', 54 : '^', 55 : '&', 56 : '*', 57 : '('};
$(document).ready(function() {
// Initial settings for ace editor
editor = ace.edit("terminal");
editor.renderer.setShowGutter(false);
editor.setShowPrintMargin(false);
editor.getSession().setMode('ace/mode/text');
// Focus on host input on page load
$("#hostname").focus();
// Move cursor to username box when enter is pressed in hostname
$("#hostname").on('keyup', function (e) {
if (e.keyCode == 13) {
$("#username").focus();
}
});
// Move cursor to password textbox when enter is pressed in username
$("#username").on('keypress', function (e) {
if (e.keyCode == 13) {
$("#password").focus();
}
});
$("#password").on('keyup', function (e) {
if (e.keyCode == 13) {
if(socket == null)
{
socket = io.connect();
socket.on('connected', function(){
// Once the socket connects, attempt using the credentials to login with SSH credentials
attemptLogin();
});
// When the SSH connection is established, write the first output to the screen
socket.on('logged in', function(output){
editor.focus();
editor.setValue(output, 1)
editor.scrollToRow(100000)
promptLength = getLastLineLengthString(output);
// Begin listening for further commands
$('#terminal').keyup(function(e){
var key = convertKeyPress(e);
sendCommand(key);
});
// Begin listening responses from the socket
socket.on('sshResponse', function(response){
response = replaceANSICodes(response);
editor.setValue(editor.getValue() + response, 1);
promptLength = getLastLineLengthString(response);
editor.scrollToRow(100000)
});
});
socket.on('login failed', function(){
$("#hostname").val('');
$("#username").val('');
$("#password").val('');
$("#hostname").focus();
});
}
else {
attemptLogin();
}
};
});
$('#terminal').click(function(){
setCursorAtEndOfEditor();
});
});
function attemptLogin()
{
socket.emit('attemptLogin', JSON.stringify(
{
domain: $("#hostname").val(),
username: $("#username").val(),
password: $("#password").val()
}));
}
function setCursorAtEndOfEditor()
{
editor.focus();
var row = editor.getLastVisibleRow();
var column = editor.getSession().getLine(row).length;
editor.gotoLine(row + 1, column);
}
function getLastLineLengthString(output)
{
output = output.split('\n');
output = output[output.length - 1];
return output.length;
}
function getLastLineValue()
{
var row = editor.getLastVisibleRow();
return editor.getSession().getLine(row - 1);
}
function replaceANSICodes(string)
{
var string = string.replace(new RegExp("\\x1b", "g"), "");
return string.replace(new RegExp("\\[[^m]*m", "g"), "");
}
function convertKeyPress(e)
{
var code = e.which;
if(code >= 48 && code <= 90)
{
// Number key special chars
if((code >= 48 && code <= 57) && e.shiftKey)
return shiftNumberKeys[code];
//
var char = String.fromCharCode(code);
if(!e.shiftKey)
char = char.toLowerCase();
}
else if(code >= 188)
{
if(e.shiftKey)
return shiftSpecialChar[code];
return specialChar[code];
}
else if(code == 13)
return '\n';
else if (code == 32)
return ' ';
else if (code == 38)
return '\e\[A';
else if (code == 8)
return '\x01\x11';
return char;
}
function sendCommand(keyPress){
socket.emit('sshKeyPress', keyPress);
}
|
import React from 'react';
import cl from './Nav.module.css';
import Friends from "./Friends/Friends";
import {NavLink} from "react-router-dom";
const Nav = (props) => {
return <nav className={cl.nav}>
<div className={cl.item}>
<NavLink to="/profile" activeClassName={cl.activeLink}>Profile</NavLink>
</div>
<div className={`${cl.item}`}>
<NavLink to="/Dialogs" activeClassName={cl.activeLink}>Messages</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/Users" activeClassName={cl.activeLink}>Users</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/Music" activeClassName={cl.activeLink}>Music</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/Settings" activeClassName={cl.activeLink}>Settings</NavLink>
</div>
<Friends friendsList={props.state.friends} />
</nav>
};
export default Nav;
|
import request from '@/utils/request'
// 统计.数量统计
export function orderStat(data) {
return request({
url: 'statistics/count',
method: 'get',
params: data
})
}
// 订单.列表
export function ordersList(data) {
return request({
url: 'orders',
method: 'get',
params: data
})
}
// 订单.详情
export function ordersInfo(id) {
return request({
url: 'orders/' + id,
method: 'get'
})
}
// 订单.发货
export function ordersExpress(id, data) {
return request({
url: 'orders/' + id + '/express',
method: 'post',
data: data
})
}
// 订单.改价
export function ordersPriceModify(id, data) {
return request({
url: 'orders/' + id + '/pay-price',
method: 'put',
data: data
})
}
// 评价.查.列表
export function evalutionsList(data) {
return request({
url: 'evalutions',
method: 'get',
params: data
})
}
// 评价.回复
export function evalutionsReply(id, data) {
return request({
url: 'evalutions/' + id + '/replies',
method: 'post',
data: data
})
}
// 评价.批量.回复
export function batchEvalutionsReply(data) {
return request({
url: 'batch/evalutions/replies',
method: 'post',
data: data
})
}
// 评价.查.个
export function evalutionsInfo(id) {
return request({
url: 'evalutions/' + id,
method: 'get'
})
}
// 退款/换货.列表
export function orderAfterSales(data) {
return request({
url: 'after-sales',
method: 'get',
params: data
})
}
// 退款/换货.操作(批准/同意/拒绝)
export function orderAfterSalesOpt(id, data) {
return request({
url: 'after-sales/' + id + '/status',
method: 'put',
data: data
})
}
export function exportOrder(data) {
return request({
url: 'orders-export',
method: 'get',
params: data
})
}
export function changeMerchantComment(id, data) {
return request({
url: 'orders/' + id + '/merchant-comment',
method: 'put',
params: data
})
}
export function changeShippingAddress(id, data) {
return request({
url: 'orders/' + id + '/shipping-address',
method: 'put',
params: data
})
}
export function getOneOrdersInfo(id) {
return request({
url: 'orders/' + id,
method: 'get'
})
}
export function getExpressInfo(data) {
return request({
url: 'express/info',
method: 'get',
params: data
})
}
// 订单.各个状态数
export function ordersCount(data) {
return request({
url: 'orders-count',
method: 'get',
params: data
})
}
// 售后.数量获取
export function afterSalesCount(data) {
return request({
url: 'after-sales-count',
method: 'get',
params: data
})
}
// 评价.查.数量
export function evaluationsCount() {
return request({
url: 'evaluations-count',
method: 'get'
})
}
// 订单.货到付款确认
export function orderConfirm(id) {
return request({
url: 'orders/' + id + '/confirm',
method: 'put'
})
}
// 订单.认领
export function orderOwnerShipGet(id, data) {
return request({
url: 'orders/' + id + '/get-ownership',
method: 'post',
data: data
})
}
// 订单.转让
export function orderOwnerShipTrans(id, data) {
return request({
url: 'orders/' + id + '/trans-ownership',
method: 'post',
data: data
})
}
// 订单.代购订单审核
export function orderPurchaseCheck(id, data) {
return request({
url: 'orders/' + id + '/purchase-check',
method: 'put',
data: data
})
}
// 订单.添加物流记录
export function orderTransRecords(id, data) {
return request({
url: 'orders/' + id + '/trans-records',
method: 'post',
data: data
})
}
// 仓库.库存信息.根据仓库区分组
export function warehouseGroupInven(data) {
return request({
url: 'warehouse-inventories-group-warehouse',
method: 'get',
params: data
})
}
// 订单.取消
export function cancelGoods(id) {
return request({
url: 'orders/' + id + '/cancel',
method: 'post'
})
}
// 订单.设置商家备注
export function orderMerchantComment(id, data) {
return request({
url: 'orders/' + id + '/merchant-comment',
method: 'put',
data: data
})
}
// 订单.海淘商品备注
export function orderGoodsComment(id, data) {
return request({
url: 'orders/' + id + '/goods-comment',
method: 'put',
data: data
})
}
// 订单.商品退款
export function orderRefundOnly(id, data) {
return request({
url: 'orders/' + id + '/refund-only',
method: 'post',
data: data
})
}
// 订单.发送消息
export function orderMessage(id, data) {
return request({
url: 'orders/' + id + '/message',
method: 'post',
data: data
})
}
|
import React, { useState } from 'react';
import "./App.css";
function App() {
const mockTodos =[
'Need to wakeup in the morning',
'Brush your Teeths'
]
const [todoList, setTodoList] = useState(mockTodos);
const [todo, setTodo] = useState('')
const addTodo =() =>{
const currentTodo =[...todoList, todo]
setTodoList(currentTodo)
setTodo('')
}
const handleChange =(e) =>{
setTodo(e.target.value);
}
return (
<div className="App">
<h1>ToDo Application</h1>
<div>
<div>
<input type="text" onChange={(e) =>handleChange(e)} value={todo}/>
<button onClick={addTodo}>Add Todo</button>
</div>
<div>
<ul>
{todoList && todoList.map(item =>{
return <li>{item}</li>
})}
</ul>
</div>
</div>
</div>
);
}
export default App;
|
import { unpkg as browser, directories, displayName, module, source } from "./package.json";
import config from "../../config/rollup/rollup.config";
export default config({
browser,
directories,
displayName,
globals: {
"@faciocode/styles/dist/index.css": "FacioStyles",
"@material-ui/core": "MuiCore",
"@material-ui/core/styles": "MuiCoreStyles",
"@material-ui/lab": "MuiLab",
lodash: "_",
react: "React",
},
module,
source,
});
|
export const TOGGLE_TOAST = 'toaster/TOGGLE_TOAST';
export const SHOW_TOAST = 'toaster/SHOW_TOAST';
export const HIDE_TOAST = 'toaster/HIDE_TOAST';
export const toggleToast = (variant, content, error, options) => ({
type: TOGGLE_TOAST,
variant,
content,
error,
options,
});
export const showToast = (variant, content, options) => ({
type: SHOW_TOAST,
variant,
content,
options,
});
export const hideToast = () => (dispatch, getState) => {
const {
toaster: { visible },
} = getState();
if (!visible) {
return;
}
dispatch({ type: HIDE_TOAST });
};
|
/* eslint-disable array-callback-return */
/* eslint-disable no-underscore-dangle */
/* eslint-disable import/prefer-default-export */
export const getPlayers = playerInfo => dispatch => {
const players = [];
playerInfo.find({ fileName: 'playerInfo' }, (err, docs) => {
docs.map(d => {
let Name = '';
if (d.Name1) {
Name = d.Name1;
}
if (d.Name2) {
Name = `${Name} ${d.Name2}`;
}
if (d.Name3) {
Name = `${Name} ${d.Name3}`;
}
const player = {
title: Name,
_id: d._id
};
players.push(player);
});
players.sort((a,b) => (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0))
dispatch({
type: 'GET_PLAYERS',
players
});
});
console.log(players);
};
|
import React from 'react'
import { withTranslation } from 'react-i18next'
import { Container } from 'reactstrap'
import Header from 'components/Headers/Header.jsx'
import { getConfiguration } from '../apollo/server'
import OrderConfiguration from '../components/Configuration/Order/Order'
import EmailConfiguration from '../components/Configuration/Email/Email'
import PaypalConfiguration from '../components/Configuration/Paypal/Paypal'
import StripeConfiguration from '../components/Configuration/Stripe/Stripe'
import DeliveryConfiguration from '../components/Configuration/Delivery/Delivery'
import CurrencyConfiguration from '../components/Configuration/Currency/Currency'
import Loader from 'react-loader-spinner'
import { gql, useQuery } from '@apollo/client'
const GET_CONFIGURATION = gql`
${getConfiguration}
`
const Configuration = props => {
const { data, loading, error } = useQuery(GET_CONFIGURATION)
if (data) console.log(data.configuration)
return (
<>
<Header />
{error ? (
'Error :('
) : loading ? (
<Container className="text-center mt-10" fluid>
<Loader
type="TailSpin"
color="#fb6340"
height={300}
width={300}
visible={loading}
/>
</Container>
) : (
<Container className="mt--7" fluid>
<Loader
type="TailSpin"
color="#FFF"
height={25}
width={30}
visible={loading}
/>
<OrderConfiguration prefix={data.configuration.orderPrefix} />
<EmailConfiguration
email={data.configuration.email}
password={data.configuration.password}
enabled={data.configuration.enableEmail}
/>
<PaypalConfiguration
clientId={data.configuration.clientId}
clientSecret={data.configuration.clientSecret}
sandbox={data.configuration.sandbox}
/>
<StripeConfiguration
publishableKey={data.configuration.publishableKey}
secretKey={data.configuration.secretKey}
/>
<DeliveryConfiguration
deliveryCharges={data.configuration.deliveryCharges}
/>
<CurrencyConfiguration
currencyCode={data.configuration.currency}
currencySymbol={data.configuration.currencySymbol}
/>
</Container>
)}
</>
)
}
export default withTranslation()(Configuration)
|
import React, { useState } from 'react'
import usercontext from './usercontext';
function UserState(props) {
const [user, setuser] = useState(null);
return (
<usercontext.Provider value={{ user: user, setuser }} >
{props.children}
</usercontext.Provider>
)
}
export default UserState;
|
const _ = require('lodash');
const IsHelpedBy = require('./neo4j/isHelpedBy');
const _singleIsHelpedBy = function (record) {
if (record.length) {
const result = {};
_.extend(result, new IsHelpedBy(record.get('isHelpedBy')));
return result;
}
else {
return null;
}
};
// Create profile
const createRelation = function (session, singleId, friendId) {
return session.run('MATCH (s:Profile),(f:Profile)' +
'WHERE s.id = {singleId} AND f.id = {friendId}'+
'CREATE (s)-[isHelpedBy:IS_HELPED_BY]->(f)'+
'RETURN isHelpedBy', { singleId, friendId }
).then(results => {
return new IsHelpedBy(results.records[0].get('isHelpedBy'));
}
)
};
module.exports = {
createRelation
};
|
import superagent from 'superagent';
import {eventChannel, buffers, END} from 'redux-saga';
export function getBlob (url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () { resolve(xhr.response); };
xhr.onerror = function (err) { reject(err); }
xhr.open('GET', url);
xhr.send();
});
};
export function uploadBlob (upload, blob) {
return new Promise(function (resolve, reject) {
const formData = new FormData();
const params = upload.params;
Object.keys(params).forEach(function (key) {
formData.append(key, params[key]);
});
formData.append('file', blob);
superagent.post(upload.form_url).send(formData)
.end(function (err, response) {
if (err) return reject(err);
resolve(response);
});
});
};
export function uploadBlobChannel ({params, form_url}, blob) {
return eventChannel(function (listener) {
const formData = new FormData();
Object.keys(params).forEach(function (key) {
formData.append(key, params[key]);
});
formData.append('file', blob);
var request = superagent.post(form_url);
request.send(formData)
.on('progress', function (event) {
listener({type: 'progress', percent: event.percent});
})
.end(function (error, response) {
if (error) {
listener({type: 'error', error});
} else {
listener({type: 'response', response});
}
listener(END);
});
return () => {
request.abort();
};
}, buffers.expanding(1));
}
|
import './App.css';
import React, { Component } from "react";
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
export default class CurrentlyLoaded extends Component {
/* this class displays the list containing all the piece cards */
render() {
return (
<div className="info_box">
<div>
<h3>Currently Loaded:</h3>
<p>data/maps/maps.sqlite3</p>
</div>
<div>
<Form.Group controlId="formFile" className="mb-3">
<Form.Label>Select Database</Form.Label>
<Form.Control type="file" />
</Form.Group>
</div>
<Button variant="primary">Load DB</Button>{' '}
</div>
)
}
}
|
// ==UserScript==
// @name WebAborn
// @version <?version_major?>.<?dateNow?>
// @namespace http://webaborn.herokuapp.com
// @description Reduce the situation you see disagreeable texts in the way replacing to some word. ('aborn' means 'purge and unable to read'.)
// @include *
// ==/UserScript
(function () {
const abornString = '<?replace_string?>';
const ng_words = [<?words_str?>];
var webaborn = function(node){
var candidates = document.evaluate('.//text()[not(parent::style) and not(parent::textarea) and not(parent::script)]', node, null, 6, null);
var i, j, lenC, lenNG, txt;
for (i=0, lenC=candidates.snapshotLength; i<lenC; i++) {
txt = candidates.snapshotItem(i).nodeValue;
for (j=0, lenNG=ng_words.length; j<lenNG; j++){
if(txt.indexOf(ng_words[j]) >= 0){
candidates.snapshotItem(i).nodeValue = <?replace_to1?>
}
}
}
candidates = document.evaluate('.//input[not(@type="text")]/@value | .//img/@alt | .//*/@title | .//a/@href', node, null, 6, null);
for (i=0, lenC=candidates.snapshotLength; i<lenC; i++) {
txt = candidates.snapshotItem(i).value;
for (j=0; j<lenNG; j++){
if(txt.indexOf(ng_words[j]) >= 0){
candidates.snapshotItem(i).value = <?replace_to2?>
}
}
}
};
var nodeText = document.evaluate('//text()', document, null, 6, null);
var nodePre = document.evaluate('//pre', document, null, 6, null);
if (nodeText.snapshotLength===1 && nodePre.snapshotLength===1){
var del = nodeText.snapshotItem(0);
var lines = del.nodeValue.split(/\r?\n/);
var ins = document.createElement('pre');
ins.style.whiteSpace = 'pre-wrap';
del.parentNode.replaceChild(ins, del);
var i, len;
for(i=0, len=lines.length; i<len; i++){
ins.appendChild(document.createTextNode(lines[i]));
ins.appendChild(document.createElement('br'));
}
}
webaborn(document);
document.addEventListener('DOMNodeInserted', function(e){ webaborn(e.target); }, false);
document.addEventListener('DOMCharacterDataModified', function(e){ webaborn(e.target); }, false);
document.addEventListener('DOMAttrModified', function(e){ webaborn(e.target); }, false);
})();
|
import datajson from 'json!../../../json/chapters.json'
const initialState = localStorage.chapters
? JSON.parse(localStorage.chapters)
: datajson
const addChapter = (key, state) => {
// console.log(key)
return Object.assign([], [...state,
{
key: state.length+1,
name: "Sample data. ",
notes: "will only save when something is edited. If you want to keep it, edit it, otherwise, refresh your page now",
partID: key.chapter.partID
}
])
}
const addLocal=(state) => {
// console.log(state)
localStorage.setItem('chapters', JSON.stringify(state))
return;
}
const chapterEdit = (action , state) => {
// console.log('action state',action,state)
var newState = state.map( (item, index) => {
// console.log(item.key,index)
if(item.key !== action.key) {
// This isn't the item we care about - keep it as-is
return item;
}
// Otherwise, this is the one we want - return an updated value
else {
// console.log(item,action)
return {
key:action.key,
partID: action.partID,
name:action.name,
notes:action.notes
}
}
});
addLocal(newState)
return newState;
}
const chapter = (state = initialState, action) => {
// console.log('action', state)
switch (action.type) {
case 'CHAPTER_SELECTED' :
return action.payload
case 'EDIT_CHAPTER_SELECTED' :
return chapterEdit(action.payload,state)
case 'ADD_CHAPTER_SELECTED' :
return addChapter(action.payload,state)
default:
return state;
}
return state;
}
export default chapter
|
module.exports = {
root: true,
extends: '@react-native-community',
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
// e.g. "@typescript-eslint/explicit-function-return-type": "off",
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/ban-ts-ignore': 'off',
'@typescript-eslint/no-var-requires': 'off',
},
};
|
import React, {
Component,
} from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import {
getCollection,
} from '@shoutem/redux-io';
import {
Button,
Caption,
Text,
Tile,
Title,
View,
} from '@shoutem/ui';
import { connectStyle } from '@shoutem/theme';
import { ext } from '../const';
import {
placeShape,
transactionShape,
} from './shapes';
const { arrayOf, func } = React.PropTypes;
/**
* A component for place loyalty points layout.
*/
class PlaceLoyaltyPointsView extends Component {
static propTypes = {
// The place
place: placeShape.isRequired,
// Called when collect points is pressed
onCollectPointsPress: func,
// Called when points history is pressed
onPointsHistoryPress: func,
// Transactions for this place
transactions: arrayOf(transactionShape),
};
render() {
const { place, onCollectPointsPress, onPointsHistoryPress, transactions } = this.props;
return (
<Tile>
<View styleName="content h-center lg-gutter-vertical vertical">
<Caption>Points collected</Caption>
<Title styleName="md-gutter-top">{place.points || 'No points collected'}</Title>
<View styleName="horizontal lg-gutter-top">
<Button
onPress={onCollectPointsPress}
styleName="secondary md-gutter-right"
>
<Text>COLLECT</Text>
</Button>
{_.size(transactions) ?
<Button onPress={onPointsHistoryPress}>
<Text>HISTORY</Text>
</Button>
:
null
}
</View>
</View>
</Tile>
);
}
}
const getTransactionsForPlace = (transactions, place) =>
_.filter(transactions, (transaction) => {
const { transactionData } = transaction;
return place.id === transactionData.location;
});
export const mapStateToProps = (state, ownProps) => {
const { allTransactions } = state[ext()];
const { place } = ownProps;
const transactions = getCollection(allTransactions, state);
return {
transactions: getTransactionsForPlace(transactions, place),
};
};
export default connect(mapStateToProps)(
connectStyle(ext('PlaceLoyaltyPointsView'))(PlaceLoyaltyPointsView),
);
|
var searchData=
[
['tloopcallback',['TLoopCallback',['../core_8h.html#a9f670b824fb6b10883cd4283f800310f',1,'core.h']]],
['tnanoenginegetbuttons',['TNanoEngineGetButtons',['../group___n_a_n_o___e_n_g_i_n_e___a_p_i.html#gaff4934f12cf7a86959c46e57aac5ae5d',1,'core.h']]],
['tnanoengineondraw',['TNanoEngineOnDraw',['../tiler_8h.html#a5db298dc5fe7132d3190e5e423b6da6a',1,'tiler.h']]]
];
|
//** Import Modules */
import React, { useEffect, useState } from 'react';
import { gsap } from 'gsap';
import { SmileOutlined, CloseOutlined } from '@ant-design/icons';
//** Import Components */
import VotingEmojiReaction from './VotingEmojiReaction';
export default function VotingExpandModal(props) {
// Get component props
const { story, closeStory, reactions, updateReaction } = props;
// Open Emoji Box
const [openEmoji, setOpenEmoji] = useState(false);
// Get src url for the images folder. This is the images folder in the public directory
const imgBaseUrl = window.location.origin + '/assets/images/emojis/svg';
useEffect(() => {
gsap.from('#expand-modal', { left: '100vw', opacity: 0, duration: 1 });
}, []);
//** Close the modal
const closeModal = () => {
gsap.to('#expand-modal', { x: '100vw', opacity: 0, duration: 1 });
setTimeout(() => {
closeStory();
}, 1000);
};
//** Open Emoji Box
const openEmojiBox = () => {
setOpenEmoji(true);
};
//** Close Emoji Box
const closeEmojiBox = () => {
setOpenEmoji(false);
};
return (
<div id="expand-modal">
<div className="inner-modal">
<div className="header">
<h3>{story.title}</h3>
<button className="close" onClick={closeModal}>
Close <CloseOutlined />
</button>
</div>
<div className="story">
<img src={story.image} alt={story.title} />
</div>
<div className="reaction">
<p>
Choose 5 different emojis to express how you feel about this story.
</p>
<div className="emoji-field" onClick={openEmojiBox} role="button">
<div className="emoji-list">
{reactions[`story${story.story}`].map((item, index) => {
return (
<img
key={index}
src={`${imgBaseUrl}/${item.emoji}.svg`}
alt={item.name}
/>
);
})}
</div>
<div className="icon">
<SmileOutlined />
<span>Keyboard</span>
</div>
</div>
{openEmoji && (
<VotingEmojiReaction
closeEmojiBox={closeEmojiBox}
updateReaction={updateReaction}
storyID={story.story}
imgBaseUrl={imgBaseUrl}
reactions={reactions}
/>
)}
</div>
</div>
</div>
);
}
|
// let datePassport = {
// number: "07BC00000",
// name: "Anne",
// surename: "Specimen",
// birthday: "1973-07-12",
// barthplace: "Perpignan"
// }
// let jsonDatePassport = JSON.stringify(datePassport);
// let linkObj = {
// pass: datePassport,
// name: "post name"
// }
// let linkDatePassport = JSON.stringify(linkObj);
// let revlinkDatePassport = JSON.parse(linkDatePassport);
let url = "https://api.instagram.com/v1/users/2093101329/media/recent/?access_token=2093101329.0e4abd3.d017a21b3e6e45408126e42cf0940d79";
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener('readystatechange', function() {
if(xhr.readyState == 4 && xhr.status == 200){
console.log('good');
}
})
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const Cc = Components.classes;
const Cu = Components.utils;
const Ci = Components.interfaces;
// Page size for pageup/pagedown
const PAGE_SIZE = 10;
const PREVIEW_AREA = 700;
const DEFAULT_MAX_CHILDREN = 100;
this.EXPORTED_SYMBOLS = ["MarkupView"];
Cu.import("resource:///modules/devtools/LayoutHelpers.jsm");
Cu.import("resource:///modules/devtools/CssRuleView.jsm");
Cu.import("resource:///modules/devtools/Templater.jsm");
Cu.import("resource:///modules/devtools/Undo.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
/**
* Vocabulary for the purposes of this file:
*
* MarkupContainer - the structure that holds an editor and its
* immediate children in the markup panel.
* Node - A content node.
* object.elt - A UI element in the markup panel.
*/
/**
* The markup tree. Manages the mapping of nodes to MarkupContainers,
* updating based on mutations, and the undo/redo bindings.
*
* @param Inspector aInspector
* The inspector we're watching.
* @param iframe aFrame
* An iframe in which the caller has kindly loaded markup-view.xhtml.
*/
this.MarkupView = function MarkupView(aInspector, aFrame, aControllerWindow)
{
this._inspector = aInspector;
this._frame = aFrame;
this.doc = this._frame.contentDocument;
this._elt = this.doc.querySelector("#root");
try {
this.maxChildren = Services.prefs.getIntPref("devtools.markup.pagesize");
} catch(ex) {
this.maxChildren = DEFAULT_MAX_CHILDREN;
}
this.undo = new UndoStack();
this.undo.installController(aControllerWindow);
this._containers = new WeakMap();
this._observer = new this.doc.defaultView.MutationObserver(this._mutationObserver.bind(this));
this._boundOnNewSelection = this._onNewSelection.bind(this);
this._inspector.selection.on("new-node", this._boundOnNewSelection);
this._onNewSelection();
this._boundKeyDown = this._onKeyDown.bind(this);
this._frame.contentWindow.addEventListener("keydown", this._boundKeyDown, false);
this._boundFocus = this._onFocus.bind(this);
this._frame.addEventListener("focus", this._boundFocus, false);
this._initPreview();
}
MarkupView.prototype = {
_selectedContainer: null,
template: function MT_template(aName, aDest, aOptions={stack: "markup-view.xhtml"})
{
let node = this.doc.getElementById("template-" + aName).cloneNode(true);
node.removeAttribute("id");
template(node, aDest, aOptions);
return node;
},
/**
* Get the MarkupContainer object for a given node, or undefined if
* none exists.
*/
getContainer: function MT_getContainer(aNode)
{
return this._containers.get(aNode);
},
/**
* Highlight the inspector selected node.
*/
_onNewSelection: function MT__onNewSelection()
{
if (this._inspector.selection.isNode()) {
this.showNode(this._inspector.selection.node, true);
this.markNodeAsSelected(this._inspector.selection.node);
} else {
this.unmarkSelectedNode();
}
},
/**
* Create a TreeWalker to find the next/previous
* node for selection.
*/
_selectionWalker: function MT__seletionWalker(aStart)
{
let walker = this.doc.createTreeWalker(
aStart || this._elt,
Ci.nsIDOMNodeFilter.SHOW_ELEMENT,
function(aElement) {
if (aElement.container && aElement.container.visible) {
return Ci.nsIDOMNodeFilter.FILTER_ACCEPT;
}
return Ci.nsIDOMNodeFilter.FILTER_SKIP;
}
);
walker.currentNode = this._selectedContainer.elt;
return walker;
},
/**
* Key handling.
*/
_onKeyDown: function MT__KeyDown(aEvent)
{
let handled = true;
// Ignore keystrokes that originated in editors.
if (aEvent.target.tagName.toLowerCase() === "input" ||
aEvent.target.tagName.toLowerCase() === "textarea") {
return;
}
switch(aEvent.keyCode) {
case Ci.nsIDOMKeyEvent.DOM_VK_DELETE:
case Ci.nsIDOMKeyEvent.DOM_VK_BACK_SPACE:
this.deleteNode(this._selectedContainer.node);
break;
case Ci.nsIDOMKeyEvent.DOM_VK_HOME:
this.navigate(this._containers.get(this._rootNode.firstChild));
break;
case Ci.nsIDOMKeyEvent.DOM_VK_LEFT:
this.collapseNode(this._selectedContainer.node);
break;
case Ci.nsIDOMKeyEvent.DOM_VK_RIGHT:
this.expandNode(this._selectedContainer.node);
break;
case Ci.nsIDOMKeyEvent.DOM_VK_UP:
let prev = this._selectionWalker().previousNode();
if (prev) {
this.navigate(prev.container);
}
break;
case Ci.nsIDOMKeyEvent.DOM_VK_DOWN:
let next = this._selectionWalker().nextNode();
if (next) {
this.navigate(next.container);
}
break;
case Ci.nsIDOMKeyEvent.DOM_VK_PAGE_UP: {
let walker = this._selectionWalker();
let selection = this._selectedContainer;
for (let i = 0; i < PAGE_SIZE; i++) {
let prev = walker.previousNode();
if (!prev) {
break;
}
selection = prev.container;
}
this.navigate(selection);
break;
}
case Ci.nsIDOMKeyEvent.DOM_VK_PAGE_DOWN: {
let walker = this._selectionWalker();
let selection = this._selectedContainer;
for (let i = 0; i < PAGE_SIZE; i++) {
let next = walker.nextNode();
if (!next) {
break;
}
selection = next.container;
}
this.navigate(selection);
break;
}
default:
handled = false;
}
if (handled) {
aEvent.stopPropagation();
aEvent.preventDefault();
}
},
/**
* Delete a node from the DOM.
* This is an undoable action.
*/
deleteNode: function MC__deleteNode(aNode)
{
let doc = nodeDocument(aNode);
if (aNode === doc ||
aNode === doc.documentElement ||
aNode.nodeType == Ci.nsIDOMNode.DOCUMENT_TYPE_NODE) {
return;
}
let parentNode = aNode.parentNode;
let sibling = aNode.nextSibling;
this.undo.do(function() {
if (aNode.selected) {
this.navigate(this._containers.get(parentNode));
}
parentNode.removeChild(aNode);
}.bind(this), function() {
parentNode.insertBefore(aNode, sibling);
});
},
/**
* If an editable item is focused, select its container.
*/
_onFocus: function MC__onFocus(aEvent) {
let parent = aEvent.target;
while (!parent.container) {
parent = parent.parentNode;
}
if (parent) {
this.navigate(parent.container, true);
}
},
/**
* Handle a user-requested navigation to a given MarkupContainer,
* updating the inspector's currently-selected node.
*
* @param MarkupContainer aContainer
* The container we're navigating to.
* @param aIgnoreFocus aIgnoreFocus
* If falsy, keyboard focus will be moved to the container too.
*/
navigate: function MT__navigate(aContainer, aIgnoreFocus)
{
if (!aContainer) {
return;
}
let node = aContainer.node;
this.showNode(node, false);
this._inspector.selection.setNode(node, "treepanel");
// This event won't be fired if the node is the same. But the highlighter
// need to lock the node if it wasn't.
this._inspector.selection.emit("new-node");
if (!aIgnoreFocus) {
aContainer.focus();
}
},
/**
* Make sure a node is included in the markup tool.
*
* @param DOMNode aNode
* The node in the content document.
*
* @returns MarkupContainer The MarkupContainer object for this element.
*/
importNode: function MT_importNode(aNode, aExpand)
{
if (!aNode) {
return null;
}
if (this._containers.has(aNode)) {
return this._containers.get(aNode);
}
this._observer.observe(aNode, {
attributes: true,
childList: true,
characterData: true,
});
let walker = documentWalker(aNode);
let parent = walker.parentNode();
if (parent) {
var container = new MarkupContainer(this, aNode);
} else {
var container = new RootContainer(this, aNode);
this._elt.appendChild(container.elt);
this._rootNode = aNode;
aNode.addEventListener("load", function MP_watch_contentLoaded(aEvent) {
// Fake a childList mutation here.
this._mutationObserver([{target: aEvent.target, type: "childList"}]);
}.bind(this), true);
}
this._containers.set(aNode, container);
// FIXME: set an expando to prevent the the wrapper from disappearing
// See bug 819131 for details.
aNode.__preserveHack = true;
container.expanded = aExpand;
container.childrenDirty = true;
this._updateChildren(container);
if (parent) {
this.importNode(parent, true);
}
return container;
},
/**
* Mutation observer used for included nodes.
*/
_mutationObserver: function MT__mutationObserver(aMutations)
{
for (let mutation of aMutations) {
let container = this._containers.get(mutation.target);
if (!container) {
// Container might not exist if this came from a load event for an iframe
// we're not viewing.
continue;
}
if (mutation.type === "attributes" || mutation.type === "characterData") {
container.update();
} else if (mutation.type === "childList") {
container.childrenDirty = true;
this._updateChildren(container);
}
}
this._inspector.emit("markupmutation");
},
/**
* Make sure the given node's parents are expanded and the
* node is scrolled on to screen.
*/
showNode: function MT_showNode(aNode, centered)
{
let container = this.importNode(aNode);
this._updateChildren(container);
let walker = documentWalker(aNode);
let parent;
while (parent = walker.parentNode()) {
this._updateChildren(this.getContainer(parent));
this.expandNode(parent);
}
LayoutHelpers.scrollIntoViewIfNeeded(this._containers.get(aNode).editor.elt, centered);
},
/**
* Expand the container's children.
*/
_expandContainer: function MT__expandContainer(aContainer)
{
if (aContainer.hasChildren && !aContainer.expanded) {
aContainer.expanded = true;
this._updateChildren(aContainer);
}
},
/**
* Expand the node's children.
*/
expandNode: function MT_expandNode(aNode)
{
let container = this._containers.get(aNode);
this._expandContainer(container);
},
/**
* Expand the entire tree beneath a container.
*
* @param aContainer The container to expand.
*/
_expandAll: function MT_expandAll(aContainer)
{
this._expandContainer(aContainer);
let child = aContainer.children.firstChild;
while (child) {
this._expandAll(child.container);
child = child.nextSibling;
}
},
/**
* Expand the entire tree beneath a node.
*
* @param aContainer The node to expand, or null
* to start from the top.
*/
expandAll: function MT_expandAll(aNode)
{
aNode = aNode || this._rootNode;
this._expandAll(this._containers.get(aNode));
},
/**
* Collapse the node's children.
*/
collapseNode: function MT_collapseNode(aNode)
{
let container = this._containers.get(aNode);
container.expanded = false;
},
/**
* Mark the given node selected.
*/
markNodeAsSelected: function MT_markNodeAsSelected(aNode)
{
let container = this._containers.get(aNode);
if (this._selectedContainer === container) {
return false;
}
if (this._selectedContainer) {
this._selectedContainer.selected = false;
}
this._selectedContainer = container;
if (aNode) {
this._selectedContainer.selected = true;
}
this._ensureSelectionVisible();
return true;
},
/**
* Make sure that every ancestor of the selection are updated
* and included in the list of visible children.
*/
_ensureSelectionVisible: function MT_ensureSelectionVisible()
{
let node = this._selectedContainer.node;
let walker = documentWalker(node);
while (node) {
let container = this._containers.get(node);
let parent = walker.parentNode();
if (!container.elt.parentNode) {
let parentContainer = this._containers.get(parent);
parentContainer.childrenDirty = true;
this._updateChildren(parentContainer, node);
}
node = parent;
}
},
/**
* Unmark selected node (no node selected).
*/
unmarkSelectedNode: function MT_unmarkSelectedNode()
{
if (this._selectedContainer) {
this._selectedContainer.selected = false;
this._selectedContainer = null;
}
},
/**
* Called when the markup panel initiates a change on a node.
*/
nodeChanged: function MT_nodeChanged(aNode)
{
if (aNode === this._inspector.selection) {
this._inspector.change("markupview");
}
},
/**
* Make sure all children of the given container's node are
* imported and attached to the container in the right order.
* @param aCentered If provided, this child will be included
* in the visible subset, and will be roughly centered
* in that list.
*/
_updateChildren: function MT__updateChildren(aContainer, aCentered)
{
if (!aContainer.childrenDirty) {
return false;
}
// Get a tree walker pointing at the first child of the node.
let treeWalker = documentWalker(aContainer.node);
let child = treeWalker.firstChild();
aContainer.hasChildren = !!child;
if (!aContainer.expanded) {
return;
}
aContainer.childrenDirty = false;
let children = this._getVisibleChildren(aContainer, aCentered);
let fragment = this.doc.createDocumentFragment();
for (child of children.children) {
let container = this.importNode(child, false);
fragment.appendChild(container.elt);
}
while (aContainer.children.firstChild) {
aContainer.children.removeChild(aContainer.children.firstChild);
}
if (!(children.hasFirst && children.hasLast)) {
let data = {
showing: this.strings.GetStringFromName("markupView.more.showing"),
showAll: this.strings.formatStringFromName(
"markupView.more.showAll",
[aContainer.node.children.length.toString()], 1),
allButtonClick: function() {
aContainer.maxChildren = -1;
aContainer.childrenDirty = true;
this._updateChildren(aContainer);
}.bind(this)
};
if (!children.hasFirst) {
let span = this.template("more-nodes", data);
fragment.insertBefore(span, fragment.firstChild);
}
if (!children.hasLast) {
let span = this.template("more-nodes", data);
fragment.appendChild(span);
}
}
aContainer.children.appendChild(fragment);
return true;
},
/**
* Return a list of the children to display for this container.
*/
_getVisibleChildren: function MV__getVisibleChildren(aContainer, aCentered)
{
let maxChildren = aContainer.maxChildren || this.maxChildren;
if (maxChildren == -1) {
maxChildren = Number.MAX_VALUE;
}
let firstChild = documentWalker(aContainer.node).firstChild();
let lastChild = documentWalker(aContainer.node).lastChild();
if (!firstChild) {
// No children, we're done.
return { hasFirst: true, hasLast: true, children: [] };
}
// By default try to put the selected child in the middle of the list.
let start = aCentered || firstChild;
// Start by reading backward from the starting point....
let nodes = [];
let backwardWalker = documentWalker(start);
if (backwardWalker.previousSibling()) {
let backwardCount = Math.floor(maxChildren / 2);
let backwardNodes = this._readBackward(backwardWalker, backwardCount);
nodes = backwardNodes;
}
// Then read forward by any slack left in the max children...
let forwardWalker = documentWalker(start);
let forwardCount = maxChildren - nodes.length;
nodes = nodes.concat(this._readForward(forwardWalker, forwardCount));
// If there's any room left, it means we've run all the way to the end.
// In that case, there might still be more items at the front.
let remaining = maxChildren - nodes.length;
if (remaining > 0 && nodes[0] != firstChild) {
let firstNodes = this._readBackward(backwardWalker, remaining);
// Then put it all back together.
nodes = firstNodes.concat(nodes);
}
return {
hasFirst: nodes[0] == firstChild,
hasLast: nodes[nodes.length - 1] == lastChild,
children: nodes
};
},
_readForward: function MV__readForward(aWalker, aCount)
{
let ret = [];
let node = aWalker.currentNode;
do {
ret.push(node);
node = aWalker.nextSibling();
} while (node && --aCount);
return ret;
},
_readBackward: function MV__readBackward(aWalker, aCount)
{
let ret = [];
let node = aWalker.currentNode;
do {
ret.push(node);
node = aWalker.previousSibling();
} while(node && --aCount);
ret.reverse();
return ret;
},
/**
* Tear down the markup panel.
*/
destroy: function MT_destroy()
{
this.undo.destroy();
delete this.undo;
this._frame.removeEventListener("focus", this._boundFocus, false);
delete this._boundFocus;
this._frame.contentWindow.removeEventListener("scroll", this._boundUpdatePreview, true);
this._frame.contentWindow.removeEventListener("resize", this._boundUpdatePreview, true);
this._frame.contentWindow.removeEventListener("overflow", this._boundResizePreview, true);
this._frame.contentWindow.removeEventListener("underflow", this._boundResizePreview, true);
delete this._boundUpdatePreview;
this._frame.contentWindow.removeEventListener("keydown", this._boundKeyDown, true);
delete this._boundKeyDown;
this._inspector.selection.off("new-node", this._boundOnNewSelection);
delete this._boundOnNewSelection;
delete this._elt;
delete this._containers;
this._observer.disconnect();
delete this._observer;
},
/**
* Initialize the preview panel.
*/
_initPreview: function MT_initPreview()
{
if (!Services.prefs.getBoolPref("devtools.inspector.markupPreview")) {
return;
}
this._previewBar = this.doc.querySelector("#previewbar");
this._preview = this.doc.querySelector("#preview");
this._viewbox = this.doc.querySelector("#viewbox");
this._previewBar.classList.remove("disabled");
this._previewWidth = this._preview.getBoundingClientRect().width;
this._boundResizePreview = this._resizePreview.bind(this);
this._frame.contentWindow.addEventListener("resize", this._boundResizePreview, true);
this._frame.contentWindow.addEventListener("overflow", this._boundResizePreview, true);
this._frame.contentWindow.addEventListener("underflow", this._boundResizePreview, true);
this._boundUpdatePreview = this._updatePreview.bind(this);
this._frame.contentWindow.addEventListener("scroll", this._boundUpdatePreview, true);
this._updatePreview();
},
/**
* Move the preview viewbox.
*/
_updatePreview: function MT_updatePreview()
{
let win = this._frame.contentWindow;
if (win.scrollMaxY == 0) {
this._previewBar.classList.add("disabled");
return;
}
this._previewBar.classList.remove("disabled");
let ratio = this._previewWidth / PREVIEW_AREA;
let width = ratio * win.innerWidth;
let height = ratio * (win.scrollMaxY + win.innerHeight);
let scrollTo
if (height >= win.innerHeight) {
scrollTo = -(height - win.innerHeight) * (win.scrollY / win.scrollMaxY);
this._previewBar.setAttribute("style", "height:" + height + "px;transform:translateY(" + scrollTo + "px)");
} else {
this._previewBar.setAttribute("style", "height:100%");
}
let bgSize = ~~width + "px " + ~~height + "px";
this._preview.setAttribute("style", "background-size:" + bgSize);
let height = ~~(win.innerHeight * ratio) + "px";
let top = ~~(win.scrollY * ratio) + "px";
this._viewbox.setAttribute("style", "height:" + height + ";transform: translateY(" + top + ")");
},
/**
* Hide the preview while resizing, to avoid slowness.
*/
_resizePreview: function MT_resizePreview()
{
let win = this._frame.contentWindow;
this._previewBar.classList.add("hide");
win.clearTimeout(this._resizePreviewTimeout);
win.setTimeout(function() {
this._updatePreview();
this._previewBar.classList.remove("hide");
}.bind(this), 1000);
},
};
/**
* The main structure for storing a document node in the markup
* tree. Manages creation of the editor for the node and
* a <ul> for placing child elements, and expansion/collapsing
* of the element.
*
* @param MarkupView aMarkupView
* The markup view that owns this container.
* @param DOMNode aNode
* The node to display.
*/
function MarkupContainer(aMarkupView, aNode)
{
this.markup = aMarkupView;
this.doc = this.markup.doc;
this.undo = this.markup.undo;
this.node = aNode;
if (aNode.nodeType == Ci.nsIDOMNode.TEXT_NODE) {
this.editor = new TextEditor(this, aNode, "text");
} else if (aNode.nodeType == Ci.nsIDOMNode.COMMENT_NODE) {
this.editor = new TextEditor(this, aNode, "comment");
} else if (aNode.nodeType == Ci.nsIDOMNode.ELEMENT_NODE) {
this.editor = new ElementEditor(this, aNode);
} else if (aNode.nodeType == Ci.nsIDOMNode.DOCUMENT_TYPE_NODE) {
this.editor = new DoctypeEditor(this, aNode);
} else {
this.editor = new GenericEditor(this.markup, aNode);
}
// The template will fill the following properties
this.elt = null;
this.expander = null;
this.codeBox = null;
this.children = null;
this.markup.template("container", this);
this.elt.container = this;
this.expander.addEventListener("click", function() {
this.markup.navigate(this);
if (this.expanded) {
this.markup.collapseNode(this.node);
} else {
this.markup.expandNode(this.node);
}
}.bind(this));
this.codeBox.insertBefore(this.editor.elt, this.children);
this.editor.elt.addEventListener("mousedown", function(evt) {
this.markup.navigate(this);
}.bind(this), false);
if (this.editor.summaryElt) {
this.editor.summaryElt.addEventListener("click", function(evt) {
this.markup.navigate(this);
this.markup.expandNode(this.node);
}.bind(this), false);
this.codeBox.appendChild(this.editor.summaryElt);
}
if (this.editor.closeElt) {
this.editor.closeElt.addEventListener("mousedown", function(evt) {
this.markup.navigate(this);
}.bind(this), false);
this.codeBox.appendChild(this.editor.closeElt);
}
}
MarkupContainer.prototype = {
/**
* True if the current node has children. The MarkupView
* will set this attribute for the MarkupContainer.
*/
_hasChildren: false,
get hasChildren() {
return this._hasChildren;
},
set hasChildren(aValue) {
this._hasChildren = aValue;
if (aValue) {
this.expander.style.visibility = "visible";
} else {
this.expander.style.visibility = "hidden";
}
},
/**
* True if the node has been visually expanded in the tree.
*/
get expanded() {
return this.children.hasAttribute("expanded");
},
set expanded(aValue) {
if (aValue) {
this.expander.setAttribute("expanded", "");
this.children.setAttribute("expanded", "");
if (this.editor.summaryElt) {
this.editor.summaryElt.setAttribute("expanded", "");
}
} else {
this.expander.removeAttribute("expanded");
this.children.removeAttribute("expanded");
if (this.editor.summaryElt) {
this.editor.summaryElt.removeAttribute("expanded");
}
}
},
/**
* True if the container is visible in the markup tree.
*/
get visible()
{
return this.elt.getBoundingClientRect().height > 0;
},
/**
* True if the container is currently selected.
*/
_selected: false,
get selected() {
return this._selected;
},
set selected(aValue) {
this._selected = aValue;
if (this._selected) {
this.editor.elt.classList.add("selected");
if (this.editor.closeElt) {
this.editor.closeElt.classList.add("selected");
}
} else {
this.editor.elt.classList.remove("selected");
if (this.editor.closeElt) {
this.editor.closeElt.classList.remove("selected");
}
}
},
/**
* Update the container's editor to the current state of the
* viewed node.
*/
update: function MC_update()
{
if (this.editor.update) {
this.editor.update();
}
},
/**
* Try to put keyboard focus on the current editor.
*/
focus: function MC_focus()
{
let focusable = this.editor.elt.querySelector("[tabindex]");
if (focusable) {
focusable.focus();
}
},
}
/**
* Dummy container node used for the root document element.
*/
function RootContainer(aMarkupView, aNode)
{
this.doc = aMarkupView.doc;
this.elt = this.doc.createElement("ul");
this.children = this.elt;
this.node = aNode;
}
/**
* Creates an editor for simple nodes.
*/
function GenericEditor(aContainer, aNode)
{
this.elt = aContainer.doc.createElement("span");
this.elt.className = "editor";
this.elt.textContent = aNode.nodeName;
}
/**
* Creates an editor for a DOCTYPE node.
*
* @param MarkupContainer aContainer The container owning this editor.
* @param DOMNode aNode The node being edited.
*/
function DoctypeEditor(aContainer, aNode)
{
this.elt = aContainer.doc.createElement("span");
this.elt.className = "editor comment";
this.elt.textContent = '<!DOCTYPE ' + aNode.name +
(aNode.publicId ? ' PUBLIC "' + aNode.publicId + '"': '') +
(aNode.systemId ? ' "' + aNode.systemId + '"' : '') +
'>';
}
/**
* Creates a simple text editor node, used for TEXT and COMMENT
* nodes.
*
* @param MarkupContainer aContainer The container owning this editor.
* @param DOMNode aNode The node being edited.
* @param string aTemplate The template id to use to build the editor.
*/
function TextEditor(aContainer, aNode, aTemplate)
{
this.node = aNode;
aContainer.markup.template(aTemplate, this);
_editableField({
element: this.value,
stopOnReturn: true,
trigger: "dblclick",
multiline: true,
done: function TE_done(aVal, aCommit) {
if (!aCommit) {
return;
}
let oldValue = this.node.nodeValue;
aContainer.undo.do(function() {
this.node.nodeValue = aVal;
aContainer.markup.nodeChanged(this.node);
}.bind(this), function() {
this.node.nodeValue = oldValue;
aContainer.markup.nodeChanged(this.node);
}.bind(this));
}.bind(this)
});
this.update();
}
TextEditor.prototype = {
update: function TE_update()
{
this.value.textContent = this.node.nodeValue;
}
};
/**
* Creates an editor for an Element node.
*
* @param MarkupContainer aContainer The container owning this editor.
* @param Element aNode The node being edited.
*/
function ElementEditor(aContainer, aNode)
{
this.doc = aContainer.doc;
this.undo = aContainer.undo;
this.template = aContainer.markup.template.bind(aContainer.markup);
this.container = aContainer;
this.markup = this.container.markup;
this.node = aNode;
this.attrs = [];
// The templates will fill the following properties
this.elt = null;
this.tag = null;
this.attrList = null;
this.newAttr = null;
this.summaryElt = null;
this.closeElt = null;
// Create the main editor
this.template("element", this);
if (this.node.firstChild || this.node.textContent.length > 0) {
// Create the summary placeholder
this.template("elementContentSummary", this);
}
// Create the closing tag
this.template("elementClose", this);
// Make the tag name editable (unless this is a document element)
if (aNode != aNode.ownerDocument.documentElement) {
this.tag.setAttribute("tabindex", "0");
_editableField({
element: this.tag,
trigger: "dblclick",
stopOnReturn: true,
done: this.onTagEdit.bind(this),
});
}
// Make the new attribute space editable.
_editableField({
element: this.newAttr,
trigger: "dblclick",
stopOnReturn: true,
done: function EE_onNew(aVal, aCommit) {
if (!aCommit) {
return;
}
try {
this._applyAttributes(aVal);
} catch (x) {
return;
}
}.bind(this)
});
let tagName = this.node.nodeName.toLowerCase();
this.tag.textContent = tagName;
this.closeTag.textContent = tagName;
this.update();
}
ElementEditor.prototype = {
/**
* Update the state of the editor from the node.
*/
update: function EE_update()
{
let attrs = this.node.attributes;
if (!attrs) {
return;
}
// Hide all the attribute editors, they'll be re-shown if they're
// still applicable. Don't update attributes that are being
// actively edited.
let attrEditors = this.attrList.querySelectorAll(".attreditor");
for (let i = 0; i < attrEditors.length; i++) {
if (!attrEditors[i].inplaceEditor) {
attrEditors[i].style.display = "none";
}
}
// Get the attribute editor for each attribute that exists on
// the node and show it.
for (let i = 0; i < attrs.length; i++) {
let attr = this._createAttribute(attrs[i]);
if (!attr.inplaceEditor) {
attr.style.removeProperty("display");
}
}
},
_createAttribute: function EE_createAttribute(aAttr, aBefore)
{
if (aAttr.name in this.attrs) {
var attr = this.attrs[aAttr.name];
var name = attr.querySelector(".attrname");
var val = attr.querySelector(".attrvalue");
} else {
// Create the template editor, which will save some variables here.
let data = {
attrName: aAttr.name,
};
this.template("attribute", data);
var {attr, inner, name, val} = data;
// Figure out where we should place the attribute.
let before = aBefore || null;
if (aAttr.name == "id") {
before = this.attrList.firstChild;
} else if (aAttr.name == "class") {
let idNode = this.attrs["id"];
before = idNode ? idNode.nextSibling : this.attrList.firstChild;
}
this.attrList.insertBefore(attr, before);
// Make the attribute editable.
_editableField({
element: inner,
trigger: "dblclick",
stopOnReturn: true,
selectAll: false,
start: function EE_editAttribute_start(aEditor, aEvent) {
// If the editing was started inside the name or value areas,
// select accordingly.
if (aEvent && aEvent.target === name) {
aEditor.input.setSelectionRange(0, name.textContent.length);
} else if (aEvent && aEvent.target === val) {
let length = val.textContent.length;
let editorLength = aEditor.input.value.length;
let start = editorLength - (length + 1);
aEditor.input.setSelectionRange(start, start + length);
} else {
aEditor.input.select();
}
},
done: function EE_editAttribute_done(aVal, aCommit) {
if (!aCommit) {
return;
}
this.undo.startBatch();
// Remove the attribute stored in this editor and re-add any attributes
// parsed out of the input element. Restore original attribute if
// parsing fails.
this._removeAttribute(this.node, aAttr.name);
try {
this._applyAttributes(aVal, attr);
this.undo.endBatch();
} catch (e) {
this.undo.endBatch();
this.undo.undo();
}
}.bind(this)
});
this.attrs[aAttr.name] = attr;
}
name.textContent = aAttr.name;
val.textContent = aAttr.value;
return attr;
},
/**
* Parse a user-entered attribute string and apply the resulting
* attributes to the node. This operation is undoable.
*
* @param string aValue the user-entered value.
* @param Element aAttrNode the attribute editor that created this
* set of attributes, used to place new attributes where the
* user put them.
* @throws SYNTAX_ERR if aValue is not well-formed.
*/
_applyAttributes: function EE__applyAttributes(aValue, aAttrNode)
{
// Create a dummy node for parsing the attribute list.
let dummyNode = this.doc.createElement("div");
let parseTag = (this.node.namespaceURI.match(/svg/i) ? "svg" :
(this.node.namespaceURI.match(/mathml/i) ? "math" : "div"));
let parseText = "<" + parseTag + " " + aValue + "/>";
// Throws exception if parseText is not well-formed.
dummyNode.innerHTML = parseText;
let parsedNode = dummyNode.firstChild;
let attrs = parsedNode.attributes;
this.undo.startBatch();
for (let i = 0; i < attrs.length; i++) {
// Create an attribute editor next to the current attribute if needed.
this._createAttribute(attrs[i], aAttrNode ? aAttrNode.nextSibling : null);
this._setAttribute(this.node, attrs[i].name, attrs[i].value);
}
this.undo.endBatch();
},
/**
* Helper function for _setAttribute and _removeAttribute,
* returns a function that puts an attribute back the way it was.
*/
_restoreAttribute: function EE_restoreAttribute(aNode, aName)
{
if (aNode.hasAttribute(aName)) {
let oldValue = aNode.getAttribute(aName);
return function() {
aNode.setAttribute(aName, oldValue);
this.markup.nodeChanged(aNode);
}.bind(this);
} else {
return function() {
aNode.removeAttribute(aName);
this.markup.nodeChanged(aNode);
}.bind(this);
}
},
/**
* Sets an attribute. This operation is undoable.
*/
_setAttribute: function EE_setAttribute(aNode, aName, aValue)
{
this.undo.do(function() {
aNode.setAttribute(aName, aValue);
this.markup.nodeChanged(aNode);
}.bind(this), this._restoreAttribute(aNode, aName));
},
/**
* Removes an attribute. This operation is undoable.
*/
_removeAttribute: function EE_removeAttribute(aNode, aName)
{
this.undo.do(function() {
aNode.removeAttribute(aName);
this.markup.nodeChanged(aNode);
}.bind(this), this._restoreAttribute(aNode, aName));
},
/**
* Handler for the new attribute editor.
*/
_onNewAttribute: function EE_onNewAttribute(aValue, aCommit)
{
if (!aValue || !aCommit) {
return;
}
this._setAttribute(this.node, aValue, "");
let attr = this._createAttribute({ name: aValue, value: ""});
attr.style.removeAttribute("display");
attr.querySelector("attrvalue").click();
},
/**
* Called when the tag name editor has is done editing.
*/
onTagEdit: function EE_onTagEdit(aVal, aCommit) {
if (!aCommit || aVal == this.node.tagName) {
return;
}
// Create a new element with the same attributes as the
// current element and prepare to replace the current node
// with it.
try {
var newElt = nodeDocument(this.node).createElement(aVal);
} catch(x) {
// Failed to create a new element with that tag name, ignore
// the change.
return;
}
let attrs = this.node.attributes;
for (let i = 0 ; i < attrs.length; i++) {
newElt.setAttribute(attrs[i].name, attrs[i].value);
}
function swapNodes(aOld, aNew) {
while (aOld.firstChild) {
aNew.appendChild(aOld.firstChild);
}
aOld.parentNode.insertBefore(aNew, aOld);
aOld.parentNode.removeChild(aOld);
}
let markup = this.container.markup;
// Queue an action to swap out the element.
this.undo.do(function() {
swapNodes(this.node, newElt);
// Make sure the new node is imported and is expanded/selected
// the same as the current node.
let newContainer = markup.importNode(newElt, this.container.expanded);
newContainer.expanded = this.container.expanded;
if (this.container.selected) {
markup.navigate(newContainer);
}
}.bind(this), function() {
swapNodes(newElt, this.node);
let newContainer = markup._containers.get(newElt);
this.container.expanded = newContainer.expanded;
if (newContainer.selected) {
markup.navigate(this.container);
}
}.bind(this));
},
}
RootContainer.prototype = {
hasChildren: true,
expanded: true,
update: function RC_update() {}
};
function documentWalker(node) {
return new DocumentWalker(node, Ci.nsIDOMNodeFilter.SHOW_ALL, whitespaceTextFilter);
}
function nodeDocument(node) {
return node.ownerDocument || (node.nodeType == Ci.nsIDOMNode.DOCUMENT_NODE ? node : null);
}
/**
* Similar to a TreeWalker, except will dig in to iframes and it doesn't
* implement the good methods like previousNode and nextNode.
*
* See TreeWalker documentation for explanations of the methods.
*/
function DocumentWalker(aNode, aShow, aFilter)
{
let doc = nodeDocument(aNode);
this.walker = doc.createTreeWalker(nodeDocument(aNode), aShow, aFilter);
this.walker.currentNode = aNode;
this.filter = aFilter;
}
DocumentWalker.prototype = {
get node() this.walker.node,
get whatToShow() this.walker.whatToShow,
get expandEntityReferences() this.walker.expandEntityReferences,
get currentNode() this.walker.currentNode,
set currentNode(aVal) this.walker.currentNode = aVal,
/**
* Called when the new node is in a different document than
* the current node, creates a new treewalker for the document we've
* run in to.
*/
_reparentWalker: function DW_reparentWalker(aNewNode) {
if (!aNewNode) {
return null;
}
let doc = nodeDocument(aNewNode);
let walker = doc.createTreeWalker(doc,
this.whatToShow, this.filter, this.expandEntityReferences);
walker.currentNode = aNewNode;
this.walker = walker;
return aNewNode;
},
parentNode: function DW_parentNode()
{
let currentNode = this.walker.currentNode;
let parentNode = this.walker.parentNode();
if (!parentNode) {
if (currentNode && currentNode.nodeType == Ci.nsIDOMNode.DOCUMENT_NODE
&& currentNode.defaultView) {
let embeddingFrame = currentNode.defaultView.frameElement;
if (embeddingFrame) {
return this._reparentWalker(embeddingFrame);
}
}
return null;
}
return parentNode;
},
firstChild: function DW_firstChild()
{
let node = this.walker.currentNode;
if (!node)
return;
if (node.contentDocument) {
return this._reparentWalker(node.contentDocument);
} else if (node instanceof nodeDocument(node).defaultView.GetSVGDocument) {
return this._reparentWalker(node.getSVGDocument());
}
return this.walker.firstChild();
},
lastChild: function DW_lastChild()
{
let node = this.walker.currentNode;
if (!node)
return;
if (node.contentDocument) {
return this._reparentWalker(node.contentDocument);
} else if (node instanceof nodeDocument(node).defaultView.GetSVGDocument) {
return this._reparentWalker(node.getSVGDocument());
}
return this.walker.lastChild();
},
previousSibling: function DW_previousSibling() this.walker.previousSibling(),
nextSibling: function DW_nextSibling() this.walker.nextSibling(),
// XXX bug 785143: not doing previousNode or nextNode, which would sure be useful.
}
/**
* A tree walker filter for avoiding empty whitespace text nodes.
*/
function whitespaceTextFilter(aNode)
{
if (aNode.nodeType == Ci.nsIDOMNode.TEXT_NODE &&
!/[^\s]/.exec(aNode.nodeValue)) {
return Ci.nsIDOMNodeFilter.FILTER_SKIP;
} else {
return Ci.nsIDOMNodeFilter.FILTER_ACCEPT;
}
}
XPCOMUtils.defineLazyGetter(MarkupView.prototype, "strings", function () {
return Services.strings.createBundle(
"chrome://browser/locale/devtools/inspector.properties");
});
|
const supertest = require("supertest");
const app = require("../src/server");
const request = supertest(app());
const {
connectToTestDb,
closeConnection,
dropDatabase,
} = require("./utils/db");
beforeAll(async (done) => {
await connectToTestDb();
done();
});
afterAll(async (done) => {
await closeConnection();
dropDatabase(done);
});
describe("Register user", () => {
it("Must return user when all is ok and not contain password", async () => {
const { body, status } = await request.post("/register").send({
name: "Edwin",
lastName: "felipe",
email: "edwinisfelipe25@gmail.com",
password: "12345678",
});
expect(status).toBe(201);
expect(Object.keys(body)).toContain("name");
expect(Object.keys(body)).toContain("lastName");
expect(Object.keys(body)).toContain("email");
expect(Object.keys(body)).not.toContain("password");
});
it("Must return 400 When data is invalid", async () => {
const { body, status } = await request.post("/register").send({
name: "E",
lastName: "F",
email: "edwinisfelipe",
password: "123456",
});
expect(status).toBe(400);
// expect(Object.keys(body)).toContain("name");
// expect(Object.keys(body)).toContain("lastName");
// expect(Object.keys(body)).toContain("email");
// expect(Object.keys(body)).not.toContain("password");
});
});
describe("Login user", () => {
it("Must return 200 and token, on ok", async () => {
const { body, status } = await request.post("/login").send({
email: "edwinisfelipe25@gmail.com",
password: "12345678",
});
console.log(body);
expect(status).toBe(200);
expect(Object.keys(body)).toContain("token");
expect(Object.keys(body)).toContain("expireDate");
});
it("Must return 404 and email error when email does not exist", async () => {
const { body, status } = await request.post("/login").send({
email: "edwinisfelipe24@gmail.com",
password: "12345678",
});
expect(status).toBe(404);
expect(Object.keys(body)).toContain("fields");
expect(body.fields).toContain("email");
});
it("Must return 400 and password error when password is not correct", async () => {
const { body, status } = await request.post("/login").send({
email: "edwinisfelipe25@gmail.com",
password: "123456",
});
expect(status).toBe(400);
expect(Object.keys(body)).toContain("fields");
expect(body.fields).toContain("password");
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.