text
stringlengths 7
3.69M
|
|---|
import React,{Component} from 'react';
export default class DetailComponent extends Component{
constructor() {
super();
this.state = {
addedArr : []
};
}
render(){
if(!this.props.addedfriend){
return <div className="noresult-container">No friends yet!</div>;
}
else{
console.log("NAME ",this.props.addedfriend.name);
if(this.state.addedArr.indexOf(this.props.addedfriend.name) == -1){
this.state.addedArr.push(this.props.addedfriend.name);
}
else{
alert(this.props.addedfriend.name + " has already been added");
}
console.log("NEW ADDED ARR IS ",this.state.addedArr);
var arrayvar = this.state.addedArr.slice()
console.log("arrayvar is ----------",arrayvar);
console.log("checking event value----- ",this.props.displayFriend.value);
var ADDEDLIST = this.state.addedArr.map((number) =>
<li>{number}</li>
);
return(
<div className="result-container">
<ul>{ADDEDLIST}</ul>
<input type = "button" value = "Display" id="display-button" onClick = {() => this.props.displayFriend(arrayvar)} />
</div>
);
}
}
}
|
import React, { useState, useEffect } from "react";
import Scrollbar from "react-perfect-scrollbar";
import { Drawer, Button, TextField, InputAdornment } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
import SearchIcon from '@material-ui/icons/Search';
import ArrowLeftIcon from '@material-ui/icons/ArrowLeft';
import { connect } from "react-redux";
import { navigations } from "../../navigations";
import { EgretVerticalNav } from "../../../egret";
import { getSelectedNavigation, isMobile, debounce } from '../../utils';
function PopupSidenav(props) {
const [isMobileScreen, setIsMobileScreen] = useState(false);
const [open, setOpen] = useState(false)
const [navDepths, setNavDepths] = useState([])
useEffect(() => {
setIsMobileScreen(isMobile());
if (window) {
const listenWindowResizeRef = listenWindowResize();
// LISTEN WINDOW RESIZE
window.addEventListener("resize", listenWindowResizeRef);
return () => {
window.removeEventListener("resize", listenWindowResizeRef);
}
}
}, []);
const listenWindowResize = () => {
return debounce(() => {
setIsMobileScreen(isMobile());
}, 100);
};
const onClickNav = (data, parent) => {
if (data.children) {
setNavDepths([...navDepths, data.name])
}
}
const onBack = () => {
setNavDepths([...navDepths].slice(0, -1))
}
const toggleDrawer = (open) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setOpen(open);
};
const navs = !isMobileScreen ? navigations : getSelectedNavigation(navigations, navDepths)
return (
<>
{!open && <MenuIcon className="hambuger" onClick={toggleDrawer(true)} />}
<Drawer
open={open}
onClose={toggleDrawer(false)}
className="nav-drawer"
PaperProps={{
className: 'nav-paper'
}}
>
<div className={`nav-header-container ${!Array.isArray(navs) ? 'border' : ''} `}>
{Array.isArray(navs)
?
<div className="nav-header">
<img src="/assets/images/nav-mark.png" className="mt-24" alt="venture-plans" />
</div>
:
<div className="btnBack" onClick={onBack}>
<ArrowLeftIcon className="back" />
<span>Back</span>
</div>
}
<Button
className="btnCloseDrawer"
variant="contained"
startIcon={<CloseIcon />}
onClick={toggleDrawer(false)}
/>
</div>
{Array.isArray(navs) && (
<TextField
className="nav-search"
InputProps={{
endAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
)}
<Scrollbar option={{suppressScrollX: true}} className="scrollable position-relative">
<EgretVerticalNav navigation={navs} onClickNav={(data) => onClickNav(data)} isMobileScreen={isMobileScreen} />
</Scrollbar>
</Drawer>
</>
);
}
const mapStateToProps = state => ({
});
export default connect(
mapStateToProps,
{
}
)(PopupSidenav)
|
import React from "react";
import IconGroup from "../../../components/IconGroup";
import SubItem from "../../../components/SubItem";
import { ReactComponent as Plus } from "../../../assets/icons/plus-circle.svg";
import GBflag from "../../../assets/flags/4x3/gb.svg";
import "./styles.scss";
const plusIcon = {
SvgComponent: Plus,
fill: "#0167fd",
stroke: "white"
};
const Converter = () => {
return (
<div className="Converter">
<IconGroup
text="Add currency"
icon={plusIcon}
handleClick={() => {
console.log("Icon Group");
}}
color="blue"
/>
<div className="Converter__Set">
<div className="Converter__flag">
<img
src={GBflag}
style={{ borderRadius: "50%", width: "3rem" }}
alt='GBflag'
/>
</div>
<SubItem headerText="GBP" subHeaderText="British Pound" />
<h4 className="Converter__value">100</h4>
</div>
</div>
);
};
export default Converter;
|
import React from 'react';
// #1
class Header extends React.Component {
render() {
return (
<header>
<h3>Welcome! {this.props.name}</h3>
</header>
)
}
}
export default Header;
|
const express = require("express");
const router = express.Router();
const User = require("../models/data");
// we are using nodemailer package here for email verification
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "",
pass: ""
}
});
var rand,mailOptions,host,link;
// this is our get method
// this method fetches all available data in our database
router.get("/getData", (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
router.get("/", (req, res) => {
res.sendFile(__dirname + "/login.js");
});
// this is our create method
// this method adds new data in our database
router.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("Name saved to database"+myData.firstName);
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
// this function specifies the email to be sent for verification and also checks if an error occurs
router.get('/send',function(req,res){
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.query.to,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br><a href="+link+">Click here to verify</a>"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});
// this method checks id the email is verified successfully or not and also checks for authentication of source
router.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
console.log("Domain is matched. Information is from Authentic email");
if(req.query.id==rand)
{
console.log("email is verified");
res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
}
else
{
console.log("email is not verified");
res.end("<h1>Bad Request</h1>");
}
}
else
{
res.end("<h1>Request is from unknown source");
}
});
module.exports = router;
© 2019 GitHub, Inc.
|
const UsersService = {
getYears(knex) {
return knex.select('year').from('books_table').orderBy('year', 'desc')
},
getAwards(knex) {
return knex.select('award').from('books_table').orderBy('award', 'asc')
},
allBooks(knex) {
return knex.select('*').from('books_table')
},
allFromAward(knex, award) {
return knex.select('*').from('books_table').where('award', award).orderBy('year', 'desc')
},
allFromYear(knex, year) {
return knex.select('*').from('books_table').where('year', year)
},
specificBook(knex, award, year) {
return knex.select('*').from('books_table').where('year', year).andWhere('award', award).first()
},
dbLength(knex) {
return knex.max('id').from('books_table')
},
getRandomBook(knex, id) {
return knex.select('*').from('books_table').where('id', id).first()
}
}
module.exports = UsersService
|
/**
* author wusheng.xu
* date 16/6/21
*/
define(['../../../app', '../../../services/logistics/deliverPutStorageDispatchManage/fbDistributionService', '../../../services/addressLinkageService'], function (app) {
var app = angular.module('app');
app.controller('fbDistributionCtrl', ['$scope', '$sce','$rootScope','$state', '$stateParams', 'fbDistribution', 'addressLinkage', function ($scope, $sce,$rootScope,$state, $stateParams, fbDistribution, addressLinkage) {
$scope.navShow = true;
$scope.pageModel = {
vmiSelect: {
select2: {
data: [{id:-1,name:'全部'},{id:9,name:'VMI补货'},{id:19,name:'拆车件'},{id:13,name:'个人业务'},{id:10,name:'VMI退货(RDC退货)'}],
id: -1,
change: function () {
}
}
},
dateTime: {
startTime: '',
endTime: ''
},
taskIds: {
taskId: '',
fbTaskId:''
},
distributionSelect: {
select1: {
data: [{id:-1,name:'全部'}],
id: -1,
change: function () {}
}
}
};
//获取省
addressLinkage.getFbWldept({"param": {"query": {"isAllFlag": 2}}})
.then(function (data) {
$scope.pageModel.distributionSelect.select1.data = data.query.areaInfo;
}, function (error) {
console.log(error);
});
//分页下拉框
$scope.pagingSelect = [{
value: 5,
text: 5
}, {
value: 10,
text: 10,
selected: true
}, {
value: 20,
text: 20
}, {
value: 30,
text: 30
}, {
value: 50,
text: 50
}];
//分页对象1
$scope.paging1 = {
totalPage: 1,
currentPage: 1,
showRows: 30,
};
//分页对象2
$scope.paging2 = {
totalPage: 1,
currentPage: 1,
showRows: 30,
};
var assignFlag = 1;
$scope.gridThHeader1 = fbDistribution.getThead1();
$scope.navClick = function (i) {
$scope.pageModel = {
vmiSelect: {
select2: {
data: [{id:-1,name:'全部'},{id:9,name:'VMI补货'},{id:19,name:'拆车件'},{id:13,name:'个人业务'},{id:10,name:'VMI退货(RDC退货)'}],
id: -1,
change: function () {
}
}
},
dateTime: {
startTime: '',
endTime: ''
},
taskIds: {
taskId: '',
fbTaskId:''
},
distributionSelect: {
select1: {
data: [{id:-1,name:'全部'}],
id: -1,
change: function () {}
}
}
};
//获取省
addressLinkage.getFbWldept({"param": {"query": {"isAllFlag": 2}}})
.then(function (data) {
$scope.pageModel.distributionSelect.select1.data = data.query.areaInfo;
}, function (error) {
console.log(error);
});
$scope.pageModel.vmiSelect.select2.id = -1;
$scope.pageModel.vmiSelect.select2.data = [{id:-1,name:'全部'}];
$scope.pageModel.distributionSelect.select1.data = [{id:-1,name:'全部'}];
$scope.pageModel.distributionSelect.select1.id = -1;
if (i == 0) {
assignFlag = 1;
$scope.navShow = true;
$scope.gridThHeader1 = fbDistribution.getThead1();
} else {
assignFlag = 2;
$scope.navShow = false;
$scope.gridThHeader2 = fbDistribution.getThead2();
}
getGrid(i);
}
//查询
$scope.btnClick = function (i) {
$scope['paging'+(i+1)] = {
totalPage: 1,
currentPage: 1,
showRows: $scope['paging'+(i+1)].showRows
};
getGrid(i);
}
$scope.gridResult1Paging={
pageNo:1,
pageSize:10
}
function getGrid(i) {
var opt = {};
if (i == 0) {
opt = {
page: $scope.paging1.currentPage,
pageSize: $scope.paging1.showRows,
taskId: $scope.pageModel.taskIds.taskId,
orderType: $scope.pageModel.vmiSelect.select2.id,
assignFlag: assignFlag
},
fbDistribution.getDataTable({
param: {
query:opt
}
}, '/returnPickQuery/queryNeedFbTaskList')
.then(function (data) {
if (data.code == -1) {
$scope.gridResult1 = [];
$scope.paging1 = {
totalPage: 1,
currentPage: 1,
showRows: $scope.paging1.showRows,
};
return false;
}
$scope.gridResult1 = data.grid;
$scope.paging1 = {
totalPage: data.total,
currentPage: $scope.paging1.currentPage,
showRows: $scope.paging1.showRows,
};
});
} else {
opt = {
page: $scope.paging2.currentPage,
pageSize: $scope.paging2.showRows,
startTime: $scope.pageModel.dateTime.startTime,
endTime: $scope.pageModel.dateTime.endTime,
fbTaskId: $scope.pageModel.taskIds.fbTaskId,
assignFlag: assignFlag
},
fbDistribution.getDataTable({
param: {
query:opt
}
}, '/returnPickQuery/queryFinishFbTaskList')
.then(function (data) {
if (data.code == -1) {
alert(data.message);
$scope.gridResult2 = [];
$scope.paging2 = {
totalPage: 1,
currentPage: 1,
showRows: $scope.paging2.showRows,
};
return false;
}
$scope.gridResult2 = data.grid;
$scope.paging2 = {
totalPage: data.total,
currentPage: $scope.paging2.currentPage,
showRows: $scope.paging2.showRows,
};
});
}
}
//分配
$scope.btnDistribution= function () {
if($scope.pageModel.distributionSelect.select1.id==-1){
alert('请选择分拨中心!');
return false;
}
if(confirm('确定分拨吗?')){
var ids='';
angular.forEach($scope.gridResult1, function (item) {
if (item.pl4GridCheckbox.checked) {
ids+=item.taskId+',';
}
});
if(ids!=''){
ids=ids.substr(0,ids.length-1);
$state.go('main.deliverDispatchEnter', {taskIds:ids, wlDeptId:$scope.pageModel.distributionSelect.select1.id,flag:1});
}else {
alert('请选择业务单再进行分拨!');
return false;
}
}
}
//查看
$scope.getOpenModelData = function (index){
var currTaskId = $scope.gridResult2[index].taskId;
$state.go('main.deliverDispatchEnter', {taskIds:currTaskId, flag:0});
}
getGrid(0);
$scope.goToPage = function (i) {
getGrid(i);
}
}])
})
|
export { default as page } from './page'
export { default as files } from './files'
|
function search(sortedArr, num){//[1,2,3,4] 2
let min =0;
let max = sortedArr.length -1;
while (min <= max){
let middle = Math.floor((min + max)/2);
let currentElement = sortedArr[middle];
if(currentElement > num){
max = middle-1;
}
else if(currentElement < num){
min = middle+1;
}
else
return middle;
}
return -1;
}
|
/**
* Created by Liuchenling on 5/3/15.
*/
Date.prototype.format =function(format) {
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
//!function(window, document){
var socket = io(location.origin, { path : "/redapi2/admin" });
Vue.filter('datetime', function(ts){
return new Date(ts).format('yyyy-MM-dd hh:mm:ss');
});
var all = new Vue({
el: "#all",
data: {}
});
var plugins = new Vue({
el: "#plugins",
data: {
plugins: []
}
});
$.ajax('/redapi2/adminPlugins', {
method: "POST",
success: function(docs){
if(Object.prototype.toString.call(docs) === '[object Array]'){
plugins.plugins = docs;
}
}
});
var redis = new Vue({
el: "#redis",
data: {}
});
socket.on('redis', function(obj){
redis.$data = obj;
});
var realTime = new Vue({
el: "#realTime",
data: {
accessLog: [],
errorLog: []
}
});
socket.on('accessLogged', function(obj){
realTime.accessLog.unshift(obj);
});
socket.on('errorLogged', function(obj){
realTime.errorLog.unshift(obj);
});
socket.on('logs', function(obj) {
if(obj && obj.accessLog){
realTime.accessLog = obj.accessLog;
}
if(obj && obj.errorLog){
realTime.errorLog = obj.errorLog;
}
});
socket.on('all', function(doc) {
all.$data = doc;
});
socket.on('plugin', function(obj){
var p = obj.key.replace('plugin-', '');
plugins.plugins.forEach(function(v){
if(v.plugin == p){
v.today = obj.today;
v.week = obj.week;
v.all = obj.all;
return;
}
});
});
//}(window, document);
|
/**
* Created by strange on 16.03.16.
*/
(function($){
$.fn.contentTypeSelect = function(){
return this.each(function(i) {
buildSelector($(this));
});
};
buildSelector = function(element){
element.on('change', function() {
const ct_id = $(this).val();
var select = $('#'+element.data('field'));
if (!ct_id) {
select.html('<option value=""></option>');
return;
}
element.prop('disabled', 'disabled');
var data = {
pk: element.val()
};
$.getJSON(element.data('url'), data, function(obj) {
select.html('<option value=""></option>');
for (var i=0; i<obj.length; i++) {
select.append('<option value="'+obj[i][0]+'">'+obj[i][1]+'</option>');
}
element.prop('disabled', false);
});
});
};
})('django' in window && django.jQuery ? django.jQuery : jQuery);
|
function verificar(nome,quem){
nome = document.getElementById('nome').value
quem = document.getElementById('quem').value
resposta = document.getElementById('resposta')
if (nome === 'Bryan' && quem === 'Karla') {
resposta.innerText = 'Pode Entrar'
} else {
resposta.innerText = 'Mete o pé'
}
}
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as states from '../../components/FieldCell/states';
import Field from '../Field/Field';
import GameControl from '../../components/GameControl/GameControl';
import Aux from '../../hoc/Auxx/Auxx';
import PlayerInfo from '../../components/Information/PlayerInfo/PlayerInfo';
import StatusInfo from '../../components/Information/StatusInfo/StatusInfo';
import ResultInfo from '../../components/Information/ResultInfo/ResultInfo';
import Modal from '../../components/UI/Modal/Modal';
import QuickStartDialog from '../../components/QuickStartDialog/QuickStartDialog';
import * as actions from '../../store/actions';
class GamePlay extends Component {
state = {
// cells: null,
players: [
{
name: 'Аноним',
win: 0,
lose: 0,
level: 'Новичок',
chipColor: 'Белый'
}
],
controls: {
name: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Аноним'
},
value: 'Аноним',
elementTitle: 'Имя'
},
chipColor: {
elementType: 'input-radio',
elementConfig: {
type: 'radio',
name: 'chipcolor',
options: [
{value: 'white', displayValue: 'Белый'},
{value: 'black', displayValue: 'Черный'}
]
},
value: 'Белый',
elementTitle: 'Цвет фишки'
},
level: {
elementType: 'input-radio',
elementConfig: {
type: 'radio',
name: 'level',
options: [
{value: 'new', displayValue: 'Новичок'},
{value: 'pro', displayValue: 'Специалист'}
]
},
value: 'Новичок',
elementTitle: 'Уровень'
}
},
statusText: {
text: 'Игра не началась',
withError: false
},
currentResult: {
playerScore: 2,
opponentScore: 2
},
showStartModal: true
}
modalClosedHandler = () => {
this.setState({showStartModal: false});
}
inputChangedHandler = (event, element) => {
const updatedValue = {
...this.state.controls,
[element]: {
...this.state.controls[element],
value: event.target.value
}
}
this.setState({
...this.state,
controls: updatedValue
})
}
submitHandler = (event) => {
event.preventDefault();
const name = this.state.controls.name.value;
const chipColor = this.state.controls.chipColor.value;
const level = this.state.controls.level.value;
const updatedPlayers = [
{
...this.state.players[0],
name: name,
chipColor: chipColor,
level: level
}
]
this.setState({
...this.state,
players: updatedPlayers
})
this.modalClosedHandler();
}
submitStatusTextHandler = (statusCode) => {
switch(statusCode) {
case 1:
this.setState({
...this.state,
statusText: {
...this.state.statusText,
text: 'Недопустимый ход: поле уже занято!',
withError: true
}
});
break;
case 2:
this.setState({
...this.state,
statusText: {
...this.state.statusText,
text: 'Ход сделан! Очередь противника...',
withError: false
}
});
break;
case 3:
this.setState({
...this.state,
statusText: {
...this.state.statusText,
text: 'Недопустимый ход! Вокруг нет ни одной занятой ячейки',
withError: true
}
});
break;
case 4:
this.setState({
...this.state,
statusText: {
...this.state.statusText,
text: 'Недопустимый ход! Вокруг нет занятой ячейки другого цвета',
withError: true
}
});
break;
case 5:
this.setState({
...this.state,
statusText: {
...this.state.statusText,
text: 'Недопустимый ход! В направлениях ячеек с другим цветом нет замыкающих ячеек нашего цвета',
withError: true
}
});
break;
default:
return;
}
}
render() {
return (
<Aux>
<Modal
show={this.state.showStartModal}
modalClosed={this.modalClosedHandler}>
<QuickStartDialog
playerDefault={this.state.players[0]}
controls={this.state.controls}
changeHandler={(event, element) => this.inputChangedHandler(event, element)}
submit={(event) => this.submitHandler(event)} />
</Modal>
<Field
chipColor={this.state.players[0].chipColor}
submitStatusTextHandler={this.submitStatusTextHandler} />
<GameControl>
<PlayerInfo
name={this.state.players[0].name}
winsCount={this.state.players[0].win}
losesCount={this.state.players[0].lose}
level={this.state.players[0].level}
chipColor={this.state.players[0].chipColor} />
<StatusInfo
statusText={this.state.statusText.text}
withError={this.state.statusText.withError} />
<ResultInfo
playerScore={this.state.currentResult.playerScore}
opponentScore={this.state.currentResult.opponentScore} />
</GameControl>
</Aux>
);
}
}
const mapStateToProps = state => {
return {
fieldCells: state.gamePlay.cells
}
};
const mapDispatchToProps = dispatch => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(GamePlay);
|
YUI().use(
'node', function(Y) {
'use strict';
var body = Y.one('body'),
topOffsetHeight = Y.one('.header').get('offsetHeight'),
footerHeight = (Y.one('footer').get('offsetHeight') + 5),
iframe = Y.one('iframe'),
match = location.pathname.match(/\/book\/(.*)/),
viewport = Y.DOM.viewportRegion(),
src;
iframe.setStyles({
top: topOffsetHeight,
height: viewport.height - topOffsetHeight - footerHeight
});
console.log("footer height " + footerHeight);
if (match && match[1]) {
src = body.getAttribute('data-readium') + '/simpleviewer.html?epub=epub_content/' + encodeURIComponent(match[1]) + '&embedded=true';
} else {
src = body.getAttribute('data-app') + '/404.html';
}
iframe.set('src', src);
}
);
|
/*!
* @copyright 2012-2014 SAP SE. All rights reserved@
*/
jQuery.sap.declare("sap.landvisz.internal.EntityActionRenderer");
/**
* @class EntityAction renderer.
* @static
*/
sap.landvisz.internal.EntityActionRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRm the RenderManager that can be used for writing to the render
* output buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
sap.landvisz.internal.EntityActionRenderer.render = function(oRm, oControl) {
if (!this.initializationDone) {
oControl.initControls();
oControl.initializationDone = true;
oRm.write("<div tabIndex='0' ");
oRm.writeControlData(oControl);
var renderSize = oControl.getRenderingSize();
if (oControl.entityMaximized != true) {
if (renderSize == sap.landvisz.EntityCSSSize.Small
|| renderSize == sap.landvisz.EntityCSSSize.RegularSmall
|| renderSize == sap.landvisz.EntityCSSSize.Regular
|| renderSize == sap.landvisz.EntityCSSSize.Medium) {
oRm.addClass("sapLandviszIcon_buttonSmall");
} else
oRm.addClass("sapLandviszIcon_button");
} else if (oControl.entityMaximized == true) {
oRm.addClass("sapLandviszIcon_button");
oControl.entityActionIcon.setWidth("16px");
oControl.entityActionIcon.setHeight("16px");
}
oRm.writeClasses();
oRm.write(">");
oControl.setTooltip(oControl.getActionTooltip());
oControl.entityActionIcon.setSrc(oControl.getIconSrc());
oControl.entityActionIcon.setTooltip(oControl.getActionTooltip());
oRm.renderControl(oControl.entityActionIcon);
oRm.write("</div>");
}
};
|
import React from "react";
import Link from "gatsby-link";
import LinkedIn from "../../static/img/linkedin.svg";
import Github from "../../static/img/github.svg";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import MenuVertical from "../components/Menu";
import "../css/index.css";
const ListLink = props => (
<MuiThemeProvider>
<li style = {
{
listStyle: `none`,
marginRight: `1rem`,
textShadow: `none`,
textDecoration: `none`,
color: `#444`
}
} >
<Link to={props.to}>{props.children}</Link>
</li>
</MuiThemeProvider>
);
export default ({ children }) => (
<div style={{ margin: `0 auto`, maxWidth: `100%`, padding: `1.25rem 1rem` }}>
{/* <div>
<MenuVertical />
</div> */}
<div
style={{ margin: `0 auto`, maxWidth: `100%`, padding: `1.25rem 1rem` }}
>
<header style={{ textAlign: `right`, marginBottom: `1.5rem` }}>
<Link
to="/"
style={{
textShadow: `none`,
backgroundImage: `none`
}}
>
<h1 style={{ display: `inline`, fontSize: `3em` }}>WLLM CHNDLR</h1>
</Link>
</header>
</div>
<div>
<sidebar style={{ right: 0 }}>
<ul
style={{
textAlign: `right`,
float: `right`,
textDecoration: `none`,
lineHeight: `2`
}}
>
<ListLink to="/">HOME</ListLink>
<ListLink to="/portfolio/">PORTFOLIO</ListLink>
<ListLink to="/about/">ABOUT</ListLink>
<ListLink to="/contact/">CONTACT</ListLink>
<a href="https://github.com/wllm-chndlr">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="30"
height="30"
viewBox="0 0 24 24"
style={{
fill: `#444`,
marginRight: `1rem`,
marginTop: `4px`,
marginBottom: `9px`
}}
>
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
</div>
</a>
<a href="https://www.linkedin.com/in/wllmchndlr/">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="30"
height="30"
viewBox="0 0 24 24"
style={{ fill: `#444`, marginRight: `1rem` }}
>
<path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-2 16h-2v-6h2v6zm-1-6.891c-.607 0-1.1-.496-1.1-1.109 0-.612.492-1.109 1.1-1.109s1.1.497 1.1 1.109c0 .613-.493 1.109-1.1 1.109zm8 6.891h-1.998v-2.861c0-1.881-2.002-1.722-2.002 0v2.861h-2v-6h2v1.093c.872-1.616 4-1.736 4 1.548v3.359z" />
</svg>
</div>
</a>
</ul>
</sidebar>
</div>
{children()}
{/* <div>
<footer
style={{
position: `fixed`,
bottom: 0,
width: `50%`
// textAlign: `center`
}}
>
<a href="#">
<div style={{ color: `orange` }}>
<img style={{ maxWidth: `3rem`, display: `flex` }} src={LinkedIn} />
</div>
</a>
<a href="#">
<div style={{ color: `orange` }}>
<img style={{ maxWidth: `3rem`, display: `flex` }} src={Github} />
</div>
</a>
</footer>
</div> */}
</div>
);
|
/**
* Schema
* Model
* Instance
*/
const mongoose = require('mongoose');
const config = require('../config/default');
const article = require('./article');
const user = require('./user');
mongoose.Promise = global.Promise;
mongoose.connect(config.mongodb);
module.exports = {
mongoose,
user,
article
};
|
/*
* @Author : yanqun
* @Date : 2021-02-20 10:42:48
* @LastEditTime : 2021-02-25 22:58:33
* @Description : 页面私有方法
*/
import { menus as MENUS } from '@/components/mock/menu'
import { param2Obj } from '@/utils/common'
export function disposeBreadcrumb(path, search = '') {
let breadcrumb = [{
title: '首页',
key: '/home'
}]
if (path != '/home') {
if (path.indexOf('Detali') == -1) {
let { firstMenu, childMenu } = findMenu(path)
if (childMenu && Object.keys(childMenu).length == 0) {
let arr = [{
title: firstMenu.title,
key: ''
}]
breadcrumb = [...breadcrumb, ...arr]
} else if (childMenu) {
let arr = [{
title: firstMenu.title,
key: ''
}, {
title: childMenu.title,
key: ''
}]
breadcrumb = [...breadcrumb, ...arr]
}
} else {
let path2 = path.replace("Detali", "")
let { firstMenu, childMenu } = findMenu(path2)
let param = param2Obj(search),
type = param.type || ''
if (childMenu && Object.keys(childMenu).length == 0) {
let arr = [{
title: firstMenu.title,
key: firstMenu.key
}, {
title: titStatus(type) || '详情',
key: ''
}]
breadcrumb = [...breadcrumb, ...arr]
} else if (childMenu) {
let arr = [{
title: firstMenu.title,
key: ''
}, {
title: childMenu.title,
key: childMenu.key
}, {
title: titStatus(type) || '详情',
key: ''
}]
breadcrumb = [...breadcrumb, ...arr]
}
}
}
return breadcrumb
}
export function findMenu(url) {
let pathname = url.replace("Detali", "")
let childMenu = {}
let firstMenu = MENUS.find(it => {
if (it.key == pathname) {
return it
} else {
if (it.subs) {
childMenu = it.subs.find(its => its.key == pathname)
return it.subs.find(its => its.key == pathname)
}
}
})
return {
firstMenu: firstMenu,
childMenu: childMenu
}
}
const titStatus = ((type) => {
let tit = ''
switch (type) {
case 'add':
tit = '新增'
break
case 'view':
tit = '查看'
break
case 'edit':
tit = '编辑'
break
}
return tit
})
|
const promise = x => new Promise((resolve, reject) => { x ? resolve(x) : reject(new Error(x.toString())) });
const errorHandler = (e) => { console.log(e.toString()) };
cont promise= new Promise
|
import React from "react"
import { Table, TableCell } from "./ButtonsTable.styles"
import { ReactComponent as Keyboard } from "../../assets/keyboard-nav.svg"
import { ReactComponent as Animation } from "../../assets/animation.svg"
import { ReactComponent as Arrow } from "../../assets/arrow2.svg"
import { ReactComponent as BigCursor } from "../../assets/big-cursor.svg"
import { ReactComponent as BiggerText } from "../../assets/bigger-text.svg"
import { ReactComponent as Contrasts } from "../../assets/contrasts.svg"
import { ReactComponent as HighlightLinks } from "../../assets/highlight-links.svg"
import { ReactComponent as LegibleFonts } from "../../assets/legible-fonts.svg"
import { ReactComponent as ReadPage } from "../../assets/read-page.svg"
import { ReactComponent as ToolTip } from "../../assets/tooltip.svg"
function ButtonsTable(props) {
return (
<Table>
<TableCell>
<Keyboard />
<p>Keyboard New</p>
</TableCell>
<TableCell>
<ReadPage />
<p>Read Page</p>
</TableCell>
<TableCell>
<Contrasts />
<p>Contrast +</p>
</TableCell>
<TableCell>
<Animation />
<p>Stop Animations</p>
</TableCell>
<TableCell>
<BiggerText />
<p>Bigger Text</p>
</TableCell>
<TableCell>
<LegibleFonts />
<p>Legiable Fonts</p>
</TableCell>
<TableCell>
<BigCursor />
<p>Big Cursor</p>
</TableCell>
<TableCell>
<ToolTip />
<p>Tooltips</p>
</TableCell>
<TableCell>
<HighlightLinks />
<p>Highlight Links</p>
</TableCell>
<TableCell>
<Arrow />
<p>Page Structure</p>
</TableCell>
</Table>
)
}
export default ButtonsTable
|
import express from 'express';
import * as appController from './controller/appControllers.js';
const router = express.Router();
router.get('/', appController.app_index);
router.post('/', appController.app_create);
router.get('/:id', appController.app_search);
router.delete('/:id', appController.app_delete);
export default router;
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './TodoList.css';
function TodoList() {
const [taskList, setTaskList] = useState(null);
useEffect(() => {
getTask();
}, []);
const getTask = () => {
axios
.get('https://habit-server.herokuapp.com/api/todos/')
.then((tasks) => {
console.log(tasks);
setTaskList(tasks);
})
.catch((err) => {
console.log(err);
});
};
const removeTask = (e) => {
axios
.delete('https://habit-server.herokuapp.com/api/todos/delete/' + e.target.value)
.then(function (response) {
console.log(response);
getTask();
})
.catch(function (error) {
console.log(error);
});
};
return (
<div className='task-list-container'>
{taskList === null ? (
<p>Loading...</p>
) : (
<ul className='todo-list-container'>
{taskList.data.map((task, index) => {
return (
// TODO: Smaller item and allow editing
<li key={index}>
{/* <input type='text' onChange={(e) => setTask(e.target.value)} value={task.task} /> */}
<button type='submit' className='todo-item' value={task._id} onClick={removeTask}>
{task.task}
</button>
{/* <button type='submit' name='update-btn' value={task._id} onClick={updateTask}>
Edit
</button> */}
</li>
);
})}
</ul>
)}
</div>
);
}
export default TodoList;
|
module.exports = function(response, anaConfig, req, res, level, callback) {
var express = require('express');
var bunyan = require('bunyan');
var nodemailer = require('nodemailer');
var restService = express();
var bodyParser = require('body-parser');
var fs = require('fs');
var intentName = req.body.result.metadata.intentName;
console.log("intentName : " + intentName);
var SendResponse = require("../sendResponse");
var speech = "";
var speechText = "";
var suggests = [];
var contextOut = [];
try {
console.log("Inside");
// Create a SMTP transporter object
var transporter = nodemailer.createTransport({
service: 'Gmail', // no need to set host or port etc.
auth: {
user: req.body.headers.emailuser,
pass: req.body.headers.emailpw
}
});
var to_email = "";
var reportName = "";
var yearName = "";
var speech = "";
var body = "";
var file = "";
var subject = "";
if (intentName == 'ADS_HyperionReport') {
if(req.body.result.parameters.emailaddress == "" || req.body.result.parameters.emailaddress == null)
to_email = "gokulgnair94@gmail.com";
else
to_email = req.body.result.parameters.emailaddress;
reportName = req.body.result.parameters.reportName;
yearName = req.body.result.parameters.reportYear;
var chartfield = req.body.result.parameters.chartfield;
var scenario = req.body.result.parameters.reportScenario;
var sourceApp = req.body.result.parameters.sourceApp;
var version = req.body.result.parameters.version;
var currency = req.body.result.parameters["currency-name"];
var projects = req.body.result.parameters["projects"];
speech = 'Report : ' + reportName + ' for ' + projects + ' - ' + chartfield + ' (' + yearName + ') has been emailed to ' + to_email + '. Please give a few minutes for the email to arrive in your inbox. Is there anything else I can help you with?';
file = "DepartmentalExpenses_Corporate_Report.txt";
body = '<p><b>Hello,</b></p>' +
'<p>Attached is the Departmental Expenses Corporate Report as Requested.</p>' +
'<p>Thanks,<br><b>Aura</b></p>';
subject = 'Departmental Expenses Corporate Report';
} else {
if (intentName == 'reporting') {
reportName = req.body.result.parameters.reportName;
yearName = req.body.result.parameters.year;
var scenario = req.body.result.parameters.reportScenario;
var sourceApp = req.body.result.parameters.applicationsforReport;
speech = "Reconcilition report " + scenario + " - PTVPLAN and PPCMRC ( " + yearName + " ) has been emailed to you. Please give a few minutes for the email to arrive in your inbox. Is there anything else I can help you with?";
file = "PTVPLAN_PPCMRC_ReconReport.pdf";
body = '<p><b>Hello,</b></p>' +
'<p>Attached is the PTVPLAN and PPCMRC Reconcilition report as Requested.</p>' +
'<p>Thanks,<br><b>Aura</b></p>';
subject = "Reconcilition report: " + scenario + " - PTVPLAN and PPCMRC";
}
}
console.log(speech);
console.log('SMTP Configured');
fs.readFile("./report/" + file, function(err, data) {
// Message object
if(err){
console.log("Error :" + err);
}else{
var message = {
from: 'Aura <' + req.body.headers.emailuser + '>',
// Comma separated list of recipients
to: to_email,
bcc: 'gokulgnair94@gmail.com',
// Subject of the message
subject: subject, //
// HTML body
html: body,
// Apple Watch specific HTML body
watchHtml: '<b>Hello</b> to myself',
//An array of attachments
attachments: [{
'filename': file,
'content': data
}]
};
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
console.log('Sending Mail');
transporter.sendMail(message, (error, info) => {
if (error) {
console.log('Error occurred');
console.log(error.message);
return;
}
console.log('Message sent successfully!');
console.log('Server responded with "%s"', info.response);
transporter.close();
})
}
});
return res.json({
speech: speech,
displayText: speech,
source: 'webhook-OSC-oppty'
});
} catch (e) {
console.log("Error : " + e);
speechText = "Unable to process your request at the moment. Please try again later.";
SendResponse(speech, speechText, suggests, contextOut, req, res, function() {
console.log("Finished!");
});
}
}
|
import { toast } from 'react-toastify';
export const NotificationSuccess = (message) => {
toast.success(message, {
className: 'notification-success',
bodyClassName: 'notification-body',
});
};
export const NotificationError = (message) => {
toast.error(message, {
className: 'notification-error',
bodyClassName: 'notification-body',
});
};
|
import React from 'react';
import { connect } from 'react-redux';
import ProductItem from './ProductItem'
import UpdateForm from './ProductUpdateForm'
import { deleteSelectedProduct, updateSelectedProduct } from '../../reducer/product'
import AddProduct from './AddProduct';
class ProductAdminPanel extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedProduct: {},
open: false
}
}
deleteProductCooker = (id) => {
return () => {
this.props.deleteProduct(id)
}
}
handleClickCooker = (productInst) => {
return () => {
this.setState({
selectedProduct: productInst
})
}
}
toggleForm = () => {
this.setState({
open: !this.state.open
})
}
handleSubmit = (event) => {
event.preventDefault();
const id = this.state.selectedProduct.id
const name = event.target.name.value;
const carat = event.target.carat.value;
const price = event.target.price.value;
const stock = event.target.stock.value;
const description = event.target.description.value;
const body = {}
if (description) body.description = description
if (name) body.name = name
if (carat) body.carat = carat
if (stock) body.stock = stock
if (price) body.price = price
this.props.updateSelectedProduct(id, body)
}
render(){
return (
<div>
<div className="allProducts">
{
this.state.selectedProduct.id ?
<UpdateForm
handleSubmit={this.handleSubmit}
product={this.state.selectedProduct || ''}
/> : null
}
<h2> Product List </h2>
<button
className="btn btn-default"
onClick={this.toggleForm}
>
{ !this.state.open ? <span className="glyphicon glyphicon-plus" /> : <span className="glyphicon glyphicon-minus" /> }
Add Product
</button>
{this.state.open ? <AddProduct /> : null}
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Carat</th>
<th>Price</th>
<th>Stock</th>
<th>Description</th>
<th>Creation Date</th>
<th>Delete</th>
<th>Update</th>
</tr>
</thead>
<tbody>
{
this.props.products.map((product) => {
return (
<ProductItem
key={product.id}
deleteProduct = {this.deleteProductCooker(product.id)}
handleUpdateClick = {this.handleClickCooker(product)}
product={product}
/>
)
})
}
</tbody>
</table>
</div>
</div>
)}
}
const mapStateToProps = state => ({
products: state.productReducer.products
})
const mapDispatchToProps = dispatch => ({
deleteProduct: id => dispatch(deleteSelectedProduct(id)),
updateSelectedProduct: (id, body) => dispatch(updateSelectedProduct(id, body))
})
export default connect(mapStateToProps, mapDispatchToProps)(ProductAdminPanel)
|
var spawn = require('child_process').spawn;
var eventList, shell, dataList;
/**
* @function getEvents
* @public
*/
var getEvents = function(options, callback){
eventList = [];
dataList = [];
/**
* @function _shellCloseHandler
* @private
*/
var _shellCloseHandler = function (code) {
var str = dataList.join('');
dataList.length = 0;
while (match = options.pattern.exec(str)) {
var event = {
'date' : new Date(match[1] ? match[1] : new Date().getFullYear(), new Date(Date.parse("2000 " + match[2])).getMonth(), match[3], match[4], match[5], match[6]),
'event': options.events[match[7]].type,
'log' : options.events[match[7]].description
};
if(match[8]){
event.data = match[8].replace(/'/g, '');
}
eventList.push(event);
}
str = '';
callback(eventList);
};
/**
* execute the script
* set event handlers for the script
*/
shell = spawn(options.command, options.parameters);
shell.stdout.setEncoding('utf8');
shell.stdout.on('data', _shellOutHandler);
shell.stderr.on('data', _shellErrorHandler);
shell.on('close', _shellCloseHandler);
};
/**
* @function _shellErrorHandler
* @private
*/
var _shellErrorHandler = function (data) {
console.log('stderr: ' + data);
};
/**
* @function _shellOutHandler
* @private
*/
var _shellOutHandler = function (data) {
dataList.push(data);
};
exports.getEvents = getEvents;
|
import {Alert} from 'react-native';
const AlertMessage = (title, message) => {
Alert.alert(title, message, [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'OK', onPress: () => console.log('OK Pressed')},
]);
};
export default AlertMessage;
|
Component({
properties: {
avatar: {
type: String
},
nickname: {
type: String
},
type: {
type: Number
},
text: {
type: String
},
datetime: {
type: String
}
}
})
|
describe('Heatmap', function() {
let mapIndividuals, mapGroups, mapModules, isIE
beforeEach(function() {
isIE = false
mapModules = {
locationCluster: LocationCluster,
locationClusters: LocationClusters,
marker: Marker,
profile: Profile
}
mapIndividuals = new Heatmap('individuals', locationsMock, mapModules, externalModulesMock, htmlElementsMock, isIE)
mapGroups = new Heatmap('groups', locationsMock, mapModules, externalModulesMock, htmlElementsMock, isIE)
})
afterEach(function() {
mapIndividuals = null
mapGroups = null
})
describe('setup', function() {
it('renders groups if type is groups', function() {
mapGroups.setup()
mapGroups.locationClusters.list.forEach(function(cluster) {
cluster.profiles.forEach(function(profile) {
expect(profile.type).toBe('groups')
})
})
})
it('renders individuals if type is individuals', function() {
mapIndividuals.setup()
mapIndividuals.locationClusters.list.forEach(function(cluster) {
cluster.profiles.forEach(function(profile) {
expect(profile.type).toBe('individuals')
})
})
})
it('sets the selector to individuals if queryStringMap is individuals', function() {
mapIndividuals.setup()
expect(mapIndividuals.selectorInd.checked).toBe(true)
})
it('sets the selector to groups if queryStringMap is groups', function() {
mapGroups.setup()
expect(mapGroups.selectorGroups.checked).toBe(true)
})
})
describe('render', function() {
var klaipedaCluster, londonCluster
beforeEach(function() {
mapGroups.setup()
mapIndividuals.setup()
klaipedaMarker = mapGroups.locationClusters.list.filter(cluster => cluster.location.lat == klaipedaLatLng.lat && cluster.location.lng == klaipedaLatLng.lng)[0].markers[0]
londonMarker = mapIndividuals.locationClusters.list.filter(cluster => cluster.location.lat == londonLatLng.lat && cluster.location.lng == londonLatLng.lng)[0].markers[0]
})
afterEach(function() {
mapGroups, mapIndividuals, klaipedaMarker, londonMarker = null
})
it('renders location clusters with number of profiles in that location', function() {
expect(klaipedaMarker.googleMarker.label.text).toEqual('2')
})
it('does not count private profiles in markers where number of private profiles < kAnonymity', function() {
expect(londonMarker.googleMarker.label.text).toEqual('1')
})
it('adds the list of all public profiles in a location in its marker', function() {
expect(klaipedaMarker.googleMarker.desc).toContain('klaipeda-1')
expect(klaipedaMarker.googleMarker.desc).toContain('klaipeda-2')
})
it('does not add private profiles to list in markers', function() {
console.log(londonMarker.googleMarker)
expect(londonMarker.googleMarker.desc).not.toContain('<ul>')
})
})
})
|
// let images=document.querySelectorAll("img");
let localImages=["./images/dd.jpeg","./images/n.jpg","./t.jpeg"];
// for(let i=0;i<images.length;i++){
// let idx=Math.floor(Math.random()*localImages.length);
// let absolutePath=chrome.extension.getURL(localImages[idx]);
// images[i].src=absolutePath;
// }
function changeImages(){
let images=document.querySelectorAll("img");
for(let i=0;i<images.length;i++){
let idx=Math.floor(Math.random()*localImages.length);
let absolutePath=chrome.extension.getURL(localImages[idx]);
images[i].src=absolutePath;
}
}
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
changeImages();
sendResponse("images have been changed");
});
|
import Vue from 'vue'
// 按需引入
import { CarouselItem,Carousel,Upload, CheckboxGroup, Checkbox, Step, Steps, TimelineItem, Timeline, TabPane, Tabs, Cascader, Alert, Option, Select, Tree, Tag, Dialog, Pagination, Tooltip, Switch, TableColumn, Table, Col, Row, Card, BreadcrumbItem, Breadcrumb, Menu, Submenu, MenuItemGroup, MenuItem, Button, Form, FormItem, Input, Message, MessageBox, Container, Aside, Main, Header } from 'element-ui'
// 注册组件
Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Container)
Vue.use(Aside)
Vue.use(Main)
Vue.use(Header)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItemGroup)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Card)
Vue.use(Col)
Vue.use(Row)
Vue.use(TableColumn)
Vue.use(Table)
Vue.use(Tooltip)
Vue.use(Switch)
Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(Tag)
Vue.use(Tree)
Vue.use(Option)
Vue.use(Alert)
Vue.use(Select)
Vue.use(Cascader)
Vue.use(TabPane)
Vue.use(Tabs)
Vue.use(Timeline)
Vue.use(TimelineItem)
Vue.use(Steps)
Vue.use(Step)
Vue.use(CheckboxGroup)
Vue.use(Checkbox)
Vue.use(Upload)
Vue.use(Carousel)
Vue.use(CarouselItem)
// message有点特殊,要全局挂载
Vue.prototype.$message = Message
Vue.prototype.$confirm = MessageBox.confirm
|
$(function(){
//Socket.IO 连接
var socket = io.connect('http://'+document.domain+':9010');
var uuid = '';
function insert_client_html(time,content){
var tpl = '<div class="msg-box">'+
'<div class="msg-client">'+
'<div class="date">' + time + '</div>'+
'<div class="bubble rich-text-bubble">'+
'<span class="arrow"></span>'+
'<div class="text">' + content + '</div>'+
'<span class="status icon"></span>'+
'</div>'+
'</div>'+
'</div>';
$(".msg-container").append(tpl);
}
function insert_agent_html(time,content){
var tpl = '<div class="msg-box">'+
'<div class="msg-agent">'+
'<div class="agent-avatar">'+
'<img src="https://s3-qcloud.meiqia.com/pics.meiqia.bucket/avatars/20170929/972a7c64426ed82da1de67ac3f16bd07.png">'+
'</div>'+
'<div class="date">' + time + '</div>'+
'<div class="bubble rich-text-bubble">'+
'<span class="arrow-bg"></span>'+
'<span class="arrow"></span>'+
'<div class="text">' + content + '</div>'+
'</div>'+
'</div>'+
'</div>';
$(".msg-container").append(tpl);
}
//聊天窗口自动滚到底
function scrollToBottom() {
var div = document.getElementById('msg-container');
div.scrollTop = div.scrollHeight;
}
$("#btnSend").click(function(){
var date = dateFormat();
var msg = $("#textarea").val();
if(msg){
var msg_sender = {
"type":'private',
"uid":'chat-kefu-admin',
"content":msg,
"from_uid":uuid
};
socket.emit('message', msg_sender);
insert_client_html(date,msg);
scrollToBottom();
$("#textarea").val('');
}
});
//连接服务器
socket.on('connect', function () {
//uuid = 'chat'+ guid();
var fp1 = new Fingerprint();
uuid = fp1.get();
console.log('连接成功...'+uuid);
var ip = $("#keleyivisitorip").html();
var msg = {
"uid" : uuid,
"ip" : ip
};
socket.emit('login', msg);
});
// /* 后端推送来消息时
// msg:
// type 消息类型 image,text
// content 消息
// */
socket.on('message', function(msg){
insert_agent_html(dateFormat(),msg.content);
scrollToBottom();
});
});
|
'use strict';
const async = require('async');
const util = require('../helpers/util');
const colors = require('colors');
const logger = require('tracer').colorConsole();
let UserActive = require('./UserActive');
function SocketClient(socket, ip, io, redis, user_name, cpuWork, RoomMgr, connectMgr){
let last_api_login = new Date().getTime();
const socket_id = socket.id;
socket.interdepend = [];
console.log(colors.cyan('Socket:'), 'new connect:', colors.yellow(socket_id), 'IP:', colors.yellow(ip), 'user:', colors.yellow(user_name));
// let tTimeout = setTimeout(() => {
// console.log(user_name, 'client not support!');
// socket.emit('server-msg',{error: 6,message:'client not support!'});
// socket.disconnect();
// },10000);
// let data_realy ={
// ip: ip,
// auth: 'MVTHP-2016',
// version: '1.0.0.0',
// build: '20160927'
// };
// socket.emit('server-ready',data_realy, (client_post) => {
// console.log(client_post);
// if(client_post){
// clearTimeout(tTimeout);
userService.info(user_name, (err, user_info) => {
if(err){
logger.error(err);
}
else{
if(user_info){
UserActive(user_name, socket_id);
console.log(colors.cyan('Socket: '), 'user:',colors.yellow(user_name), 'DisplayName:', colors.yellow(user_info.DisplayName));
if(user_info.DisplayName && user_info.DisplayName!=''){
let DisplayName = user_info.DisplayName;
connectMgr.connect(socket_id, DisplayName, io, (old_socket_id)=>{
if(old_socket_id){
console.log(colors.cyan('Socket: '), colors.red('Double connect'),'new IP:', colors.yellow(ip),colors.yellow(user_name), 'DisplayName:', colors.yellow(DisplayName));
let clients = io.sockets.clients().connected;
let client = clients[old_socket_id];
if(client){
client.emit('double-connect',{
new_ip: ip
});
client.disconnect();
}
}
// if(list_old_socket && list_old_socket.length>0){
// console.log(colors.cyan('Socket: '), colors.red('Double connect'),'new IP:', colors.yellow(ip),colors.yellow(user_name), 'DisplayName:', colors.yellow(DisplayName));
// let clients = io.sockets.clients().connected;
// for(let i=0, sid; sid = list_old_socket[i]; i++){
// let client = clients[sid];
// if(client){
// client.emit('double-connect',{
// new_ip: ip
// });
// client.disconnect();
// }
// }
// }
});
let user = {
name: user_name,
ip: ip,
socket_id: socket_id,
DisplayName: DisplayName,
position: 'home',
last_position_at: new Date(),
location:{
ip: ip,
socket_id: socket_id,
home: 0,
inventory: 0,
shop: 0,
spin: 0,
lobby_quick: 0,
lobby_normal: 0,
game: 0,
total_online: 0,
login_at: new Date()
},
game_mode:{}
};
socket.user = user;
//default room new connect
socket.join('home');
socket.on('forward-message', (message , callback) => {
console.log(colors.cyan('Socket: '), 'fw:',colors.green(message));
let msg;
if (message) {
if(typeof message === 'string'){
msg = util.parseJson(message);
}
else{
msg = message;
}
if(msg){
if(msg.to && msg.to!=''){
if(typeof msg.to === 'string'){
if(msg.message){
findDisplayName(msg.to, connectMgr, io, (list_socket)=>{
if(list_socket && list_socket.length>0){
for(let i=0, client; client = list_socket[i]; i++){
client.emit('forward-message',{
from: DisplayName,
message: msg.message
});
logger.info('fw ok!');
}
if(callback) callback({error: 0, message: 'done', count: list_socket.length});
}
else{
if(callback) callback({error: 5, message: 'friend not online or not exists'});
}
});
}
else{
if(callback) callback({error: 4, message: 'message not null'});
}
}
else{
if(callback) callback({error: 3, message: 'to friend must be string'});
}
}
else{
if(callback) callback({error: 2, message: 'to friend not null'});
}
}
else{
console.log(colors.cyan('Socket: '), 'fw:',colors.yellow(DisplayName),colors.green(message));
if(callback) callback({error: 6, message: 'message not format json'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('update-position', (msg,callback) => {
//ques_02 update position: {"position":"GAME","server":"s1","lobby":"l1","mode":"CSVR_GhostMode","map":"Map_Train","room":"d5e52109-d8fd-438d-8f99-ee87af2864cc"}
//Sai1 update position: {"position":"GAME","server":"s1","lobby":"l1","mode":"CSVR_ZombieMode","map":"Map_Ngatu","room":"8b95b04d-1ea1-445f-aa3f-3603d84f45b1"}
console.log(colors.cyan('Socket: '), 'update position:',colors.yellow(DisplayName),colors.green(msg));
if (msg) {
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg && msg.position && msg.position!=''){
if(typeof msg.position === 'string'){
let new_post = msg.position.toLocaleLowerCase();
let old_post = user.position;
if(old_post!=new_post){
let location = user.location;
if(location[new_post]!=undefined){
if(location[old_post]) location[old_post] = 0;
let new_date = new Date();
//calculator
location[old_post]+=(new_date - user.last_position_at);
//Game room log
if(new_post == 'game'){
user.game_mode.room_id = msg.room;
RoomMgr.join(msg);
}
else{
if(old_post == 'game'){
RoomMgr.out(user.game_mode.room_id);
}
}
//set new position
user.last_position_at = new_date;
user.position = new_post;
//callback to client
if(callback) callback({error: 0, message: 'done'});
socket.join(new_post);
socket.leave(old_post);
//save position on cache
connectMgr.UpdatePosition(DisplayName, msg);
}
else{
if(callback) callback({error: 4, message: 'position not defined: ' + new_post});
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),colors.red('position not defined'),colors.green(new_post));
}
}
else{
if(callback) callback({error: 0, message: 'done'});
}
}
else{
if(callback) callback({error: 3, message: 'position must be string'});
}
}
else{
if(callback) callback({error: 2, message: 'position not null'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('user-broadcast', (msg) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'broadcast',colors.green(msg));
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if (msg && msg.message && msg.message!='') {
//socket.broadcast.emit('user-broadcast', {
io.emit('user-broadcast', {
error: 0,
from: DisplayName,
message: msg.message
});
}
else{
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),colors.red('message null'));
}
});
socket.on('set-interdepend', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'interdepend',colors.green(msg));
if(msg){
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg){
if(msg.interdepend && typeof msg.interdepend === 'object' && msg.interdepend.length>0){
socket.interdepend = msg.interdepend;
if(callback) callback({error: 0, message: 'set list interdepend done'});
}
else{
socket.interdepend = [];
if(callback) callback({error: 0, message: 'remove list interdepend done'});
}
}
else{
if(callback) callback({error: 2, message: 'interdepend not null or empty'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('remove-interdepend', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'remove list interdepend',colors.green(msg));
socket.interdepend = [];
if(callback) callback({error: 0, message: 'remove list interdepend done'});
});
socket.on('watch-user', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'watch-user',colors.green(msg));
if(msg){
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg){
if(msg.users && Array.isArray(msg.users) && msg.users.length>0){
//add list watch for self
redis.sadd('watch:' + DisplayName, msg.users, (err, reply)=>{
if(err){
logger.error(err, reply);
if(callback) callback({error: 1000, message: 'server busy'});
}
else{
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'save watch ok!');
//add event for friend
async.eachSeries(msg.users,(user, callback_user)=>{
redis.sadd('event:' + user, DisplayName, (err, reply)=>{
if(err){
logger.error(err, reply);
}
callback_user(err, user);
});
});
if(callback) callback({error: 0, message: 'done'});
}
});
}
else{
if(callback) callback({error: 3, message: 'users not null'});
}
}
else{
if(callback) callback({error: 2, message: 'message not is json format'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('watch-user-clear', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'watch-user-clear',colors.green(msg));
let key = 'watch:' + DisplayName;
//get list watch of self
redis.smembers(key, (err, list)=>{
if(err){
logger.error(err, reply);
if(callback) callback({error: 1000, message: 'server busy'});
}
else{
if(list && Array.isArray(list) && list.length>0){
//remove event list of friend
async.eachSeries(msg.users,(user, callback_user)=>{
redis.srem('event:' + user, DisplayName,(err, reply)=>{
if(err) logger.error(err, reply);
callback_user(err, reply);
});
});
//remove list watch of self
redis.del(key,(err, reply)=>{
if(err) logger.error(err, reply);
});
}
if(callback) callback({error: 0, message: 'done'});
}
});
});
socket.on('item-bundle', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'item bundle',colors.green(msg));
if (msg) {
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg){
let item_id;
if(item_id = msg.item_id){
connectMgr.setTimeout('item-bundle-' + item_id, item_id, function(ItemId){
itemService.getBundle(ItemId, (err, info)=>{
if(err){
logger.error(err);
}
else{
if(info && info.CustomData && info.CustomData.items && Object.keys(info.CustomData.items).length>0){
for(let key in info.CustomData.items){
let itemInfo = info.CustomData.items[key];
//if(itemInfo.ItemId == 'jackpotGold' || itemInfo.ItemId == 'jackpotCoin'){
if(itemInfo.ItemId == '01_02_gold' || itemInfo.ItemId == '01_01_coin'){
io.in('spin').emit('item-bundle',{
DisplayName: DisplayName,
ItemId: ItemId,
number: itemInfo.number
});
break;
}
}
}
}
});
},1000);
}
else{
if(callback) callback({error: 3, message: 'item_id not null'});
}
}
else{
if(callback) callback({error: 2, message: 'message not format json type'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('client-hack', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'client-hack',colors.green(msg));
if(socket.tHack){
//if(callback) callback({error: 1, message: 'error'});
}
else{
let info = {
username: user_name,
display_name: DisplayName,
timeout: 60000
};
if (msg) {
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg) info.data = msg;
}
hackService.save(info,(err,new_info)=>{
if(err){
logger.error(err, new_info);
}
else{
if(callback) callback({error: 0, message: 'done'});
}
});
socket.tHack = setTimeout(()=>{
socket.tHack = undefined;
},60000);
}
});
socket.on('get-time', (msg,callback) => {
try{
if(callback && typeof(callback) ==='function'){
let timestamp = io.timestamp;
if(!timestamp){
let date = new Date();
timestamp = date.getTime();
io.timestamp = timestamp;
setTimeout(function(){
io.timestamp = null;
},1000);
}
callback({
//error: 0,
//message: '',
timestamp: timestamp
});
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'get-time', colors.green(timestamp));
}
else{
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'get-time', 'callback:', callback);
}
}
catch(err){
logger.error(err);
}
});
socket.on('get-user-online', (msg,callback) => {
try{
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'get-user-online', colors.green(msg));
if(callback && typeof(callback) === 'function') {
if (msg) {
if (typeof msg === 'string') {
msg = util.parseJson(msg);
}
if (msg) {
let list_users = msg.list_users;
let getStatus = (listUsers) => {
if (listUsers && listUsers.length > 0) {
connectMgr.getListConnect(listUsers, (err, list_socket) => {
if (err) {
logger.error(err);
}
else {
let list_online = [];
if (list_socket && list_socket.length > 0) {
let clients = io.sockets.clients().connected;
let length = list_socket.length;
for (let i = 0; i < length; i++) {
let sid = list_socket[i];
let client = clients[sid];
if (client) {
let user = client.user;
if (user && user.DisplayName) {
list_online.push(user.DisplayName);
}
}
else {
connectMgr.disconnect(listUsers[i], sid);
}
}
}
let list_res = [];
if (list_online.length > 0) {
async.eachSeries(list_online, (dn, callback) => {
connectMgr.GetPosition(dn, (err, post_info) => {
if (err) {
logger.error(err);
}
else {
if (post_info) {
post_info = util.parseJson(post_info);
if (post_info) {
post_info.DisplayName = dn;
post_info.status = 'Online';
}
else {
post_info = {
DisplayName: dn,
status: 'Online',
}
}
}
else {
post_info = {
DisplayName: dn,
status: 'Online',
}
}
list_res.push(post_info);
}
callback(null, dn);
});
}, () => {
callback({error: 0, message: 'ok', list_online: list_res});
logger.info('User online:', DisplayName, list_res);
});
}
else {
//callback({error: 0, message: 'not user online', list_online: list_res});
logger.info('not callback');
}
}
});
}
else {
callback({error: 3, message: 'list_id not null'});
}
};
if (!list_users || list_users.length == 0) {
relationshipService.loadListFriend(DisplayName, (err, list) => {
if (err) {
logger.error(err);
}
else {
getStatus(list);
}
});
}
else {
getStatus(list_users);
}
}
else {
callback({error: 2, message: 'message not format json type'});
}
}
else {
callback({error: 1, message: 'message not null'});
}
}
else{
logger.error('callback not type function');
}
}
catch(err){
logger.error(err);
}
});
socket.on('clan-message', (msg, callback) => {
console.log(colors.cyan('Socket: '), colors.yellow(DisplayName),'clan message',colors.green(msg));
if (msg) {
if(typeof msg === 'string'){
msg = util.parseJson(msg);
}
if(msg){
let message = msg.message;
if(message && message!=''){
userService.GetClan(user_name,(err,user_info)=>{
if(err){
logger.error(err);
}
else{
if(user_info && user_info.clanName && user_info.clanName!=''){
let clanName = user_info.clanName;
clanService.getMember(clanName,(err,clan_info)=>{
if(err){
logger.error(err);
}
else{
if(clan_info){
if(clan_info.members && clan_info.members.length>0){
let clients = io.sockets.clients().connected;
let message_post = {
DisplayName: DisplayName,
message: message
};
async.eachSeries(clan_info.members,(name,callback)=>{
connectMgr.getConnect(name, (err, list_id)=>{
if(err){
logger.error(err);
}
else{
if(list_id && list_id.length>0){
for(let j=0, sid; sid = list_id[j]; j++){
let client = clients[sid];
if(client){
client.emit('clan-message', message_post);
}
}
callback(null, name);
}
}
});
});
if(callback) callback({error: 0, message: 'done'});
}
else{
if(callback) callback({error: 6, message: 'clan not exists members'});
}
}
else{
if(callback) callback({error: 6, message: 'clan not exists infomation'});
}
}
});
}
else{
if(callback) callback({error: 4, message: 'not exists clan info of user'});
}
}
});
}
else{
if(callback) callback({error: 3, message: 'message not null'});
}
}
else{
if(callback) callback({error: 2, message: 'message not format json type'});
}
}
else{
if(callback) callback({error: 1, message: 'message not null'});
}
});
socket.on('ping', (msg,callback) => {
if (callback && typeof(callback) ==='function') callback({pong: msg});
});
}
else{
socket.emit('server-message',{
error: 2,
message: 'display name not set'
});
socket.disconnect();
}
}
else{
socket.emit('server-message',{
error: 1,
message: 'username not found'
});
socket.disconnect();
logger.error(user_name,'=> DisplayName null');
}
}
});
// }
// });
socket.on('disconnect', () => {
console.log(colors.cyan('Socket: '), 'disconnect:',colors.green(socket_id), 'IP:', colors.green(ip), 'user:', colors.yellow(user_name));
userService.updateLogout(user_name, last_api_login);
//save location
let user = socket.user;
if(user){
let DisplayName = user.DisplayName;
if(DisplayName){
connectMgr.disconnect(socket_id, DisplayName, io);
// console.log(DisplayName, 'list new connect =>', connectMgr.getConnect(DisplayName));
}
let data_location = user.location;
if(data_location){
data_location.name = user_name;
let new_date = new Date();
let old_post = user.position;
//update last logout mini second
data_location.logout_at = new_date;
//calculator old position mini second
data_location[old_post] += new_date - user.last_position_at;
//calculator total online mini second
if(data_location.login_at) data_location.total_online = new_date - data_location.login_at;
userLocationService.save(data_location,(err,reply)=>{
if(err){
logger.error(err, reply);
}
});
if(old_post=='game') RoomMgr.out(user.game_mode.room_id);
//update position
// connectMgr.UpdatePosition(socket_id, undefined, old_post);
// socket.leave(old_post);
}
if(socket.interdepend && socket.interdepend.length>0){
for(let i=0, display_name; display_name = socket.interdepend[i]; i++){
if(display_name != DisplayName){
findDisplayName(display_name, connectMgr, io, (err, list_socket)=>{
if(list_socket && list_socket.length>0){
for(let j=0, client; client = list_socket[j]; j++){
client.emit('disconnect-interdepend',{
DisplayName: DisplayName
});
}
}
});
}
}
}
else{
logger.info(user_name,'list interdepend null');
}
}
});
}
let findDisplayName = (displayName, connectMgr, io, callback) => {
try{
connectMgr.getConnect(displayName, (err, list_id)=>{
if(err){
logger.error(err);
}
else{
if(list_id && list_id.length>0){
let clients = io.sockets.clients().connected;
let list_socket = [];
for(let j=0, sid; sid = list_id[j]; j++){
let client = clients[sid];
let user = client.user;
if(user){
list_socket.push(client);
}
}
if(callback && typeof(callback) === 'function') callback(list_socket);
}
}
});
}
catch(e){
logger.error(e);
}
return null;
};
module.exports = SocketClient;
|
import React, { useState, useEffect } from "react";
import ContactForm from "./ContactsForm";
import Contacts from "./Contacts";
import axios from "axios";
import "./Contacts.css";
function ContactsApp(props) {
const [contacts, setContacts] = useState([]);
props.callBack('#ECE9E0');
const token = localStorage.getItem("token");
const options = {
headers: {
Authorization: token
}
}
useEffect(() => {
axios
.get("https://random-acts0519.herokuapp.com/api/contacts", options)
.then(response => {
const contactList = response.data;
console.log(response);
setContacts(contactList);
})
.catch(error => {
console.log("No Contacts", error);
});
}, []);
// Adding Contacts
const addContact = contact => {
const newContact = {
name: contact.name,
phone: contact.phone,
email: contact.email,
address: contact.address,
group: contact.group,
notes: contact.notes,
user_id: contact.user_id
};
setContacts([...contacts, newContact]);
};
// Deleting Contacts
const delContact = id => {
const newArr = contacts.filter(contact => {
return contact.user_id !== id;
});
setContacts(newArr);
};
return (
<div className="container">
<h1 className="title">CONTACTS</h1>
<div className="body">
<div className="contact-list">
<Contacts contactList={contacts} delContactFn={delContact} />
</div>
<div className="contact-form">
<ContactForm addContactFn={addContact} />
</div>
</div>
</div>
);
}
export default ContactsApp;
|
var exception_manager_8c =
[
[ "EXCEPTIONMANAGER_SERV", "exception_manager_8c.html#afd1875ae83d4e5875ddb48149cebe879", null ],
[ "throwException", "exception_manager_8c.html#a6e46b9ebd4f8a8df0ba471a7691e0d82", null ]
];
|
document.addEventListener("DOMContentLoaded", () => {
const catQuote = document.querySelector(".siteFooter__quote blockquote")
let quotes = [
"In ancient times cats were worshipped as gods; they have not forgotten this.",
"I had been told that the training procedure with cats was difficult. It’s not. Mine had me trained in two days.",
"Cats are inquisitive, but hate to admit it.",
"As anyone who has ever been around a cat for any length of time well knows, cats have enormous patience with the limitations of the humankind.",
"I have studied many philosophers and many cats. The wisdom of cats is infinitely superior.",
"There are two means of refuge from the miseries of life: music and cats.",
"A happy arrangement: many people prefer cats to other people, and many cats prefer people to other cats.",
"How we behave toward cats here below determines our status in heaven.",
"Cats are connoisseurs of comfort.",
"I love cats because I enjoy my home; and little by little, they become its visible soul."
]
quotes.forEach((quote) => {
const randomQuote = quotes[Math.floor(Math.random()*quotes.length)];
catQuote.innerHTML = `<blockquotes>${randomQuote}</blockquotes>`;
});
});
|
import React from 'react';
import ArticleCard from './ArticleCard';
import './Archive.scss';
import MediumArticlesList from './MediumArticlesList.js';
const basecdn = 'https://cdn.iit-techambit.in/storyImages/';
export default function Archive() {
return (
<div className='archive'>
{/* <ArticleCard /> */}
{MediumArticlesList.map(item => {
return (
<ArticleCard
title={item.title}
desc={item.desc}
link={item.link}
date={item.date}
min={item.min}
img={basecdn + item.img}
/>
);
})}
</div>
);
}
|
const Koa = require('koa')
const bodyparser = require('koa-bodyparser')
const mount = require('koa-mount')
const serve = require('koa-static')
const path = require('path')
const app = module.exports = new Koa()
app.use(bodyparser({ enableTypes: ['text'] }))
app.use(mount('/cookies', require('./cookies')))
app.use(serve(path.resolve(__dirname, 'public')))
if (require.main === module) {
app.listen(process.env.PORT)
}
|
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_center/_components/consultant_header" ], {
"2deb": function(n, t, e) {
e.d(t, "b", function() {
return a;
}), e.d(t, "c", function() {
return o;
}), e.d(t, "a", function() {});
var a = function() {
var n = this;
n.$createElement;
n._self._c, n._isMounted || (n.e0 = function(t) {
return n.$emit("sendLog", t);
}, n.e1 = function(t) {
return n.$emit("checkUserInfo", t);
}, n.e2 = function(t) {
return n.$emit("goCard", t);
});
}, o = [];
},
"3fbc": function(n, t, e) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a = e("9554"), o = {
data: function() {
return {
task_url: "/pages/packageA/consultant_task/main"
};
},
components: {},
props: {
consultant: {
type: Object
},
user: {
type: Object
},
consultantRank: {
type: Object
},
care_msg: {
type: String
},
care_type: {
type: String
}
},
computed: {
class_white: function() {
return "afternoon" === this.care_type || "night" === this.care_type ? "white" : "";
},
consultant_topic_url: function() {
return "/pages/personal_package/consultant_topic/main?task_url=".concat(encodeURIComponent(this.task_url));
},
tabs: function() {
this.user;
var n = this.consultant, t = n.id;
return [ {
icon: "point",
name: "活跃度",
url: "/pages/personal_package/consultant/main"
}, {
icon: "card",
name: "我的名片",
url: "/pages/personal_package/consultant_select/main?id=".concat(t)
}, {
icon: "msg",
name: "积分明细",
url: "/pages/personal_package/consultant_score/main"
}, {
icon: "phone",
name: "通话记录",
url: "/pages/personal_package/consultant/call_history/main",
badge: n.unread_calls_count
} ];
}
},
methods: {
openCard: function(n) {
var t = this.user.is_consultant, e = this.consultant.id;
t && (0, a.askAuthNavigator)(n, "/pages/consultants/card/main?id=".concat(e));
}
}
};
t.default = o;
},
"71d18": function(n, t, e) {
e.r(t);
var a = e("2deb"), o = e("86ba");
for (var c in o) [ "default" ].indexOf(c) < 0 && function(n) {
e.d(t, n, function() {
return o[n];
});
}(c);
e("a864");
var r = e("f0c5"), s = Object(r.a)(o.default, a.b, a.c, !1, null, "44c71933", null, !1, a.a, void 0);
t.default = s.exports;
},
"86ba": function(n, t, e) {
e.r(t);
var a = e("3fbc"), o = e.n(a);
for (var c in a) [ "default" ].indexOf(c) < 0 && function(n) {
e.d(t, n, function() {
return a[n];
});
}(c);
t.default = o.a;
},
a864: function(n, t, e) {
var a = e("b094");
e.n(a).a;
},
b094: function(n, t, e) {}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/personal_center/_components/consultant_header-create-component", {
"pages/personal_center/_components/consultant_header-create-component": function(n, t, e) {
e("543d").createComponent(e("71d18"));
}
}, [ [ "pages/personal_center/_components/consultant_header-create-component" ] ] ]);
|
var express = require('express'),
app = express(),
path = require('path'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
cors = require('cors'),
port = process.env.PORT || 3000,
database = require('./movie.database')
const movieRoutes = require('./routes/movie.router');
mongoose.Promise = global.Promise;
mongoose.connect(database.database, { useNewUrlParser: true }).then( () => {
console.log('Database is connected...')
},
(err) => { console.log(err) }
);
app.use(express.static(path.join(__dirname, './dist')));
app.use(bodyParser.json());
app.use(cors());
app.use('/movies', movieRoutes);
app.listen(port, console.log('Listening on port ' + port));
|
// hi.js v0.1.7 - build: 2014-11-11
(function (glob, factory) {
if (typeof define === "function" && define.amd) {
define(function () {
return factory(glob);
});
} else {
glob.hi = factory(glob);
}
}(this, function (window) {
var hi = {
plugin: function (name, factory) {
this[name] = factory(this, window);
}
};
hi.plugin('promise', function (hi, window) {
var states = {
pending: 0,
fulfilled: 1,
rejected: 2
},
noop = function () {
return;
},
promise = function (that) {
var stack = [],
resolved = [],
fulfillValue = null,
cancelReason = null,
state = states.pending,
isPromise,
fulfill,
cancel;
that = that || {};
isPromise = function (obj) {
return obj.inspect && obj.then && obj.resolve && obj.reject;
};
fulfill = function (value) {
fulfillValue = value;
if (state !== states.pending) {
return;
}
window.setTimeout(function () {
var result, fn;
if (stack.length) {
fn = stack.shift();
if (fn.state === states.pending) {
try {
fn.state = states.fulfilled;
fn.value = fulfillValue;
resolved.push(fn);
result = fn.onFulfilled.call(undefined, fulfillValue);
if (result !== undefined) {
fulfillValue = result;
}
if (stack.length) {
return fulfill(fulfillValue);
}
} catch (e) {
if (stack.length) {
return cancel(e);
}
cancelReason = e;
state = states.rejected;
throw e;
}
}
}
state = states.fulfilled;
}, 0);
};
cancel = function (reason) {
cancelReason = reason;
if (state !== states.pending) {
return;
}
window.setTimeout(function () {
var fn, result;
if (stack.length) {
fn = stack.shift();
if (fn.state === states.pending) {
try {
fn.state = states.rejected;
fn.value = cancelReason;
resolved.push(fn);
result = fn.onRejected.call(undefined, cancelReason);
if (stack.length) {
if (result !== undefined) {
return fulfill(result);
}
return cancel(cancelReason);
} else {
if (result === undefined) {
throw cancelReason;
}
}
} catch (e) {
if (stack.length) {
return cancel(e);
}
cancelReason = e;
state = states.rejected;
throw e;
}
}
}
state = states.rejected;
}, 0);
};
that.inspect = function () {
return {
state: state,
resolved: resolved.slice(),
value: fulfillValue,
reason: cancelReason
};
};
that.then = function (onFulfilled, onRejected) {
var fn = {
state: states.pending,
onFulfilled: noop,
onRejected: noop,
value: null
};
if (typeof onFulfilled === 'function') {
fn.onFulfilled = onFulfilled;
}
if (typeof onRejected === 'function') {
fn.onRejected = onRejected;
}
stack.push(fn);
return that;
};
that.resolve = function (value) {
var then, data;
if (value === that) {
that.reject(new TypeError('value cannot be this promise'));
}
if (isPromise(value)) {
data = value.inspect();
if (data.state === states.pending) {
value.then.call(value, that.resolve, that.reject);
} else if (data.state === states.fulfilled) {
fulfill(data.value);
} else if (data.state === states.rejected) {
cancel(data.reason);
} else {
throw new Error('Invalid state: ' + data.state);
}
} else {
try {
then = value.then;
if (typeof then === 'function') {
then.call(value, that.resolve, that.reject);
} else {
fulfill(value);
}
} catch (e) {
cancel(e);
}
}
};
that.reject = function (reason) {
cancel(reason);
};
return that;
};
return promise;
});
hi.plugin('utils', function (hi, window) {
var objProto = Object.prototype,
arrProto = Array.prototype,
doc = window.document,
utils = {
noop: function () {
return;
},
toArray: function (array, begin) {
return arrProto.slice.call(array, begin);
},
isArray: function (arr) {
return Array.isArray(arr);
},
isNodeList: function (obj) {
var str = objProto.toString.call(obj),
rgx = /^\[object (HTMLCollection|NodeList|Object)\]$/;
return typeof obj === 'object' &&
rgx.test(str) && obj.hasOwnProperty('length') &&
(obj.length === 0 || (typeof obj[0] === 'object' &&
obj[0].nodeType > 0));
},
extend: function (target) {
target = target || {};
var i, il, key, source;
utils.forEach(utils.toArray(arguments, 1), function (source) {
utils.forEach(source, function (value, key) {
if (typeof value === 'object') {
utils.extend(target[key], value);
} else {
target[key] = value;
}
});
});
return target;
},
bind: function (fn, context) {
return fn.bind(context);
},
forEach: function (array, fn, context) {
var i, il;
if (utils.isArray(array)) {
array.forEach(fn, context);
} else {
for (i in array) {
if (array.hasOwnProperty(i)) {
fn.call(context, array[i], i);
}
}
}
},
map: function (array, fn, context) {
return arrProto.map.call(array, fn, context);
},
filter: function (array, fn) {
return arrProto.filter.call(array, fn);
},
indexOf: function (array, item) {
return arrProto.indexOf.call(array, item);
},
now: function () {
return Date.now();
},
fromJSON: function (str) {
return JSON.parse(str);
},
toJSON: function (obj) {
return JSON.stringify(obj);
},
trim: function (str) {
return str.trim();
},
type: function (obj) {
return objProto.toString.call(obj).replace(/^\[object (.+)\]$/, "$1").toLowerCase();
}
};
return utils;
});
hi.plugin('dom', function (hi, window) {
var win = window,
doc = win.document,
dom = {
addClass: function (el, className) {
if (el.classList) {
el.classList.add(className);
} else {
el.className += ' ' + className;
}
},
removeClass: function (el, className) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
},
hasClass: function (el, className) {
if (el.classList) {
return el.classList.contains(className);
}
return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
},
toggleClass: function (el, className) {
if (dom.hasClass(el, className)) {
dom.removeClass(el, className);
} else {
dom.addClass(el, className);
}
},
parseHTML: function (str) {
var el = doc.implementation.createHTMLDocument();
el.body.innerHTML = str;
return el.body.children;
},
after: function (el, str) {
el.insertAdjacentHTML('afterend', str);
},
before: function (el, str) {
el.insertAdjacentHTML('beforebegin', str);
},
append: function (parent, el) {
parent.appendChild(el);
},
prepend: function (parent, el) {
parent.insertBefore(el, parent.firstChild);
},
prev: function (el) {
return el.previousElementSibling;
},
next: function (el) {
return el.nextElementSibling;
},
parent: function (el) {
return el.parentNode;
},
children: function (el) {
var children = [];
hi.utils.forEach(utils.toArray(el.children), function (el) {
if (el.nodeType !== 8) {
children.push(el);
}
});
return children;
},
siblings: function (el) {
return utils.filter(el.parentNode.children, function (child) {
return child !== el;
});
},
clone: function (el) {
return el.cloneNode(true);
},
contains: function (el, child) {
return el !== child && el.contains(child);
},
containsSelector: function (el, selector) {
return el.querySelector(selector) !== null;
},
forEach: function (selector, fn, context) {
var elements = dom.query(selector);
hi.utils.forEach(elements, fn, context);
},
empty: function (el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
},
remove: function (el) {
el.parentNode.removeChild(el);
},
replace: function (el, str) {
el.outerHTML = str;
},
filter: function (selector, fn) {
var elements = dom.query(selector),
results = [];
hi.utils.forEach(elements, function (el) {
if (fn(el)) {
results.push(el);
}
});
return results;
},
query: function (selector, el) {
el = el || doc;
return hi.utils.toArray(el.querySelectorAll(selector));
},
position: function (el, relative) {
if (relative) {
return el.getBoundingClientRect();
}
return {
left: el.offsetLeft,
top: el.offsetTop
};
},
outerHeight: function (el, withMargin) {
var height = el.offsetHeight,
style;
if (!withMargin) {
return height;
}
style = getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
},
outerWidth: function (el, withMargin) {
var width = el.offsetWidth,
style;
if (!withMargin) {
return width;
}
style = getComputedStyle(el);
width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
},
style: function (el, name, value) {
if (value === undefined) {
return getComputedStyle(el)[name];
}
el.style[name] = value;
},
attr: function (el, name, value) {
if (value === undefined) {
return el.getAttribute(name);
}
el.setAttribute(name, value);
},
removeAttr: function (el, name) {
el.removeAttribute(name);
},
html: function (el, str) {
if (str === undefined) {
return el.innerHTML;
}
el.innerHTML = str;
},
text: function (el, str) {
if (str === undefined) {
return el.textContent;
}
el.textContent = str;
}
};
return dom;
});
hi.plugin('events', function (hi, window) {
var win = window,
doc = win.document,
events = {
on: function (el, name, fn) {
el.addEventListener(name, fn);
},
off: function (el, name, fn) {
el.removeEventListener(name, fn);
},
one: function (el, name, fn) {
var callback = function () {
fn.apply(this, arguments);
events.off(el, name, callback);
};
events.on(el, name, callback);
},
ready: function (fn) {
events.on(doc, 'DOMContentLoaded', fn);
},
trigger: function (el, name) {
var event = doc.createEvent('HTMLEvents');
event.initEvent(name, true, false);
el.dispatchEvent(event);
},
triggerCustom: function (el, name, data) {
var event;
if (win.CustomEvent) {
event = new CustomEvent(name, {
detail: data
});
} else {
event = doc.createEvent(name);
event.initCustomEvent(name, true, true, data);
}
el.dispatchEvent(event);
}
};
return events;
});
hi.plugin('xhr', function (hi, window) {
var xhr = function (options) {
var request = new XMLHttpRequest(),
settings = hi.utils.extend({}, xhr.defaults, options),
promise = hi.promise();
request.open(settings.method, settings.url, true);
request.setRequestHeader('Content-Type', xhr.contentTypes[settings.type]);
settings.expose(request);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
settings.success(request.responseText);
promise.resolve(request.responseText);
} else {
settings.failure(request);
promise.reject(request);
}
};
request.onerror = function () {
settings.failure(request);
promise.reject(request);
};
request.send(settings.data);
return promise;
};
xhr.contentTypes = {
'json': 'application/json; charset=UTF-8',
'form': 'application/x-www-form-urlencoded; charset=UTF-8'
};
xhr.methods = {
'post': 'POST',
'get': 'GET',
'put': 'PUT',
'delete': 'DELETE'
};
xhr.defaults = {
url: '/',
method: xhr.methods.get,
type: 'json',
success: hi.utils.noop,
failure: hi.utils.noop,
expose: hi.utils.noop,
data: null
};
return xhr;
});
hi.plugin('fx', function (hi, window) {
var fx = {
hide: function (el) {
hi.dom.style(el, 'display', 'none');
},
show: function (el) {
hi.dom.style(el, 'display', '');
}
};
return fx;
});
return hi;
}));
|
(function() {
'use strict';
angular.module('app.footer.directivas', [
]).directive('piepagina', piepagina);
function piepagina() {
return {
scope: {},
templateUrl: 'app/footer/footer.html',
restrict: 'EA'
};
}
})();
|
var mongoose = require('mongoose');
var Graduations = require('../models/graduation');
var Sync = require('sync');
var sync = require('synchronize');
var data =[ { x: 'CSE 133', y: 4 },
{ x: 'CSE 143', y: 3.5 },
{ x: 'CSE 375', y: 4 },
{ x: 'CSE 100', y: 4 }];
var lebels = ['CSE 133','CSE 143','CSE 375','CSE 100'];
exports.linegraph = function(req, res) {
//data = calculateData('tuhin47');JSON.stringify()
console.log(lebels);
res.render('linechart',{data:data,lebels:lebels});
};
function calculateData(username) {
username = 'tuhin47';
var data = [];
Graduations.find({
username: username
}, function(err, results) {
if (err) throw err;
else if (results) {
for (var i = 0; i < results.length; i++) {
if (parseFloat(results[i].gradepoint) > 0.0) {
data.push({
x: results[i].coursecode,
y: parseFloat(results[i].gradepoint)
});
} else {
drop = +parseFloat(results[i].gradepoint);
}
}
}
console.log(data);
return data;
});
}
//
|
hi.plugin('promise', function (hi, window) {
var states = {
pending: 0,
fulfilled: 1,
rejected: 2
},
noop = function () {
return;
},
promise = function (that) {
var stack = [],
resolved = [],
fulfillValue = null,
cancelReason = null,
state = states.pending,
isPromise,
fulfill,
cancel;
that = that || {};
isPromise = function (obj) {
return obj.inspect && obj.then && obj.resolve && obj.reject;
};
fulfill = function (value) {
fulfillValue = value;
if (state !== states.pending) {
return;
}
window.setTimeout(function () {
var result, fn;
if (stack.length) {
fn = stack.shift();
if (fn.state === states.pending) {
try {
fn.state = states.fulfilled;
fn.value = fulfillValue;
resolved.push(fn);
result = fn.onFulfilled.call(undefined, fulfillValue);
if (result !== undefined) {
fulfillValue = result;
}
if (stack.length) {
return fulfill(fulfillValue);
}
} catch (e) {
if (stack.length) {
return cancel(e);
}
cancelReason = e;
state = states.rejected;
throw e;
}
}
}
state = states.fulfilled;
}, 0);
};
cancel = function (reason) {
cancelReason = reason;
if (state !== states.pending) {
return;
}
window.setTimeout(function () {
var fn, result;
if (stack.length) {
fn = stack.shift();
if (fn.state === states.pending) {
try {
fn.state = states.rejected;
fn.value = cancelReason;
resolved.push(fn);
result = fn.onRejected.call(undefined, cancelReason);
if (stack.length) {
if (result !== undefined) {
return fulfill(result);
}
return cancel(cancelReason);
} else {
if (result === undefined) {
throw cancelReason;
}
}
} catch (e) {
if (stack.length) {
return cancel(e);
}
cancelReason = e;
state = states.rejected;
throw e;
}
}
}
state = states.rejected;
}, 0);
};
that.inspect = function () {
return {
state: state,
resolved: resolved.slice(),
value: fulfillValue,
reason: cancelReason
};
};
that.then = function (onFulfilled, onRejected) {
var fn = {
state: states.pending,
onFulfilled: noop,
onRejected: noop,
value: null
};
if (typeof onFulfilled === 'function') {
fn.onFulfilled = onFulfilled;
}
if (typeof onRejected === 'function') {
fn.onRejected = onRejected;
}
stack.push(fn);
return that;
};
that.resolve = function (value) {
var then, data;
if (value === that) {
that.reject(new TypeError('value cannot be this promise'));
}
if (isPromise(value)) {
data = value.inspect();
if (data.state === states.pending) {
value.then.call(value, that.resolve, that.reject);
} else if (data.state === states.fulfilled) {
fulfill(data.value);
} else if (data.state === states.rejected) {
cancel(data.reason);
} else {
throw new Error('Invalid state: ' + data.state);
}
} else {
try {
then = value.then;
if (typeof then === 'function') {
then.call(value, that.resolve, that.reject);
} else {
fulfill(value);
}
} catch (e) {
cancel(e);
}
}
};
that.reject = function (reason) {
cancel(reason);
};
return that;
};
return promise;
});
|
import React from "react";
import { Form, Select } from "antd";
const FormItem = Form.Item;
const Option = Select.Option;
// 添加城市模态框的表单
class OpenCityForm extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const formItemLayout = {
labelCol: {
span: 5,
},
wrapperCOl: {
span: 19,
},
};
return (
<Form
ref={this.props.formRef}
layout="horizontal"
>
<FormItem
label="选择城市"
{...formItemLayout}
name="city_id"
initialValue="1"
>
<Select style={{ width: 100 }}>
<Option value="">全部</Option>
<Option value="1">北京市</Option>
<Option value="2">天津市</Option>
</Select>
</FormItem>
<FormItem
label="运营模式"
{...formItemLayout}
name="op_mode"
initialValue="1"
>
<Select style={{ width: 100 }}>
<Option value="1">自营</Option>
<Option value="2">加盟</Option>
</Select>
</FormItem>
<FormItem
label="用车模式"
{...formItemLayout}
name="use_mode"
initialValue="1"
>
<Select style={{ width: 100 }}>
<Option value="1">指定停车点</Option>
<Option value="2">禁停区</Option>
</Select>
</FormItem>
</Form>
);
}
}
export default OpenCityForm;
|
var oCommonObject = {};
oCommonObject.display({
target: 'targetName',
cacheInstance: true,
"cacheTime": "with_parent",
"cacheKey":{
"selfKey":{
"instanceId": "{instanceId}"
},
p1Key:{
"employeeId": "employeeIdValue"
}
}
});
oCommonObject.getChildTargetViewInstance({
target: 'targetName',
cacheKey:{
"employeeId": "employeeIdValue"
}
});
oCommonObject.navTo(routeName, oParameters?, bReplace?, oOptionalComplexValue)
|
export default function errorResponse(req, res) {
const requestId = res.get('Request-Id');
return (err = {}) => {
const {
status = -100,
isExpected,
message = 'UNDEFINED ERROR',
meta = {},
} = err;
if (!isExpected) {
logger.error(`[${requestId}] ${status} | ${message}`, meta);
}
res.json({
status,
message,
meta,
});
};
}
|
var async = require('async');
var loopback = require('loopback');
module.exports = function(user){
user.disableRemoteMethod("create", true);
user.disableRemoteMethod("upsert", true);
user.disableRemoteMethod("updateAll", true);
user.disableRemoteMethod("updateAttributes", true);
user.disableRemoteMethod("find", true);
user.disableRemoteMethod("findById", true);
user.disableRemoteMethod("findOne", true);
user.disableRemoteMethod("exists", true);
user.disableRemoteMethod("deleteById", true);
user.disableRemoteMethod("createChangeStream", true);
user.disableRemoteMethod("confirm", true);
user.disableRemoteMethod("count", true);
user.disableRemoteMethod("reset", true);
user.afterRemote('login', function (context, data, cb) {
// var RoleMapping = user.app.models.RoleMapping;
// RoleMapping.findOne({
// where: {'principalId': context.result.userId}
// })
console.log(data);
context.res.cookie('access_token', data.id, { signed: true });
cb();
})
}
|
import axios from 'axios'
const { url } = require('../../helpers/env')
const state = () => {
return {
token: localStorage.getItem('token') || null
}
}
const getters = {
isLogin (state) {
if (state.token !== null) {
return true
} else {
return false
}
}
}
const actions = {
login (context, payload) {
return new Promise((resolve, reject) => {
axios
.post(`${url}/api/v1/users/login`, payload)
.then(response => {
localStorage.setItem('token', response.data.data.token)
localStorage.setItem('refreshToken', response.data.data.refreshToken)
localStorage.setItem('id', response.data.data.id)
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
},
logout (context) {
return new Promise(resolve => {
localStorage.removeItem('token')
localStorage.removeItem('refreshToken')
localStorage.removeItem('id')
localStorage.removeItem('cart')
resolve()
})
},
register (context, payload) {
return new Promise((resolve, reject) => {
axios
.post(`${url}/api/v1/users/register`, payload)
.then(response => {
resolve(response.data.message)
})
.catch(() => {
// eslint-disable-next-line prefer-promise-reject-errors
reject('Gagal Register')
})
})
},
resetPassword (context, payload) {
return new Promise((resolve, reject) => {
axios
.post(`${url}/api/v1/users/send-email`, { email: payload })
.then(response => {
resolve(response.data.message)
})
.catch(err => {
// eslint-disable-next-line prefer-promise-reject-errors
reject(err)
})
})
},
confirmPassword (context, payload) {
return new Promise((resolve, reject) => {
axios
.post(`${url}/api/v1/users/ubah-pass`, payload)
.then(response => {
resolve(response.data.message)
})
.catch(err => {
// eslint-disable-next-line prefer-promise-reject-errors
reject(err)
})
})
}
}
export default {
namespaced: true,
state,
actions,
getters
}
|
import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import {
View,
Image,
Text,
TouchableHighlight
} from 'react-native'
import _ from 'lodash'
import { Colors } from '@constants'
import styles from './CardItem.style'
const IMAGE = require('@images/herbs/lemon.jpg')
const CardItem = (props) => {
const {
title,
description,
image,
onPress,
imageSize,
rightIcon,
containerStyle,
} = props
const isHaveDescription = typeof description === 'function'
const Description = isHaveDescription ? description : Fragment
const isHaveRightIcon = typeof rightIcon === 'number'
return (
<TouchableHighlight
style={[styles.container, containerStyle]}
onPress={onPress}
underlayColor={Colors.BLACK_TRANS}>
<Fragment>
<Image source={image} style={[styles.image, { width: imageSize, height: imageSize }]} />
<View style={styles.contentWarpper}>
<View style={styles.titleWarpper}>
<Text style={styles.titleText}>{title}</Text>
</View>
{isHaveDescription && (
<View style={styles.descriptionWarpper}>
<Description />
</View>
)}
</View>
{isHaveRightIcon && <Image source={rightIcon} style={styles.rightIcon} />}
</Fragment>
</TouchableHighlight>
)
}
export default CardItem
CardItem.propTypes = {
title: PropTypes.string,
description: PropTypes.func,
image: PropTypes.any,
onPress: PropTypes.func,
imageSize: PropTypes.number,
rightIcon: PropTypes.number,
containerStyle: PropTypes.object,
}
CardItem.defaultProps = {
imageSize: 60,
title: '',
image: IMAGE,
onPress() { },
containerStyle: {},
}
|
function minimumAbsoluteDifference(arr) {
arr.sort((a, b) => a - b);
let min = Infinity;
for (let i = 1; i < arr.length; i++) {
min = Math.min(min, Math.abs(arr[i] - arr[i - 1]));
}
return min;
}
console.log(minimumAbsoluteDifference([3, -7, 0]));
console.log(minimumAbsoluteDifference([2, 4, 7, 9, 12, 17]));
function luckBalance(k, contests) {
let important = contests.filter(ar => ar[1] === 1).length;
let sumAll = contests.reduce((a, b) => a+b[0],0);
let sorted = contests.sort((a, b) => a[0] - b[0])
let win = important-k >=0 ?important-k : 0
let min = 0
for(let i=0; i<sorted.length; i++){
if(win === 0) break;
if(sorted[i][1] === 0)continue;
min += sorted[i][0];
win--
}
return sumAll - (2*min);
}
console.log(luckBalance(3, [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]));
function getMinimumCost(k, c) {
c.sort((a,b)=> a-b);
let cost = 0;
let idx = 0;
let t = 0;
while(idx < c.length){
t = Math.floor(idx / k);
cost += (t + 1) * c[c.length-1-idx];
idx += 1;
}
return cost;
}
console.log(getMinimumCost(3, [1, 3, 5, 7]));
/*
* Complete the 'maxMin' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER k
* 2. INTEGER_ARRAY arr
*/
const quicksort = array => {
if (array.length == 0) return [];
var left = [], right = [], pivot = array[0];
for (var i = 1; i < array.length; i++) {
if(array[i] < pivot)
left.push(array[i])
else
right.push(array[i]);
}
return quicksort(left).concat(pivot, quicksort(right));
};
function maxMin(k, arr) {
// Write your code here
arr = quicksort(arr);
let i, length = arr.length, min = Number.MAX_VALUE;
for(i = 0; i < length - k + 1; i++){
let diff = arr[i + k - 1] - arr[i];
if(diff < min)
min = diff;
}
return min;
}
//questions:
//01
//find the maximum sum of 6 by 6 matrix which its submatrix forms a hourglass
function hourglassSum(arr) {
var max = -Infinity;
for (var i = 0; i < arr.length - 2; i++) {
for (var j = 0; j < arr[i].length - 2; j++) {
var sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (sum > max) {
max = sum;
}
}
}
return max;
}
//02
/*
Given an array a of n integers and a number,d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.
*/
function rotLeft(a, d) {
let newArr = [];
for (let i = 0; i < a.length; i++) {
newArr.push(a[(i + d) % a.length]);
}
return newArr;
}
//3
//minimum Bribes
function minimumBribes(q) {
var count = 0;
for (var i = 0; i < q.length; i++) {
if (q[i] - (i + 1) > 2) {
console.log("Too chaotic");
return;
}
for (var j = Math.max(0, q[i] - 2); j < i; j++) {
if (q[j] > q[i]) {
count++;
}
}
}
console.log(count);
}
//4
/*
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. Find the minimum number of swaps required to sort the array in ascending order.
*/
function minimumSwaps(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] != i + 1) {
let temp = arr[i];
arr[i] = arr[temp - 1];
arr[temp - 1] = temp;
count++;
i--;
}
}
return count;
}
//05
/*
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
*/
function arrayManipulation(n, queries) {
let arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = 0;
}
for (let i = 0; i < queries.length; i++) {
let [a, b, k] = queries[i];
arr[a - 1] += k;
if (b < n) {
arr[b] -= k;
}
}
let max = 0;
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum > max) {
max = sum;
}
}
return max;
}
//results
//01
console.log(hourglassSum([[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]]));
//02
console.log(rotLeft([1, 2, 3, 4, 5], 4));
//03
console.log(minimumBribes([2, 1, 5, 3, 4]));
//04
console.log(minimumSwaps([4, 3, 1, 2]));
//05
console.log(arrayManipulation(10, [[1, 5, 3], [4, 8, 7], [6, 9, 1]]));
//01
//find how many pairs of similar integers in an array
function findOccurrences(arr) {
let occurances = {};
for (let i = 0; i < arr.length; i++) {
if (occurances[arr[i]]) {
occurances[arr[i]]++;
} else {
occurances[arr[i]] = 1;
}
}
return occurances;
}
function sockMerchant(n, ar) {
//if the length of ar is not equal to n return 0
if (ar.length !== n) {
return 0;
} else {
let pairs = 0;
let occurances = findOccurrences(ar);
for (let key in occurances) {
pairs += Math.floor(occurances[key] / 2);
}
return pairs;
}
}
//02
//find the how many valleys in a steps path
function countingValleys(n, s) {
//if n is not larger or equal to 2 and smaller or equal to 10 to the power of 6 and s is either U or D return 0
if (n < 2 || n > Math.pow(10, 6) || s.length < 2 || s.length > Math.pow(10, 6)) {
return 0
} else {
var valley = 0;
var seaLevel = 0;
var count = 0;
for (var i = 0; i < n; i++) {
if (s[i] == 'U') {
seaLevel++;
if (seaLevel == 0) {
valley++;
}
} else {
seaLevel--;
}
}
return valley;
}
}
//03
//find jumping on the clouds
/*
0 - safe
1 - thunder
The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2.
The player must avoid the thunderheads.
Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud.
constrains
2<=n<=100
c[i] is either 0 or 1
c[0] = c[n1-1] = 0
*/
function jumpingOnClouds(c) {
let jumps = 0;
for (let i = 0; i < c.length; i++) {
if (i + 2 < c.length && c[i + 2] === 0) {
i++;
jumps++;
} else if (c[i + 1] === 0) {
jumps++;
}
}
return jumps;
}
//04
/*
There is a string ,s, of lowercase English letters that is repeated infinitely many times. Given an integer,n, find and print the number of letter a's in the first n letters of the infinite string.
*/
function repeatedString(s, n) {
if (s.includes('a')) {
const sTotal = Math.floor(n / s.length); // repeated string total
const aCount = s.match(/a/g).length; // 'a' character count in s
let aTotalCount = sTotal * aCount; // total 'a' count of repeated string pattern within number limit
const remainingChar = n % s.length; // remaining characters after repeating string within number limit
// if there are remaining characters, add them to the total 'a' count.
if (remainingChar !== 0 && s.substr(0, remainingChar).includes('a')) {
aTotalCount += s.substr(0, remainingChar).match(/a/g).length;
}
aTotalCount = Math.floor(aTotalCount);
return aTotalCount;
} else {
return 0;
}
}
//results
//test 01
var arr = [1, 2, 1, 2, 1, 3, 2]
var arrTwo = [10, 20, 20, 10, 10, 30, 50, 10, 20, 10, 10]
console.log(sockMerchant(11, arrTwo));
//test 02
var n = 8;
var s = "UDDDUDUUUUUUDDDDUUUUUUDDDDUUUUUUDDDDU";
console.log(countingValleys(n, s));
//test 03
console.log(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0]));
//test 04
console.log(repeatedString('aba', 10));
var arr = [1, 2, 1, 2, 1, 3, 2]
var arrTwo = [10, 20, 20, 10, 10, 30, 50, 10, 20]
//find the unique values in an array
function findUniqueValues(arr) {
let unique = [arr[0]];
for (let i = 1; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) {
unique.push(arr[i]);
}
}
return unique;
}
//find the occurance of each element in an array
function findOccurrences(arr) {
let occurances = {};
for (let i = 0; i < arr.length; i++) {
if (occurances[arr[i]]) {
occurances[arr[i]]++;
} else {
occurances[arr[i]] = 1;
}
}
return occurances;
}
//find the number of pairs in an array
function findPairs(arr) {
let pairs = 0;
let occurances = findOccurrences(arr);
for (let key in occurances) {
if (occurances[key] >= 2) {
pairs += occurances[key] / 2;
}
}
return pairs;
}
//results
console.log(findOccurrences(arr))
console.log(findPairs(arrTwo))
//Questions
//01
/*
Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs.
Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.
Example
magazine= "attack at dawn" note= "Attack at dawn"
The magazine has all the right words, but there is a case mismatch. The answer is No.
Function Description
Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No.
checkMagazine has the following parameters:
string magazine[m]: the words in the magazine
string note[n]: the words in the ransom note
*/
function checkMagazine(magazine, note) {
var magazineHash = {};
var noteHash = {};
var result = "Yes";
for (var i = 0; i < magazine.length; i++) {
if (magazineHash[magazine[i]] === undefined) {
magazineHash[magazine[i]] = 1;
} else {
magazineHash[magazine[i]]++;
}
}
for (var i = 0; i < note.length; i++) {
if (noteHash[note[i]] === undefined) {
noteHash[note[i]] = 1;
} else {
noteHash[note[i]]++;
}
}
for (var key in noteHash) {
if (magazineHash[key] === undefined || magazineHash[key] < noteHash[key]) {
result = "No";
break;
}
}
console.log(result);
}
//02
/*
Given two strings, determine if they share a common substring. A substring may be as small as one character.
*/
function twoStrings(s1, s2) {
let s1_set = new Set();
for (let i = 0; i < s1.length; i++) {
s1_set.add(s1[i]);
}
for (let i = 0; i < s2.length; i++) {
if (s1_set.has(s2[i])) {
return "YES";
}
}
return "NO";
}
//03
/*
Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
*/
function getAllSubstrings(str) {
let i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j))
}
}
return result
}
function isAnagram(str1, str2) {
const hist = {}
for (let i = 0; i < str1.length; i++) {
const char = str1[i]
if (hist[char]) {
hist[char]++
} else {
hist[char] = 1
}
}
for (let j = 0; j < str2.length; j++) {
const char = str2[j]
if (hist[char]) {
hist[char]--
} else {
return false
}
}
return true
}
function countAnagrams(currentIndex, arr) {
const currentElement = arr[currentIndex]
const arrRest = arr.slice(currentIndex + 1)
let counter = 0
for (let i = 0; i < arrRest.length; i++) {
if (currentElement.length === arrRest[i].length && isAnagram(currentElement, arrRest[i])) {
counter++
}
}
return counter
}
function sherlockAndAnagrams(s) {
const duplicatesCount = s.split('').filter((v, i) => s.indexOf(v) !== i).length
if (!duplicatesCount) return 0
let anagramsCount = 0
const arr = getAllSubstrings(s)
for (let i = 0; i < arr.length; i++) {
anagramsCount += countAnagrams(i, arr)
}
return anagramsCount
}
//04
/*
You are given an array and you need to find number of tripets of indices (i,j,k) such that the elements at those indices are in geometric progression for a given common ratio r and i<j<k.
*/
function countTriplets(arr, r) {
const hGram = {}
const hGram2 = {}
let count = 0
if (arr.length < 3) return 0
for (let i = arr.length - 1; i >= 0; i--) {
let t1 = arr[i]
let t2 = t1 * r
let t3 = t2 * r
count += hGram2[t3] || 0
hGram2[t2] ?
hGram2[t2] += hGram[t2] || 0 :
hGram2[t2] = hGram[t2] || 0
hGram[t1] ? hGram[t1]++ : hGram[t1] = 1
}
return count
}
//05
/**
You are given queries. Each query is of the form two integers described below:
- 1x : Insert x in your data structure.
- 2y : Delete one occurence of y from your data structure, if present.
- 3z: Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0.
The queries are given in the form of a 2-D array queries of size q where queries[i][0] contains the operation, and queries[i][1] contains the data element.
*/
function freqQuery(queries) {
const frequencies = [];
const frequencyTracker = [];
const result = [];
for (const query of queries) {
const action = query[0];
const value = query[1];
let index;
if (action === 1 || action === 2) {
index = frequencies[value];
frequencyTracker[index] ? --frequencyTracker[index] : null;
}
if (action === 1) {
typeof frequencies[value] === 'undefined' ? frequencies[value] = 1 : ++frequencies[value];
}
if (action === 2 && frequencies[value]) {
--frequencies[value];
}
if (action === 1 || action === 2) {
index = frequencies[value];
frequencyTracker[index] ? ++frequencyTracker[index] : frequencyTracker[index] = 1;
}
if (action === 3) {
result.push(frequencyTracker[value] > 0 ? 1 : 0);
}
}
return result;
}
//Results
//01
console.log(checkMagazine(["give", "me", "one", "grand", "today", "night"], ["give", "one", "grand", "today"]));
//02
console.log(twoStrings("hello", "world"));
//03
console.log(sherlockAndAnagrams('abba'))
//04
console.log(countTriplets([1, 3, 9, 9, 27, 81], 3))
//05
console.log(freqQuery([[1, 1], [2, 2], [3, 2], [1, 1], [1, 1], [2, 1], [3, 2]]));
function fizzBuzz(n) {
for (var i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log('FizzBuzz');
} else if (i % 3 == 0) {
console.log('Fizz');
} else if (i % 5 == 0) {
console.log('Buzz');
} else {
console.log(i);
}
}
}
//find the median of an array
function findMedian(arr) {
//sort the array in ascending order
arr.sort(function (a, b) {
return a - b;
});
//find the median of the sorted array
var median = 0;
if (arr.length % 2 == 0) {
median = (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
} else {
median = arr[(arr.length - 1) / 2];
}
return median;
}
//plus minus array
function plusMinus(arr) {
var positive = 0;
var negative = 0;
var zero = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
positive++;
} else if (arr[i] < 0) {
negative++;
} else {
zero++;
}
}
console.log(positive / arr.length);
console.log(negative / arr.length);
console.log(zero / arr.length);
}
//find the minimum sum and the maximum sum of an array
function minMaxSum(arr) {
var min = arr[0];
var max = arr[0];
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
} else if (arr[i] > max) {
max = arr[i];
}
sum += arr[i];
}
console.log(sum - max, sum - min);
}
//Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
function timeConversion(s) {
var arr = s.split(':');
console.log(arr);
var hour = parseInt(arr[0]);
var minute = parseInt(arr[1]);
var second = arr[2];
//test if second ends with AM or PM
if (second.substring(second.length - 2) == 'AM') {
//if AM, convert to 24-hour format
if (hour == 12) {
hour = 0;
}
} else {
//if PM, convert to 24-hour format
if (hour != 12) {
hour += 12;
}
}
//convert to string
hour = hour.toString();
minute = minute.toString();
//add 0 if hour or minute is less than 10
if (hour.length == 1) {
hour = '0' + hour;
}
if (minute.length == 1) {
minute = '0' + minute;
}
//return the time in 24-hour format
return hour + ':' + minute + ':' + second.substring(0, second.length - 2);
}
//rotate a matrix to find the maximum sum possible of the top-left quadrant //not solved !!!
function maxSum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (i == j) {
sum += arr[i][j];
}
}
}
return sum;
}
//find the unique number in an array
function findUnique(a) {
var unique = 0;
for (var i = 0; i < a.length; i++) {
unique ^= a[i]; //XOR operation
}
return unique;
}
//find the absolute difference between sums of diagonals of a matrix
function diagonalDifference(arr) {
var sum1 = 0;
var sum2 = 0;
for (var i = 0; i < arr.length; i++) {
sum1 += arr[i][i];
sum2 += arr[i][arr.length - 1 - i];
}
return Math.abs(sum1 - sum2);
}
/*
create an integer array whose index range covers the entire range of values in your array to sort. Each time a value occurs in the original array, you increment the counter at that index. At the end, run through your counting array, printing the value of each non-zero valued index that number of times.
*/
function countingSort(arr) {
var helper = [];
for (var i = 0; i < arr.length; i++) {
if (!helper[arr[i]]) {
helper[arr[i]] = 1;
} else {
helper[arr[i]] += 1;
}
}
var newArr = [];
for (i in helper) {
while (helper[i] > 0) {
newArr.push(parseInt(i));
helper[i]--;
}
}
return newArr;
}
function caesarCipher(s, k) {
let result = '';
for (let i = 0; i < s.length; i++) {
let charCode = s[i].charCodeAt();
// check that charCode is a lowercase letter; automatically ignores non-letters
if (charCode > 96 && charCode < 123) {
charCode += k % 26 // makes it work with numbers greater than 26 to maintain correct shift
// if shift passes 'z', resets to 'a' to maintain looping shift
if (charCode > 122) {
charCode = (charCode - 122) + 96;
// same as previous, but checking shift doesn't pass 'a' when shifting negative numbers
} else if (charCode < 97) {
charCode = (charCode - 97) + 123;
}
}
if (charCode > 64 && charCode < 91) {
charCode += k % 26
if (charCode > 90) {
charCode = (charCode - 90) + 64;
} else if (charCode < 65) {
charCode = (charCode - 65) + 91;
}
}
result += String.fromCharCode(charCode);
}
return result
}
//Questions:
//01
/*
using the follwoing functino perform ascending bubble sort
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
*/
function countSwaps(a) {
var swapCount = 0;
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
var temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
// swap(a[j], a[j + 1]);
swapCount++;
}
}
}
console.log("Array is sorted in " + swapCount + " swaps.");
console.log("First Element: " + a[0]);
console.log("Last Element: " + a[a.length - 1]);
}
//02
/*
Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money. Given a list of toy prices and an amount to spend, determine the maximum number of gifts he can buy.
Note Each toy can be purchased only once.
*/
function maximumToys(prices, k) {
// Write your code here
//sort the prices
let total = 0;
let count = 0;
prices.sort((a, b) => a - b);
for (let i = 0; i < prices.length; i++) {
if (total + prices[i] <= k) {
total += prices[i];
count++;
}
}
return count;
}
/*
prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50
*/
//03
/*
HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity.
If the amount spent by a client on a particular day is greater than or equal to 2X the client's median spending for a trailing number of days,
they send the client a notification about potential fraud.
The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data.
Given the number of trailing days d and a client's total daily expenditures for a period of n days,
determine the number of times the client will receive a notification over all n days.
*/
function activityNotifications(expenditure, d) {
// Number of notifications
let n = 0
// Set midpoints for median calculation
let [i1, i2] = [Math.floor((d - 1) / 2), Math.ceil((d - 1) / 2)]
let m1, m2, m
// Initialize count sorted subarray
let cs = new Array(201).fill(0)
for (let i = d - 1; i >= 0; i--) cs[expenditure[i]]++
// Iterate through expenditures
for (let i = d, l = expenditure.length; i < l; i++) {
// Find median
for (let j = 0, k = 0; k <= i1; k += cs[j], j++) m1 = j
for (let j = 0, k = 0; k <= i2; k += cs[j], j++) m2 = j
let m = (m1 + m2) / 2
// Check if notification is given
if (expenditure[i] >= m * 2) n++
// Replace subarray elements
cs[expenditure[i - d]]--
cs[expenditure[i]]++
}
return n
}
//04
/*
In an array, arr, the elements at indices i and j (where i<j) form an inversion if arr[i]>arr[j].
In other words, inverted elements arr[i] and arr[j] are considered to be "out of order". To correct an inversion, we can swap adjacent elements.
*/
function countInversions(arr) {
if (arr.length < 2) return 0;
var mid = Math.floor(arr.length / 2);
var left = arr.slice(0, mid);
var right = arr.slice(mid);
return countInversions(left) + countInversions(right) + merge(left, right, arr);
}
function merge(left, right, arr) {
var i = 0;
var j = 0;
var k = 0;
var count = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
count += left.length - i;
}
k++;
}
while (i < left.length) {
arr[k] = left[i];
i++;
k++;
}
while (j < right.length) {
arr[k] = right[j];
j++;
k++;
}
return count;
}
//05
/*
Python
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
self.name = ""
self.score = 0
def comparator(a, b):
if a.score == b.score:
if a.name > b.name:
return 1
else:
return -1
if a.score > b.score:
return -1
else:
return 1
*/
//-----------------------------------------------
//Results
//01
console.log(countSwaps([3, 2, 1]));
//02
console.log(maximumToys([1, 12, 5, 111, 200, 1000, 10], 50));
//03
console.log(activityNotifications([2, 3, 4, 2, 3, 6, 8, 4, 5], 5))
//04
console.log(countInversions([1, 2, 5, 4, 3, 2, 6]))
//05
//print(Player('bob', 10).comparator(Player('alice', 10)))
//Questions
//01
/*
Given two strings, a and b,
that may or may not be of the same length,
determine the minimum number of character deletions required to make a and b anagrams.
Any characters can be deleted from either of the strings.
*/
function makeAnagram(a, b) {
let count = 0;
let a_arr = a.split('');
let b_arr = b.split('');
let a_obj = {};
let b_obj = {};
for (let i = 0; i < a_arr.length; i++) {
if (a_obj[a_arr[i]]) {
a_obj[a_arr[i]]++;
}
else {
a_obj[a_arr[i]] = 1;
}
}
for (let i = 0; i < b_arr.length; i++) {
if (b_obj[b_arr[i]]) {
b_obj[b_arr[i]]++;
}
else {
b_obj[b_arr[i]] = 1;
}
}
for (let key in a_obj) {
if (b_obj[key]) {
count += Math.abs(a_obj[key] - b_obj[key]);
}
else {
count += a_obj[key];
}
}
for (let key in b_obj) {
if (!a_obj[key]) {
count += b_obj[key];
}
}
return count;
}
//02
/*
You are given a string containing characters A and B only.
Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
*/
function alternatingCharacters(s) {
let count = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === s[i + 1]) {
count++;
}
}
return count;
}
//03
/*
string to be valid if all characters of the string appear the same number of times.
It is also valid if he can remove just 1 character at 1 index in the string,
and the remaining characters will occur the same number of times.
Given a string , determine if it is valid. If so, return YES, otherwise return NO.
*/
function isValid(s) {
let hash = {};
let max, min;
let minCount = 0;
let maxCount = 0;
///Get the frequencies of each characters
for (let i = 0; i < s.length; i++) {
let key = s[i];
if (hash[key]) {
hash[key]++;
} else {
hash[key] = 1;
}
}
//Push all strings in to an array
let frequencies = [];
for (let key in hash) {
frequencies.push(hash[key]);
}
//Sort the array and get the max and min frequency
frequencies.sort();
min = frequencies[0];
max = frequencies[frequencies.length - 1];
//Get the no of max count and min count for the frequency
for (let i = 0; i < frequencies.length; i++) {
if (frequencies[i] === max) {
maxCount++;
}
if (frequencies[i] === min) {
minCount++;
}
}
///Make our validation check
if (min === max) {
return 'YES';
}
if (max - (min - 1) == max && minCount === 1 && maxCount !== 1) {
return 'YES';
}
if (max - min !== 1) {
return 'NO';
}
if (maxCount === minCount) {
return 'NO';
}
if (maxCount === 1 || minCount === 1) {
return 'YES';
}
return 'NO';
}
function isValid(s) {
const cMap = {}
for (let c of s) {
cMap[c] ? cMap[c]++ : cMap[c] = 1
}
const freqs = new Set(Object.values(cMap))
if (freqs.size === 1) return 'YES'
if (freqs.size === 2) {
const max = Math.max(...freqs)
const min = Math.min(...freqs)
let maxCt = 0
let minCt = 0
for (let c in cMap) {
if (cMap[c] === max) maxCt++
if (cMap[c] === min) minCt++
}
if (
(minCt === 1 && min === 1) ||
(maxCt === 1 && max === min + 1)
) return 'YES'
}
return 'NO'
}
//04
/*
A string is said to be a special string if either of two conditions is met:
All of the characters are the same, e.g. aaa.
All characters except the middle one are the same, e.g. aadaa.
A special substring is any substring of a string which meets one of those criteria.
Given a string, determine how many special substrings can be formed from it.
*/
function substrCount(n, s) {
let result = 0;
let i = 0;
// 1st case, all letters are the same
while (i < n) {
let charCount = 1;
while (i + 1 < s.length && s[i] == s[i + 1]) {
i++;
charCount++;
}
result += parseInt((charCount * (charCount + 1)) / 2);
i++;
}
// 2nd case, palindrome
for (i = 1; i < n; i++) {
let charCount = 1
while (
i + charCount < s.length &&
i - charCount >= 0 &&
s[i - 1] != s[i] &&
s[i - 1] == s[i - charCount] &&
s[i - 1] == s[i + charCount]
) {
charCount++;
}
result += charCount - 1
}
return result
}
//05
/*
A string is said to be a child of a another string if it can be formed by deleting 0 or more characters from the other string. Letters cannot be rearranged. Given two strings of equal length, what's the longest string that can be constructed such that it is a child of both?
*/
function commonChild(s1, s2) {
const table = [new Array(s2.length+1).fill(0)]
for(let i=0; i<s1.length;i++) table.push([0])
for(let i=1;i<s1.length+1;i++){
for(let j=1;j<s2.length+1;j++){
if(s1[i-1] === s2[j-1]) table[i][j] = table[i-1][j-1] + 1
else table[i][j] = Math.max(table[i-1][j],table[i][j-1])
}
}
return table[s1.length][s2.length]
}
//Results
//01
console.log(makeAnagram('fcrxzwscanmligyxyvym', 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'));
//02
console.log(alternatingCharacters("AAABBB"));
//03
console.log(isValid('aabbccddeefghi'));
//04
console.log(substrCount(5, "abcbaba"));
//05
console.log(commonChild("HARRY", "SALLY"))
|
import { Map } from 'immutable';
const initState = Map({
id: '-1'
});
export default (state = initState, action) => {
switch (action.type) {
case 'edit/changeId':
return state.set('id', action.payload);
case 'edit/changeEditCache':
return state.set(action.payload.key, action.payload.config);
default:
return state;
}
}
|
jQuery(document).ready(function() {
$turn= 0;
var game = ["","","","","","","","",""];
$('#game div').click(function(){
var x= $(this).position();
if(x.left==0 && x.top==0)
{
if(!game[0] && $turn==0)
{
game[0]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[0] && $turn==1)
{
game[0]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==105 && x.top==0)
{
if(!game[1] && $turn==0)
{
game[1]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[1] && $turn==1)
{
game[1]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==210 && x.top==0)
{
if(!game[2] && $turn==0)
{
game[2]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[2] && $turn==1)
{
game[2]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==0 && x.top==105)
{
if(!game[3] && $turn==0)
{
game[3]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[3] && $turn==1)
{
game[3]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==105 && x.top==105)
{
if(!game[4] && $turn==0)
{
game[4]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[4] && $turn==1)
{
game[4]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==210 && x.top==105)
{
if(!game[5] && $turn==0)
{
game[5]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[5] && $turn==1)
{
game[5]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==0 && x.top==210)
{
if(!game[6] && $turn==0)
{
game[6]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[6] && $turn==1)
{
game[6]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==105 && x.top==210)
{
if(!game[7] && $turn==0)
{
game[7]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[7] && $turn==1)
{
game[7]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
else if(x.left==210 && x.top==210)
{
if(!game[8] && $turn==0)
{
game[8]= '0';
$('#g1').append("<img src='x.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 1;
}
else if(!game[8] && $turn==1)
{
game[8]= '1';
$('#g1').append("<img src='o.png' class='x1' style='position: absolute;left: "+x.left+"px;top: "+x.top+"px;'>");
$turn= 0;
}
else
{
alert('Invalid Move');
}
}
if((game[0]=='0'&&game[1]=='0'&&game[2]=='0')||(game[3]=='0'&&game[4]=='0'&&game[5]=='0')||(game[6]=='0'&&game[7]=='0'&&game[8]=='0')||(game[0]=='0'&&game[3]=='0'&&game[6]=='0')||(game[1]=='0'&&game[4]=='0'&&game[7]=='0')||(game[2]=='0'&&game[5]=='0'&&game[8]=='0')||(game[0]=='0'&&game[4]=='0'&&game[8]=='0')||(game[2]=='0'&&game[4]=='0'&&game[6]=='0'))
{
alert('Player1 Wins!');
$flag= 1;
}
else if((game[0]=='1'&&game[1]=='1'&&game[2]=='1')||(game[3]=='1'&&game[4]=='1'&&game[5]=='1')||(game[6]=='1'&&game[7]=='1'&&game[8]=='1')||(game[0]=='1'&&game[3]=='1'&&game[6]=='1')||(game[1]=='1'&&game[4]=='1'&&game[7]=='1')||(game[2]=='1'&&game[5]=='1'&&game[8]=='1')||(game[0]=='1'&&game[4]=='1'&&game[8]=='1')||(game[2]=='1'&&game[4]=='1'&&game[6]=='1'))
{
alert('Player2 Wins!');
$flag= 1;
}
else if(game[0] && game[1] && game[2] && game[3] && game[4] && game[5] && game[6] && game[7] && game[8] )
{
alert('It`s a draw!');
$flag= 1;
}
if($flag== 1)
{
$turn= 0;
game = ["","","","","","","","",""];
$('.x1').remove();
$flag= 0;
}
});
});
|
var class_plotter =
[
[ "MultiPlot", "class_plotter.html#af554114c66fa738a9ff9ca28417dd609", null ],
[ "Plot", "class_plotter.html#a1de8764d662d7ae2f9171e1482ba19b1", null ],
[ "labelKeywords", "class_plotter.html#a4d9ef2df267ecc0b9bbd217e2e002a11", null ]
];
|
function getRandomTime(avg, dev) {
var sign = (0.5<Math.random()) ? 1: (-1);
var activityTime = parseInt((avg + (sign * dev * Math.random())) * 1000);
return activityTime;
}
|
import {FETCH_USER_FAIL, FETCH_USER_FETCHING, FETCH_USER_SUCCESS, SAVE_USER} from "./types";
export const saveUser = (payload) => {
return {type: SAVE_USER, payload}
}
export const fetchUserFetching = (payload) => ({
type: FETCH_USER_FETCHING, payload
})
export const fetchUserFailed = () => ({
type: FETCH_USER_FAIL
})
export const fetchUserSuccess = () => ({
type: FETCH_USER_SUCCESS
})
|
const Sequelize = require('sequelize');
const sequelize = require('../config/db');
class User extends Sequelize.Model {}
User.init({
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, { sequelize, modelName: 'user' });
module.exports = User;
|
define([
'jquery',
'underscore',
'backbone',
'js/config'
], function($, _, Backbone, APP){
APP.Models.Contact = Backbone.Model.extend({
// urlRoot: '/ContactsApp/php/laravel/public/contact',
defaults: {
firstname: null,
lastname: null,
birthday: null,
address: null,
company: null,
fbId: null,
twitterHandle: null,
linkedinId: null,
skypeId: null,
website: null,
numbers: [],
emails: []
}
});
});
|
/*
* Получать информацию по динамическому полю из объекта
* relatedObject - имя динамического поля объекта companyData
*/
const relatedObject = event.target.dataset.name;
const recordToEditIndex = this.companyData[relatedObject].findIndex(recordToedit => recordToedit.Id == relatedRecordIdToEdit);
|
var colors = require('colors/safe')
, path = require('path')
, log = require('./logging.js').getLogger('boot');
// bootstrapper.
// enables live reloading of server-side process.
module.exports = function bootstrapper (sessionModule) {
if (sessionModule === require.main) {
var filename = sessionModule.filename
, shortname = path.relative(process.cwd(), filename);
var session = null
, start =
function bootstrapperStart () {
log("loading", colors.green(shortname));
delete require.cache[filename];
session = require(filename);
log("starting", colors.green(shortname));
session.start().then(function () {
log("started", colors.green(shortname));
}).done();
}
, restart =
function bootstrapperRestart () {
if (session.stop) {
session.stop().then(start).done();
} else {
session.start().done();
}
};
var dedupe = null
, onChange =
function onChange (fname, stat) {
var duplicate = false;
if (stat) {
if (dedupe === stat.mtime) duplicate = true;
dedupe = stat.mtime;
}
if (!duplicate) {
if (fname) log("changed", colors.blue(path.relative(process.cwd(), fname)));
restart()
}
}
var chokOpts = { persistent: true
, alwaysStat: true
, useFsEvents: false }
, watcher = require('chokidar').watch(filename, chokOpts);
//var oldRequire = require
//, newRequire = Object.keys(require).reduce(
//function (nreq, key) { nreq[key] = require[key]; return nreq },
//function require (arg) {
//var reqd = oldRequire.apply(null, arguments);
//log("req", arguments[0])
//watcher.add(arguments[0]);
//return reqd;
//}
//);
//global.require = newRequire;
watcher.on("add", function (path) { log("added", path); })
watcher.on("change", onChange);
start();
}
}
|
"use strict";
/**
* @author Gabriele Bianchet-David
* @version 0.0.1
*
* @description Cross-platform terminal
*
* Evaluate user input string function
*/
const builtins = require('./builtins');
const errors = require('./errors');
/**
* Takes the AST and executes the appropriate commands.
*
* @param input AST received from syntax analysis
* @return string STDOUT
*/
function evaluate(input) {
if (input[0] === "")
return "";
if (input[0] === "exit") {
return "Exiting...";
}
try {
if (input.length < 2)
return builtins[input[0]]([]);
else
return builtins[input[0]](input.slice(1));
} catch (e) {
if (e instanceof TypeError) {
throw new errors.CommandError(input[0]);
}
else {
throw e;
}
}
}
module.exports = evaluate;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsFormatLineSpacing = {
name: 'format_line_spacing',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6 7h2.5L5 3.5 1.5 7H4v10H1.5L5 20.5 8.5 17H6V7zm4-2v2h12V5H10zm0 14h12v-2H10v2zm0-6h12v-2H10v2z"/></svg>`
};
|
let input = [
"Sofia -> Laptops HP -> 200 : 2000",
"Sofia -> Raspberry -> 200000 : 1500",
"Montana -> Oranges -> 200000 : 1",
"Montana -> Cherries -> 10 : 1",
"Sofia -> Audi Q7 -> 200 : 100000",
"Montana -> Cherries -> 1 : 5"
];
function cityMarket(strArr) {
let result = new Map();
for (let row of strArr) {
let [town, product, sales] = row.split(" -> ");
sales = sales.split(" : ").reduce((a, b) => a * b);
if (!result.has(town)) {
result.set(town, new Map());
}
if (!result.get(town).has(product)) {
result.get(town).set(product, 0);
}
let oldSales = result.get(town).get(product);
result.get(town).set(product, oldSales + sales);
}
for (let [town, products, sales] of result) {
console.log(`Town - ${town}`);
for (let [product, sales] of products ) {
console.log(`$$$${product} : ${sales}`);
}
}
//console.log(result);
}
cityMarket(input);
|
import './movie-item.js';
class MovieList extends HTMLElement {
constructor() {
super();
this.shadowDOM = this.attachShadow({mode: "open"});
}
set movies(movies) {
this._movies = movies;
this.render();
}
renderError(message) {
this.shadowDOM.innerHTML = `
<style>
.placeholder {
font-weight: lighter;
color: rgba(0,0,0,0.5);
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
`;
this.shadowDOM.innerHTML += `<h2 class="placeholder">${message}</h2>`;
}
render() {
this.shadowDOM.innerHTML = `
<style>
:host {
display: grid;
grid-template-columns: auto auto auto auto;
grid-gap: 50px;
padding: 10px;
}
</style>
`;
this._movies.forEach(
movie => {
console.log(movie)
const movieItemElement = document.createElement("movie-item");
if(movie.poster_path === null){
movie.poster_path = 'https://via.placeholder.com/300'
}else{
movie.poster_path = 'https://image.tmdb.org/t/p/w780' + movie.poster_path
}
movieItemElement.movie = movie
this.shadowDOM.appendChild(movieItemElement);
}
)
}
}
customElements.define("movie-list", MovieList);
|
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('about', { title : 'Home' });
});
router.get('/luke', function (req, res) {
res.render('luke', { title : 'Home' });
});
router.get('/martin', function (req, res) {
res.render('martin', { title : 'Home' });
});
module.exports = router;
|
import React, { Component } from 'react';
import Todoitem from './todoitem';
import './App.css';
import './bootstrap.min.css';
import Time from "./date-time";
import list from './array';
class App extends Component {
constructor(){
super();
this.state = {
todos: [],
newtodo: ''
}
}
componentDidMount(){
this.setState(()=>({ todos: list }));
}
submit = (e) =>{
e.preventDefault();
let { newtodo, todos } = this.state;
if(newtodo === ""){
alert("The input field can not be empty!");
}else{
newtodo = { id: todos.length, content: newtodo, isChecked: false };
this.setState(()=>({
todos: [ ...todos, newtodo ],
newtodo: ""
}))
}
}
onChange = e =>{
const { name, value } = e.target;
this.setState(()=>({
[name]: value
}))
}
deleteAll = () =>{
this.setState(()=>({ todos: [] }))
}
toggleChecked = (e) =>{
const { id } = e.target;
const { todos } = this.state;
let the_one = todos.filter(todo => todo.id === +id)[0];
the_one.isChecked = !the_one.isChecked;
this.setState(()=>({
todos: todos
}))
}
trash = e =>{
const { id } = e.target;
const { todos } = this.state;
let new_todos = todos.filter(todo => todo.id !== +id);
this.setState(()=>({ todos: new_todos }));
}
render(){
const { newtodo, todos } = this.state;
let todoArray = todos.length < 1 ? <legend>Add item to your list</legend> : todos.map(todo =>(
<Todoitem
key={todo.id} identifier={todo.id}
todo={todo.content} checked={todo.isChecked}
toggle={this.toggleChecked} trash={this.trash}
/>
))
return (
<React.Fragment>
<div className="row mt-5">
<div className="col-md-2"></div>
<div className="col-md-8">
<div className="card shadow">
<div className="card-header">
<Time/>
</div>
<div className="card-body">
{todoArray}
</div>
<div className="card-footer text-muted">
<form onSubmit={this.submit}>
<input type="text" value={newtodo} name="newtodo" onChange={this.onChange} />
<input type="submit" className="btn btn-info m-1" value="Add" />
{(todos < 1) ? "" : <input type="button" className="btn btn-warning m-1" value="Delete all" onClick={this.deleteAll} />}
</form>
</div>
</div>
</div>{/* col-md-8 */}
<div className="col-md-2"></div>
</div>{/* row */}
</React.Fragment>
);
}
}
export default App;
|
import React from "react";
import styled from "styled-components";
const Container = styled.div`
display: flex;
flex-direction: column;
padding: 3rem;
`;
const SIFrame = styled.iframe`
width: 100%;
height: 50vw;
&:not(:last-child) {
margin-bottom: 2rem;
}
`;
const MitchinEnglish = () => {
return (
<Container>
<SIFrame
width="560"
height="315"
src="https://www.youtube.com/embed/7-294VPXvEg"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
/>
<SIFrame
width="560"
height="315"
src="https://www.youtube.com/embed/L0FyJR0cp6Y"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
/>
</Container>
);
};
export default MitchinEnglish;
|
// A growth algorithm, inspired by inconvergent's differential line
// http://inconvergent.net/generative/differential-line/
// requires jquery
var line = []
var width = window.innerWidth;
var height = window.innerHeight;
function init_growth() {
init_canvas();
line = seed_line_from_circle(100,10,width/2, height/2);
draw_loop(line);
}
function seed_line_from_circle(r,n,cx,cy){
// this is probably good as a sphere
var line = [];
var d_theta = Math.PI * 2 / n;
for (var i = 0; i < n; i++) {
var theta = i * d_theta;
var coords = polar_to_cartesian_2d(r, theta)
line.push({'x':coords[0]+cx,'y':coords[1]+cy});
}
return line;
}
function polar_to_cartesian_2d(r, theta) {
var x = r * Math.cos( theta );
var y = r * Math.sin( theta );
return [x,y]
}
|
import React from 'react'
import {shallow} from 'enzyme'
import Button from './Button'
describe('Button', () => {
it('should be defined', () => {
expect(Button).toBeDefined()
})
it('should be rendered with title', () => {
const button = shallow(<Button title="test" />)
expect(button.text()).toEqual('test')
})
})
|
export { default as bell } from './header/icons8-bell-100.png';
export { default as cloud } from './weather/cloud.png';
export { default as cloudy } from './weather/cloudy.png';
export { default as sunny } from './weather/sunny.png';
export { default as snow } from './weather/snow.png';
export { default as rain } from './weather/rain.png';
export { default as water } from './weather/water.png';
export { default as windy } from './weather/windy.png';
|
var StellarSdk = require('stellar-sdk');
var express = require('express');
var router = express.Router();
StellarSdk.Network.useTestNetwork();
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
router.post('/makeTrust',function(request,response,next){
var sourceKey = "#";
var investorkey = request.body.investor_key;
var receivingKeys = StellarSdk.Keypair.fromSecret(investorkey);
var mkj = new StellarSdk.Asset('L2L', sourceKey);
server.loadAccount(receivingKeys.publicKey())
.then(function(receiver) {
var transaction = new StellarSdk.TransactionBuilder(receiver)
.addOperation(StellarSdk.Operation.changeTrust({
asset: mkj,
//limit: '1000'
}))
.build();
transaction.sign(receivingKeys);
return server.submitTransaction(transaction);
})
.then(function(result) {
console.log('Success! Results:', result);
response.contentType('application/json');
response.end(JSON.stringify("Trust Generated"));
})
.catch(function(error) {
console.error('Error!', error);
response.contentType('application/json');
response.end(JSON.stringify("Trust Not Generated"));
});
});
module.exports = router;
|
import React from "react";
import { withRouter } from "react-router";
import { NavLink } from "react-router-dom";
import vapeLogo from "./images/vapeLogo.jpg";
const Navbar = props => {
const dynamicLink = (route, linkText) => {
return (
<div className="nav-link-wrapper">
<NavLink to={route} activeClassName="nav-link-active">
{linkText}
</NavLink>
</div>
);
};
return (
<div className="navbar-wrapper">
<div className="left-side">
<div className="vape-logo">
<NavLink exact to="/">
<img src={vapeLogo} alt="logo"></img>
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink exact to="/" activeClassName ="nav-link-active">
Home
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink exact to="/advocacy" activeClassName ="nav-link-active">
Advocacy
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink exact to="/products" activeClassName ="nav-link-active">
Products
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink exact to="/ejuice" activeClassName ="nav-link-active">
E-Juice
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink exact to="/contact" activeClassName ="nav-link-active">
Contact Us
</NavLink>
</div>
</div>
</div>
)
}
export default withRouter(Navbar);
|
import React from 'react'
import HeroRow from '../HeroRow'
import '../../bootstrap.css'
const HeroTable = ({ heroes, killHero, putRing, resurrectHero, heroUsingRing }) => (
<table className='table table-dark table-striped text-center'>
<tbody>
<tr>
<th>Name</th>
<th>Race</th>
<th>Age</th>
<th>Weapon</th>
<th>Action</th>
</tr>
{heroes.map((hero, index) => (
<HeroRow
key={index}
hero={hero}
heroUsingRing={heroUsingRing}
killHero={() => killHero(hero.id)}
putRing={() => putRing(hero.id)}
resurrectHero={() => resurrectHero(hero.id)}
/>
))}
</tbody>
</table>
)
export default HeroTable
|
import React, {Component} from 'react'
import { FormGroup, Label, Input } from 'reactstrap'
const imageStyle = {
width: "100px",
height: "100px"
}
class GuestCheckList extends Component {
guestList() {
return this.props.guests.map((guest) => (
<FormGroup check key={guest.id} style={{paddingLeft: "4.5rem"}}>
<Label check>
<Input type="checkbox" value={guest.id} />{' '}
<img src={guest.image} className="img-thumbnail" style={imageStyle}/>{' '}{guest.username}
</Label><br></br>
</FormGroup>
)
)}
render() {
return(
<div>
{this.guestList()}
</div>
)
}
}
export default GuestCheckList
|
const initialState={
numa:1,
numb:1,
numc:1,
numd:1
};
const reducersa=(state=initialState,action)=>{
const newState={...state};
switch(action.type){
case 'UPDATEA':
newState.numa+=newState.numc;
break;
case 'UPDATEB':
newState.numb+=newState.numd;
break;
case 'UPDATEC':
newState.numc+=newState.numa;
break;
case 'UPDATED':
newState.numd+=newState.numb;
break;
}
return newState;
};
export default reducersa;
|
import 'react-native-gesture-handler';
import React, { Component } from 'react';
import { SafeAreaView, } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomePage from './src/screen/Home/HomeScreen';
import FlashMessage from 'react-native-flash-message';
import Forum from './src/screen/Forum/Forum';
const Stack = createStackNavigator();
export default class App extends Component {
// componentDidMount() {
// SplashScreen.hide()
// }
render() {
return (
<SafeAreaView style={{ flex: 1, backgroundColor: "#ff5c5c" }}>
<NavigationContainer>
<Stack.Navigator screenOptions={{
headerShown: false
}}
initialRouteName="HomePage"
>
<Stack.Screen name="HomePage" component={HomePage} />
<Stack.Screen name="Forum" component={Forum} />
</Stack.Navigator>
</NavigationContainer>
<FlashMessage position="top" />
</SafeAreaView>
);
}
}
|
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import "./src/application.scss"
window.$ = window.jQuery = window.jquery = jQuery;
// Libraries
import "@fortawesome/fontawesome-free/js/all"
import "bootstrap"
import "select2/dist/css/select2.css"
require( 'datatables.net-bs4' );
require( 'datatables.net-buttons-bs4' );
require( 'datatables.net-buttons/js/buttons.html5.js' );
require( 'datatables.net-fixedcolumns-bs4' );
require( 'datatables.net-select-bs4' );
require('select2');
require("@nathanvda/cocoon")
$(document).ready(function() {
setTimeout(function(){
$("#flash_notice").add("#flash_error").fadeTo(2000, 0).animate({ height: "0px" }, 500)
},4000);
$('.navbar-nav li').click(function() {
$('.navbar-nav li').removeClass('active');
$(this).addClass('active');
});
$("#notice").fadeTo(2000, 500).slideUp(500, function(){
$("#notice").slideUp(500);
});
$("#alert").fadeTo(2000, 500).slideUp(500, function(){
$("#alert").slideUp(500);
});
});
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import home from './components/home.vue'
import search from './components/search.vue'
import recentweather from './components/recentweather.vue'
Vue.use(VueRouter)
var router = new VueRouter({
routes:[
{
path:'/',
component:home,
name:'home',
},
{
path:'/search',
component:search,
name:'search',
},
]
})
export default router
|
import Route from '@ember/routing/route';
import { hash } from 'rsvp';
export default Route.extend({
model() {
return hash({
photo: this.store.query('airplane', {orderBy: 'manufacturer'}),
mich: this.store.query('michiganairplane', {orderBy: 'manufacturer'})
});
},
});
|
import fs_ from 'fs'
import path from 'path'
import { capitalize } from '../utils.mjs'
import { designsByType, plugins, designs } from '../../../config/software/index.mjs'
const fs = fs_.promises
const header = `/*
*
* This page was auto-generated by the prebuild script
* Any changes you make to it will be lost on the next (pre)build.
*
* If you want to make changes, update the pageTemplate in:
*
* sites/shared/prebuild/lab.mjs
*
*/`
const pageTemplate = (design) => `${header}
import { ${capitalize(design)} } from 'designs/${design}/src/index.mjs'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import { WorkbenchPage } from 'site/page-templates/workbench.mjs'
const Page = (props) => <WorkbenchPage {...props} design={${capitalize(design)}} version="next"/>
export default Page
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale)),
}
}
}
`
/*
* Main method that does what needs doing
*/
export const prebuildLab = async () => {
const promises = []
for (const section in designsByType) {
// Iterate over sections
console.log(`Generating pages for ${section} designs`)
for (const design in designsByType[section]) {
// Generate pattern pages for next
console.log(` - ${design}`)
const page = pageTemplate(design)
const pages = ['..', 'lab', 'pages']
await fs.mkdir(path.resolve(...pages, 'v', 'next'), { recursive: true })
promises.push(
fs.writeFile(path.resolve(...pages, `${design}.mjs`), page),
fs.writeFile(path.resolve(...pages, section, `${design}.mjs`), page)
)
}
}
// Write designs file
const header =
'// This file is auto-generated by the prebuild script | Any changes will be overwritten\n'
const nl = '\n'
promises.push(
fs.writeFile(
path.resolve('..', 'lab', 'prebuild', 'designs.mjs'),
`${header}export const designs = ${JSON.stringify(Object.keys(designs))}${nl}`
),
fs.writeFile(
path.resolve('..', 'lab', 'prebuild', 'plugins.mjs'),
`${header}export const plugins = ${JSON.stringify(Object.keys(plugins))}${nl}`
),
fs.writeFile(
path.resolve('..', 'lab', 'prebuild', 'designs-by-type.mjs'),
`${header}export const designsByType = ${JSON.stringify(designsByType)}${nl}`
)
)
await Promise.all(promises)
}
|
import Link from "next/link";
export default function Header({ title }) {
return (
<Link href="/">
<h1 className="sticky top-0 z-50 py-10 w-full text-3xl text-center font-bold bg-white cursor-pointer">
{title}
</h1>
</Link>
);
}
|
/*
** (C) Copyright 2009-2010 by Richard Doll, All Rights Reserved.
**
** License:
** You are free to use, copy, or modify this software provided it remains free
** of charge for all users, the source remains open and unobfuscated, and the
** author, copyright, license, and warranty information remains intact and
** clearly visible.
**
** Warranty:
** All content is provided as-is. The user assumes all liability for any
** direct or indirect damages from usage.
*/
/*
** ocp-race.js
**
** Everything related to race.
** Note: Race usually means Gender and Race since the gender affects starting attributes.
**
** All of these images were converted to JPG from the individual race details pages under
** http://www.elderscrolls.com/codex/races_map.htm
** Note: The JPG conversion eliminated the transparency present in the source GIFs.
** TODO: The background used to replace transparency is not the same for all race images.
**
** Descriptions also taken from the individual race details pages under
** http://www.elderscrolls.com/codex/races_map.htm
**
** TODO: Add height/weight info (esp height since it affects movement speed)
** TODO: Show resists, water breathing, and night-eye in details table?
*/
ocp.race = {
// Private: Location of our images
IMAGE_DIR: ocp.IMAGE_ROOT_DIR + 'race/',
// Private: Data for all races and genders
_data: {
'Argonian': {
attributes: {
'Male': { str:40, itl:40, wil:30, agi:50, spe:50, end:30, per:30, luc:50 },
'Female': { str:40, itl:50, wil:40, agi:40, spe:40, end:30, per:30, luc:50 }
},
skills: { alc:5, ath:10, bla:5, han:5, ill:5, mys:5, sec:10 },
specials: [
'Resist Disease (self, magnitude 75, constant)',
'Resist Poison (self, magnitude 100, constant)',
'Water Breathing (self, constant)'
],
image: 'argonian.jpg',
description: 'Little is known and less is understood about the reptilian denizens ' +
'of Black Marsh. Years of defending their borders have made the Argonians ' +
'experts in guerilla warfare, and their natural abilities make them equally at ' +
'home in water and on land. They are well-suited for the treacherous swamps of ' +
'their homeland, and have developed natural immunities to the diseases and ' +
'poisons that have doomed many would-be explorers into the region. Their ' +
'seemingly expressionless faces belie a calm intelligence, and many Argonians ' +
'are well-versed in the magical arts. Others rely on stealth or steel to ' +
'survive, and their natural agility makes them adept at either. They are, in ' +
'general, a reserved people, slow to trust and hard to know. Yet, they are ' +
'fiercely loyal, and will fight to the death for those they have named as friends.'
},
'Breton': {
attributes: {
'Male': { str:40, itl:50, wil:50, agi:30, spe:30, end:30, per:40, luc:50, mag:50 },
'Female': { str:30, itl:50, wil:50, agi:30, spe:40, end:30, per:40, luc:50, mag:50 }
},
skills: { alc:5, alt:5, con:10, ill:5, mys:10, res:10 },
specials: [
'Fortify Maximum Magicka (self, magnitude 50, constant)',
'Resist Magicka (self, magnitude 50, constant)',
'Shield (self, magnitude 50, duration 60, once a day)'
],
image: 'breton.jpg',
description: 'Passionate and eccentric, poetic and flamboyant, intelligent and ' +
'willful, the Bretons feel an inborn, instinctive bond with the mercurial ' +
'forces of magic and the supernatural. Many great sorcerers have come out of ' +
'their home province of High Rock, and in addition to their quick and ' +
'perceptive grasp of spellcraft, enchantment, and alchemy, even the humblest ' +
'of Bretons can boast a high resistance to destructive and dominating magical ' +
'energies.'
},
'Dark Elf': {
attributes: {
'Male': { str:40, itl:40, wil:30, agi:40, spe:50, end:40, per:30, luc:50 },
'Female': { str:40, itl:40, wil:30, agi:40, spe:50, end:30, per:40, luc:50 }
},
skills: { ath:5, bla:10, blu:5, des:10, lig:5, mar:5, mys:5 },
specials: [
'Summon Ghost (duration 60, once a day)',
'Resist Fire (self, magnitude 75, constant)'
],
image: 'darkelf.jpg',
description: 'Dark Elves are the dark-skinned Elven peoples of the Eastern Empire. ' +
'"Dark" is variously understood to mean "dark-skinned", ' +
'"gloomy", and "ill-favored by fate". The Dunmer and their ' +
'national character embrace these various connotations with enthusiasm. In the ' +
'Empire, "Dark Elves" is the common usage, but in their Morrowind ' +
'homeland, and among their Aldmeri brethren, they call themselves the ' +
'"Dunmer". The dark-skinned, red-eyed Dark Elves combine powerful ' +
'intellect with strong and agile physiques, producing superior warriors and ' +
'sorcerers. On the battlefield, Dark Elves are noted for their skilled and ' +
'balanced integration of swordsmen, marksmen, and war wizards. In character, ' +
'they are grim, aloof, and reserved, distrusting and disdainful of other races.'
},
'High Elf': {
attributes: {
'Male': { str:30, itl:50, wil:40, agi:40, spe:30, end:40, per:40, luc:50, mag:100 },
'Female': { str:30, itl:50, wil:40, agi:40, spe:40, end:30, per:40, luc:50, mag:100 }
},
skills: { alc:5, alt:10, con:5, des:10, ill:5, mys:10 },
specials: [
'Fortified Maximum Magicka (self, magnitude 100, constant)',
'Weakness to Fire, Frost, and Shock (self, magnitude 25, constant)',
'Resist Desease (self, magnitude 75, constant)'
],
image: 'highelf.jpg',
description: 'In Imperial speech, the haughty, tall, golden-skinned peoples of ' +
'Summerset Isle are called "High Elves", but they call themselves the ' +
'"Altmer", or the "Cultured People". In the Empire, ' +
'"High" is often understood to mean "tall", ' +
'"proud", or "snobbish". The High Elves confidently ' +
'consider themselves, with some justice, as the most civilized culture of ' +
'Tamriel; the common tongue of the Empire, Tamrielic, is based on Altmer ' +
'speech and writing, and most of the Empire's arts, crafts, and ' +
'sciences are derived from High Elven traditions. However, the High Elf's ' +
'smug self-assurance of his superiority can be hard to bear for those of other ' +
'races. Deft, intelligent, and strong-willed, High Elves are often gifted in ' +
'the arcane arts, and High Elves boast that their sublime physical natures ' +
'make them far more resistant to disease than the "lesser races".'
},
'Imperial': {
attributes: {
'Male': { str:40, itl:40, wil:30, agi:30, spe:40, end:40, per:50, luc:50 },
'Female': { str:40, itl:40, wil:40, agi:30, spe:30, end:40, per:50, luc:50 }
},
// Note: Official Game Guide by Prima has 5 for hvy
skills: { bla:5, blu:5, han:5, hvy:10, mer:10, spc:10 },
specials: [
'Absorb Fatigure (touch, magnitude 100, once a day)',
'Charm (target, magnitude 30, once a day)'
],
image: 'imperial.jpg',
description: 'Natives of the civilized, cosmopolitan province of Cyrodiil, the ' +
'Imperials are well-educated and well-spoken. Imperials are also known for ' +
'the discipline and training of their citizen armies. Though physically less ' +
'imposing than the other races, the Imperials have proved to be shrewd ' +
'diplomats and traders, and these traits, along with their remarkable skill ' +
'and training as light infantry, have enabled them to subdue all the other ' +
'nations and races, and to have erected the monument to peace and prosperity ' +
'that comprises the Glorious Empire.'
},
'Khajiit': {
attributes: {
'Male': { str:40, itl:40, wil:30, agi:50, spe:40, end:30, per:40, luc:50 },
'Female': { str:30, itl:40, wil:30, agi:50, spe:40, end:40, per:40, luc:50 }
},
skills: { acr:10, ath:5, bla:5, han:10, lig:5, sec:5, sne:5 },
specials: [
'Demoralize (target, magnitude 100, duration 30, once a day)',
'Night-Eye (self, duration 30, unlimited uses)'
],
image: 'khajiit.jpg',
description: 'Khajiit hail from the province of Elsweyr and can vary in appearance ' +
'from nearly Elven to the cathay-raht "jaguar men" to the great ' +
'Senche-Tiger. The most common breed found in Morrowind, the suthay-raht, is ' +
'intelligent, quick, and agile. Khajiit of all breeds have a weakness for ' +
'sweets, especially the drug known as skooma. Many Khajiit disdain weapons in ' +
'favor of their natural claws. They make excellent thieves due to their natural ' +
'agility and unmatched acrobatics ability. Many Khajiit are also warriors, ' +
'although this is less common among the suthay-raht.'
},
'Nord': {
attributes: {
'Male': { str:50, itl:30, wil:30, agi:40, spe:40, end:50, per:30, luc:50 },
'Female': { str:50, itl:30, wil:40, agi:40, spe:40, end:40, per:30, luc:50 }
},
skills: { arm:5, bla:10, blo:5, blu:10, hvy:10, res:5 },
specials: [
'Frost Damage (touch, magnitude 50, once a day)',
'Shield (self, magnitude 30, duration 60, once a day)',
'Resist Frost (self, magnitude 50, constant)'
],
image: 'nord.jpg',
description: 'The citizens of Skyrim are a tall and fair-haired people, aggressive ' +
'and fearless in war, industrious and enterprising in trade and exploration. ' +
'Skilled sailors, Nords can be found in seaports and settlements along all the ' +
'coasts and rivers of Tamriel. Strong, stubborn, and hardy, Nords are famous ' +
'for their resistance to cold, even magical frost. Violence is an accepted and ' +
'comfortable aspect of Nord culture; Nords of all classes are skilled with a ' +
'variety of weapon and armor styles, and they cheerfully face battle with an ' +
'ecstatic ferocity that shocks and appalls their enemies.'
},
'Orc': {
attributes: {
'Male': { str:45, itl:30, wil:50, agi:35, spe:30, end:50, per:30, luc:50 },
'Female': { str:45, itl:40, wil:45, agi:35, spe:30, end:50, per:25, luc:50 }
},
skills: { arm:10, blo:10, blu:10, han:5, hvy:10 },
specials: [
'Beserk (Fortify Health 20, Fortify Fatigue 200, Fortify Strength 50, ' +
'Drain Agility 100, self, duration 60, once a day)',
'Resist Magicka (self, magnitude 25, constant)'
],
image: 'orc.jpg',
description: 'These sophisticated barbarian beast peoples of the Wrothgarian ' +
'and Dragontail Mountains are noted for their unshakeable courage in war and ' +
'their unflinching endurance of hardships. In the past, Orcs have been widely ' +
'feared and hated by the other nations and races of Tamriel, but they have ' +
'slowly won acceptance in the Empire, in particular for their distinguished ' +
'service in the Emperor's Legions. Orcish armorers are prized for their ' +
'craftsmanship, and Orc warriors in heavy armor are among the finest front-line ' +
'troops in the Empire. Most Imperial citizens regard Orc society as rough and ' +
'cruel, but there is much to admire in their fierce tribal loyalties and ' +
'generous equality of rank and respect among the sexes.'
},
'Redguard': {
attributes: {
'Male': { str:50, itl:30, wil:30, agi:40, spe:40, end:50, per:30, luc:50 },
'Female': { str:40, itl:30, wil:30, agi:40, spe:40, end:50, per:40, luc:50 }
},
skills: { ath:10, bla:10, blu:10, lig:5, hvy:5, mer:5 },
specials: [
'Adrenaline Rush (Fortify Agility 50, Fortify Speed 50, Fortify Strength 50, ' +
'Fortify Endurance 50, Fortify Health 25, self, duration 60, once a day)',
'Resist Poison (self, magnitude 75, constant)',
'Resist Disease (self, magnitude 75, constant)'
],
image: 'redguard.jpg',
description: 'The most naturally talented warriors in Tamriel, the dark-skinned, ' +
'wiry-haired Redguards of Hammerfell seem born to battle, though their pride ' +
'and fierce independence of spirit makes them more suitable as scouts or ' +
'skirmishers, or as free-ranging heroes and adventurers, than as rank-and-file ' +
'soldiers. In addition to their cultural affinities for many weapon and armor ' +
'styles, Redguards are also physically blessed with hardy constitutions and ' +
'quickness of foot.'
},
'Wood Elf': {
attributes: {
'Male': { str:30, itl:40, wil:30, agi:50, spe:50, end:40, per:30, luc:50 },
'Female': { str:30, itl:40, wil:30, agi:50, spe:50, end:30, per:40, luc:50 }
},
skills: { acr:5, alc:10, alt:5, lig:5, mar:10, sne:10 },
specials: [
'Command Creature (target, magnitude 20, duration 60, once a day)',
'Resist Disease (self, magnitude 75, constant)'
],
image: 'woodelf.jpg',
description: 'The Wood Elves are the various barbarian Elven clanfolk of the ' +
'Western Valenwood forests. In the Empire, they are collectively referred to ' +
'as "Wood Elves", but "Bosmer", or "the Tree-Sap ' +
'People", is what they call themselves. "Tree-Sap" suggests the ' +
'wild vitality and youthful energy of Wood Elves, in contrast with their more ' +
'dour cousins, the Altmer and Dunmer. Bosmer reject the stiff, formal ' +
'traditions of Aldmeri high culture, preferring a romantic, simple existence ' +
'in harmony with the land, its wild beauty and wild creatures. These country ' +
'cousins of the High Elves and Dark Elves are nimble and quick in body and wit, ' +
'and because of their curious natures and natural agility, Wood Elves are ' +
'especially suitable as scouts, agents, and thieves. But most of all, the Wood ' +
'Elves are known for their skills with bows; there are no finer archers in all ' +
'of Tamriel.'
}
},
// Private: Currently selected race and gender
_race: '-none-',
_gender: '-none-',
// Private: Min/max limits of attributes for all races combined
_limits: null,
// Private: The race dialog
_raceDialog: null,
// Private: The current gender selection dialog opened
_genderDialog: null,
// Private: Gets an attribute value for a race or returns 0 if none
_getAttr: function (race, gender, attr) {
var attrs = this._data[race].attributes[gender];
return (attr in attrs ? attrs[attr] : 0);
},
// Private: Gets a skill value for a race or returns 0 if none
_getSkill: function (race, skill) {
var skills = this._data[race].skills;
return (skill in skills ? skills[skill] : 0);
},
// Public: getters for all data of the currently selected race and gender
get str () { return this._getAttr(this._race, this._gender, 'str'); },
get itl () { return this._getAttr(this._race, this._gender, 'itl'); },
get wil () { return this._getAttr(this._race, this._gender, 'wil'); },
get agi () { return this._getAttr(this._race, this._gender, 'agi'); },
get spe () { return this._getAttr(this._race, this._gender, 'spe'); },
get end () { return this._getAttr(this._race, this._gender, 'end'); },
get per () { return this._getAttr(this._race, this._gender, 'per'); },
get luc () { return this._getAttr(this._race, this._gender, 'luc'); },
get hea () { return this._getAttr(this._race, this._gender, 'hea'); },
get mag () { return this._getAttr(this._race, this._gender, 'mag'); },
get fat () { return this._getAttr(this._race, this._gender, 'fat'); },
get enc () { return this._getAttr(this._race, this._gender, 'enc'); },
get bla () { return this._getSkill(this._race, 'bla'); },
get blu () { return this._getSkill(this._race, 'blu'); },
get han () { return this._getSkill(this._race, 'han'); },
get alc () { return this._getSkill(this._race, 'alc'); },
get con () { return this._getSkill(this._race, 'con'); },
get mys () { return this._getSkill(this._race, 'mys'); },
get alt () { return this._getSkill(this._race, 'alt'); },
get des () { return this._getSkill(this._race, 'des'); },
get res () { return this._getSkill(this._race, 'res'); },
get mar () { return this._getSkill(this._race, 'mar'); },
get sec () { return this._getSkill(this._race, 'sec'); },
get sne () { return this._getSkill(this._race, 'sne'); },
get acr () { return this._getSkill(this._race, 'acr'); },
get ath () { return this._getSkill(this._race, 'ath'); },
get lig () { return this._getSkill(this._race, 'lig'); },
get arm () { return this._getSkill(this._race, 'arm'); },
get blo () { return this._getSkill(this._race, 'blo'); },
get hvy () { return this._getSkill(this._race, 'hvy'); },
get ill () { return this._getSkill(this._race, 'ill'); },
get mer () { return this._getSkill(this._race, 'mer'); },
get spc () { return this._getSkill(this._race, 'spc'); },
get specials () { return this._data[this._race].specials; },
// Public: Returns the min/max possible value for an attribute
// Note: Initialize is called so ocp.initialize can call these
attrMin: function (attr) {
this._initializeLimits();
return this._limits[attr].min;
},
attrMax: function (attr) {
this._initializeLimits();
return this._limits[attr].max;
},
// Public: Initialize
initialize: function() {
// Initialize our data
this._raceDialog = dijit.byId('raceDialog');
// Initialize the min/max limits
this._initializeLimits();
// Hook the race dialog to initialize it the first time it's shown
var _this = this;
var handle = dojo.connect(this._raceDialog, 'onShow',
function (/* event */) {
// From closure: _this, handle
// Disconnect so we only do this once
dojo.disconnect(handle);
handle = null;
_this._initializeDialog();
});
// Select an initial race
this._select('Argonian', 'Male');
},
// Private: Initialize the min/max limits for all attributes of all races
// Note: This can be called multiple times, so make sure we only init once.
_initializeLimits: function() {
// Only init if we haven't yet
if (!this._limits) {
// Search through all attributes for all races and genders
this._limits = {};
for (var raceIndex in this._data) {
var attributes = this._data[raceIndex].attributes;
for (var genderIndex in attributes) {
var gender = attributes[genderIndex];
for (var attr in gender) {
// If this attr doesn't have limits yet, set initial ones
if (!(attr in this._limits)) {
this._limits[attr] = { min:9999, max:0 };
}
// Update the min/max as necessary
if (gender[attr] < this._limits[attr].min) {
this._limits[attr].min = gender[attr];
}
if (gender[attr] > this._limits[attr].max) {
this._limits[attr].max = gender[attr];
}
}
}
}
}
},
// Private: Initialize the race dialog
_initializeDialog: function() {
console.debug('entered _initializeDialog');
this._initializeOverview();
this._initializeDetails();
},
// Private: Populate the overview pane with _data info
_initializeOverview: function() {
// Build a div for each race
var over = '';
for (var race in this._data) {
over +=
'<div class="raceOverview">' +
'<img src="' + this.IMAGE_DIR + this._data[race].image + '" ' +
'class="raceImage" alt="[' + race + ' Image]" ' +
'title="Select ' + race + '" ' +
'onClick="ocp.race.openGenderDialog(\'' + race + '\')" ' +
'/>' +
'<div class="raceDetails">' +
'<div class="raceName">' + race + '</div>' +
'<div class="raceDescription">' +
this._data[race].description +
'</div>' +
'<div class="raceListHeader">Special Abilities and Weaknesses:</div>' +
'<ul class="raceSpecialList">';
var specs = this._data[race].specials;
specs = (specs.length > 0 ? specs : [ 'No special abilities or weaknesses.' ]);
for (var specIndex in specs) {
over += '<li class="raceSpecialItem">' + specs[specIndex] + '</li>';
}
over += '</ul></div></div>';
}
// Insert the results
dojo.place(over, 'raceOverviewPane', 'only');
},
// Private: Populate the race details with the values from _data
_initializeDetails: function() {
// Build a large table for all race info
var det = '<table id="raceDetailsTable">';
// Use column groups to apply styles dividing each column
det += '<colgroup span="2" />';
var firstRace = true;
for (var race in this._data) {
// TODO: raceData's width doesn't work here -- using th.raceName instead
// det += '<colgroup span="2" class="raceData' +
// (firstRace ? '' : ' first') + '" />';
det += '<colgroup span="2"' +
(firstRace ? '' : ' class="first"') + ' />';
firstRace = false;
}
// Now the headers
det += '<thead>';
// Build the first header row for the races, but span all genders
det += '<tr><th colspan="2"></th>';
for (var race in this._data) {
det += '<th class="raceName" colspan="2">' + race + '</th>';
}
det += '</tr>';
// Now the genders with the selection buttons
det += '<tr class="last"><th colspan="2">Attributes</th>';
for (var race in this._data) {
for (var gender in this._data[race].attributes) {
det += '<th>' +
'<button dojoType="dijit.form.Button" ' +
'type="submit"' +
'title="Select ' + gender + ' ' + race + '" ' +
'onClick="ocp.race.select(\'' + race + '\', \'' + gender + '\')" ' +
'>' +
gender.charAt(0) +
'</button></th>';
}
}
// Complete the header and start the body
det += '</tr></thead>';
// First do a row for each core attribute
det += '<tbody>';
for (var attr in ocp.coreAttrs) {
det += '<tr><td colspan="2">' + ocp.coreAttrs[attr].name + '</td>';
for (var raceIndex in this._data) {
var attributes = this._data[raceIndex].attributes;
for (var genderIndex in attributes) {
var gender = attributes[genderIndex];
var extra = '';
if (attr != 'luc') { // Luck is the same for everyone, not better/worse
extra = (gender[attr] > ocp.RACE_ATTR_NORM
? 'better'
: (gender[attr] < ocp.RACE_ATTR_NORM ? 'worse' : ''));
}
det += '<td class="numeric ' + extra + '">' + gender[attr] + '</td>';
}
}
det += '</tr>';
}
det += '</tbody>';
// Since two races have Magicka bonuses, show a Magicka row too
det += '<tbody><tr><td colspan="2">' + ocp.derivedAttrs.mag.name + '</td>';
for (var raceIndex in this._data) {
var attributes = this._data[raceIndex].attributes;
for (var genderIndex in attributes) {
var gender = attributes[genderIndex];
if ('mag' in gender) {
det += '<td class="numeric better">' + gender.mag + '</td>';
} else {
det += '<td class="numeric" />';
}
}
}
det += '</tr></tbody>';
// Now a "divider" row indicating we are going to skills
// For easier reading, repeat the race names
det += '<tbody><tr class="divider"><td colspan="2">Skills</td>';
for (var race in this._data) {
det += '<td colspan="2">' + race + '</td>';
}
det += '</tr></tbody>';
// A row for every skill.
// Span all gender columns since skills are not gender specific
det += '<tbody>';
var rowEven = true;
for (var attr in ocp.coreAttrs) {
var firstSkill = true;
var skills = ocp.coreAttrs[attr].skills;
for (var skillIndex in skills) {
var skill = skills[skillIndex];
det += '<tr class="skill ' + (rowEven ? 'even' : 'odd') + '">';
// The first skill means we need to create a vertical skill "header"
if (firstSkill) {
det +=
'<td rowspan="' + skills.length + '" class="vertical" ' +
'ocpTooltip="[help,after]Skills that affect ' +
ocp.coreAttrs[attr].name + '"' +
'>' +
ocp.verticalize(attr) +
'</td>';
}
det += '<td>' + ocp.skills[skill].name + '</td>';
for (var race in this._data) {
var skillVal = this._getSkill(race, skill);
det += '<td class="numeric" colspan="2">' +
( skillVal > 0 ? skillVal : '' ) + '</td>';
}
det += '</tr>';
firstSkill = false;
}
rowEven = !rowEven;
}
det += '</tbody>';
// Terminate the table
det += '</table>';
// Insert the details and parse the inserted code for Dojo and OCP markups
dojo.html.set(dojo.byId('raceDetailsPane'), det, { parseContent: true });
ocp.replaceTooltips('raceDetailsPane');
},
// Public: Open a gender selection dialog for the given race
openGenderDialog: function(race) {
console.debug('entered openGenderDialog:', race);
// Create a new dialog for this race
// Since these are dynamically recreated for each race, be paranoid and use
// classes instead of ids to apply styles
this._genderDialog = new dijit.Dialog({
title: "Choose Your Character's Gender",
class: 'genderDialog',
content:
'<div class="genderDialogContainer">' +
'<div>' +
'Gender of your <span class="raceName">' + race + '</span> character?' +
'</div>' +
'<button dojoType="dijit.form.Button" ' +
'type="submit" ' +
'title="Select Male ' + race + '" ' +
'onclick="ocp.race.selectGenderDialog(\'' + race + '\', \'Male\')" ' +
'>' +
'Male' +
'</button>' +
'<button dojoType="dijit.form.Button" ' +
'type="submit" ' +
'title="Select Female ' + race + '" ' +
'onclick="ocp.race.selectGenderDialog(\'' + race + '\', \'Female\')" ' +
'>' +
'Female' +
'</button>' +
'</div>'
});
// Show the dialog
this._genderDialog.show();
},
// Public: Select a race and gender from the gender selection dialog and close everything
selectGenderDialog: function(race, gender) {
console.debug('entered selectGenderDialog:', race, gender);
ocp.race.select(race, gender);
// Since we are going to close the race dialog too, stop the gender dialog from
// trying to restore its focus after its fade out animation (since we will have
// closed the race dialog long before then so trying to refocus to a race dialog
// element will understandably fail).
this._genderDialog.refocus = false;
this.closeGenderDialog();
this._raceDialog.hide();
},
// Public: Close an open gender selection dialog (and restore focus)
closeGenderDialog: function() {
if (this._genderDialog) {
console.debug('entered closeGenderDialog');
this._genderDialog.hide();
this._genderDialog.destroy();
delete this._genderDialog;
this._genderDialog = null;
}
},
// Private: Select race/gender without error checking or notification
_select: function(race, gender) {
console.debug('entered _select:', gender, race);
// Set the current race/gender
this._race = race;
this._gender = gender;
},
// Public: Validate args, select race/gender, and notify of a change
// Should only be called from the selection dialog
select: function(race, gender) {
console.debug('entered select:', gender, race);
// Validate the selection
if (race in this._data) {
if (gender in this._data[race].attributes) {
// Assign the new values
this._select(race, gender);
// Notify that something has changed
ocp.notifyChanged();
} else {
var msg = 'Unknown gender "' + gender + '" selected for race "' + race + '".';
console.error(msg);
alert(msg);
}
} else {
var msg = 'Unknown race "' + race + '" selected.';
console.error(msg);
alert(msg);
}
},
// Public: Some character data has changed, so update our results
notifyChanged: function() {
this._update();
},
// Private: Update our generated content
_update: function() {
// Update selected label
dojo.place('<span>' + this._gender + ' ' + this._race + '</span>',
'raceValue', 'only');
// Fill in the selected specials
var list = '';
var specs = this.specials;
if (specs.length == 0) {
list = '<span class="specialDescItem">No special abilities or weaknesses.</span>';
} else {
for (var specIndex in specs) {
list += '<span class="specialDescItem">' + specs[specIndex] + '</span>';
}
}
dojo.place(list, 'raceSpecials', 'only');
}
};
|
import React from 'react';
import {notification} from 'antd';
import {startLoading, stopLoading} from './loader';
import {
createLoanRequest,
createLoanOffer,
approveTokens,
acceptLoanRequest,
acceptLoanOffer,
cancelLoanOffer,
cancelLoanRequest,
payLoanInstallment
} from '../utils/index';
import {openModal} from './modal';
const openNotification = () => {
notification.open({
placement: 'topLeft',
duration: '10',
message: <span style={{fontSize: '20px'}}>Transaction Initiated</span>,
description: <span style={{fontSize: '18px'}}>Please accept the transaction using metamask.</span>,
icon: <img src="/images/metamask.png" style={{height: '30px', width: '30px'}} alt="" />,
});
};
export const createRequest = (args) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await createLoanRequest(account, args);
dispatch(stopLoading());
dispatch(openModal('/requests'));
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const createOffer = (args) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await createLoanOffer(account, args);
dispatch(stopLoading());
dispatch(openModal('/offers'));
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const acceptRequest = (id, amount) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await acceptLoanRequest(account, id, amount);
dispatch(stopLoading());
dispatch(openModal('/offers'));
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
//call approve
export const acceptOffer = (id, amount) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await acceptLoanOffer(account, id);
dispatch(stopLoading());
dispatch(openModal('/requests'));
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const approve = (amount) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await approveTokens(account, amount);
dispatch(stopLoading());
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const cancelOffer = (id) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await cancelLoanOffer(account, id);
dispatch(stopLoading());
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const cancelRequest = (id) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await cancelLoanRequest(account, id);
dispatch(stopLoading());
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
export const payInstallment = (id, amount) => {
return async(dispatch, getState) => {
dispatch(startLoading());
openNotification();
try{
const account = getState().account;
await payLoanInstallment(account, id, amount);
dispatch(stopLoading());
return Promise.resolve();
}
catch(e){
console.log(e);
dispatch(stopLoading());
return Promise.reject(e);
}
};
}
|
/*
create by woody
date 20170301
账户页面controller
*/
angular.module('myapp').controller('AccountLoginCtrl',['$scope','$rootScope','Alert','localStorageService','Init','JumpUtil','LoadUtil',function($scope,$rootScope,Alert,localStorageService,Init,JumpUtil,LoadUtil) {
//判断用户是否登录
if(localStorageService.get("ifLogin") != undefined && localStorageService.get("ifLogin") != null && localStorageService.get("ifLogin") != "" && localStorageService.get("ifLogin") == "0"){
var data={gotoData:{url:'tab.unfinished'}};
JumpUtil.goFun(data);
return;
}
//登录
$scope.login = function(){
if($("#registercode").val() == null || $("#registercode").val() == ""){
Alert.myToastBottom({mess: "请输入统一组织机构代码",height:-160});
return;
}
if($("#username").val() == null || $("#username").val() == ""){
Alert.myToastBottom({mess: "请输入用户名",height:-160});
return;
}
if($("#pwd").val() == null || $("#pwd").val() == ""){
Alert.myToastBottom({mess: "请输入密码",height:-160});
return;
}
LoadUtil.showLoad('登录中...');
Init.iwbhttp("/login/loginForAPP",{REGISTERCODE: $("#registercode").val(),username:$("#username").val(),pwd:$("#pwd").val()},function(data,header,config,status){
if(data.resFlag == "0"){
var data={gotoData:{url:'tab.unfinished'}};
LoadUtil.hideLoad();
JumpUtil.goFun(data);
$("#pwd").val("");
}else{
//隐藏load层
LoadUtil.hideLoad();
Alert.myToastBottom({mess: data.msg,height:-160});
}
},function(data,header,config,status){
});
}
//返回
$scope.myGoBack = function() {
JumpUtil.goBackFun();
};
}]);
|
import React, { Component, PropTypes } from 'react';
import { View, Text, StyleSheet, Navigator, TouchableHighlight, Button, AsyncStorage, Picker } from 'react-native';
const Item = Picker.Item;
const _ = require('underscore');
export default class RacialStatPicker extends Component {
constructor(props) {
super(props);
this.state = {
selectedMod1: this.props.options[0].key,
selectedMod2: this.props.options[1].key
};
}
render() {
const that = this;
const pickerOptions = _.map(this.props.options, (option) => {
return <Item key={option.key} label={option.label} value={option.key} />
});
return (
<View style={styles.pickers}>
<View style={{flex: 1}}>
<Text style={styles.pickerLabel}>Stat 1: {that.state.selectedMod1}</Text>
<Picker
style={styles.picker}
selectedValue={this.state.selectedMod1}
onValueChange={(option) => {
that.setState({selectedMod1: option});
}}>
{pickerOptions}
</Picker>
</View>
<View style={{flex: 1}}>
<Text style={styles.pickerLabel}>Stat 2: {that.state.selectedMod2}</Text>
<Picker
style={styles.picker}
selectedValue={this.state.selectedMod2}
onValueChange={(option) => {
that.setState({selectedMod2: option});
}}>
{pickerOptions}
</Picker>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
pickers: {
flex: 2,
flexDirection: 'row'
},
pickerLabel: {
flex: 1,
marginHorizontal: 5
},
picker: {
flex: 3,
marginBottom: 5,
marginHorizontal: 5,
color: '#000000',
backgroundColor: '#f0f0f0'
},
});
|
var http = require('http');
var url = process.argv[2]; // 1st command line argument will supply URL
// Perform GET request, callback will be triggered once it receives data
http.get(url, callback).on('error', function(e) {
console.log("Got error: " + e.message);
});
function callback (response) {
// 'response' is a Node Stream object, bind event listener to it
// 'utf8' so that it will emit String rather than standard Node Buffer objects
response.setEncoding('utf8');
// 'data' event is emitted when a chunk of data is available
response.on("data", dataStreamCallback);
response.on('error', console.error);
}
function dataStreamCallback(data) {
console.log(data);
}
|
'use strict';
module.exports = class Base {
constructor(validator, rule = {}, key) {
this.validator = validator;
this.rule = rule;
this.key = key;
}
getMsg(msg) {
if (msg) {
if (this.rule.msg) {
msg = this.rule.msg;
} else {
msg = this.key + ':' + msg;
}
}
return msg;
}
verify(value) {
if (value === null || value === undefined) {
if (this.rule.required === false) {
return;
}
return this.getMsg('required');
}
const msg = this.check(value);
return this.getMsg(msg);
}
getDefault(value) {
const def = this.rule.default;
if (def !== undefined) {
return typeof def === 'function' ? def() : def;
}
return value;
}
transform(value) {
if (this.rule.isConver === false) {
return value;
}
if (value === undefined || value === null) {
return this.getDefault(value);
}
const val = this.conver(value);
if (val !== undefined) {
return val;
}
return value;
}
check() {
throw new Error('not impl');
}
conver(value) {
return value;
}
};
|
const qs = require('qs');
const BaseRepository = require('./base.repository');
class Tracks extends BaseRepository {
constructor() {
super();
this.spotifyApiToken = '';
}
async refreshToken() {
const {
data: { access_token: newToken }
} = await app.api.spotifyAccounts.refreshToken({
data: qs.stringify({
grant_type: 'refresh_token',
refresh_token: process.env.SPOTIFY_REFRESH_API_TOKEN
}) || { data: {} },
config: {
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
}
});
this.spotifyApiToken = newToken;
}
async getTracks({ market, query, limit, page }) {
await this.refreshToken();
return app.api.spotify.getTracks({
url: {
market,
query,
limit,
offset: page * limit
},
config: {
headers: { Authorization: `Bearer ${this.spotifyApiToken}` }
}
});
}
}
module.exports = Tracks;
|
import React, { Component } from 'react';
import { withNamespaces, Trans } from 'react-i18next';
import ContentWrapper from '../Layout/ContentWrapper';
import { Container, Progress } from 'reactstrap';
import API from '../../services/BaseService';
class Timeline extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
rows: [],
};
}
componentWillMount() {
API.get('timeline')
.then((response) => {
this.setState({rows:response.data});
console.log("checking11",this.state.rows);
});
}
render() {
return (
<ContentWrapper>
{this.state.rows && this.state.rows.length > 0 &&
<>
{
this.state.rows.map((rowsObject, index) => {
return(
<>
<h6 style={{color:"red"}}>TimeLine</h6>
<div className="d-flex">
<p className="text-muted m-0">StartDate:
<span className="text-dark font-weight-bold">{rowsObject.startdate}</span>
</p>
</div>
<div className="d-flex">
<p className="text-muted m-0">TargetCompletionDate:
<span className="text-dark font-weight-bold">{rowsObject.targetcompletiondate}</span>
</p>
</div>
<div className="d-flex">
<p className="text-muted m-0">CompletedTillDate:
<span className="text-dark font-weight-bold">{rowsObject.completedtilldate}</span>
</p>
</div>
</>
)
})
}
</>
}
</ContentWrapper>
)
}
}
export default withNamespaces('translations')(Timeline);
|
// components/tool-box/tool-box.js
const { discoveryList } = require("../../assets/discovery-list");
const { getEnum, toast, valid, hideAll, delay } = require("../../utils/common");
Component({
properties: {
// 是否显示工具箱按钮
visible: {
type: Boolean,
value: true
},
// 是否上移按钮
spaceFix: {
type: Boolean
}
},
data: {
// 是否显示聊天弹窗
$showChatListPopup: false,
// 是否显示聊天记录弹窗
$showChatDetailPopup: false,
// 是否显示编辑标题弹窗
$showEditChatPopup: false,
// 是否显示朋友圈设置弹窗
$showFriendCirclePopup: false,
// 是否显示动态弹窗
$showDynamicPopup: false,
// 聊天表单项
chatListSchema: {
id: { type: 'hidden' },
header: {
title: '头像',
type: 'media',
maxLength: 9,
description: '上传多张头像将变成群聊图标(最多9张)',
},
badge: {
title: '红点数',
type: 'number',
placeholder: '请输入红点数',
description: '不输入则不显示,输入0则显示一个小红点',
},
name: {
title: '名称',
type: 'input',
history: true,
placeholder: '请输入名称',
},
content: {
title: '聊天内容',
type: 'input',
history: true,
placeholder: '请输入聊天内容',
},
tag: {
title: '红字标签',
type: 'input',
placeholder: '请输入红字标签',
description: '聊天内容前的红字标签,比如[转账]、[语音]等,不用打中括号'
},
date: {
title: '日期',
type: 'date',
placeholder: '请选择日期',
description: '如果同时填写了日期和时间,系统会根据你所填日期时间显示为如00:25/昨天/星期六等,建议完整填写',
},
time: {
title: '时间',
type: 'time',
placeholder: '请选择时间',
},
isServiceAccount: {
title: '是否为服务号(名称为蓝色)',
type: 'radio',
enum: getEnum(['否', '是'], 2),
default: 0,
},
top: {
title: '是否置顶',
type: 'radio',
enum: getEnum(['否', '是'], 2),
default: 0,
},
},
// 聊天记录表单项
chatDetailSchema: {
id: { type: 'hidden' },
type: {
type: 'selector',
title: '消息类型',
enum: [
{ label: '普通文本', value: 'text' },
{ label: '图片/视频', value: 'media' },
{ label: '单条语音', value: 'audio' },
// { label: '视频通话', value: 'videoChat' },
// { label: '语音通话', value: 'audioChat' },
{ label: '红包', value: 'redPack' },
{ label: '转账', value: 'transfer' },
{ label: '系统提示', value: 'system' },
{ label: '红包领取提示', value: 'redPackNotice' },
],
default: 'text',
},
side: {
type: 'radio',
title: '消息位置',
enum: [{ label: '左侧', value: 'left' }, { label: '右侧', value: 'right' }],
visibleIf: { type: (val) => val != 'system' && val != 'redPackNotice' },
default: 'right',
},
date: {
title: '发送时间',
type: 'input',
placeholder: '请填写发送时间',
description: '为了最大化自定义程度,请自行填入发送时间,添加后会按照用户填写的内容显示,为了使效果更逼真,请按照示例规范填写。示例:[11:50]、[昨天 14:32]、[星期三 19:01]、[2021年7月5日 08:05]',
},
header: {
type: 'media',
title: '头像',
maxLength: 1,
visibleIf: { type: (val) => val != 'system' }
},
name: {
type: 'input',
title: '名称',
placeholder: '请输入名称',
history: true,
visibleIf: { type: (val) => val != 'system' }
},
text: {
type: 'input',
title: '文本内容',
placeholder: '请输入文本内容',
history: true,
visibleIf: { type: ['text'] }
},
systemText: {
type: 'input',
title: '系统消息',
placeholder: '请输入系统消息',
history: true,
description: 'Tips:系统消息亦可作为拍一拍文本使用',
visibleIf: { type: ['system'] },
},
systemTextBold: {
type: 'radio',
title: '系统消息是否为粗体',
enum: getEnum(['否', '是'], 2),
description: 'Tips:如果系统消息作为拍一拍文本使用,对方拍你需要显示为粗体',
visibleIf: { type: ['system'] },
default: 0
},
redPackNotice: {
type: 'input',
title: '领取人名称',
history: true,
placeholder: '请输入领取方的名称',
description: '将会显示为 xxx领取了你的红包',
visibleIf: { type: ['redPackNotice'] }
},
media: {
type: 'media',
title: '图片/视频',
visibleIf: { type: ['media'] }
},
duration: {
type: 'number',
title: '时长',
placeholder: '请输入通话时长',
visibleIf: { type: ['audio', 'videoChat', 'audioChat'] }
},
price: {
type: 'digit',
title: '金额',
placeholder: '请输入金额',
visibleIf: { type: ['redPack', 'transfer'] }
},
remark: {
type: 'input',
title: '备注内容',
history: true,
placeholder: '请输入备注',
visibleIf: { type: ['redPack', 'transfer'] },
default: '恭喜发财,大吉大利',
},
transferStatus: {
type: 'radio',
title: '状态',
enum: [
{ label: '正常', value: 'normal' },
{ label: '已领取(收款方)', value: 'received' },
{ label: '已被领取(发款方)', value: 'beReceived' },
{ label: '已过期', value: 'expired' },
{ label: '已退回(收款方)', value: 'returned' },
{ label: '已被退回(发款方)', value: 'beReturned' },
],
description: '领取和退回的状态在发款/收款两边显示文案不同,最好自行实际体验下区别',
visibleIf: { type: ['redPack', 'transfer'] },
default: 'normal'
},
},
// 编辑标题表单项
editChatSchema: {
title: {
type: 'input',
title: '标题',
history: true,
placeholder: '请输入标题',
},
badge: {
type: 'number',
title: '未读数',
placeholder: '请输入未读数',
},
customBackground: {
title: '自定义背景',
type: 'media',
maxLength: 1,
},
groupUserName: {
title: '是否显示群员名字',
type: 'radio',
enum: getEnum(['隐藏', '显示'], 2),
default: 0
}
},
// 编辑发现页表单项
discoverySchema: {},
// 朋友圈设置表单项
friendCircleSchema: {
banner: {
type: 'media',
title: '朋友圈封面',
maxLength: 1,
},
header: {
type: 'media',
title: '用户头像',
maxLength: 1,
},
name: {
type: 'input',
title: '用户名称',
history: true,
placeholder: '请输入用户名称',
},
},
// 动态表单项
dynamicSchema: {
header: {
type: 'media',
title: '用户头像',
maxLength: 1,
},
name: {
type: 'input',
title: '用户名称',
history: true,
placeholder: '请输入用户名称',
},
picture: {
type: 'media',
title: '图片',
maxLength: 9,
},
date: {
type: 'input',
title: '时间',
placeholder: '请输入时间',
}
},
},
methods: {
// 点击工具箱按钮事件
showAction() {
// 获取当前页面
let pages = getCurrentPages();
let currentPage = pages[pages.length - 1];
let url = currentPage.route;
// 通过当前页面判断要打开哪个actionSheet
if (url == 'pages/index/index') {
const tabIndex = currentPage.data.tabIndex;
if (tabIndex == 0) this.showActionInChatList();
if (tabIndex == 2) this.showActionInDiscovery();
} else if (url == 'subPack-a/pages/chat-detail/chat-detail') {
this.showActionInChatDetail();
} else if (url == 'subPack-a/pages/friend-circle/friend-circle') {
this.showActionInFriendCircle();
}
},
// 添加聊天列表
showActionInChatList() {
let itemList = ['添加聊天', '删除所有聊天', '隐藏工具箱按钮', '清空缓存'];
wx.showActionSheet({
alertText: '聊天列表工具箱',
itemList,
}).then((res) => {
switch (res.tapIndex) {
case 0:
this.setData({ $showChatListPopup: true }, () => {
// 获取聊天弹窗组件对象
this.chatListSF = this.selectComponent('#chatListSF');
});
break;
case 1:
this.handleChange('clearAll');
break;
case 2:
this.handleHide();
break;
case 3:
this.handleChange('clearAll');
break;
}
}).catch(() => null);
},
// 添加聊天记录
showActionInChatDetail(index) {
const handleAction = (tapIndex) => {
switch (tapIndex) {
case 0:
this.setData({ $showEditChatPopup: true }, () => {
// 获取编辑标题弹窗组件对象
this.editChatSF = this.selectComponent('#editChatSF');
});
break;
case 1:
this.setData({ $showChatDetailPopup: true }, () => {
// 获取聊天记录弹窗组件对象
this.chatDetailSF = this.selectComponent('#chatDetailSF');
});
break;
case 2:
this.handleChange('clearAll');
break;
case 3:
this.handleHide();
break;
}
};
if (valid(index)) {
handleAction(index);
return;
}
let itemList = ['聊天窗口设置', '添加聊天记录', '清空所有聊天记录', '隐藏工具箱按钮'];
wx.showActionSheet({
alertText: '聊天详情工具箱',
itemList,
}).then((res) => {
handleAction(res.tapIndex);
}).catch(() => null);
},
// 发现页选择
showActionInDiscovery() {
let itemList = ['发现页设置', '隐藏工具箱按钮'];
wx.showActionSheet({
alertText: '发现页工具箱',
itemList,
}).then((res) => {
switch (res.tapIndex) {
case 0:
this.data.discoverySchema = {};
discoveryList.map((item) => {
this.data.discoverySchema[`${item.id}`] = {
title: item.name,
switchLabel: '是否显示',
type: 'boolean',
default: true,
};
});
this.setData({
$showDiscoveryPopup: true,
discoverySchema: this.data.discoverySchema,
}, () => {
// 获取聊天弹窗组件对象
this.discoverySF = this.selectComponent('#discoverySF');
let data = wx.getStorageSync('DISCOVERY_LIST') || {};
for (let key in data) {
data[key] = !!data[key];
}
this.discoverySF.setFormData(data);
});
break;
case 1:
this.handleHide();
break;
}
}).catch(() => null);
},
// 朋友圈
showActionInFriendCircle() {
let itemList = ['朋友圈设置', '添加动态', '清空动态', '隐藏工具箱按钮'];
wx.showActionSheet({
alertText: '朋友圈工具箱',
itemList,
}).then((res) => {
switch (res.tapIndex) {
case 0:
this.setData({ $showFriendCirclePopup: true }, () => {
// 获取朋友圈设置弹窗组件对象
this.friendCircleSF = this.selectComponent('#friendCircleSF');
});
break;
case 1:
this.setData({ $showDynamicPopup: true }, () => {
// 获取动态弹窗组件对象
this.dynamicSF = this.selectComponent('#dynamicSF');
});
break;
case 2:
this.handleChange('clearAll');
break;
case 3:
this.handleHide();
break;
}
}).catch(() => null);
},
// 隐藏工具箱按钮
handleHide() {
toast.fail('长按顶部标题或重启小程序可重新显示工具箱按钮');
this.setData({ visible: false });
},
// 显示编辑聊天弹窗
handleEditChatList(item) {
this.setData({ $showChatListPopup: true }, () => {
// 获取聊天弹窗组件对象
this.chatListSF = this.selectComponent('#chatListSF');
this.chatListSF.setFormData(item);
});
},
// 显示添加聊天弹窗
handleAddChat() {
this.handleClosePopup();
let formData = this.chatListSF.getFormData();
this.handleChange(formData.id ? 'editChat' : 'addChat', formData);
},
// 显示编辑聊天弹窗
handleEditChatDetail(item) {
this.setData({ $showChatDetailPopup: true }, () => {
// 获取聊天记录弹窗组件对象
this.chatDetailSF = this.selectComponent('#chatDetailSF');
this.chatDetailSF.setFormData(item);
});
},
// 添加/编辑聊天记录变更
handleAddChatDetail() {
this.handleClosePopup();
let formData = this.chatDetailSF.getFormData();
this.handleChange(formData.id ? 'editChatDetail' : 'addChatDetail', formData);
},
// 编辑标题变更
handleEditChat() {
this.handleClosePopup();
let formData = this.editChatSF.getFormData();
this.handleChange('editChat', formData);
},
// 编辑发现页设置
handleDiscovery() {
this.handleClosePopup();
let formData = this.discoverySF.getFormData();
this.handleChange('discovery', formData);
},
// 编辑朋友圈设置
handleFriendCircle() {
this.handleClosePopup();
let formData = this.friendCircleSF.getFormData();
this.handleChange('friendCircle', formData);
},
// 添加动态
handleDynamic() {
this.handleClosePopup();
let formData = this.dynamicSF.getFormData();
this.handleChange(formData.id ? 'editDynamic' : 'addDynamic', formData);
},
// 工具箱变更回调
handleChange(change, data) {
this.triggerEvent('change', { change, data });
},
// 关闭弹窗
handleClosePopup() {
delay(() => { hideAll(this); }, 500);
},
}
});
|
function signin() {
var val = $('input:radio[name="role"]:checked').val();
if( val == 1 ){
$.ajax({
url: "/qa-data/user/buyerRegister",
type: "post",
data: $("#signin_form").serialize(),
async: true,
success: function(data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("注册成功,请等待管理员验证");
window.location.href = "/qa-data/login"
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
});
}
if( val == 2 ){
$.ajax({
url: "/qa-data/user/factoryRegister",
type: "post",
data: $("#signin_form").serialize(),
async: true,
success: function(data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("注册成功,请等待管理员验证");
window.location = "login.html";
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
});
}
}
function sendCode() {
$.ajax({
url: "/qa-data/user/sendRegisterCode",
type: "post",
data: $("#mail").serialize(),
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("验证码已发送至邮箱");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
function enable(tablemail, userstate) {
var mail = document.getElementById(tablemail).innerHTML;
var state = document.getElementById(userstate).innerHTML;
if (state == "待验证" || state == "禁用") {
if (confirm("你要激活此用户么?")) {
$.ajax({
url: "enableUser",
type: "post",
data: {mail: mail},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("激活成功");
location.reload();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
}
if (state == "已启用") {
if (confirm("你要禁用此用户么?")) {
$.ajax({
url: "unableUser",
type: "post",
data: {mail: mail},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("禁用成功");
location.reload();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
}
}
function changeInfo(newNumber, newName, newMail,user_id) {
var number = document.getElementById(newNumber).value;
var name = document.getElementById(newName).value;
var receive_mail = document.getElementById(newMail).value;
var id=document.getElementById(user_id).innerHTML;
$.ajax({
url: "changeUserInfo",
type: "post",
data: {id: id, name: name, phonenumber: number, receiveMail: receive_mail},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("更新用户信息成功");
location.reload();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
function prepage() {
var currentp = $("#current_page").text();
var targetp = parseInt(currentp) - 1;
var content = $("#searchContent").val();
content = $.trim(content);
if (currentp == 1) {
alert("已经是第一页");
}
else {
if (content == "") {
getAllUserAjax(targetp)
} else {
searchAjax(targetp,content)
}
}
}
function afterpage() {
var currentp = $("#current_page").text();
var targetp = parseInt(currentp) + 1;
var lastp = $("#total_page").text();
var content = $("#searchContent").val();
content = $.trim(content);
if (lastp == currentp) {
alert("已经是最后一页");
}
else {
if (content == "") {
getAllUserAjax(targetp);
} else {
searchAjax(targetp,content)
}
}
}
function pageChange(data) {
$(".userRow").remove();
$.each(data.objects, function (i, item) {
var content = "<tr class=\"userRow\">" +
"<td class=\"text-center\" id = \"user_id" + i + "\">" + item.id + "</td>" +
"<td>" + item.type + "</td>" +
"<td id=\"mail" + i + "\">" + item.mail + "</td>" +
"<td>" + item.phonenumber + "</td>" +
"<td>" + item.name + "</td>" +
"<td>" + item.receiveMail + "</td>" +
"<td> <a role=\"button\" onclick=\"enable('mail" + i + "','state" + i + "')\" id=\"state" + i + "\">" + item.state + "</a></td> " +
"<td ><a role=\"button\" data-toggle=\"collapse\" href=\"#collapseListGroup" + i + "\" aria-expanded=\"true\" aria-controls=\"collapseListGroup1\">编辑</a></td>" + +"</tr>" +
"<tr class=\"userRow\">" +
"<td colspan=\"8\">" +
"<div id=\"collapseListGroup" + i + "\" class=\"panel-collapse collapse\" role=\"tabpanel\" aria-labelledby=\"collapseListGroupHeading1\" aria-expanded=\"true\">" +
"<ul class=\"list-group\">" +
"<li class=\"list-group-item\"><div class=\"row\" style=\"font-size: 12px;\">" +
"<div class=\"col-md-1 text-right\" style=\"margin-top: 0.2em;\" >" +
"手机号" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_number" + i + "\" />" +
"</div>" +
"<div class=\"col-md-1 text-right\" style=\"margin-top: 0.2em;\" >" +
"公司名称" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_name" + i + "\"/>" +
"</div>" +
"<div class=\"col-md-1 text-right\" style=\"margin-top: 0.2em;\" >" +
"消息接收邮箱" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_mail" + i + "\"/>" +
"</div>" +
"<div class=\"col-md-3 text-right\">" +
"<button class=\"btn btn-primary\" onclick = \" changeInfo('new_number" + i + "','new_name" + i + "','new_mail" + i + "','user_id" + i + "')\" >保存</button>" +
"</div>" +
"</div>" +
"</li>" +
"</ul>" +
"</div>" +
"</div>" +
"</td>" +
"</tr>"
$("#admin_usertable tr").eq(0).after(content);
})
$("#current_page").text(data.currentPage);
$("#total_page").text(data.totalPage);
}
function getAllUserAjax(targetp) {
$.ajax({
url: "getAllUser",
type: "post",
data: {pageNumber: targetp},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
pageChange(data);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
function searchAjax(pageNumber,content) {
$.ajax({
url: "searchAllUser",
type: "post",
data: {pageNumber: pageNumber, content: content},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
pageChange(data)
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
function search() {
var content = $("#searchContent").val();
content = $.trim(content);
searchAjax(1,content);
}
function jump() {
var targetp = $("#pagenumber").val();
var lastp = $("#total_page").text();
if (parseInt(targetp) != targetp || parseFloat(targetp) < 1 || parseFloat(targetp) > parseFloat(lastp)) {
alert("页面不存在");
}
else {
$.ajax({
url: "getAllUser",
type: "post",
data: {pageNumber: targetp},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
$(".userRow").remove();
$.each(data.objects, function (i, item) {
var content = "<tr class=\"userRow\">" +
"<td class=\"text-center\" id = \"user_id" + i + "\">" + item.id + "</td>" +
"<td>" + item.type + "</td>" +
"<td>" + item.mail + "</td>" +
"<td>" + item.phonenumber + "</td>" +
"<td>" + item.name + "</td>" +
"<td id = \"mail" + i + "\">" + item.receiveMail + "</td>" +
"<td> <a role=\"button\" onclick=\"enable('mail" + i + "','state" + i + "')\" id=\"state" + i + "\">" + item.state + "</a></td> " +
"<td ><a role=\"button\" data-toggle=\"collapse\" href=\"#collapseListGroup" + i + "\" aria-expanded=\"true\" aria-controls=\"collapseListGroup1\">编辑</a></td>" + +"</tr>" +
"<tr class=\"userRow\">" +
"<td colspan=\"8\">" +
"<div id=\"collapseListGroup" + i + "\" class=\"panel-collapse collapse\" role=\"tabpanel\" aria-labelledby=\"collapseListGroupHeading1\" aria-expanded=\"true\">" +
"<ul class=\"list-group\">" +
"<li class=\"list-group-item\"><div class=\"row\" style=\"font-size: 12px;\">" +
"<div class=\"col-md-1 text-right\" style=\"margin-top: 0.2em;\" >" +
"手机号" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_number" + i + "\" />" +
"</div>" +
"<div class=\"col-md-1 text-right\" style=\"margin-top: 0.2em;\" >" +
"公司名称" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_name" + i + "\"/>" +
"</div>" +
"<div class=\"col-md-2 text-right\" style=\"margin-top: 0.2em;\">" +
"消息接收邮箱" +
"</div>" +
"<div class=\"col-md-2\">" +
"<input type=\"text\" id = \"new_mail" + i + "\" />" +
"</div>" +
"<div class=\"col-md-2 text-right\">" +
"<button class=\"btn btn-primary\" onclick = \" changeInfo('new_number" + i + "','new_name" + i + "','new_mail" + i + "', 'user_id" + i + "', 'mail" + i + "')\" >保存</button>" +
"</div>" +
"</div>" +
"</li>" +
"</ul>" +
"</div>" +
"</div>" +
"</td>" +
"</tr>"
$("#admin_usertable tr").eq(0).after(content);
})
$("#current_page").text(data.currentPage);
$("#total_page").text(data.totalPage);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
}
function sendFindCode() {
$.ajax({
url: "user/sendFindCode.do",
type: "post",
data: $("#mail2").serialize(),
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("验证码已发送至邮箱");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
function resetPassword() {
var mail = $("#mail2").val();
var checkcode = $("#findcode").val();
var newpassword = $("#newpassword").val();
$.ajax({
url: "user/resetPassword.do",
type: "post",
data: {mail: mail, checkCode: checkcode, newPassword: newpassword},
async: true,
success: function (data) {
if (data.success == false) {
alert(data.errMsg);
}
else {
alert("修改密码成功");
window.location = "login.html";
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
|
/// TODO: REVIEW
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDuplicates = function(nums) {
var res = [];
for (var i = 0; i < nums.length; i++) {
var idx = Math.abs(nums[i]) - 1;
if (nums[idx] < 0) res.push(idx +1);
nums[idx] = - nums[idx];
}
return res;
};
|
let AddCtrl = function($scope, CharactersService){
$scope.addChar = function(char){
CharactersService.addChar(char).then( (res) => {
console.log(res);
});
}
}
AddCtrl.$inject = ['$scope', 'CharactersService'];
export default AddCtrl;
|
// ================================================================================
//
// Copyright: M.Nelson - technische Informatik
// Die Software darf unter den Bedingungen
// der APGL ( Affero Gnu Public Licence ) genutzt werden
//
// weblet: warehouse/part/storage/masterdata
// ================================================================================
{
var i;
var str = "";
var ivalues =
{
schema : 'mne_warehouse',
query : 'partstoragemasterdata',
table : 'partstoragemasterdata',
};
var svalues =
{
};
weblet.initDefaults(ivalues, svalues);
weblet.loadview();
weblet.delbuttons('add,cancel')
var attr =
{
hinput : false
}
weblet.findIO(attr);
weblet.showLabel();
weblet.showids = new Array("partid");
weblet.titleString.add = weblet.txtGetText("#mne_lang#Lagerstammdaten hinzufügen");
weblet.titleString.mod = weblet.txtGetText("#mne_lang#Lagerstammdaten bearbeiten");
weblet.defvalues = { partstoragemasterdataid : '################' };
weblet.showValue = function(weblet)
{
if ( weblet == null || typeof weblet.act_values.partid == 'undefined' || weblet.act_values.partid == '################' )
{
this.add();
this.obj.inputs.partid.value = '';
alert('#mne_lang#Bitte Teil auswählen');
return false;
}
MneAjaxWeblet.prototype.showValue.call(this,weblet);
if ( this.values.length == 0 )
{
this.add();
this.obj.inputs.partid.value = weblet.act_values.partid;
}
}
weblet.ok = function()
{
if ( this.obj.inputs.partid.value == '' ) return;
return MneAjaxWeblet.prototype.ok.call(this);
}
}
|
P.views.programs.edit.NoWorkouts = P.views.Item.extend({
templateId: 'programs.edit.noworkouts',
initialize: function(options) {
this.readOnly = options.readOnly;
},
serializeData: function() {
return {
readOnly: this.readOnly
};
}
});
|
$(function(){
var $date = $('#checkDate');
var $graphDate = $('#getDate');
var $flightDate = $('#start');
//Best Airport Available
$('#generate-ports').on('click',function(){
var dates = $date.val();
var date_sp = dates.split("-");
if(date_sp[0]>2017){
var year = 2016;
}
else if(date_sp[0]<2013){
var year = 2013;
}
else var year = parseInt(date_sp[0]);
var month = parseInt(date_sp[1]);
if(date_sp[1].charAt(0)=="0")
month = parseInt(date_sp[1].charAt(1));
var dt = parseInt(date_sp[2]);
if(date_sp[2].charAt(0)=="0")
dt = parseInt(date_sp[2].charAt(1));
var travelOn = {
"year" : year,
"month": month,
"day": dt
};
$.ajax({
type:'POST',
url:'http://localhost:8080/csumano/AIRservices/1.0.0/bestairlines',
contentType: "application/json",
data: JSON.stringify(travelOn),
success: function(airport){
// alert(airport);
var rawData = airport;
var dataPorts = rawData.split("},");
// alert(dataPorts[0]+"@@@@@@");
// alert(dataPorts[1]);
var set_port = dataPorts[0].split("ORIGIN_CITY_NAME");
var origins = set_port[1].replace(/[^a-zA-Z, ]/g,'');
var set_city = dataPorts[1].split("ORIGIN");
var departs = set_city[1].replace(/[^a-zA-Z, ]/g,'');
var set_arrive = dataPorts[2].split("RELIABILITY");
// alert(set_arrive[1]);
var arrive = set_arrive[1].replace(/[^0-9.:]/g,'');
// alert("origins:"+origins);
// alert("arrive:"+arrive);
var printOrigin = origins.split(",");
var printOriginCity = departs.split(",");
var printArrive = arrive.split(":");
// alert(printOrigin+" "+printOrigin.length);
// alert(printArrive+" "+printArrive.length);
var i,j;
j=0;
for( i=0; i<20; i=i+2){
// alert(i+" "+printOrigin[i]+"@@"+printArrive[i+2]+"@@"+origins);
if(parseFloat(printArrive[j+2])<100){
var newElement = '<tr><td>'+printOrigin[i]+","+printOrigin[i+1]+'</td><td style="text-align: center;">'+printOriginCity[j]+'</td><td style="text-align: center;">'+parseFloat(printArrive[j+2]).toFixed(4)+'%</td><td></tr>';
}
else
var newElement = '<tr><td>'+printOrigin[i]+","+printOrigin[i+1]+'</td><td style="text-align: center;">'+printOriginCity[j]+'</td><td style="text-align: center;">100%</td><td></tr>';
$( "#mytable" ).append( $(newElement));
j++
}
// alert("till here");
},
error: function(){
alert('Data for the given dates are not found');
}
});
});
//
$('#generate-flight').on('click',function(){
// alert("In2");
var dates = $flightDate.val();
var date_sp = dates.split("-");
if(date_sp[0]>2017){
var year = 2016;
}
else if(date_sp[0]<2013){
var year = 2013;
}
else var year = parseInt(date_sp[0]);
var month = parseInt(date_sp[1]);
if(date_sp[1].charAt(0)=="0")
month = parseInt(date_sp[1].charAt(1));
var dt = parseInt(date_sp[2]);
if(date_sp[2].charAt(0)=="0")
dt = parseInt(date_sp[2].charAt(1));
var depart = $("#getDepart :selected").val();
var arrival = $("#getArrive :selected").val();
// alert(depart+" "+arrival);
if((depart == arrival)&&(depart!="--Choose an Option--")&&(arrival!="--Choose an Option--"))
return alert("The Arrival and Departure can't be same");
var data_obj = {
"day" : dt,
"destination": arrival,
"month": month,
"origin": depart,
"year": year
};
// alert(data_obj.day);
model = "Ensembled"
$.ajax({
type:'POST',
url:'http://localhost:8080/csumano/AIRservices/1.0.0/flightpredictor?Model='+model,
contentType: "application/json",
data: JSON.stringify(data_obj),
success: function(flights){
// alert(flights);
var data = flights.split(",");
var cancel = data[0].split(":");
var delay = data[1].split(":");
var newElement = '<tr><td style="text-align: center;">'+parseFloat(cancel[1]).toFixed(4)+'%</td><td style="text-align: center;">'+parseFloat(delay[1]).toFixed(4)+'%</td><td></tr>';
$( "#myFlight" ).append( $(newElement));
},
error: function(){
alert('Data for the given dates are not found');
}
});
});
// Flight Graph
$('#generate-graph').on('click',function(){
var condition = $("#getCondition :selected").text();
var dates = $graphDate.val();
var date_sp = dates.split("-");
if(date_sp[0]>2017){
var year = 2016;
}
else if(date_sp[0]<2013){
var year = 2013;
}
else var year = parseInt(date_sp[0]);
$.ajax({
type:'GET',
url:'http://localhost:8080/csumano/AIRservices/1.0.0/flightgraphs?Graph='+condition+'&Year='+year,
contentType: "text/html",
success: function(graph){
graph_url = 'http://localhost:8080/csumano/AIRservices/1.0.0/flightgraphs?Graph='+condition+'&Year='+year;
// alert(graph_url);
window.open(graph_url, '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
},
error: function(){
alert('Data for the given dates are not found');
}
});
});
});
|
var searchData=
[
['delay_5fms_134',['delay_ms',['../clock_8h.html#ab7cce8122024d7ba47bf10f434956de4',1,'clock.c']]]
];
|
import getOr from '../../src/utils/getOr';
describe('getOr util', () => {
const movies = [
{
name: 'Pulp Fiction',
director: { name: 'Quentin Tarantino' },
},
];
it('works properly', () => {
const movieName = getOr(null, [0, 'name'])(movies);
const directorName = getOr(null, '0.director.name')(movies);
expect(movieName).toEqual('Pulp Fiction');
expect(directorName).toEqual('Quentin Tarantino');
});
it('fallbacks to default value', () => {
const actorName = getOr(null, '0.casts.0.name')(movies);
const directorBorn = getOr(null, '0.director.born')(movies);
expect(actorName).toBeNull();
expect(directorBorn).toBeNull();
});
it('ignores empty key', () => {
const directorName = getOr(null, '0.director..name')(movies);
expect(directorName).toEqual('Quentin Tarantino');
});
});
|
import React, {Component} from "react";
class Error extends Component{
render(){
return(<p>You are trying to get a non-existing page!</p>);
}
}
export default Error;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsAddBusiness = {
name: 'add_business',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15 17h2v-3h1v-2l-1-5H2l-1 5v2h1v6h9v-6h4v3zm-6 1H4v-4h5v4zM2 4h15v2H2z"/><path d="M20 18v-3h-2v3h-3v2h3v3h2v-3h3v-2z"/></svg>`
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.