text stringlengths 7 3.69M |
|---|
import { combineReducers } from 'redux';
import undoable from 'redux-undo';
import TodoListReducer from './TodoList/reducer';
const StoreReducers = combineReducers({
// todoList: TodoListReducer
todoList: undoable(TodoListReducer, {
debug: true
})
})
export default StoreReducers;
|
$(document).ready(function(){
$('.form').mouseenter(function(){
$('.form').fadeTo('slow', 0.3);
$('.form').mouseleave(function(){
$('.form').fadeTo('slow', 1);
});
});
$('#home').mouseenter(function(){
$('#home').css("color", "#b82f2f");
$('#home').mouseleave(function(){
$('#home').css("color", "#ccc");
});
});
$('#login').mouseenter(function(){
$('#login').css("color", "#b82f2f");
$('#login').mouseleave(function(){
$('#login').css("color", "#ccc");
});
});
$('#about').mouseenter(function(){
$('#about').css("color", "#b82f2f");
$('#about').mouseleave(function(){
$('#about').css("color", "#ccc");
});
});
$('#contact').mouseenter(function(){
$('#contact').css("color", "#b82f2f");
$('#contact').mouseleave(function(){
$('#contact').css("color", "#ccc");
});
});
$('#social').mouseenter(function(){
$('#social').css("color", "#b82f2f");
$('#social').mouseleave(function(){
$('#social').css("color", "#ccc");
});
});
var $click_count = 0
$('#banner').click(function(){
console.log($click_count)
$message0 = "My name is Trunks. This is going to sound really strange, but I\'m not from this time. I traveled here in a time machine twenty years from the future."
$message1 = "Vegeta was right. Only he, yourself, and Gohan have Saiyan blood. And I got mine from him. He\'s my father."
$message2 = "In three years on the morning of May twelfth at ten A.M., a horribly destructive duo will show up on an island southwest of South City."
$message3 = "They have dreadful power, even by our standards. They\'re monsters, Goku. That\'s the best way I know to describe them, they\'re monsters."
$message4 = "Once this pair surfaces, the Earth and everything you know will be gone for good."
$message5 = "These androids are ruthless, they delight in causing pain and chaos. Living on Earth in my time is like living in a nightmare. Always running and hiding and looking for a way out."
$message6 = "I\'m all that's left, I\'m doing the best I can!"
$message7 = "I agreed with my mother that I should travel back in time, but I had my own reasons for wanting to go. I had hoped that in the past, with Goku\'s help, I would find the androids had some weakness."
$message8 = "That way I could go back to the future. And even though I still wouldn\'t be able to bring back all those already gone, I might be able to save the people who are left."
$message9 = "I don\'t remember my dad, so it\'s really great to get to meet him. He\'s a cranky guy, but he\'s impressive."
$message10 = "Well look, I better be off My mom\'s worried sick about me. She needs to know that everything went OK."
$message11 = "Father, you\'re so tough and proud, hard and cold like a rock. But still, deep down, your heart beats like mine does."
$message12 = "I know you feel. I\'m your son and I will always love you. I\'m glad I got to see you, Dad."
if ($click_count == 0) {
showText('#introParagraph p', $message0, 0, 40);
$click_count += 1;
console.log($click_count)
} else if ($click_count == 1) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message1, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 2) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message2, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 3) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message3, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 4) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message4, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 5) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message5, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 6) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message6, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 7) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message7, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 8) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message8, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 9) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message9, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 10) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message10, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 11) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message11, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 12) {
jQuery('#introParagraph p').html('');
showText('#introParagraph p', $message12, 0, 40);
$click_count += 1
console.log($click_count)
} else if ($click_count == 13) {
jQuery('#introParagraph p').html('');
jQuery('#introParagraph p').html('<img src="https://media2.giphy.com/media/N9x3LJ3ZV17A4/200.gif#3" height="300px" width="400px"/>');
$click_count += 1
console.log($click_count)
} else if ($click_count > 13) {
jQuery('#introParagraph p').html('');
$click_count += 1
console.log($click_count)
}
});
var audio = document.getElementById('audio');
document.getElementById('mute').addEventListener('click', function(e) {
e = e || window.event;
audio.muted = !audio.muted;
e.preventDefault();
}, false);
});
|
(function () {
"use strict";
//Array used for the listview
var searchedPeopleArray = [];
//List used for the listview
var personList = new WinJS.Binding.List(searchedPeopleArray);
var publicMembers = {
searchedPeopleArray: searchedPeopleArray,
personList: personList
};
//Namespace used for the listview
WinJS.Namespace.define("personListViewNamespace", publicMembers);
WinJS.UI.Pages.define("/pages/personPicker/personPicker.html", {
ready: function (element, state) {
//Initialization of variables
document.getElementById('personPageTitle').innerText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['pageTitle'];
document.getElementById('personSearchButton').innerText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['searchButton'];
document.getElementById('personClearButton').innerText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['clearButton'];
document.getElementById('personAssignButton').innerText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['assignButton'];
if (!state) {
WinJS.Navigation.state = {};
state = WinJS.Navigation.state;
}
if (!Array.isArray(state.assignees)) {
//Keeps track of assigned assignees
state.assignees = [];
}
//Keeps track of currently selected people (assigned and unassigned)
state.tempAssignees = state.assignees.slice();
if (typeof state.multiple !== 'boolean') {
state.multiple = true;
}
var clearButton = document.getElementById("personClearButton");
//Event listeners and initial state of page elements
//Search button was pressed
document.getElementById("personSearchButton").addEventListener("click", personSearchHandler);
//A key was pressed in the search box. Check for enter key press.
document.getElementById("personSearchBox").addEventListener("keypress", keyPressHandler);
//Assign-button was pressed
document.getElementById("personAssignButton").addEventListener("click", personAssignHandler);
//If multiple people can be selected
if (state.multiple === true) {
document.getElementById("personListview").addEventListener("iteminvoked", peopleCheckHandler);
}
//If only a single person can be selected
else {
document.getElementById("personListview").addEventListener("iteminvoked", personCheckHandler);
}
if (state.multiple === true) {
document.getElementById("personPageBreak").innerHTML = "<br />";
document.getElementById("personAssignButton").style.float = "none";
clearButton.style.visibility = "visible";
clearButton.disabled = false;
clearButton.addEventListener("click", clearHandler);
}
//After listview is loaded, check if there were any assignees
document.getElementById("personListview").addEventListener("loadingstatechanged", checkIfDone);
//Set appbar to only have "settings" option
document.querySelector("#defaultAppbar").winControl.showOnlyCommands(["cmdSettings"]);
},
unload: function () {
//Respond to navigations away from this page.
clearPersonListView();
}
});
//Checks if listView is completely loaded
function checkIfDone(event) {
//If listview's processing is done
if (event.currentTarget.winControl.loadingState === 'complete') {
//Check if any of the found people are already selected
personListViewNamespace.searchedPeopleArray.forEach(function (element, index, array) {
if (element.selected === true) {
//Set the person's backgroundColor to custom active background color or gray.
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor) {
document.getElementsByClassName(element.itemClass)[0].parentNode.parentNode.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor;
}
else {
document.getElementsByClassName(element.itemClass)[0].parentNode.parentNode.style.backgroundColor = '#808080';
}
}
});
//Set progress bar to hidden, display listview, update buttons and remove the event listener
document.getElementById("personProgress").style.visibility = "hidden";
WinJS.UI.Animation.enterContent(event.currentTarget, null);
updatePersonButtons();
event.currentTarget.removeEventListener("loadingstatechanged", checkIfDone);
}
}
//For selecting a single person
function personCheckHandler(event) {
var invokedItem = personListViewNamespace.searchedPeopleArray[event.detail.itemIndex];
var tempAssignees = WinJS.Navigation.state.tempAssignees;
var searchIndex = -1;
//Check that there were no other selected items in the tempAssignees array. If there were, remove them.
tempAssignees.forEach(function (element, index, array) {
//If the element is not the currently selected element
if (element.userName !== invokedItem.userName) {
//If found, remove the person from tempAssignees
tempAssignees.splice(index, 1);
}
});
//Unselect item
if (invokedItem.selected === true) {
invokedItem.selected = false;
//Find the person in tempAssignees
tempAssignees.forEach(function (element, index, array) {
if (element.userName === invokedItem.userName) {
searchIndex = index;
}
});
//If found, remove the person from tempAssignees
if (searchIndex != -1) {
tempAssignees.splice(searchIndex, 1);
}
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor) {
//Find the correct node to set the it's backgroundColor to the theme's backgroundColor. It's class is "win-itembox win-pressed".
document.getElementsByClassName(invokedItem.itemClass)[0].parentNode.parentNode.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor;
}
else {
//Find the correct node to set the it's backgroundColor to the theme's backgroundColor. It's class is "win-itembox win-pressed".
document.getElementsByClassName(invokedItem.itemClass)[0].parentNode.parentNode.style.backgroundColor = window.getComputedStyle(document.body).backgroundColor;
}
}
//Select item
else {
//Set all people to unselected, then select the person and save in tempAssignees[0]
personListViewNamespace.searchedPeopleArray.forEach(function (element, index, array) {
element.selected = false;
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor) {
document.getElementsByClassName(element.itemClass)[0].parentNode.parentNode.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor;
}
else {
document.getElementsByClassName(element.itemClass)[0].parentNode.parentNode.style.backgroundColor = window.getComputedStyle(document.body).backgroundColor;
}
})
invokedItem.selected = true;
tempAssignees[0] = invokedItem;
//Find the correct node to set the it's backgroundColor to custom active background color or gray.
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor) {
document.getElementsByClassName(invokedItem.itemClass)[0].parentNode.parentNode.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor;
}
else {
document.getElementsByClassName(invokedItem.itemClass)[0].parentNode.parentNode.style.backgroundColor = '#808080';
}
}
updatePersonButtons();
}
//For selecting multiple people
function peopleCheckHandler(event) {
var invokedItem = personListViewNamespace.searchedPeopleArray[event.detail.itemIndex];
var tempAssignees = WinJS.Navigation.state.tempAssignees;
var searchIndex = -1;
//Unselect person
if (invokedItem.selected === true) {
invokedItem.selected = false;
//Find the person in tempAssignees
tempAssignees.forEach(function (element, index, array) {
if (element.userName === invokedItem.userName) {
searchIndex = index;
}
});
//If found, remove the person from tempAssignees
if (searchIndex != -1) {
tempAssignees.splice(searchIndex, 1);
}
//If custom theme's listColor is set
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor) {
//Turn the selection into the theme's background color
event.target.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].listColor;
}
else {
//Turn the selection into the theme's background color
event.target.style.backgroundColor = window.getComputedStyle(document.body).backgroundColor;
}
}
//Select person
else {
invokedItem.selected = true;
//Add the person to tempAssignees
tempAssignees.push(invokedItem);
//Set the selection's backgroundColor to custom active background color or gray.
if (malfiGlobals.customTheme[malfiGlobals.invokedDiv] && malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor) {
event.target.style.backgroundColor = malfiGlobals.customTheme[malfiGlobals.invokedDiv].activeBackgroundColor;
}
else {
event.target.style.backgroundColor = '#808080';
}
}
updatePersonButtons();
}
//Perform a search for users
function personSearchHandler() {
//Set listview to hidden and progress to visible
var listviewElement = document.getElementById("personListview");
var searchString = document.getElementById("personSearchBox").value.trim();
var deferred = $.Deferred();
var listElement = {};
WinJS.UI.Animation.exitContent(listviewElement, null).then(function () {
document.getElementById("personProgress").style.visibility = "visible";
malfiGlobals.session[malfiGlobals.invokedDiv].getPeople(searchString, deferred);
});
deferred.done(function (resultArray) {
var listview = document.getElementById("personListview").winControl;
var dataSource = listview.itemDataSource;
personListViewNamespace.searchedPeopleArray = [];
dataSource.beginEdits();
//Erase previous data
for (var i = 0; i < listview._selection._selected._itemsCount; i++) {
dataSource.remove(dataSource._list._keys[0]);
}
//Insert new data
resultArray.forEach(function (element, index, resultArray) {
//Object to be inserted to list
listElement = {
userName: element.userName,
name: '',
jobtitle: '',
selected: false,
//Has the prefix 'listviewItem_' because the username might match other classes
itemClass: 'listviewItem_' + element.userName
}
if (element.firstName) { listElement.name = listElement.name.concat(element.firstName, ' '); }
if (element.lastName) { listElement.name = listElement.name.concat(element.lastName); }
//If the person didn't have a given name, use userName
if (listElement.name.length === 0) { listElement.name = listElement.name.concat(element.userName); }
if (element.jobtitle) { listElement.jobtitle = listElement.jobtitle.concat(element.jobtitle); }
//Check if already selected
WinJS.Navigation.state.tempAssignees.forEach(function (aElement, aIndex, aArray) {
if (listElement.userName === aElement.userName) {
listElement.selected = true;
}
});
personListViewNamespace.searchedPeopleArray.push(listElement);
dataSource.insertAtEnd(null, listElement);
});
document.getElementById("personListview").addEventListener("loadingstatechanged", checkIfDone);
dataSource.endEdits();
})
deferred.fail(function (jqXHR, textStatus, errorThrown) {
var msg = new Windows.UI.Popups.MessageDialog(textStatus + ': ' + errorThrown);
malfiGlobals.popupQueue.showSync(msg);
})
}
//Key pressed in textbox
function keyPressHandler(event) {
//If enter was pressed
if (event.keyCode === 13) {
personSearchHandler();
}
}
//Returns the selected assignees to previous page
function personAssignHandler() {
var state = WinJS.Navigation.state;
//Copy tempAssignees to assignees
state.assignees = state.tempAssignees.slice();
WinJS.Navigation.back();
}
//Update the assignment button with this
function updatePersonButtons() {
var button = document.getElementById("personAssignButton");
var personCount = WinJS.Navigation.state.tempAssignees.length;
var buttonText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['assignButton'];
var multiple = WinJS.Navigation.state.multiple;
//When choosing multiple people
if (multiple === true) {
//If at least one person has been selected
if (personCount > 0) {
buttonText = buttonText.concat(" ", personCount);
if (personCount === 1) {
buttonText = buttonText.concat(" ",malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['person']);
}
else {
buttonText = buttonText.concat(" ", malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['people']);
}
button.disabled = false;
}
//If no people are selected
else {
buttonText = malfiGlobals.strings[malfiGlobals.invokedDiv]['personPicker']['assignButton'];
button.disabled = true;
}
}
//When choosing a single person
else {
//If at least one person has been selected
if (personCount > 0) {
button.disabled = false;
}
//If no people are selected
else {
button.disabled = true;
}
}
button.innerHTML = buttonText
}
//Clears the selected tempAssignees
function clearHandler() {
var tempAssignees = WinJS.Navigation.state.tempAssignees;
//Clear tempAssignees array
tempAssignees.splice(0, tempAssignees.length);
//Set all people to unselected
personListViewNamespace.searchedPeopleArray.forEach(function (element, index, array) {
element.selected = false;
document.getElementsByClassName(element.itemClass)[0].parentNode.parentNode.style.backgroundColor = window.getComputedStyle(document.body).backgroundColor;
});
//Update assign button
updatePersonButtons();
}
//Clears listView when navigating out from the page
function clearPersonListView() {
var listview = document.getElementById("personListview").winControl;
var dataSource = listview.itemDataSource;
personListViewNamespace.searchedPeopleArray = [];
dataSource.beginEdits();
//Erase previous data
for (var i = 0; i < listview._selection._selected._itemsCount; i++) {
dataSource.remove(dataSource._list._keys[0]);
}
dataSource.endEdits();
}
})(); |
//存在的问题
/*
1.当方向是向右的时候,不能左滑动,同理
2.蛇本身的碰撞检测问题以及蛇与四边碰撞检测问题
*
* */
var canvas=document.getElementById("canvas");
var w=document.body.clientWidth;
var h=document.body.clientHeight;
canvas.width=w;
canvas.height=h;
var cxt=canvas.getContext("2d");
cxt.lineJoin='round';
cxt.lineCap='round';
var text=document.querySelector(".text")
var num=0
var pos={
x:0,
y:0
}
var posEnd={
x:0,
y:0
}
var direction='right'
//蛇头
var snakeHead={
x:0,
y:0,
w:20,
h:20,
color:'red'
}
drawSnake(snakeHead)
canvas.addEventListener("touchstart",touchstart,false)
canvas.addEventListener("touchmove",touchmove,false)
canvas.addEventListener("touchend",touchend,false)
//创造随机数
function random(min,max){
return Math.round(Math.random()*(max-min)+min)
}
var fps=0;
var snakeBodys=[];
//创造食物类
function snakeFood(){
this.x,this.y,this.color,this.r=10,this.set()
}
snakeFood.prototype.set=function(){
this.x=random(0,w);
this.y=random(0,h);
this.color="rgb("+random(100,255)+","+random(100,255)+","+random(100,255)+")";
}
var foods=[]
for (var i=0;i<15;i++) {
var food=new snakeFood()
foods.push(food)
}
//绘制食物
function foodArc(obj){
cxt.beginPath();
cxt.fillStyle=obj.color;
cxt.arc(obj.x,obj.y,obj.r,0,Math.PI*2,false);
cxt.closePath();
cxt.fill();
}
//碰撞检测
function collision(obj1,obj2){
var obj11=obj1.x;
var obj1r=obj1.x+obj1.w;
var obj1t=obj1.y;
var obj1b=obj1.y+obj1.h;
var obj21=obj2.x;
var obj2r=obj2.x+20;
var obj2t=obj2.y;
var obj2b=obj2.y+20;
if( obj1b<obj2t || obj11>obj2r || obj1t>obj2b || obj1r<obj21){
//没碰上
return false
}else{
return true
}
}
//运动函数
function animate(){
fps++;
if(fps % 15 === 0){
cxt.clearRect(0,0,w,h)
var snakeBody={
x:snakeHead.x,
y:snakeHead.y,
w:snakeHead.w,
h:snakeHead.h,
color:'#000'
}
if(snakeBodys.length>=4){
snakeBodys.shift()
}
snakeBodys.push(snakeBody)
switch(direction){
case 'right' :
snakeHead.x+=20
break;
case 'left' :
snakeHead.x-=20
break;
case 'top' :
snakeHead.y-=20
break;
case 'bottom' :
snakeHead.y+=20
break;
}
drawSnake(snakeHead)
for (var i=0;i<snakeBodys.length;i++) {
var snakeB=snakeBodys[i];
drawSnake(snakeB)
}
for(var i=0;i<foods.length;i++){
var food=foods[i]
foodArc(food)
if(collision(snakeHead,food)){
// snakeBody.color=food.color;
snakeBodys.push(snakeBody);
food.set();
num++;
text.innerHTML='您目前积分是'+num
console.log('碰上')
}
}
}
requestAnimationFrame(animate)
}
animate()
//画蛇
function drawSnake(obj){
cxt.beginPath()
cxt.fillStyle=obj.color;
cxt.rect(obj.x,obj.y,obj.w,obj.h)
cxt.closePath()
cxt.fill()
}
function touchstart(e){
e.preventDefault()
var e=e.touches[0];
pos={
x:parseInt(e.pageX),
y:parseInt(e.pageY)
}
}
function touchmove(e){
e.preventDefault()
var e=e.touches[0];
posEnd={
x:parseInt(e.pageX),
y:parseInt(e.pageY)
}
}
//滑动方向判断
function touchend(e){
var abs=Math.abs(posEnd.x-pos.x)-Math.abs(posEnd.y-pos.y)
var absX=posEnd.x-pos.x;
var absY=posEnd.y-pos.y;
if(absX > 0 && abs > 0){
direction='right'
console.log("向右")
}else if(absX < 0 && abs > 0){
direction='left'
console.log("向左")
}else if(absY > 0 && abs < 0){
direction='bottom'
console.log("向下")
}else if(absY < 0 && abs < 0){
direction='top'
console.log("向上")
}
}
|
JR.Views.PostsFormView = Backbone.View.extend({
events: {
"click button.submit": "postAction"
},
render: function(){
var formTemplate = JST["posts/form"]();
this.$el.html(formTemplate);
return this
},
postAction: function(event){
event.preventDefault();
var that = this;
this.collection.create({post: {title: that.$("#title").val(),
body: that.$("#body").val()}});
Backbone.history.navigate("#/");
}
}); |
import { gql } from '@apollo/client'
export const GET_FAVORITES = gql `
query getFavorites {
favorites {
_id
title
overview
poster_path
popularity
tags
}
}
` |
import React from "react";
import PropTypes from "prop-types";
import Button from "./Button";
const Header = ({ title, onAdd, showCunt }) => {
return (
<header className="header">
<h1>{title}</h1>
<Button
onClick={onAdd}
text={showCunt ? "Close" : "Add"}
color={showCunt ? "red" : "green"}
/>
</header>
);
};
Header.propTypes = {
title: PropTypes.string.isRequired,
};
export default Header;
|
"use strict";
var config = require('./config');
var generator = require('./storyboard_generator/bin');
module.exports = function (gulp, plugins, options) {
return function (cb) {
generator.generate(config, function (error) {
if(cb){
cb(error);
}
});
};
}; |
import styled from 'styled-components'
export const ContainerWrapper = styled.main `
height: 100vh;
width: 100%;
background-color: #1066d0c9;
box-shadow: 0 0 8px 8px #1066d0c9;
margin: -8 auto;
`
export const FormStyled = styled.form `
display: flex;
height: 70px;
padding: 10px;
margin: 0;
align-items: center;
justify-content: space-around;
`
export const Input = styled.input `
text-align: center;
width: 100px;
box-shadow: 0 0 10px 10px #1066d0;
height: 50px;
font-size: 2em;
margin-left: 10px;
border: 2px solid #4477ff;
border-radius: 5px;
color: #0f0;
`
export const SubmitInput = styled.input `
width: 100px;
height: 50px;
border: none;
font-weight: 600;
font-size: 20px;
background-color: #ff0707;
`
export const Text = styled.label `
width: 70px;
font-size: 2em;
color: #00ff00;
`
export const FieldStyle = styled.section `
padding: 5%;
width: 80%;
margin: 0 auto;
background-color: white;
box-shadow: 0 0 200px #1066d0 inset;
`
export default {} |
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import TechnicalIndicator from '../TechnicalIndicator'
import { PSY } from '../technicalIndicatorType'
export default class PsychologicalLine extends TechnicalIndicator {
constructor () {
super({
name: PSY,
calcParams: [12, 6],
shouldCheckParamCount: true,
plots: [
{ key: 'psy', type: 'line' },
{ key: 'psyMa', type: 'line' }
]
})
}
/**
* 计算psy
* 公式:PSY=N日内的上涨天数/N×100%。
*
* @param dataList
* @param calcParams
* @returns {[]}
*/
calcTechnicalIndicator (dataList, calcParams) {
let upCount = 0
let psySum = 0
const upList = []
const result = []
this._calc(dataList, i => {
const psy = {}
const upFlag = dataList[i].close - dataList[i].open > 0 ? 1 : 0
upList.push(upFlag)
upCount += upFlag
if (i >= calcParams[0] - 1) {
psy.psy = upCount / calcParams[0] * 100
psySum += psy.psy
if (i >= calcParams[0] + calcParams[1] - 2) {
psy.psyMa = psySum / calcParams[1]
psySum -= result[i - (calcParams[1] - 1)].psy
}
upCount -= upList[i - (calcParams[0] - 1)]
}
result.push(psy)
})
return result
}
}
|
//
// JumpBack Button
// Brian Slakter and Andrew Packer
// August 21, 2014
//
//get number of pages to jump back
function getJumpCount(history) {
var jumpCount = 0;
//get unique root of current URL (URL previous to final '/')
var curUrl = history[history.length-1];
//if URL ends in '/', remove it
if (curUrl.lastIndexOf("/") == curUrl.length-1) {
curUrl = curUrl.substring(0, curUrl.length-1);
}
//remove text after last '/'
curUrl = curUrl.substring(0, curUrl.lastIndexOf("/"));
//curUrl has now been modified to the root we are concerned with
var curRoot = curUrl;
//search history until another unique root is found
for (i = history.length-2; i > 0; i--) {
//extract root from nextUrl as we did for curUrl
var nextUrl = history[i];
if (nextUrl.lastIndexOf("/") == nextUrl.length-1) {
nextUrl = nextUrl.substring(0, nextUrl.length-1);
}
nextUrl = nextUrl.substring(0, nextUrl.lastIndexOf("/"));
var nextRoot = nextUrl;
//if root is different from that of current page,
//this is where we jump back to
if (nextRoot != curRoot) {
jumpCount = history.length-i-1;
break;
}
}
return jumpCount;
}
//called when the user clicks the JumpBack Button
chrome.browserAction.onClicked.addListener(function(tab) {
//access chrome local storage
chrome.storage.local.get(tab.index.toString(), function(items) {
//get history from chrome storage
var curTabHistory = items[tab.index.toString()];
var jumpCount = getJumpCount(curTabHistory);
if (jumpCount > 0) {
//jump back
chrome.tabs.update(tab.id,
{ 'url': 'javascript:history.go(-' + jumpCount + ')' });
//remove history of pages skipped over from local storage
for (i = 0; i <= jumpCount; i++) {
curTabHistory.pop();
}
}
//update history in chrome storage
chrome.storage.local.set(items);
});
});
//called when tab is created
chrome.tabs.onCreated.addListener(function(tab) {
//Create object to hold history in array
var newTab = {};
//use tab index as key
newTab[tab.index] = [];
//store page in history
if (tab.url) {
newTab[tab.index].push(tab.url);
}
//update history in chrome storage
chrome.storage.local.set(newTab);
});
//called when tab updated with new web page
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
//if change info status is loading and url is defined
if (changeInfo.url != undefined && changeInfo.status == "loading") {
//access chrome local storage
chrome.storage.local.get(tab.index.toString(), function(items) {
//add web page to history, and updated history in chrome storage
curTabHistory = items[tab.index.toString()];
curTabHistory.push(changeInfo.url);
chrome.storage.local.set(items);
});
}
});
//update history for tabs once a tab is moved
chrome.tabs.onMoved.addListener(function(tabId, moveInfo) {
var replacedData = null;
var movedData = null;
var tempData = null;
//access storage and history relevant to tab that is moved
chrome.storage.local.get(moveInfo.fromIndex.toString(), function(items) {
movedData = items[moveInfo.fromIndex.toString()];
});
//access storage and history relevant to tab in location where moved
//tab will be placed, update in chrome storage
chrome.storage.local.get(moveInfo.toIndex.toString(), function(items) {
replacedData = items[moveInfo.toIndex.toString()];
items[moveInfo.toIndex.toString()] = movedData;
chrome.storage.local.set(items);
});
var curIndex = moveInfo.toIndex;
//tab moved left - update storage of tabs to right of new tab location
if (moveInfo.fromIndex > moveInfo.toIndex) {
curIndex++;
//update storage based on cascading effects from moving tab
while (curIndex <= moveInfo.fromIndex) {
chrome.storage.local.get(curIndex.toString(), function(items) {
tempData = items[moveInfo.toIndex.toString()];
items[moveInfo.toIndex.toString()] = replacedData;
replacedData = tempData;
chrome.storage.local.set(items);
});
curIndex++;
}
}
//tab moved right - update storage of tabs to left of new tab location
else if (moveInfo.fromIndex < moveInfo.toIndex) {
curIndex--;
//update storage based on cascading effects from moving tab
while (curIndex >= moveInfo.fromIndex) {
chrome.storage.local.get(curIndex.toString(), function(items) {
tempData = items[moveInfo.toIndex.toString()];
items[moveInfo.toIndex.toString()] = replacedData;
replacedData = tempData;
chrome.storage.local.set(items);
});
curIndex--;
}
}
});
|
let token = sessionStorage.getItem('token');
let json = {};
function joinPartida() {
let index = event.target.className;
sessionStorage.setItem('idPartida', `${json.games[index].id}`);
sessionStorage.setItem('nombrePartida', `${json.games[index].name}`);
window.location.href = "salaEquipos.html";
}
fetch("http://15.188.14.213:11050/api/v1/games/", {
method: "GET",
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
if (response.ok) {
return response.text();
} else {
alert("Fallo al recuperar la lista de partidas del servidor.");
throw "Respesta incorrecta por parte del servidor";
}
})
.then(data => {
json = JSON.parse(data);
let lista = document.querySelector(".listaPartidas");
for (let i = 0; i < json.games.length; i++) {
lista.innerHTML += `<tr>
<td>${json.games[i].name}</td>
<td><button type="button" class="${i}">Unirse</button>
</tr>`;
}
let listaBotones = document.querySelectorAll(".listaPartidas button");
for (let i = 0; i < listaBotones.length; i++) {
listaBotones[i].addEventListener('click', joinPartida);
}
})
.catch(err => console.log(err));
let atras = document.querySelector(".flechaIz");
atras.onclick = function() {
window.location.href = "onlineInicio.html";
}
document.querySelector(".botonBuscar").onclick = function() {
let query = document.querySelector(".buscador").value;
if (query != "") {
fetch(`http://15.188.14.213:11050/api/v1/games/${query}`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
if (response.ok) {
return response.text();
} else {
alert("No se ha podido encontrar la partida buscada.");
throw "Respesta incorrecta por parte del servidor";
}
})
.then(data => {
sessionStorage.setItem('idPartida', query);
window.location.href = "salaEquipos.html";
})
.catch(err => console.log(err));
}
} |
"use strict";
exports.__esModule = true;
var task_1 = require("./task");
var Board = /** @class */ (function () {
function Board(header) {
var _this = this;
this.tasks = [];
this.notesSection = document.createElement("div");
this.pageAddButton = document.createElement("button");
this.title = header;
this.notesSection.className = "notesSection";
this.pageAddButton.id = "pageAddButton";
this.pageAddButton.innerHTML = "Dodaj kartkę";
this.notesSection.appendChild(this.pageAddButton);
this.pageAddButton
.addEventListener("click", function () { return _this.initialTask(); });
this.getTasks();
this.writeTasks();
}
Board.prototype.initialTask = function () {
var content = prompt("Nazwij karteczkę");
if (content != null) {
var task = new task_1.Task(content);
this.tasks.push(task);
this.saveTask();
location.reload();
}
};
Board.prototype.saveTask = function () {
localStorage.setItem('task', JSON.stringify(this.tasks));
};
Board.prototype.getTasks = function () {
if (JSON.parse(localStorage.getItem('task')) != null)
this.tasks = JSON.parse(localStorage.getItem('task'));
};
Board.prototype.writeTasks = function () {
var _this = this;
this.tasks.forEach(function (task) {
_this.drawTask(task);
});
};
Board.prototype.drawTask = function (task) {
var taskSection = document.createElement("div");
var taskDescription = document.createElement("p");
taskSection.className = "taskSection";
taskDescription.className = "taskDescription";
taskDescription.innerHTML = task.description;
taskSection.appendChild(taskDescription);
this.notesSection.appendChild(taskSection);
};
return Board;
}());
exports.Board = Board;
|
function toggleNavigation(){
$('.page-header').toggleClass('menu-expanded');
$('.page-nav').toggleClass('collapse');
}
//EVENTOS DEL DOM
$(window).on('load', function () {
$('.toggle-nav').click(toggleNavigation);
}); |
const a = require('a');
module.exports = {
sam: 'sonite',
a: a
}; |
import {colors} from '../../config';
const styles = {
container: {
width: '100%',
height: 50,
backgroundColor: colors.primary,
alignItems: 'center',
justifyContent: 'center',
marginVertical: 10,
borderRadius: 4,
},
transparentContainer: {
width: '100%',
height: 50,
backgroundColor: 'transparent',
alignItems: 'center',
justifyContent: 'center',
marginVertical: 10,
},
title: {
color: 'white',
fontSize: 16,
},
transparentTitle: {
color: colors.primary,
},
};
export default styles;
|
var firebaseConfig = {
apiKey: "AIzaSyAQPAqzqDgY-ySsmEakXlyTo8BjbR7QKwM",
authDomain: "my-news-network-15401.firebaseapp.com",
databaseURL: "https://my-news-network-15401.firebaseio.com",
projectId: "my-news-network-15401",
storageBucket: "my-news-network-15401.appspot.com",
messagingSenderId: "100486016337",
appId: "1:100486016337:web:5a9a185b0a8797e1423770",
measurementId: "G-SS97Q9PSGK"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
$(document).ready(async function () {
var trigger = $('.hamburger'),
overlay = $('.overlay'),
isClosed = false;
trigger.click(function () {
hamburger_cross();
});
function hamburger_cross() {
if (isClosed == true) {
overlay.hide();
trigger.removeClass('is-open');
trigger.addClass('is-closed');
isClosed = false;
} else {
overlay.show();
trigger.removeClass('is-closed');
trigger.addClass('is-open');
isClosed = true;
}
}
var news = [];
var newspost = [];
var loadCount = 0;
const docRef = firebase.firestore()
.collection("NewsArticles");
const snapshot = await docRef.get();
snapshot.forEach(doc => {
news.push(doc.data());
});
news.forEach(printNews);
function printNews(value) {
if (value.title.search('Singapore') == -1
&& value.entities.search('Singapore') == -1
&& value.source != "The Straits Times") {
newspost.push(
'<div class="card">'
+'<div class="card-body">'
+'<h5 class="card-title">'+value.source+'</h5>'
+'<h6 class="card-subtitle mb-2 text-muted">'+value.publishedDate+'</h6>'
+'<p class="card-text" id="news1">'+value.title+'</p>'
+'<a href="'+value.link+'" class="card-link">Card link</a>'
+'<a href="#" class="card-link">Another link</a>'
+'</div>'
+'</div>'
);
}
}
newspost.forEach(pNews);
function pNews(value) {
$("#timeline").append(value);
}
function postnews() {
$("#timeline").append(newspost[loadCount]);
loadCount++;
}
$(window).on("scroll", function() {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight < 0.1) {
// when scroll to bottom of the page
postnews();
}
});
/* $("#timeline").infiniteScroll({
// options
path: '',
append: '.card',
history: false,
});
$("#timeline").on( 'load.infiniteScroll', postnews );
*/
/* var nextPenSlugs = [
'3d9a3b8092ebcf9bc4a72672b81df1ac',
'2cde50c59ea73c47aec5bd26343ce287',
'd83110c5f71ea23ba5800b6b1a4a95c4',
];
function getPenPath() {
var slug = nextPenSlugs[ this.loadCount ];
if ( slug ) {
return 'https://s.codepen.io/desandro/debug/' + slug;
}
}
var $container = $("#timeline").infiniteScroll({
path: getPenPath,
append: '.post',
status: '.page-load-status',
});
$container.infiniteScroll('appendItems', newspost); */
/* var news = document.getElementById('news1');
docRef = firebase.firestore()
.collection("NewsArticles")
.doc("ABElyp3icaUVUz8mZKBF");
docRef.get().then(function(doc) {
if (doc.exists) {
news.innerHTML = doc.data().title;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
news.innerHTML = query.title; */
$('[data-toggle="offcanvas"]').click(function () {
$('#wrapper').toggleClass('toggled');
});
}); |
'use strict'
process.on('unhandledRejection', (err) => {
console.warn(err)
process.exit(1)
})
const Hapi = require('hapi')
const options = require('./options')
const server = Hapi.server(options.server)
const init = async () => {
await server.register(require('./plugins'))
require('./routes')(server)
await server.start()
console.log(`Server running at: ${server.info.uri}`)
}
try {
init()
} catch (err) {
console.error('Server start fails')
console.warn(err)
process.exit(1)
}
|
var somme = 0;
for (var i = 0; i < 10; ++i) {
somme = somme + i;
} |
//time functions
var appStartTime = -1;
var deltaTime = -1;
var oldFrameTime = -1;
var avgDeltaTime = -1;
var avgFPS = 0;
var currentFrameTime = -1;
/*
performance.now() is in milliseconds
The timestamp is not actually high-resolution.
To mitigate security threats such as Spectre, browsers currently round the results to varying degrees.
(Firefox started rounding to 1 millisecond in Firefox 60.)
Some browsers may also slightly randomize the timestamp.
The precision may improve again in future releases;
browser developers are still investigating these timing attacks and how best to mitigate them.
treba enejblat getTimeµs() kad browseri pocnu podrzavat to
treba onda zamijenit funkcije sa getTimeµs() na mjestima oznacenim sa : //replace with getTimeµs()
*/
/*
var USECONDS_IN_SECOND = 1000.0 * 1000.0;
var SECONDS_IN_USECOND = 1.0 / (1000.0 * 1000.0);
export function getTimeµs(){ return performance.now(); }
*/
var MSECONDS_IN_SECOND = 1000.0;
var SECONDS_IN_MSECOND = 1.0 / (1000.0);
export function getTimems(){ return performance.now(); }
export function getDeltaSeconds(old_time){
let current_time = getTimems(); //replace with getTimeµs()
return (current_time - old_time) * SECONDS_IN_MSECOND; //replace with SECONDS_IN_USECOND
}
export function getSecondsSinceStart(){ return getDeltaSeconds(appStartTime); }
export function getTime(){ return getSecondsSinceStart(); }
export function init(){
appStartTime = getTimems();
oldFrameTime = appStartTime;
deltaTime = 1.0/60.0;
avgDeltaTime = 1.0/60.0;
avgFPS = 60.0;
currentFrameTime = appStartTime;
}//replace with getTimeµs()
export function getAvgDeltaTime(){ return avgDeltaTime; }
export function getDeltaTime(){ return deltaTime; }
export function getAvgFPS(){ return avgFPS; }
export function getFrameTime(){ return currentFrameTime; }
function lerp(a, b, t){ return (1.0-t)*a + t*b; }
export function Update(){
currentFrameTime = getSecondsSinceStart();
deltaTime = currentFrameTime - oldFrameTime;
if((oldFrameTime > 0.0) && (deltaTime > 1.0/120.0) &&(deltaTime < 1.0)){
avgDeltaTime = lerp(avgDeltaTime, deltaTime, 1.0/30.0);
avgFPS = 1.0/avgDeltaTime;
}
oldFrameTime = currentFrameTime;
return currentFrameTime;
} |
import { Avatar, Button, Divider, IconButton, makeStyles, TextField } from '@material-ui/core'
import React, { useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { useDispatch, useSelector } from 'react-redux'
import { getUserInfo, loadDefaultImage } from 'store/selectors/Selectors'
import TextareaAutosize from '@material-ui/core/TextareaAutosize';
import ImageOutlinedIcon from '@material-ui/icons/ImageOutlined';
import { addNewTweet } from 'store/ducks/AddTweet/AddTweetReducer'
const useStyles = makeStyles((theme) => ({
form: {
display: 'flex',
textAlign: 'center',
alignItems: 'start',
'& .MuiTextField-root': {
margin: theme.spacing(2),
minWidth: 500
}
},
buttonWrapper: {
width: '100%',
justifyContent: 'center'
},
button: {
maxWidth: 225,
padding: '7px 15px',
margin: theme.spacing(1.2),
borderRadius: 9999,
fontWeight: 600,
textTransform: 'capitalize'
},
formFooter: {
display: 'flex',
justifyContent: 'space-between',
marginLeft: 50
},
formAvatar: {
width: theme.spacing(6.5),
height: theme.spacing(6.5),
marginRight: 15,
},
formInput: {
border: 0,
marginTop: theme.spacing(1.4),
width: '100%',
fontSize: 20,
resize: 'none',
fontWeight: 400,
fontFamily: 'inherit',
color: '#7d8e9e',
outline: 'none',
'&::placeholder': {
color: '#7d8e9e',
fontWeight: 400,
}
},
icon: {
height: 48,
width: 48
},
preview: {
marginTop: 15,
width: 100,
maxHeight: 100,
borderRadius: 15,
objectFit: 'contain',
marginLeft: 60
},
}));
export const SubmitForm = () => {
const classes = useStyles()
const user = useSelector(state => getUserInfo(state))
const defaultUserImage = useSelector(state => loadDefaultImage(state))
const [imagePreview, setImagePreview] = useState(null)
const dispatch = useDispatch()
const { handleSubmit, control, register, formState: { isDirty } } = useForm()
const handelSubmit = ({ body, image }) => {
dispatch(addNewTweet({ body, image: image[0] }))
setImagePreview(null)
}
const handleChange = (e) => {
const file = e.target.files[0];
setImagePreview(URL.createObjectURL(file))
}
const handleError = (errors) => {
console.log(errors)
}
const registerOptions = {
body: { required: "Body is required" }
}
return <form onSubmit={handleSubmit(handelSubmit, handleError)} >
<div className={classes.form}>
<Avatar src={user.photo ? `data:${user.photo.contentType};base64, ${user.photo.imageBase64}` : defaultUserImage} className={classes.formAvatar} alt={`Аватарка пользователя`} />
<Controller
name='body'
control={control}
rules={registerOptions.body}
render={({ onChange, value }) => <TextareaAutosize
className={classes.formInput}
placeholder="What's happening?"
onChange={onChange} value={value}
rowsMax={20} />}
/>
</div>
{imagePreview && <img src={imagePreview} alt='preview' className={classes.preview} />}
<div className={classes.formFooter}>
<IconButton
component="label"
color='primary'
className={classes.icon}
>
<ImageOutlinedIcon style={{ fontSize: 24 }} />
<input type="file" hidden name='image' ref={register} onChange={(e) => handleChange(e)} />
</IconButton>
<Button
className={classes.button}
type='submit'
variant='contained'
color='primary'
disabled={!isDirty}
>
Tweet
</Button>
</div>
</form >
}
|
/**
* Created by liangtong on 2018/10/30.
* Email : liangtong@itcast.cn
* 格式:
* <pages url="" options="" show="" :params="" @callback=""></pages>
* 必填项
* 属性url:查询路径(内部自动进行ajax查询)
* 扩展项:
* 属性options:基本参数设置(内容需大括号)
* pageSize : 每页显示个数(默认值2)
* pageList:显示列表(默认值[2,4,8])
* preNum:当前页前将显示页面个数(默认值3)
* nextNum:当前页后将显示页面个数(默认值3)
* 属性show:拥有控制分页条显示
* showAllNum :是否显示所有的数字导航条(默认false,显示的是动态导航条)
* 属性params:初始化查询条件【注意:必须冒号开头,此次的数据从vue的数据区域获得】
* 数据:必须是对象
* 例如:
* new Vue({
* data : {
* user : {
* }
* }
* });
* 事件callback:查询成功后获得函数
* 数据:必须是函数(函数有一个参数,表示查询结果)
* 例如:
* new Vue({
* methods : {
* show : function( data ){
* }
* }
* });
* 温馨提示:当从show获得查询结果后,可以进行数据遍历,但需要在data区域存放。
* new Vue({
* data : {
* this.list = [] //存放查询结果
* },
* show : function(data){ //查询结果
* this.list = data;
* }
* })
* //标签遍历即可
* <tr v-for="user in list"> //显示查询结果
* </tr>
*
*
* 实例:
* 默认情况:
* <pages url="/user" @callback="show"></pages>
* 扩展项:
* <pages url="/user" options="{pageSize:1,pageList:[1,2,4,8]}" @callback="show"></pages>
*
* <pages url="/user" options="{pageSize:1,pageList:[1,2,4,8],preNum:2,nextNum:2}" @callback="show"></pages>
*
* <pages url="/user" options="{pageSize:1,pageList:[1,2,4,8]}" show="{showAllNum:true}" @callback="show"></pages>
*
* <pages url="/user" options="{pageSize:1,pageList:[1,2,4,8]}" show="{showAllNum:true}" :params="user" @callback="show"></pages>
*
* 条件查询:在使用分页条工具时,需要使用处理“条件查询”
* 编写步骤:
* 1.给查询按钮绑定click事件
* 2.给分页条命名 <pages ref="名称">
* 3.在绑定事件中执行固定代码
* this.$refs.名称.czxy_findAll(1 , this.参数 );
* 分析
* 查询条件按钮需要绑定click事件,执行固定的代码
* this.$refs.bookPage.czxy_findAll(1 , this.bookParam );
* //调用分页条内部函数(第几页,条件)
* //格式:this.$refs.引用名称.czxy_findAll( pageNum , params )
* 注意:在使用分页条时,必须命名
* <pages ref="名称"></pages>
* 例如:
* <pages url="/book" ref="bookPage" @callback="show" :params="bookParam"></pages>
*/
Vue.component("pages",{
template :`
<nav aria-label="Page navigation">
<div class="btn-group" style="vertical-align: top;">
<button type="button" class="btn btn-default">{{pageSize}}</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li v-for="n in pageList" @click.prevent="changePageList(n)"><a href="#">{{n}}</a></li>
</ul>
</div>
<ul class="pagination" style="margin: 0;padding-left: 10px;">
<li>
<a href="#" aria-label="Previous" v-if="hasPreviousPage" @click.prevent="czxy_findAll(1)">
<span aria-hidden="true">首页</span>
</a>
</li>
<li>
<a href="#" aria-label="Previous" v-if="hasPreviousPage" @click.prevent="czxy_findAll(prePage)" >
<span aria-hidden="true" >上一页</span>
</a>
</li>
<li v-for="i in numList" :class="{active:(i==pageNum)}">
<a href="#" @click.prevent="czxy_findAll(i)">{{i}}</a>
</li>
<li>
<a href="#" aria-label="Next" v-if="hasNextPage" @click.prevent="czxy_findAll(nextPage)">
<span aria-hidden="true">下一页</span>
</a>
</li>
<li>
<a href="#" aria-label="Next" v-if="hasNextPage" @click.prevent="czxy_findAll(pages)">
<span aria-hidden="true">尾页</span>
</a>
</li>
</ul>
<form class="form-inline" style="display: inline-block;vertical-align: top;padding-left: 20px;">
<span>总共{{total}}条记录,当前第</span>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" style="width: 70px;" v-model="goNum" @key.enter.prevent="goPage" placeholder="第几页">
</div>
</div>
<span>/{{pages}}页</span>
<button type="submit" class="btn btn-primary" @click.prevent="goPage">GO</button>
</form>
</nav>
` ,
data : function(){
return {
"pageNum": 1,
"pageSize" : 2 ,
"total" : 1,
"pageList" : [2,4,6],
"pages": 2, //总分页数
"prePage": 1,
"nextPage": 1,
"isFirstPage": true,
"isLastPage": false,
"hasPreviousPage": false,
"hasNextPage": true,
"start" : 1,
"end" : 10,
"preNum" : 3, //前面显示几个
"nextNum" : 3, //后面显示几个
"numList" : [],
"showAllNum" : false, //显示数据导航
"goNum" : 1
}
},
methods : {
/**
* 查询所有
* @param pageNum
*/
czxy_findAll : function(pageNum){
//拼凑条件
var myurl = this.url + "?pageNum=" + pageNum + "&pageSize=" + this.pageSize;
//拼凑条件
if(this.params) {
for(key in this.params){
myurl += "&" + key + "=" + this.params[key];
}
}
axios.get(myurl).then(res => {
//计算值
this.calculateValue(pageNum, res.data.total);
this.$emit( "callback" , res.data.list);
});
},
/**
* 计算分页数据
* @param pageNum
*/
calculateValue : function(pageNum , total){
//当前页
this.pageNum = pageNum;
//跳转页面与当前页面同步
this.goNum = this.pageNum;
//总条数
this.total = total;
//总分页数
//this.pages = (this.total + this.pageSize - 1) / this.pageSize;
if(this.total % this.pageSize == 0 ){
this.pages = this.total / this.pageSize;
} else {
this.pages = Math.floor(this.total / this.pageSize) + 1;
}
//前后页数
this.prePage = Math.max(this.pageNum - 1 , 1 );
this.nextPage = Math.min(this.pageNum + 1 , this.pages);
//是否首尾页
this.isFirstPage = this.pageNum == 1;
this.isLastPage = this.pageNum == this.pages;
//是否前后页
this.hasPreviousPage = this.pageNum > 1;
this.hasNextPage = this.pageNum < this.pages;
//动态导航
this.start = 1;
this.end = this.start + this.preNum + this.nextNum;
if(this.pages <= this.end){
this.end = this.pages;
} else {
this.start = this.pageNum - this.preNum;
this.end = this.pageNum + this.nextNum;
if(this.start < 1){
this.start = 1;
this.end = this.start + this.preNum + this.nextNum;
}
if(this.end > this.pages){
this.end = this.pages;
this.start = this.pages - this.preNum - this.nextNum;
}
}
//动态导航,记录数据用于显示
this.numList = [];
if(this.showAllNum){
for(var i = 1 ; i <= this.pages ; i ++){
this.numList.push( i );
}
} else {
for(var i = this.start ; i <= this.end ; i ++){
this.numList.push( i );
}
}
},
changePageList : function(n){
this.pageSize = n;
this.czxy_findAll(1);
},
goPage : function(){
if(! /^[\d]+$/g.test(this.goNum)){
this.goNum = 1;
}
if(this.goNum < 1 || this.goNum > this.pages){
this.goNum = 1;
}
this.czxy_findAll(this.goNum);
}
},
props : {
"url" : {
required : true
} ,
"options": {
},
"show" : {
},
"params" :{
}
},
created : function(){
//处理参数数据
if(this.options ){
var _options = eval( "(" + this.options + ")");
//TODO 不好使
//Vue.util.mergeOptions(this , _options );
if(_options.pageSize){
this.pageSize = _options.pageSize;
}
if(_options.pageList){
this.pageList = _options.pageList;
}
if(_options.preNum){
this.preNum = _options.preNum;
}
if(_options.nextNum){
this.nextNum = _options.nextNum;
}
}
//处理显示数据
if(this.show){
var _show = eval( "(" + this.show + ")");
if( typeof(_show.showAllNum) == 'boolean'){
this.showAllNum = _show.showAllNum;
}
}
//跳转文本框的默认值
this.goNum = this.pageNum;
//页面加载查询第一页
this.czxy_findAll( 1 );
}
});
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const FieldSchema = new Schema({
host: {
type: mongoose.Schema.Types.ObjectId,
ref: "host"
},
location: {
street: {
type: String,
required: true
},
state: {
type: String,
required: true
},
country: {
type: String,
required: true
},
zip: {
type: Number,
required: true
}
},
availability: {
type: [String],
required: true
},
insurance: [
{
company: {
type: String,
required: true
},
location: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
description: {
type: String,
required: true
}
}
],
social: {
youtube: {
type: String
},
facebook: {
type: String
},
instagram: {
type: String
},
twitter: {
type: String
}
},
miscellaneous: {
lights: {
type: Boolean,
required: true
},
bathrooms: {
type: Boolean,
required: true
},
grass: {
type: String,
required: true
},
soccer_nets: {
type: Boolean,
required: true
},
field_goal: {
type: Boolean,
required: true
}
},
summary: {
type: String
},
reviews: {
type: [String]
},
price: {
type: Number,
required: true
},
security_deposit: {
type: Number
},
photos: {
type: [String],
required: true
},
profile_photo: {
type: String,
required: true
},
contact: {
phone: {
type: String,
required: true
},
email: {
type: String,
required: true
},
mailing_address: {
type: String,
required: true
}
}
});
module.exports = Field = mongoose.model("field", FieldSchema);
|
/**
* **가장 긴 공통 부분 문자열(Longest Common Subsequence)**이란 A, B 두 문자열이 주어졌을 때 두 열에 공통으로 들어 있는 요소로 만들 수 있는 가장 긴 부분열을 말합니다. 여기서 부분열이란 다른 문자열에서 몇몇의 문자가 빠져 있어도 순서가 바뀌지 않은 열을 말합니다.
예를 들어 S1 = ['T', 'H', 'I', 'S', 'I', 'S', 'S', 'T', 'R', 'I', 'N', 'G', 'S'] S2 = ['T', 'H', 'I', 'S', 'I', 'S']라는 두 문자열이 있을 때 둘 사이의 부분 공통 문자열의 길이는 ['T', 'H', 'I', 'S', 'I', 'S']의 6개가 됩니다.
이처럼 **두 문자열이 주어지면 가장 긴 부분 공통 문자열의 길이를 반환하는 프로그램**을 만들어 주세요.
두 개의 문자열이 한 줄에 하나씩 주어집니다. 문자열은 알파벳 대문자로만 구성되며 그 길이는 100글자가 넘어가지 않습니다.
출력은 이 두 문자열의 가장 긴 부분 공통 문자열의 길이를 반환하면 됩니다.
**- Test Case -**
**입력**
THISISSTRINGS
THISIS
**출력**
6
-
**입력**
THISISSTRINGS
TATHISISKKQQAEW
**출력**
6
-
**입력**
THISISSTRINGS
KIOTHIKESSISKKQQAEW
**출력**
3
-
**입력**
THISISSTRINGS
TKHKIKSIS
**출력**
3
*/
function sol(string){
let result = [];
for (let i=1; i<string.length+1; i++){
for (let j=0; j<i; j++){
result.push(string.slice(j, j+string.length-i+1));
}
}
return result;
}
const inputOne = prompt('첫번째 문자열을 입력해주세요.');
const inputTwo = prompt('두번째 문자열을 입력해주세요.');
const arrayOne = sol(inputOne);
const arrayTwo = sol(inputTwo);
//공통 부분 문자열 찾기- 교집합
let intersection = arrayOne.filter(x => arrayTwo.includes(x));
//문자열 길이로 내림차순 정렬
intersection.sort((a,b)=>{
return b.length-a.length;
});
console.log(intersection[0].length);
|
import React from 'react';
const TailorTour = () => {
return (
<>
<h2 className="tailortour-title"><span>Tailor tour</span> - Trải nghiệm theo cách của bạn</h2>
<p>Thiết kế lịch trình theo mong muốn. Đi đoàn riêng an toàn. Để lại thông tin chúng tôi sẽ liên lạc ngay</p>
<div className="row">
<div className="col l-6 m-6 c-12">
<div className="tailortour-form">
<div className="tailortour-name">
<label htmlFor="">Họ Tên</label>
<input className="tailortour-input" type="text" />
</div>
<div className="tailortour-phonenumber">
<label htmlFor="">Điện thoại</label>
<input className="tailortour-input" type="text" />
</div>
<div className="tailortour-email">
<label htmlFor="">Email</label>
<input className="tailortour-input" type="text" />
</div>
<div className="tailortour-experience">
<label htmlFor="">Cách bạn trải nghiệm</label>
<textarea className="tailortour-textarea" placeholder="Thời gian, số khách dự kiến, địa điểm yêu thích, loại hình khách sạn..." cols="30" rows="10"></textarea>
</div>
<div className="tailortour-button">
<button className="tailortour-btn">Yêu cầu tư vấn</button>
</div>
</div>
</div>
<div className="col l-6 m-6 c-0">
<div className="tailortour-avatar">
<i className="fas fa-user-circle"></i>
</div>
<div className="tailortour-consultant">
<p>Tư vấn ngay? Gọi tổng đài</p>
<h3><i className="fas fa-phone-alt"></i> (028) 3933 8002</h3>
<p>8h30 - 18h00 hàng ngày</p>
</div>
<div className="tailortour-qrcode">
<img src="https://cdn1.ivivu.com/app-icon/iVIVUcode.png" alt="qrcode" />
</div>
</div>
</div>
</>
);
};
export default TailorTour; |
import React, { Component} from 'react';
import { DropTarget } from 'react-dnd';
import { shapes } from '../types';
class HoleTriangle extends Component {
constructor(props) {
super(props);
this.state = { fill: false, count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
const { connectDropTarget, isOver, canDrop } = this.props;
const style = canDrop&&isOver ? styles.triangleFill : styles.triangle;
return connectDropTarget(
<div style={style}>
<h1 style={styles.counterStyle}>{this.state.count}</h1>
</div>
);
}
}
const styles = {
triangle: {
width: 0,
height: 0,
borderLeft: '100px solid transparent',
borderRight: '100px solid transparent',
borderBottom: '200px solid white',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItem : 'center'
},
triangleFill: {
width: 0,
height: 0,
borderLeft: '100px solid transparent',
borderRight: '100px solid transparent',
borderBottom: '200px solid purple',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItem : 'center'
},
triangleDanger: {
width: 0,
height: 0,
borderLeft: '100px solid transparent',
borderRight: '100px solid transparent',
borderBottom: '200px solid red',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItem : 'center'
},
counterStyle: {
fontSize: 100
}
};
const holeTarget = {
drop(props,monitor,component) {
component.increment();
}
}
const collect = (connect,monitor) => {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
};
}
export default DropTarget(shapes.TRIANGLE,holeTarget,collect)(HoleTriangle); |
/*globals jQuery,window,document*/
/*
*
* Wijmo Library 2.2.1
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Dual licensed under the Wijmo Commercial or GNU GPL Version 3 licenses.
* licensing@wijmo.com
* http://wijmo.com/license
*
*
* * Wijmo Combobox widget.
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.position.js
* jquery.wijmo.wijlist.js
*
*/
(function ($) {
"use strict";
var inputCSS = "wijmo-wijcombobox-input",
stateHover = "ui-state-hover",
stateActive = "ui-state-active",
stateFocus = "ui-state-focus",
conerLeft = "ui-corner-left",
conerRight = "ui-corner-right",
triggerHTML = "<div class='wijmo-wijcombobox-trigger ui-state-default " +
"ui-corner-right'>" +
"<span class='ui-icon ui-icon-triangle-1-s'></span>" +
"</div>",
labelHTML = "<label class='wijmo-wijcombobox-label ui-widget-content'></label>";
$.widget("wijmo.wijcombobox", {
options: {
/// <summary>
/// A value that specifies the underlying data source provider of wijcombobox.
/// Default: null.
/// Type: wijdatasource/Array
/// Code example:
/// var testArray = [
/// {label: 'c++',value: 'c++'},
/// {label: 'java',value: 'java'},
/// {label: 'php',value: 'php'}];
/// $("#tags").wijcombobox("option", "data", testArray);
/// </summary>
/// <remarks>
/// This option could either be a wijdatasource object
/// or an Object Array containing an item such as
/// {label: "label text", value: "value"}.
/// </remarks>
data: null,
/// <summary>
/// A value that specifies the text in the wijcombobox label.
/// Default: null.
/// Type: String.
/// Code example: $("#tags").wijcombobox("option", "labelText", "Text")
/// </summary>
labelText: null,
/// <summary>
/// A value that determines the minimum length of text
/// that can be entered in the wijcombobox text box to issue an AJAX request.
/// Default: 4.
/// Type: Number.
/// Code example: $("#tags").wijcombobox("option", "minLength", 5)
/// </summary>
minLength: 4,
/// <summary>
/// A value that determines the duration (in milliseconds) of the time
/// to delay before autocomplete begins after typing stops.
/// Default: 300.
/// Type: Number.
/// Code example: $("#tags").wijcombobox("option", "delay", 500)
/// </summary>
delay: 300,
/// <summary>
/// A value that specifies the animation options for a drop-down list
/// when it is visible.
/// Default: null.
/// Type: Object.
/// Code example:
/// var animationOptions = {
/// animated: "Drop",
/// duration: 1000
/// };
/// $("#tags").wijcombobox("option", "showingAnimation", animationOptions)
/// </summary>
showingAnimation: null,
/// <summary>
/// A value specifies the animation options for the drop-down list
/// when it is hidden.
/// Default: null.
/// Type: Object.
/// Code example:
/// var animationOptions = {
/// animated: "Drop",
/// duration: 1000
/// };
///$("#tags").wijcombobox("option", "hidingAnimation", animationOptions)
/// </summary>
hidingAnimation: null,
/// <summary>
/// A value that determines whether to show the trigger of wijcombobox.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "showTrigger", false)
/// </summary>
showTrigger: true,
/// <summary>
/// A value that specifies the position of the drop-down list trigger.
/// Default: "right".
/// Type: String.
/// Code example: $("#tags").wijcombobox("option", "triggerPosition", "left")
/// </summary>
triggerPosition: "right",
/// <summary>
/// A value that specifies the height of the drop-down list.
/// Default: 300.
/// Type: Number.
/// Code example: $("#tags").wijcombobox("option", "dropdownHeight", 300)
/// </summary>
/// <remarks>
/// If the total height of all items is less than the value of this option,
/// it will use the total height of items as the height of the drop-down list.
/// </remarks>
dropdownHeight: 300,
/// <summary>
/// A value that specifies the width of the drop-down list.
/// Default: "auto".
/// Type: Number/String("auto").
/// Code example: $("#tags").wijcombobox("option", "dropdownWidth", 500)
/// </summary>
/// <remarks>
/// When this option is set to "auto", the width of the drop-down
/// list is equal to the width of wijcombobox.
/// </remarks>
dropdownWidth: "auto",
/// <summary>
/// A value that determines whether to select the item
/// when the item gains focus or is activated.
/// Default: false.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "selectOnItemFocus", true)
/// </summary>
selectOnItemFocus: false,
/// <summary>
/// A value determines whether to shorten the drop-down list items
/// by matching the text in the textbox after typing.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "autoFilter", false)
/// </summary>
autoFilter: true,
/// <summary>
/// A value that determines whether to start the auto-complete
/// function after typing in the text if a match exists.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "autoComplete", false)
/// </summary>
autoComplete: true,
/// <summary>
/// A value that determines whether to highlight the keywords in an item.
/// If "abc" is typed in the textbox,
/// all "abc" matches are highlighted in the drop-down list.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "highlightMatching", false)
/// </summary>
highlightMatching: true,
/// <summary>
/// A value that specifies the position options of the drop-down list.
/// The default value of the "of" options is the input of wijcombobox.
/// Default: {}.
/// Type: Object.
/// Code example:
/// var positionOptions = {my:"right", at:"top"};
/// $("#tags").wijcombobox("option", "dropDownListPosition", positionOptions)
/// </summary>
dropDownListPosition: {},
/// <summary>
/// An array that specifies the column collections of wijcombobox.
/// Example: columns: [{name: "header1", width: 150},
/// {name: "header2", width: 150},
/// {name: "header3", width: 150}]
/// Default: [].
/// Type: Array.
/// Code example: $("#tags").wijcombobox("option", "columns", [
/// {name: 'header1', width: 150},
/// {name: 'header2', width: 150},
/// {name: 'header3', width: 150}
/// ]);
/// </summary>
columns: [],
/// <summary>
/// A value that specifies the selection mode of wijcombobox.
/// Default: "Single".
/// Type: String.
/// Code example: $("#tags").wijcombobox("option",
/// "selectionMode", "multiple")
/// </summary>
/// <remarks>
/// Possible options are: "single" and "multiple".
/// </remars>
selectionMode: "single",
/// <summary>
/// A value that specifies the separator for
/// the multiple selected items text in the textbox.
/// Default: ",".
/// Type: String.
/// Code example: $("#tags").wijcombobox("option",
/// "multipleSelectionSeparator", ";")
/// </summary>
multipleSelectionSeparator: ",",
/// <summary>
/// A value that determines whether to check the input text against
/// the text of the selected item when the focus blurs.
/// Default: false.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "forceSelectionText", true)
/// </summary>
/// <remarks>
/// If the text does not match any item, input text will restore
/// to text the selected item or empty if no item is selected.
/// </remarks>
forceSelectionText: false,
/// <summary>
/// A function called when any item in list is selected.
/// Default: null.
/// Type: Function.
/// Code example:
/// Supply a function as an option.
/// $("#tags").wijcombobox({select: function(e, data) { } });
/// Bind to the event by type: wijcomboboxselect
/// $("#tags").bind("wijcomboboxselect", function(e, data) {} );
/// </summary>
/// <param name="e" type="EventObj">
/// EventObj that relates to this event.
/// </param>
/// <param name="item" type="Object">
/// item to be rendered.
/// item.element: LI element with this item.
/// item.list: wijlist instance.
/// item.label: label of item.
/// item.value: value of item.
/// item.text: could be set in handler to override rendered label of item.
/// </param>
select: null,
/// <summary>
/// A value that determines whether input is editable.
/// Default: true.
/// Type: Boolean.
/// Code example: $("#tags").wijcombobox("option", "isEditable", false)
/// </summary>
isEditable: true,
/// <summary>
/// A value that specifies the index of the item to select
/// when using single mode.
/// If the selectionMode is "multiple", then this option could be set
/// to an array of Number which contains the indices of the items to select.
/// Default: -1.
/// Type: Number/Array.
/// Code example: $("#tags").wijcombobox("option", "selectedIndex", 0);
/// The following example gets the selected item:
/// var selectedIndex = $("#tags").wijcombobox("option","selectedIndex");
/// var selectedItem = $("#tags").wijcombobox("option","data")[selectedIndex];
/// </summary>
/// <remarks>
/// If no item is selected, it will return -1.
/// </remarks>
selectedIndex: -1,
/// <summary>
/// A value that specifies the value of the item to select
/// when using single mode.
/// Default: null.
/// Type: Number/String/Object.
/// Code example: $("#tags").wijcombobox("option", "selectedValue", "c++")
/// </summary>
/// <remarks>
/// If no item is selected, it will return null.
/// </remarks>
selectedValue: null,
/// <summary>
/// A function called when drop-donw list is opened.
/// Default: null.
/// Type: Function.
/// Supply a function as an option.
/// Code example: $("#tags").wijcombobox("open", function(e, data) {});
/// Bind to the event by type: wijcomboboxopen
/// $("#tags").bind("wijcomboboxopen", function(e, data) {} );
/// </summary>
/// <param name="e" type="EventObj">
/// The jquery event object.
/// </param>
open: null,
/// <summary>
/// A function called when drop-donw list is closed.
/// Default: null.
/// Type: Function.
/// Supply a function as an option.
/// Code example: $("#tags").wijcombobox("close", function(e, data) {});
/// Bind to the event by type: wijcomboboxclose
/// $("#tags").bind("wijcomboboxclose", function(e, data) {} );
/// </summary>
/// <param name="e" type="EventObj">
/// The jquery event object.
/// </param>
close: null,
/// <summary>
/// A value added to the width of the target select element
/// to account for the scroll bar width of superpanel.
/// Default: 6.
/// Type: Number.
/// <remarks>
/// Unit for this value is pixel.
/// Because the width of the scroll bar may be different between browsers
/// if wijcombobox is initialized with the width of the HTML select element,
/// the text may be hidden by the scroll bar of wijcombobox.
/// </remarks>
/// Code example: $("#tags").wijcombobox("option", "selectElementWidthFix", 5)
/// </summary>
selectElementWidthFix: 6,
/// <summary>
/// A function called before searching the list.
/// Default: null.
/// Type: Function.
/// Code example:
/// Supply a function as an option.
/// $("#tags").wijcombobox({search: function(e, data) { } });
/// Bind to the event by type: wijcomboboxsearch
/// $("#tags").bind("wijcomboboxsearch", function(e, data) {} );
/// </summary>
/// <param name="e" type="EventObj">
/// The jquery event object.
/// </param>
/// <param name="data" type="Object">
/// data.datasrc: The datasource of wijcombobox.
/// data.term: The text to search.
/// </param>
search: null,
/// <summary>
/// A function called when select item is changed.
/// Default: null.
/// Type: Function.
/// Code example:
/// Supply a function as an option.
/// $("#tags").wijcombobox({changed: function(e, data) { } });
/// Bind to the event by type: wijcomboboxchanged
/// $("#tags").bind("wijcomboboxchanged", function(e, data) {} );
/// </summary>
/// <param name="e" type="EventObj">
/// The jquery event object.
/// </param>
/// <param name="data" type="Object">
/// data.oldItem: The old item.
/// data.newItem: The new item.
/// data.oldIndex: The old index of selected item.
/// data.newIndex: The new index of selected item.
/// </param>
changed: null,
/// <summary>
/// The object contains the options of wijlist.
/// Default: null.
/// Type: Object.
/// Code example:
/// var listoptions = {addHoverItemClass: false};
/// $("#tags").wijcombobox("option", "listOptions", listoptions)
/// </summary>
listOptions: null
},
_create: function () {
var t = this;
// inits selected items
t.selectedItem = null;
t.selectedItems = [];
// enable touch support:
if (window.wijmoApplyWijTouchUtilEvents) {
$ = window.wijmoApplyWijTouchUtilEvents($);
}
// inits wijcombobox
t._createDOMElements();
t._bindInputEvents();
t._initDropDownList();
t.repaint();
t._checkSelectIndex();
if (t._usingRemoteData() && t.options.data) {
t.originalDataSourceLoaded = t.options.data.loaded;
}
//update for visibility change
if (t.element.is(":hidden") &&
t.element.wijAddVisibilityObserver) {
t.element.wijAddVisibilityObserver(function () {
t.repaint();
if (t.element.wijRemoveVisibilityObserver) {
t.element.wijRemoveVisibilityObserver();
}
}, "wijcombobox");
}
},
_checkSelectIndex: function () {
var self = this, index,
o = self.options;
if (o.selectedIndex === -1 && o.selectedValue) {
$.each(o.data, function (i, item) {
if (o.data[i].value === o.selectedValue) {
self.options.selectedIndex = i;
return false;
}
});
}
index = o.selectedIndex;
if (!self._usingRemoteData() && (index >= 0 || $.isArray(index))) {
self.search(null, "checkindex");
}
},
repaint: function () {
/// <summary>
/// Repaints wijcombobox. Returns true if it succeeds;
/// otherwise, returns false.
/// Code example: $("#tags").wijcombobox("repaint");
/// </summary>
/// <returns type="Boolean">
/// Returns true if it succeeds; otherwise, returns false.
/// </returns>
var o = this.options, self = this;
if (self.element.is(":visible") || self._comboDiv ||
(self._select !== undefined && self._input.is(":visible"))) {
self._showTrigger();
if (o.disabledState) {
var dis = o.disabled;
self.disable();
o.disabled = dis;
}
if (o.disabled) {
self.disable();
}
return true;
}
return false;
},
_bindInputEvents: function () {
var self = this, input, o, code, keyCode;
input = self._input;
o = self.options;
// self.element is an html input element.
input.bind("keydown.wijcombobox", function (event) {
if (o.disabledState === true || o.disabled) {
return;
}
code = event.keyCode;
keyCode = $.ui.keyCode;
switch (code) {
case keyCode.UP:
self._move("previous", event);
// prevent moving cursor to beginning of
//text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
self._move("next", event);
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
case keyCode.ENTER:
// when menu is open or has focus
if (self.menu.active) {
event.preventDefault();
//update for issue 24045
if (o.selectionMode === "multiple" &&
self.menu &&
self.menu.items &&
self.menu.items.length === 1) {
$.each(self.selectedItems, function (index, i) {
if (i !== self.menu.items[0]) {
i.selected = false;
}
});
}
//end
self.menu.select(event);
}
//update for issue 24134 at 2012/7/19
event.preventDefault();
//end
break;
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
input.trigger("wijcomboblur");
if (!self.menu.active ||
(o.selectionMode === "multiple" && keyCode.TAB === code)) {
return;
}
self.menu.select(event);
// remove selection from input.
var end = input.val().length;
self._selectText(end, end, input);
break;
case keyCode.ESCAPE:
self.close(event);
break;
case keyCode.LEFT:
case keyCode.RIGHT:
case keyCode.SHIFT:
case keyCode.CONTROL:
case keyCode.HOME:
case keyCode.END:
case keyCode.DELETE:
case keyCode.PAGE_UP:
case keyCode.PAGE_DOWN:
// ignore metakeys (shift, ctrl, alt)
break;
case 18: //alt key
input.trigger("wijcomboblur");
break;
default:
// keypress is triggered before the input value is changed
window.clearTimeout(self.searching);
if (o.isEditable === false) {
if (self._cacheKey === undefined) {
self._cacheKey = "";
}
self._cacheKey += String.fromCharCode(code);
}
self.searching = window.setTimeout(function () {
var term;
if (o.isEditable === false) {
term = self._cacheKey;
self._cacheKey = undefined;
}
else {
term = input.val();
}
self.search(term, event);
}, o.delay);
break;
}
}).bind("wijcomboblur.wijcombobox", function (event) {
window.clearTimeout(self.searching);
self._addInputFocus(false, stateFocus);
// TODO try to implement this without a timeout,
// see clearTimeout in search()
self.closing = window.setTimeout(function () {
self.close(event, true);
}, 150);
}).bind("focus.wijcombobox", function () {
self._addInputFocus(true, stateFocus);
}).bind("blur.wijcombobox", function () {
if (!self.menu.element.is(":visible")) {
input.trigger("wijcomboblur");
}
//self.options.currentText = input.val();
self._change();
});
},
_addInputFocus: function (add, css) {
var self = this, wrap, key, arrow;
wrap = self._input.parent();
key = add ? "addClass" : "removeClass";
arrow = self._triggerArrow;
wrap[key](css);
if (arrow !== undefined) {
arrow[key](css);
}
},
_renderColumnsHeader: function (header) {
var ul = $("<ul class='wijmo-wijcombobox-rowheader'></ul>");
$.each(this.options.columns, function (index, column) {
var li = $("<li class='wijmo-wijcombobox-cell ui-widget-header'></li>");
li.html(column.name);
if (column.width !== undefined) {
li.width(column.width);
}
li.appendTo(ul);
});
header.append(ul);
},
_hasSameValueText: function (item1, item2) {
return item1.label === item2.label && item1.value === item2.value;
},
_initDropDownList: function () {
var self = this, doc, menuElement, o, header, listOptions;
doc = self.element[0].ownerDocument;
if (!self._comboDiv) {
menuElement = $("<div class='wijmo-wijcombobox-list'></div>");
} else {
menuElement = self._oriList;
}
o = self.options;
if (o.columns.length > 0) {
menuElement.addClass("wijmo-wijcombobox-multicolumn");
header = $("<div class='wijmo-wijsuperpanel-header " +
"ui-state-default'></div>");
self._renderColumnsHeader(header);
menuElement.append(header);
}
listOptions = {
keepHightlightOnMouseLeave: true,
selectionMode: o.selectionMode,
addHoverItemClass: o.columns.length === 0,
focus: function (e, item) {
var i = item;
if (o.selectOnItemFocus) {
self.menu.select(null, {
notCloseAfterSelected: true
});
}
if (o.columns.length > 0) {
i.element.prev().addClass("wijmo-wijcombobox-active-prev");
i.element.find(".wijmo-wijcombobox-row>.wijmo-wijcombobox-cell")
.addClass("ui-state-hover");
}
},
selected: function (event, ui) {
window.clearTimeout(self.closing);
var mode = o.selectionMode, item, newIndex, oldIndex, oldItem;
item = ui.item;
if (self._trigger("select", event, item)) {
if (mode === "single") { // single mode selection
// local data select
if (!self._usingRemoteData()) {
//update for fixing bug 17528 by wh at 2011/10/9
//if(ui.selectedIndex !== undefined){
// newIndex = ui.selectedIndex;
//}else
//{
// newIndex = $.inArray(item, self.items);
//}
newIndex = $.inArray(item, self.items);
if (newIndex === undefined) {
newIndex = ui.selectedIndex;
}
//end for fixing bug 17528
if (newIndex !== o.selectedIndex) {
self._input.val(item.label);
oldItem = self.selectedItem;
if (oldItem !== null) {
oldItem.selected = false;
}
self.selectedItem = item;
oldIndex = o.selectedIndex;
o.selectedIndex = newIndex;
//update for get selected value by wh at 2012/2/29
o.selectedValue = self.selectedItem.value;
//end for get selected value
// fire select change event
if (self._select !== undefined) {
self._select[0].selectedIndex = o.selectedIndex;
self._select.trigger("change");
}
self._trigger("changed", null, {
oldItem: oldItem,
selectedItem: self.selectedItem,
newIndex: o.selectedIndex,
oldIndex: oldIndex
});
} else {
// for fixing bug 24133 at 2012/8/6
if (self.selectedItem &&
self._input.val() !== self.selectedItem.label) {
self._input.val(item.label);
}
}
}
else {
// If items have the same text and value,
// they are considered to be same in remote mode.
if (self.selectedItem === null ||
!self._hasSameValueText(item, self.selectedItem)) {
self._input.val(item.label);
self.selectedItem = item;
self._trigger("changed", null, {
selectedItem: item
});
}
}
}
else { // multiple selection mode
if (!self._usingRemoteData()) {
self.selectedItems = ui.selectedItems;
self._selectedItemsToInputVal(self.selectedItems);
self._trigger("changed", null, {
selectedItem: item,
selectedItems: self.selectedItems
});
///TODO: show helper list
}
}
}
if ((ui.data === undefined || !ui.data.notCloseAfterSelected) &&
mode === "single") {
self.close(event);
self._input.focus();
}
},
blur: function (e, item) {
var d = item.element;
if (o.columns.length > 0 && d) {
d.find(".wijmo-wijcombobox-row>.wijmo-wijcombobox-cell")
.removeClass("ui-state-hover");
d.prev().removeClass("wijmo-wijcombobox-active-prev");
}
},
itemRendering: function (event, data) {
var item = data, css;
css = "";
if (item.isSeparator) {
css += " wijmo-wijcombobox-separator";
}
if (item.selected) {
css += " wijmo-wijcombobox-selecteditem";
}
if (css.length > 0) {
item.element.addClass(css);
}
//update for js error when fixing select don't fire
//by wuhao at 2011/10/24
//Add condition: item.label
if (self._keypress && o.isEditable &&
o.columns.length === 0 && o.highlightMatching &&
$.trim(self._input.val()).length > 0 && item.label) {
item.text = item.label.replace(
new RegExp("(?![^&;]+;)(?!<[^<>]*)(" +
self._escapeRegex(self._input.val()) +
")(?![^<>]*>)(?![^&;]+;)", "gi"),
"<span class='ui-priority-primary'>$1</span>");
}
else {
item.text = undefined;
}
},
itemRendered: function (event, data) {
var item = data, li, u;
if (item.cells === undefined) {
return;
}
li = item.element;
li.empty();
u = $("<ul class='wijmo-wijcombobox-row'></ul>");
$.each(item.cells, function (index, cell) {
var l = $("<li class='wijmo-wijcombobox-cell " +
"ui-state-default'></li>");
//Fix a bug that columns.width doesn't work.
if (o.columns && o.columns.length > index) {
if (typeof o.columns[index].width !== "undefined") {
l.width(o.columns[index].width);
}
}
//end comments.
l.append(cell);
l.attr("title", cell);
u.append(l);
});
li.append(u);
},
superPanelOptions: {
resized: function (e) {
var m = self.menu, ele = m.element;
o.dropdownWidth = ele.outerWidth();
o.dropdownHeight = ele.outerHeight();
self._positionList();
self.menu.refreshSuperPanel();
}
}
};
listOptions = $.extend(true, listOptions, o.listOptions);
self.menu = menuElement.appendTo("body", doc)
.wijlist(listOptions)
.zIndex(self._input.zIndex() + 1)
.css({
top: 0,
left: 0
}).hide().data("wijlist");
self._menuUL = self.menu.ul;
},
_getSelectedItemsText: function (items) {
var s = "", self, sep;
self = this;
sep = self.options.multipleSelectionSeparator;
self.selectedItems = items;
$.each(items, function (index, item) {
//update for bug 24045
if (item) {
s += item.label + sep;
}
});
if (s.length > 0) {
s = s.substr(0, s.lastIndexOf(sep));
}
return s;
},
_selectedItemsToInputVal: function (items) {
var self = this;
self._input.val(self._getSelectedItemsText(items));
},
_createDOMElements: function () {
var self = this, comboElement, ele, input, wrapperElement;
wrapperElement = $("<div class='wijmo-wijcombobox-wrapper " +
"ui-state-default ui-corner-all'>" +
"</div>");
// check if element is a select element
ele = self.element;
// create from a select element
if (ele.is("select")) {
comboElement =
$("<div role='combobox' class='wijmo-wijcombobox " +
"ui-widget ui-helper-clearfix'>" +
"</div>");
comboElement.append(wrapperElement);
self._comboElement = comboElement;
self._select = ele;
// add class to set font size to get the correct width of select.
ele.addClass("ui-widget");
input = self._input = $("<input role='textbox' " +
"aria-autocomplete='list' aria-haspopup='true' />")
.insertAfter(ele);
if (!self.options.data) {
self.options.data = self._convertSelectOptions();
}
} else if (ele.is("div") && $(ele.children()[0]).is("input[type='text']") &&
$(ele.children()[1]).is("div")) {
//div tag
self._comboElement = self._comboDiv = comboElement = ele;
self._oriList = $(ele.children()[1]);
input = self._input = $(ele.children()[0]);
wrapperElement.prependTo(comboElement).append(input);
ele.addClass("wijmo-wijcombobox ui-widget ui-helper-clearfix");
ele.attr("role", "combobox");
}
else {
comboElement =
$("<div role='combobox' class='wijmo-wijcombobox " +
"ui-widget ui-helper-clearfix'>" +
"</div>");
comboElement.append(wrapperElement);
self._comboElement = comboElement;
input = self._input = ele;
}
if (!self._comboDiv) {
comboElement.insertBefore(input);
//update for fixing bug 17328 at 2011/10/18 by wuhao
//add visible judge for visibility change at 2012/7/24
if (self.element.is(":visible")) {
input.width(input.width());
}
//end for fixing bug 17328
comboElement.children(".wijmo-wijcombobox-wrapper").append(input);
}
input.attr({
autocomplete: "off",
role: "textbox",
"aria-wijcombobox": "list",
"aria-haspopup": "true"
}).addClass(inputCSS);
self._oldWidth = ele.css("width");
if (self.options.isEditable === false) {
input.attr("readonly", "readonly");
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
wrapperElement.bind("click", function () {
if (self.options.disabledState === true ||
self.options.disabled) {
return;
}
self._triggerClick();
});
}
comboElement.bind("mouseenter", function () {
if (self.options.disabledState === true ||
self.options.disabled) {
return;
}
self._addInputFocus(true, stateHover);
}).bind("mouseleave", function () {
self._addInputFocus(false, stateHover);
});
},
_convertSelectOptions: function () {
var items = [], self, selectOptions;
self = this;
selectOptions = self._select.get(0).options;
$.each(selectOptions, function (idx, opt) {
items.push({ label: opt.text, value: opt.value });
});
self.options.selectedIndex = self._select[0].selectedIndex;
return items;
},
getComboElement: function () {
return this._comboElement;
},
_showTrigger: function () {
var self = this, o, input, inputWrapper, comboElement,
selectClone, selectWidth = 0,
trigger, label, sp, padding, labelPadding, triggerPadding;
o = self.options;
input = self._input;
inputWrapper = input.parent();
comboElement = self._comboElement;
trigger = self._triggerArrow;
label = self._label;
// set size
if (self._select !== undefined) {
//update for fixing bug 15920 by wuhao
if (!$.browser.msie) {
selectWidth = self._select.width();
} else {
selectClone = self._select.clone();
self._select.after(selectClone);
selectWidth = selectClone.width();
selectClone.remove();
}
input.width(selectWidth +
(o.data.length > 20 ? o.selectElementWidthFix : 0));
// input.width(self._select.width() +
// (o.data.length > 20 ? o.selectElementWidthFix : 0));
//end for bug 15920.
self._select.hide();
}
//update for fixing bug 15920 by wuhao
input.css("margin-left", "");
input.css("margin-right", "");
//end for bug 15920.
comboElement.width(inputWrapper[0].offsetWidth);
//comboElement.height(inputWrapper[0].offsetHeight);
// show label
if (o.labelText !== null) {
label = self._label = $(labelHTML);
inputWrapper.append(label.html(o.labelText));
}
else {
if (label !== undefined) {
label.remove();
self._label = undefined;
}
}
if (o.showTrigger) {
input.removeClass("ui-corner-all");
if (trigger === undefined) {
trigger = self._triggerArrow = $(triggerHTML);
comboElement.append(trigger);
trigger.bind("mouseover.triggerevent", self, function (e) {
if (o.disabledState === true || o.disabled) {
return;
}
var ct = $(e.currentTarget);
ct.addClass(stateHover);
}).bind("mousedown.triggerevent", self, function (e) {
if (o.disabledState === true || o.disabled) {
return;
}
var ct = $(e.currentTarget);
ct.addClass(stateActive);
}).bind("mouseup.triggerevent", self, function (e) {
var ct = $(e.currentTarget);
ct.removeClass(stateActive);
}).bind("click.triggerevent", self, function () {
if (o.disabledState === true || o.disabled) {
return;
}
self._triggerClick();
});
}
if (o.triggerPosition === "right") {
trigger.css({ left: "", right: "0px" });
trigger.removeClass(conerLeft);
trigger.addClass(conerRight);
}
else {
trigger.css({ "right": "", "left": "0px" });
trigger.removeClass(conerRight);
trigger.addClass(conerLeft);
}
trigger.setOutHeight(comboElement.innerHeight());
sp = trigger.find("span");
sp.css("margin-left", (trigger.innerWidth() - sp[0].offsetWidth) / 2);
sp.css("margin-top", (trigger.innerHeight() - sp[0].offsetHeight) / 2);
}
else {
if (trigger !== undefined) {
trigger.unbind(".triggerevent");
trigger.remove();
self._triggerArrow = undefined;
}
input.removeClass("ui-corner-left");
input.removeClass("ui-corner-right");
input.addClass("ui-corner-all");
}
// padding
padding = labelPadding = triggerPadding = 0;
if (label !== undefined) {
labelPadding += label[0].offsetWidth;
}
if (trigger !== undefined) {
triggerPadding = trigger[0].offsetWidth;
}
padding = labelPadding + triggerPadding;
input.setOutWidth(inputWrapper.innerWidth() - padding);
padding = padding === 0 ? "" : padding;
if (o.triggerPosition === "right") {
input.css("margin-left", "");
input.css("margin-right", padding);
if (label !== undefined) {
label.css("left", "");
label.css("right", triggerPadding);
}
}
else {
input.css("margin-right", "");
input.css("margin-left", padding);
if (label !== undefined) {
label.css("right", "");
label.css("left", triggerPadding);
}
}
},
_triggerClick: function (e) {
var self = this, term = "";
window.clearTimeout(self.closing);
if (self.menu.element.is(":visible")) {
self.close();
}
else {
// TODO: click open should not render again.
if (self._usingRemoteData()) {
term = self._input.val();
}
self.search(term, e);
}
},
destroy: function () {
/// <summary>
/// Removes the wijcombobox functionality completely.
/// This returns the element back to its pre-init state.
/// Code example: $("#tags").wijcombobox("destroy");
/// </summary>
var self = this,
ele = self.element;
if (self.options.isEditable === false) {
ele.removeAttr("readonly");
}
if (self._select !== undefined) {
self._select.removeClass("ui-widget");
self._select.show();
self._input.remove();
}
else if (self._comboDiv) {
self._comboDiv
.removeClass("wijmo-wijcombobox ui-widget ui-helper-clearfix");
self._comboDiv.removeAttr("role");
self._input.insertBefore(self._comboDiv);
self._comboDiv.children(".wijmo-wijcombobox-wrapper").remove();
}
else {
ele.css("width", self._oldWidth);
ele.removeClass(inputCSS);
ele.removeAttr("autocomplete").removeAttr("role")
.removeAttr("aria-wijcombobox").removeAttr("aria-haspopup");
ele.insertBefore(self._comboElement);
ele.css("padding", "");
}
self._comboElement.remove();
self.menu.destroy();
self.menu.element.remove();
$.Widget.prototype.destroy.call(self);
},
_setOption: function (key, value) {
var self = this, ele, input, items, inputWrapper,
label = self._label, triggerPadding,
triggerWidth = 0,
o = self.options;
ele = self._comboElement;
input = self.element;
inputWrapper = input.parent();
if (self._triggerArrow) {
triggerWidth = self._triggerArrow.outerWidth();
}
$.Widget.prototype._setOption.apply(self, arguments);
if (key === "disabled") {
if (value) {
ele.addClass("wijmo-wijcombobox-disabled ui-state-disabled");
input.attr("disabled", "disabled");
if (self._comboDiv) {
self._input
.addClass("wijmo-wijcombobox-disabled ui-state-disabled")
.attr("disabled", "disabled");
}
//for fixing bug 24043 in tfs
if (self._triggerArrow) {
self._triggerArrow.unbind("click.triggerevent");
}
self.close();
}
else {
ele.removeClass("wijmo-wijcombobox-disabled ui-state-disabled");
input.removeAttr("disabled");
if (self._comboDiv) {
self._input
.removeClass("wijmo-wijcombobox-disabled ui-state-disabled")
.removeAttr("disabled");
}
//for fixing bug 24043 in tfs
if (self._triggerArrow) {
self._triggerArrow.bind("click.triggerevent", self, function () {
if (o.disabledState === true) {
return;
}
self._triggerClick();
});
}
}
} else if (key === "labelText") {
if (o.labelText !== null) {
label = self._label = $(labelHTML);
self._input.parent()
.append(label.html(o.labelText));
if (self._triggerArrow !== undefined) {
triggerPadding = self._triggerArrow[0].offsetWidth;
}
if (o.triggerPosition === "right") {
if (label !== undefined) {
label.css("left", "");
label.css("right", triggerPadding);
}
}
else {
if (label !== undefined) {
label.css("right", "");
label.css("left", triggerPadding);
}
}
self.repaint();
}
else {
if (label !== undefined) {
label.remove();
self._label = undefined;
}
}
} else if (key === "showTrigger") {
self._showTrigger();
if (!o.showTrigger && self.element.is("select")) {
input.width(input.width() + triggerWidth);
}
} else if (key === "triggerPosition") {
input.width(input.width() + triggerWidth);
self._showTrigger();
} else if (key === "selectionMode") {
self.menu._setOption("selectionMode", value);
} else if (key === "isEditable") {
if (value) {
input.removeAttr("readonly");
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
$(".wijmo-wijcombobox-wrapper",
self._comboElement[0]).bind("click", function () {
self._triggerClick();
});
}
else {
input.attr("readonly", "readonly");
$(".wijmo-wijcombobox-wrapper",
self._comboElement[0]).unbind("click");
}
}
//Add comments by RyanWu@20110119.
//For fixing the issue that first open the dropdown list and choose one item,
//then set the new data to the combo and click the dropdown list,
//an exception will be thrown.
else if (key === "data") {
self.selectedItem = null;
self.options.selectedIndex = -1;
//update for get selectedvalue option by wh at 2012/2/29
self.options.selectedValue = null;
//end for get selectedValue option
self._input.val("");
}
//end by RyanWu@20110119.
else if (key === "selectedIndex") {
if (value > -1) {
if (self.selectedItem !== null) {
self.selectedItem.selected = false;
}
items = self.items;
if (!items) {
items = self.options.data;
}
if (items && items[value] !== null) {
self.selectedItem = items[value];
self.selectedItem.selected = true;
self._input.val(self.selectedItem.label);
o.selectedValue = self.selectedItem.value;
}
} else if (value <= -1 || !value) {
self._clearSelection();
}
}
else if (key === "selectedValue") {
if (value) {
if (self.selectedItem !== null) {
self.selectedItem.selected = false;
}
items = self.items;
if (!items) {
items = self.options.data;
}
$.each(items, function (index, item) {
if (items[index].value === value) {
self.selectedItem = items[index];
self.selectedItem.selected = true;
self._input.val(self.selectedItem.label);
self.options.selectedIndex = index;
return false;
}
});
} else {
self._clearSelection();
}
}
},
search: function (value, eventObj) {
/// <summary>
/// Searches the wijcombobox drop-down list for the given value.
/// Code example: $("#tags").wijcombobox("search", "C++");
/// </summary>
/// <param name="value" type="String">
/// Text to search in the drop-down list
/// </param>
/// <param name="eventObj" type="Object">
/// The jquery event object.
/// </param>
var self = this, o, datasource, d;
o = self.options;
datasource = o.data;
window.clearTimeout(self.closing);
d = {
value: value,
e: eventObj,
self: self
};
// load data when data is not loaded yet
// or datasource is using a proxy to obtain data.
if (datasource !== null || self._comboDiv) {
// check index will skip search event
if (eventObj !== "checkindex") {
if (self._trigger("search", eventObj,
{ datasrc: datasource, term: d }) === false) {
return;
}
}
if ($.isArray(datasource) || self._comboDiv) {
self._hideShowArrow(false);
self._onListLoaded(datasource, d);
}
else {
if (self._usingRemoteData() &&
eventObj !== undefined && value.length < o.minLength) {
return;
}
self._hideShowArrow(false);
//update for: datasource loaded event don't fired
// in combobox
datasource.loaded = function (e, data) {
self._onListLoaded(e, data);
if (self.originalDataSourceLoaded) {
self.originalDataSourceLoaded(e, data);
}
};
datasource.load(d);
}
}
},
_clearSelection: function () {
var self = this, o = self.options;
if (o.selectionMode === "single") {
if (self.selectedItem !== null) {
self.selectedItem.selected = false;
}
self.selectedItem = null;
} else {
if (self.selectedItems) {
$.each(self.selectedItems, function (index, item) {
if (item.selected) {
item.selected = false;
}
});
self.selectedItem = null;
self.selectedItems = null;
}
}
o.selectedValue = null;
self._input.val("");
},
_usingRemoteData: function () {
var o = this.options.data, r = false;
if (!$.isArray(o) && o !== null && o.proxy !== null) {
r = true;
}
return r;
},
_hideShowArrow: function (show) {
// hide arrow to show
var self = this, input, arrow;
input = self.element;
arrow = self._triggerArrow;
if (arrow !== undefined) {
arrow[show ? "show" : "hide"]();
}
input[show ? "removeClass" : "addClass"]("wijmo-wijcombobox-loading");
},
_onListLoaded: function (datasource, data) {
var self = data.self, ele, o, searchTerm, items, idx, itemsToRender;
ele = self._input;
o = self.options;
searchTerm = data.value;
if (datasource === null) {
items = null;
} else {
items = $.isArray(datasource) ? datasource : datasource.items;
}
self.items = items;
if (data.e === "checkindex") {
idx = o.selectedIndex;
if (o.selectionMode === "multiple" && $.isArray(idx)) {
$.each(idx, function (i, n) {
var itm = items[n];
itm.selected = true;
self.selectedItems.push(itm);
});
self._selectedItemsToInputVal(self.selectedItems);
}
else {
items[idx].selected = true;
self.selectedItem = items[idx];
ele.val(self.selectedItem.label);
}
self._hideShowArrow(true);
return;
}
// only fileter result when using local data.
if (!self._usingRemoteData() && items) {
self._filter(items, searchTerm);
itemsToRender = $.grep(items, function (item1) {
return !o.autoFilter || item1.match;
});
}
else {
self._topHit = null;
itemsToRender = items;
}
if ((itemsToRender && itemsToRender.length > 0) || self._comboDiv) {
// open dropdown list
self._openlist(itemsToRender, data, searchTerm);
// trigger dropdown open event.
self._trigger("open");
self._addInputFocus(true, stateFocus);
}
else {
self.close(null, true);
}
self._hideShowArrow(true);
},
close: function (event, skipAnimation) {
/// <summary>
/// Closes drop-down list.
/// Code example: $("#tags").wijcombobox("close", null, false);
/// </summary>
/// <param name="event" type="EventObj">
/// The jquery event object.
/// </param>
/// <param name="skipAnimation" type="Boolean">
/// A value indicating whehter to skip animation.
/// </param>
var self = this, menu, hidingAnimation, hidingStyle;
menu = self.menu;
self._dropDownHeight = menu.element.outerHeight();
self._dropDownWidth = menu.element.outerWidth();
window.clearTimeout(self.closing);
// test parent element is need, hidingAnimation
// because some effect will wrap the target element.
if (menu.element.is(":visible") && !menu.element.is(":animated") &&
!menu.element.parent().is(":animated")) {
self._trigger("close", event);
menu.deactivate();
hidingAnimation = self.options.hidingAnimation;
//add for size animation by wuhao 2011/7/16
if (hidingAnimation && (hidingAnimation.effect === "size" ||
hidingAnimation.animated === "size")) {
hidingAnimation.options = $.extend({
to: {
width: 0,
height: 0
}
}, hidingAnimation.options);
}
hidingStyle = menu.element.attr("style");
//end for size animation
if (skipAnimation !== true && hidingAnimation) {
menu.element.hide(
//update for modifying animation name by wh at 2011/9/26
//hidingAnimation.effect,
hidingAnimation.effect || hidingAnimation.animated,
hidingAnimation.options,
hidingAnimation.speed || hidingAnimation.duration,
//end for modifying name
function () {
//add for size animation by wuhao 2011/7/16
menu.element.removeAttr("style")
.attr("style", hidingStyle)
.hide();
//end for size animation
if (hidingAnimation.callback) {
hidingAnimation.callback.apply(this, arguments);
}
});
}
else {
menu.element.hide();
}
self._addInputFocus(false, stateFocus);
$(document).unbind("click", self.closeOnClick);
}
},
_change: function () {
// TODO: finish _change event.
var self = this, o, f, m, ele, t, itm, items;
o = self.options;
f = o.forceSelectionText;
m = o.selectionMode;
ele = self._input;
t = ele.val();
itm = self.selectedItem;
items = self.selectedItems;
if (f) {
if (m === "single") {
if (itm !== null) {
if (itm.label !== t) {
ele.val(itm.label);
}
}
else {
ele.val("");
}
}
}
//Todo: when input something to combobox,
//the text will restore in multiple mode
//Maybe it need to be adjusted.
if (m === "multiple") {
//update for add issue: when iseditable is false
//click the all the combobox, the dropdown list will open
//self._selectedItemsToInputVal(self.selectedItems);
if (!self.selectedItems || self.selectedItems.length === 0) {
items = [itm];
}
self._selectedItemsToInputVal(items);
}
},
_openlist: function (items, data, searchTerm) {
var self = data.self, eventObj = data.e, keypress, textWidth, menuElement,
o, oldPadding, verticalBorder = 2, headerHeight = 0, dropDownHeight,
origCloseOnClick, h, showingAnimation, showingStyle, showingSize;
keypress = self._keypress = !!eventObj;
o = self.options;
menuElement = self.menu.element;
//update for fixing issue 18124 at 2011/11/3 by wh
//menuElement.zIndex(self.element.zIndex() + 1);
menuElement.zIndex(self.element.zIndex() + 100);
//end for 18124
if (self._comboDiv) {
//update for case 20689 at 2012/4/11
if (!self.listHasCreated) {
//update for issue 24130 at 2012/7/20
//self.menu.setTemplateItems(items);
self.menu.setTemplateItems(o.data);
//end
self.menu.renderList();
self.listHasCreated = true;
}
//update for issue 24130 at 2012/7/20
if (searchTerm !== null && searchTerm !== undefined) {
self._topHit = self.menu.filterTemplateItems(searchTerm);
}
//update for issue 24130 at 2012/7/20
} else {
self.menu.setItems(items);
self.menu.renderList();
}
// show dropdown
self.menu.element.show();
if (o.dropdownWidth === "auto") {
textWidth = self._comboElement.outerWidth();
}
else {
textWidth = o.dropdownWidth;
}
oldPadding = menuElement.css("padding");
menuElement.css("padding", "0px");
menuElement.setOutWidth(textWidth);
menuElement.css("padding", oldPadding);
dropDownHeight = o.dropdownHeight;
/*update for fix issue:dropdownHeight
* take no effect when the original
* element is select
if (self._select !== undefined) {
dropDownHeight = 20 * self._menuUL
.children(".wijmo-wijlist-item:first").outerHeight();
}*/
//For fixing bug 15778
//h = Math.min(self._menuUL.outerHeight() + verticalBorder, dropDownHeight);
if (menuElement.children(".wijmo-wijsuperpanel-header")) {
headerHeight = menuElement
.children(".wijmo-wijsuperpanel-header").outerHeight() || 0;
}
//end for fixing bug 15778
h = Math.min(self._menuUL.outerHeight() + verticalBorder + headerHeight,
dropDownHeight);
menuElement.setOutHeight(h);
self.menu.refreshSuperPanel();
self._positionList();
if (!keypress && self.selectedItem !== undefined) {
self.menu.activate(null, self.selectedItem, true);
}
if (keypress && eventObj.keyCode !== $.ui.keyCode.BACKSPACE) {
if (o.isEditable) {
self._runAutoComplete();
}
else {
self.menu.activate(null, self._topHit, true);
}
}
else {
showingAnimation = self.options.showingAnimation;
if (o.showingAnimation !== null &&
!(eventObj !== undefined &&
eventObj.keyCode === $.ui.keyCode.BACKSPACE)) {
self.menu.element.hide();
//Add comments by RyanWu@20101105.
//For fixing the issue that list items are transparent
//when choosing bounce effect.
//self.menu.element.show(
//showingAnimation.effect,
//showingAnimation.options,
//showingAnimation.speed,
//showingAnimation.callback);
//add for size animation by wuhao 2011/7/16
showingSize = {
from: { width: 0, height: 0 },
to: { width: self._dropDownWidth || menuElement.outerWidth(),
height: self._dropDownHeight || menuElement.outerHeight()
}
};
if (showingAnimation && (showingAnimation.effect === "size" ||
showingAnimation.animated === "size")) {
showingAnimation.options =
$.extend(showingSize, showingAnimation.options);
}
showingStyle = menuElement.attr("style");
//end for size animation
menuElement.show(
//update for modify animation name by wh at 2011/9/26
//showingAnimation.effect,
showingAnimation.effect || showingAnimation.animated,
//end for modifu animation name
showingAnimation.options,
showingAnimation.speed || showingAnimation.duration,
function () {
//add for size animation by wuhao 2011/7/16
menuElement.removeAttr("style")
.attr("style", showingStyle)
.show();
//end for size animation
if (showingAnimation.callback) {
showingAnimation.callback.apply(this, arguments);
}
if ($.browser.msie) {
menuElement.css("filter", "");
}
});
//end by RyanWu@20101105.
}
}
if (!self.hasOwnProperty("closeOnClick")) {
origCloseOnClick = self.closeOnClick;
self.closeOnClick = function (e) {
return origCloseOnClick(e);
};
}
//update for issue 2012/6/14: place combobox in expander
//open the dropdown, then collapse the expander
//the dropdown is still open
//$(document).bind("click", self, self.closeOnClick);
$(document).bind("mouseup", self, self.closeOnClick);
},
closeOnClick: function (e) {
var self = e.data, t = e.target;
if (!$.contains(self._comboElement[0], t) &&
!$.contains(self.menu.element[0], t)) {
self.close();
$(".wijmo-wijcombobox-wrapper", self._comboElement[0])
.removeClass("ui-state-hover")
.removeClass("ui-state-focus");
$(".wijmo-wijcombobox-trigger", self._comboElement[0])
.removeClass("ui-state-hover")
.removeClass("ui-state-focus");
}
},
_positionList: function () {
var self = this, positionOptions, defaultPosition;
positionOptions = self.options.dropDownListPosition;
defaultPosition = {
my: "left top",
at: "left bottom",
of: self._comboElement,
collision: "none"
};
defaultPosition = $.extend(defaultPosition, positionOptions);
self.menu.element.position(defaultPosition);
},
_runAutoComplete: function () {
var self = this, ele, topHit, oldText, fullText, start, end;
ele = self._input;
topHit = self._topHit;
if (!self.options.autoComplete || topHit === null) {
return;
}
self.menu.activate(null, topHit, true);
oldText = ele.val();
fullText = topHit.label;
ele.val(fullText);
start = oldText.length;
end = fullText.length;
self._selectText(start, end, ele);
},
_selectText: function (start, end, input) {
var v = input.val(), inputElement = input.get(0), range;
if (v.length > 0) {
if (inputElement.setSelectionRange !== undefined) {
inputElement.setSelectionRange(start, end);
}
else if (inputElement.createTextRange !== undefined) {
range = inputElement.createTextRange();
range.moveStart("character", start);
range.moveEnd("character", end - v.length);
range.select();
}
}
},
_move: function (direction, event) {
if (!this.menu.element.is(":visible")) {
this.search("", event);
return;
}
if (this.menu.first() && /^previous/.test(direction) ||
this.menu.last() && /^next/.test(direction)) {
//update for fixing bug 15964 by wuhao
//this.menu.deactivate();
//end for bug 15964.
return;
}
this.menu[direction](event);
},
_escapeRegex: function (value) {
if (value === undefined) {
return value;
}
return value.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
},
_filter: function (array, searchTerm) {
var term1 = this._escapeRegex(searchTerm), matcher, topHit = null;
/// TODO : start with or contains and case sensitive.
if (!array) {
return null;
}
matcher = new RegExp(term1, "i");
$.each(array, function (index, item) {
if (term1 === undefined || term1.length === 0) {
item.match = true;
return;
}
var matchResult = matcher.exec(item.label);
if (matchResult === null) {
item.match = false;
}
else {
if (topHit === null && matchResult.index === 0) {
topHit = item;
}
item.match = matchResult.index >= 0;
}
});
this._topHit = topHit;
return array;
}
});
} (jQuery));
|
import { combineReducers } from 'redux';
import components from './componentReducer';
const RootReducer = combineReducers({
components
});
export default RootReducer; |
import React from 'react';
import NoResults from '../elements/NoResults';
import NoResultsImage from '../../img/tommy.jpg';
import Message from './Message';
import Spinner from '../layout/Spinner';
const MessageList = ({ messages, loading, user, toggleChat }) => {
const userAndFriendsMessages = messages.filter(
(message) =>
message.recipient._id === user._id || message.sender._id === user._id
);
return (
<div>
{loading ? (
<Spinner />
) : !loading && userAndFriendsMessages.length === 0 ? (
<NoResults
image={NoResultsImage}
text1="All because you wanted to save a couple extra pennies..."
text2="Messages between you and friends will display here"
/>
) : (
userAndFriendsMessages.map((message) => (
<Message
toggleChat={(message) => toggleChat(message)}
message={message}
key={message._id}
user={user}
/>
))
)}
</div>
);
};
export default MessageList;
|
import React, { Component, Fragment } from 'react';
import { Row, Col, Form, Select, Input, Button, message, Table, Pagination, Tabs } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { router } from 'umi';
import styles from './TaskScheduling.less';
const { Option } = Select;
const { TabPane } = Tabs;
import PMTabA from './PMTabA';
import PMTabB from './PMTabB';
import PMTabC from './PMTabC';
import PMTabD from './PMTabD';
@connect(({ orderA, loading }) => ({ orderA, loading: loading.models.orderA }))
class PersonnelManagementA extends Component {
state = {
TabsPage: '1',
//人员管理 上表格 所有数据来源
data: {
list: [], //table 表格数据
total: 10, //当前页面总数据量
current: 1, //默认显示第几页
pageSize: 10, //每页显示多少数据
loading: true,
},
baseAdminId: '',
//下tab页A表格的数据
dataSourcePMTabA: {
list: [], //table 表格数据
total: 10, //当前页面总数据量
current: 1, //默认显示第几页
pageSize: 10, //每页显示多少数据
loading: false,
},
Highlight: '', //高亮显示
};
constructor(props) {
super(props);
}
componentDidMount() {
this.start();
}
//获取所有表格数据
start = parmas => {
const { dispatch } = this.props;
dispatch({
type: 'orderA/pdaUserManage',
payload: parmas,
callback: res => {
if (res.code === 1000) {
res.rst.list.map((item, index) => {
item.key = index;
});
res.rst.loading = false; // 取消下表格加载状态
this.setState({ data: res.rst });
this.state.Highlight = this.state.data.list[0].baseAdminId; // 将第一条数据的baseAdminId 赋值给 state 的高亮
this.state.baseAdminId = this.state.data.list[0].baseAdminId; //获取到
this.onRowClick(this.state.data.list[0]); // 将第一条数据传入 获取下表格数据的函数,自动获取 baseAdminId 并且发送请求。模拟点击事件。
}
},
});
};
//查询按钮
search = () => {
this.state.data.loading = true;
const parmasA = this.props.form.getFieldsValue();
let parmas = {};
if (parmasA.Akey === 'userNum' && parmasA.Avalue !== undefined && parmasA.Avalue !== '') {
parmas.userNum = parmasA.Avalue;
}
if (parmasA.Akey === 'userName' && parmasA.Avalue !== undefined) {
parmas.userName = parmasA.Avalue;
}
if (parmasA.Akey === 'userMobile' && parmasA.Avalue !== undefined) {
parmas.userMobile = parmasA.Avalue;
}
parmas.userStatus = parmasA.userStatus;
this.start(parmas);
};
//重置按钮
resetFields = () => {
this.props.form.resetFields();
this.start();
};
//储存当前点击任务的wmsTaskId 到 state
// 传入下表格的数据 //唯一区分的是 baseAdminId (pdaId)
onRowClick(record) {
this.state.dataSourcePMTabA.loading = true;
this.state.baseAdminId = record.baseAdminId;
this.setState({ Highlight: record.baseAdminId });
let parmas = {}; //0待审核 1未分配 2抢单中 3未确定 4进行中 5任务完成状态 6任务异常 7已关闭任务
if (this.state.TabsPage === '1') {
parmas.taskStatus = 3;
}
if (this.state.TabsPage === '2') {
parmas.taskStatus = 4;
}
if (this.state.TabsPage === '3') {
parmas.isWarning = 1;
}
if (this.state.TabsPage === '4') {
parmas.taskStatus = 5;
}
this.taskManageByPda(parmas);
}
//判断当前行 是否时点击的行
setRowClassName = (record, index) => {
return record.baseAdminId === this.state.Highlight ? `${styles.Highlight}` : '';
};
//////////////////////////////////////////////////////////////
//获取下表格数据
taskManageByPda = parmas => {
const { dispatch } = this.props;
let payload = {
pdaId: this.state.baseAdminId,
};
if (parmas !== undefined) {
payload.pageSize = parmas.pageSize;
payload.pageNum = parmas.pageNum;
payload.taskStatus = parmas.taskStatus;
payload.isWarning = parmas.isWarning;
}
dispatch({
type: 'orderA/taskManageByPda',
payload: payload,
callback: res => {
if (res.code === 1000) {
res.rst.list.map((item, index) => {
item.key = index;
});
res.rst.loading = false;
this.setState({ dataSourcePMTabA: res.rst });
}
},
});
};
//下tab页切换的函数
bottomChange = e => {
this.state.dataSourcePMTabA.loading = true;
this.state.TabsPage = e;
let parmas = {}; //0待审核 1未分配 2抢单中 3未确定 4进行中 5任务完成状态 6任务异常 7已关闭任务
if (this.state.TabsPage === '1') {
parmas.taskStatus = 3;
this.taskManageByPda(parmas);
}
if (this.state.TabsPage === '2') {
parmas.taskStatus = 4;
this.taskManageByPda(parmas);
}
if (this.state.TabsPage === '3') {
parmas.isWarning = 1;
this.taskManageByPda(parmas);
}
if (this.state.TabsPage === '4') {
parmas.taskStatus = 5;
this.taskManageByPda(parmas);
}
};
//发送短信提醒
sendMsgForRemind(record) {
let startTime = new Date(record.sendLastTime); // 开始时间
let endTime = new Date(); // 结束时间
let usedTime = endTime - startTime; // 相差的毫秒数
let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
let num = 2 - record.sendCount;
if (num <= 2) {
const { dispatch } = this.props;
let payload = {};
payload.pdaId = record.pdaId; // 1 pda主键ID
payload.taskCode = record.taskCode; // 2 任务编码
payload.taskType = record.taskType; // 3 任务类型
dispatch({
type: 'orderA/sendMsgForRemind',
payload: payload,
callback: res => {
if (res.code === 1000) {
message.success(`提醒成功,短信已成功发送!剩余 ${num} 次提醒!`);
} else {
message.warning(`提醒失败,${60 - minutes}分钟后才能再次提醒!`);
}
},
});
} else {
message.warning('本次任务的提醒次数已用完!');
}
}
render() {
//表格头部信息
const columnsPMTabA = [
{
title: '序号',
dataIndex: '1',
key: '1',
width: 50,
render: (text, record, index) => {
return index + 1;
},
},
{
title: '操作',
dataIndex: '2',
width: 120,
key: '2',
render: (text, record) => {
if (record.taskStatus === 3) {
return (
<Fragment>
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
<span
style={{ color: 'green', cursor: 'pointer', marginLeft: '10px' }}
onClick={this.sendMsgForRemind.bind(this, record)}
>
提醒
</span>
</Fragment>
);
} else {
return (
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
);
}
},
},
{ title: '任务编号', dataIndex: 'taskCode', width: 170, key: 'taskCode' },
{
title: '任务类型',
dataIndex: 'taskType',
width: 120,
key: 'taskType',
render: text => {
if (text === 0) {
return '销售发货';
}
if (text === 1) {
return '生产领料';
}
if (text === 2) {
return '生产补料';
}
if (text === 3) {
return '采购退货';
}
if (text === 4) {
return '其他领料';
}
if (text === 6) {
return '采购收货';
}
if (text === 7) {
return '生产收货';
}
if (text === 8) {
return '销售退货';
}
if (text === 9) {
return '生产退料';
}
},
},
{
title: '任务预警',
dataIndex: 'isWarning',
width: 120,
key: 'isWarning',
render: text => {
if (text === 0) {
return <span style={{ color: 'green' }}>正常</span>;
}
if (text === 1) {
return <span style={{ color: 'red' }}>超时</span>;
}
},
},
{ title: '任务创建时间', dataIndex: 'taskCreatedTime', width: 180, key: 'taskCreatedTime' },
{ title: '计划执行时间', dataIndex: 'taskPlanTime', width: 180, key: 'taskPlanTime' },
{ title: '备注', dataIndex: 'remarks', key: 'remarks' },
];
const columnsPMTabB = [
{
title: '序号',
dataIndex: '1',
key: '1',
width: 50,
render: (text, record, index) => {
return index + 1;
},
},
{
title: '操作',
dataIndex: '2',
width: 80,
key: '2',
render: (text, record) => {
return (
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
);
},
},
{ title: '任务编号', dataIndex: 'taskCode', width: 170, key: 'taskCode' },
{
title: '任务类型',
dataIndex: 'taskType',
width: 120,
key: 'taskType',
render: text => {
if (text === 0) {
return '销售发货';
}
if (text === 1) {
return '生产领料';
}
if (text === 2) {
return '生产补料';
}
if (text === 3) {
return '采购退货';
}
if (text === 4) {
return '其他领料';
}
if (text === 6) {
return '采购收货';
}
if (text === 7) {
return '生产收货';
}
if (text === 8) {
return '销售退货';
}
if (text === 9) {
return '生产退料';
}
},
},
{
title: '任务预警',
dataIndex: 'isWarning',
width: 120,
key: 'isWarning',
render: text => {
if (text === 0) {
return <span style={{ color: 'green' }}>正常</span>;
}
if (text === 1) {
return <span style={{ color: 'red' }}>超时</span>;
}
},
},
{ title: '任务创建时间', dataIndex: 'taskCreatedTime', width: 180, key: 'taskCreatedTime' },
{ title: '计划执行时间', dataIndex: 'taskPlanTime', width: 180, key: 'taskPlanTime' },
{ title: '备注', dataIndex: 'remarks', key: 'remarks' },
];
const columnsPMTabC = [
{
title: '序号',
dataIndex: '1',
key: '1',
width: 50,
render: (text, record, index) => {
return index + 1;
},
},
{
title: '操作',
dataIndex: '2',
width: 80,
key: '2',
render: (text, record) => {
if (record.taskStatus === 3) {
return (
<Fragment>
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
<span
style={{ color: 'green', cursor: 'pointer', marginLeft: '10px' }}
onClick={this.sendMsgForRemind.bind(this, record)}
>
提醒
</span>
</Fragment>
);
} else {
return (
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
);
}
},
},
{ title: '任务编号', dataIndex: 'taskCode', width: 170, key: 'taskCode' },
{
title: '任务类型',
dataIndex: 'taskStatus',
width: 120,
key: 'taskStatus',
render: text => {
if (text === 0) {
return '待审核';
}
if (text === 1) {
return '未分配';
}
if (text === 2) {
return '抢单中';
}
if (text === 3) {
return '未确定';
}
if (text === 4) {
return '进行中';
}
if (text === 5) {
return '任务完成状态';
}
if (text === 6) {
return '任务异常';
}
if (text === 7) {
return '已关闭任务';
}
},
},
{
title: '任务预警',
dataIndex: 'isWarning',
width: 120,
key: 'isWarning',
render: text => {
if (text === 0) {
return <span style={{ color: 'green' }}>正常</span>;
}
if (text === 1) {
return <span style={{ color: 'red' }}>超时</span>;
}
},
},
{ title: '任务创建时间', dataIndex: 'taskCreatedTime', width: 180, key: 'taskCreatedTime' },
{ title: '计划执行时间', dataIndex: 'taskPlanTime', width: 180, key: 'taskPlanTime' },
{ title: '备注', dataIndex: 'remarks', key: 'remarks' },
];
const columnsPMTabD = [
{
title: '序号',
dataIndex: '1',
key: '1',
width: 50,
render: (text, record, index) => {
return index + 1;
},
},
{
title: '操作',
dataIndex: '2',
width: 80,
key: '2',
render: (text, record) => {
return (
<span
style={{ color: '#0066cc', cursor: 'pointer' }}
onClick={() => {
if (record.taskType <= 4) {
router.push({
pathname: '/ShippingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} // 小于4 是发货
if (record.taskType >= 6) {
router.push({
pathname: '/ReceivingGoods/TaskQuery',
state: { taskCode: record.taskCode },
});
} //大于6 是收货
}}
>
详情
</span>
);
},
},
{ title: '任务编号', dataIndex: 'taskCode', width: 170, key: 'taskCode' },
{ title: '创建时间', dataIndex: 'taskCreatedTime', width: 180, key: 'taskCreatedTime' },
{
title: '任务预警',
dataIndex: 'isWarning',
width: 120,
key: 'isWarning',
render: text => {
if (text === 0) {
return <span style={{ color: 'green' }}>正常</span>;
}
if (text === 1) {
return <span style={{ color: 'red' }}>超时</span>;
}
},
},
{ title: '计划执行时间', dataIndex: 'taskPlanTime', width: 180, key: 'taskPlanTime' },
{ title: '结束时间', dataIndex: 'taskEndTime', width: 180, key: 'taskEndTime' },
{ title: '备注', dataIndex: 'remarks', key: 'remarks' },
];
//上表格头部信息
const columns = [
{
title: '序号',
dataIndex: '1',
key: '1',
width: 50,
render: (text, record, index) => {
return index + 1;
},
},
{ title: '账号', dataIndex: 'baseAdminName', width: 150, key: 'baseAdminName' },
{ title: '姓名', dataIndex: 'baseAdminRealName', width: 150, key: 'baseAdminRealName' },
{ title: '手机号', dataIndex: 'baseAdminMobile', width: 120, key: 'baseAdminMobile' },
{ title: '待确认', dataIndex: 'waitSureNum', width: 100, key: 'waitSureNum' },
{ title: '进行中', dataIndex: 'conductNum', width: 120, key: 'conductNum' },
{ title: '任务预警', dataIndex: 'overTimeNum', width: 120, key: 'overTimeNum' },
{ title: '待完成总数', dataIndex: 'waitCompleteNum', width: 120, key: 'waitCompleteNum' },
{ title: '已完成数', dataIndex: 'completeNum', width: 120, key: 'completeNum' },
{ title: '终止任务', dataIndex: 'stopNum', width: 120, key: 'stopNum' },
{ title: '最后登录时间', dataIndex: 'baseAdminLastLoginTime', key: 'baseAdminLastLoginTime' },
];
const { getFieldDecorator } = this.props.form;
const Aafter = getFieldDecorator('Akey', { initialValue: 'userNum' })(
<Select style={{ width: '90px' }}>
<Option value="userNum">账号</Option>
<Option value="userName">姓名</Option>
<Option value="userMobile">手机号</Option>
</Select>
);
return (
<PageHeaderWrapper style={{ height: '30px', overflow: 'hidden' }}>
{/* 搜索框 */}
<Row
style={{
height: '45px',
borderBottom: '1px solid rgb(242,242,242)',
boxSizing: 'border-box',
background: '#fff',
}}
>
<Form>
{/* 账号 姓名 手机号 */}
<Col span={5} style={{ margin: '0 10px 0 20px' }}>
<Form.Item>
{getFieldDecorator('Avalue')(
<Input addonBefore={Aafter} size="small" placeholder={'请输入...'} />
)}
</Form.Item>
</Col>
{/* 按钮 */}
<Col span={3} offset={1} style={{ marginTop: '9px' }}>
<Button
type="primary"
size="small"
style={{ marginRight: '10px' }}
onClick={this.search}
>
查询
</Button>
<Button type="primary" onClick={this.resetFields} size="small">
重置
</Button>
</Col>
</Form>
</Row>
{/* 上表格和分页器 */}
<Row
style={{ height: 'auto', boxSizing: 'border-box', background: '#fff' }}
className={styles.TabsTable1}
style={{ marginTop: '0px' }}
>
{/* 表格 */}
<Table
columns={columns}
dataSource={this.state.data.list}
size="middle"
bordered={true}
pagination={false}
scroll={{ x: '110%', y: 350 }}
loading={this.state.data.loading}
//点击行高亮显示
onRow={record => {
return { onClick: this.onRowClick.bind(this, record) };
}}
rowClassName={this.setRowClassName}
/>
{/* 分页器 */}
<Pagination
size="small"
showSizeChanger
showQuickJumper
style={{ marginTop: '10px' }}
current={this.state.data.current}
pageSize={this.state.data.pageSize}
total={this.state.data.total}
showTotal={total => `共${total}条数据`}
onChange={(page, pageSize) => {
this.state.data.loading = true;
let parmas = {};
parmas.pageNum = page;
this.start(parmas);
}}
onShowSizeChange={(current, size) => {
this.state.data.loading = true;
let parmas = {};
parmas.pageSize = size;
this.start(parmas);
}}
/>
</Row>
{/* 下 Tab 标签页 */}
<Tabs
defaultActiveKey="1"
onChange={this.bottomChange}
className={styles.TabsTable}
size="small"
style={{
height: '330px',
boxSizing: 'border-box',
background: '#fff',
marginTop: '5px',
padding: '0 10px',
}}
>
{/* PMTabA 待确认 */}
<TabPane tab="待确认" key="1">
<PMTabA
columnsPMTabA={columnsPMTabA}
dataSourcePMTabA={this.state.dataSourcePMTabA}
baseAdminId={this.state.baseAdminId}
taskManageByPda={this.taskManageByPda} //获取表格所有数据
/>
</TabPane>
<TabPane tab="进行中" key="2">
<PMTabB
columns={columnsPMTabB}
dataSourceB={this.state.dataSourcePMTabA}
baseAdminId={this.state.baseAdminId}
taskManageByPda={this.taskManageByPda} //获取表格所有数据
/>
</TabPane>
<TabPane tab="任务预警" key="3">
<PMTabC
columns={columnsPMTabC}
dataSourceC={this.state.dataSourcePMTabA}
baseAdminId={this.state.baseAdminId}
taskManageByPda={this.taskManageByPda} //获取表格所有数据
/>
</TabPane>
<TabPane tab="已完成" key="4">
<PMTabD
columns={columnsPMTabD}
dataSourceD={this.state.dataSourcePMTabA}
baseAdminId={this.state.baseAdminId}
taskManageByPda={this.taskManageByPda} //获取表格所有数据
/>
</TabPane>
</Tabs>
</PageHeaderWrapper>
);
}
}
const PersonnelManagement = Form.create({ name: 'PersonnelManagementA' })(PersonnelManagementA);
export default PersonnelManagement;
|
import React from 'react';
import {Value} from 'slate';
import {loadQuestion} from './helper';
import { PopUpModel } from '../../helper/popup';
import RichTextEditor from '../rich-text-editor/container';
import { OptionsComponent } from '../question-option/component';
export default class QuestionListComponent extends React.Component{
render (){
let {questions} = this.props;
return (
<div className="container-fluid">
<div className="row">
<div className="col">
<table className="table table-hover">
<thead>
<TestQuestionTableHeader />
</thead>
<tbody>
{questions.map((question,index)=>{
return (
<TestQuestionTableBodyRow key={index}
question={question} {...this.props}
/>);
})
}
</tbody>
</table>
</div>
</div>
</div>
);
}
};
class TestQuestionTableBodyRow extends React.Component{
state = {
question:'',
choiceName:''
}
componentWillMount =()=>{
}
render (){
let { question } = this.props;
return (question?<tr>
<th><span className="options-toggler"
>{question.id}</span></th>
<td className="text-style">
<RichTextEditor
id={this.props.question.id}
readOnly={true}
value={Value.fromJSON(JSON.parse(this.props.question.desc))}/>
<div className="container text-style">
<div className="row ">
<div className="mr-1 ">
A:
</div>
<RichTextEditor
id={this.props.question.id}
readOnly={true}
value={Value.fromJSON(JSON.parse(this.props.question.optionA))}/>
</div>
<div className="row">
<div className="mr-1">
B:
</div>
<RichTextEditor
id={this.props.question.id}
readOnly={true}
value={Value.fromJSON(JSON.parse(this.props.question.optionB))}/>
</div>
<div className="row">
<div className="mr-1">
C:
</div>
<RichTextEditor
id={this.props.question.id}
readOnly={true}
value={Value.fromJSON(JSON.parse(this.props.question.optionC))}/>
</div>
<div className="row">
<div className="mr-1">
D:
</div>
<RichTextEditor
id={this.props.question.id}
readOnly={true}
value={Value.fromJSON(JSON.parse(this.props.question.optionD))}/>
</div>
<div className="row">
<div className="container">
<div className="row">
<div className="mr-4">Type : {question.typeName?question.typeName:' '} </div>
<div className="mr-4">Subject : {question.subjectName?question.subjectName:' '}</div>
<div className="mr-4">Chapter : {question.subjectName?question.chapterName:' '}</div>
<div className="mr-2">Complexity Level : {question.complexityLevel?question.complexityLevel:' '}</div>
</div>
</div>
</div>
</div>
</td>
<td>
<button className="btn btn-danger"
onClick={()=>this.props.onQuestionRemove(this.props.testId,question.id)}
>Remove</button></td>
</tr>:<tr><td>Loading question...</td></tr>
);
}
};
let TestQuestionTableHeader =()=>{
return (
<tr>
<th>ID</th>
<th>Description</th>
<th>Action</th>
</tr>
);
}; |
import react from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => {
return (
<h2>teste</h2>
)
}
export default Navbar; |
import React from 'react'
window.React = React
// import App from './app'
import App from './app.js'
React.render(<App />, document.getElementById('root'))
|
function addNumbers(num1,num2){
var sum=0;
for(let i=0;i<arguments.length;i++){
sum=sum+arguments[i];
}
return sum;
}
console.log(addNumbers(2,3,4,5)) |
'use strict';
module.exports = {
POSTMAN_SCHEMA: 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json',
META_KEY: 'x-postman-meta',
AUTH_TYPES: ['awsv4', 'digest', 'hawk', 'oauth1'],
METHODS: ['get', 'put', 'post', 'patch', 'delete', 'head', 'options'],
};
|
(function() {
App.module('Example.Form', function (Form, App, Backbone, Marionette, $, _) {
Form.Controller = App.Controllers.Base.extend({
initialize: function(options) {
this.region = options.region;
this.View = Form.View;
this.entity = App.request('entities:profile');
// would be wrapped in a promise, but using fake data
this.entity.fetch();
this.showBaseView();
},
// these two methods are good candidates for scaffolding
getBaseView: function() {
return new this.View({
model: this.entity
});
},
showBaseView: function() {
var view = this.getBaseView();
this.region.show(view);
}
});
});
})(this); |
const AbstractItem = require('./abstractItem')
class Tray extends AbstractItem {
constructor(caption) {
super(caption)
this.tray = []
}
add(item){
this.tray.push(item)
}
makeHTML() {
throw new Error("makeHTML method is not implemented")
}
}
const generateTray = (_makeHTML) => {
if (typeof _makeHTML !== 'function') throw new Error("_makeHTML must be function")
Tray.prototype.makeHTML = _makeHTML
return Tray
}
module.exports = generateTray
|
var EventUtil = {
addHandler:function(element,type,handler){
if(element.addEventListener){
element.addEventListener(element,handler,false);
}else if (element.attachEvent){
element.attachEvent("on"+type,handler);
}else{
element["on"+type] = handler;
}
},
removeHandler:function(element,type,handler){
if (element.removeEventListener) {
element.removeEventListener(element,handler,false);
}else if (element.detachEvent) {
element.detachEvent("on"+type,handler);
}else{
element["on"+type] = null;
}
}
}
EventUtil.addHandler(window,"load",function(event){
var div = document.getElementById("myDiv");
EventUtil.addHandler(div,"contextmenu",function(event){
event = EventUtil.getEvent(event);
EventUtil.preventDefault(event);
var menu = document.getElementById("myMenu");
menu.style.left = event.clientX+"px";
menu.style.top = event.clientY+"px";
menu.style.visibility = "visible";
});
EventUtil.addHandler(document,"click",function(event){
document.getElementById("myMenu").style.visibility = "hidden";
})
});
|
import React from 'react';
//import './BasicDetail.scss';
import { Row, Col } from 'react-bootstrap';
import Header from '../components/Header/customHeader';
import { TextField } from 'formik-material-ui';
import InputLabel from '@material-ui/core/InputLabel';
import NativeSelect from '@material-ui/core/NativeSelect';
import FormControl from '@material-ui/core/FormControl';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Paper from '@material-ui/core/Paper';
import BasicNavigator from '../components/BottomNavigator';
import { Typography } from '@material-ui/core';
import Box from '../components/Box';
import * as Yup from 'yup';
import { Formik, Form, Field } from 'formik';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import { connect } from 'react-redux';
import moment from 'moment';
import * as actions from '../../redux/actions/index';
import SubscribedItem from '../components/ViewSubscriptionComponent';
import CircularProgress from '@material-ui/core/CircularProgress';
import DialogTitle from '@material-ui/core/DialogTitle';
import Zoom from '@material-ui/core/Zoom';
import Grow from '@material-ui/core/Grow';
import './CreateSubscriptionPlan.scss';
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
root: {
padding: theme.spacing(3, 2),
width: '100%'
},
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
textField: {
// marginLeft: theme.spacing(1),
// marginRight: theme.spacing(1),
// width: 200,
},
button: {
width: 224,
textTransform: 'none',
fontWeight: 'normal'
}
}));
// const subscriptionPlans = [
// {
// segment: 'Cash',
// duration: 90,
// type: 'Intraday',
// scrip: 'EQUITY',
// amount: 2000
// },
// {
// segment: 'Options',
// duration: 180,
// type: 'Positional',
// scrip: 'NIFTY',
// amount: 1000
// },
// {
// segment: 'Futures',
// duration: 360,
// type: 'Intraday',
// //scrip:'EQUITY',
// amount: 2000
// },
// {
// segment: 'Investment',
// duration: 180,
// type: 'Positional',
// //scrip:'NIFTY',
// amount: 1000
// }
// ];
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
const CreateSubscriptionPlan = props => {
React.useEffect(() => {
if (props.signinData) {
props.getSubscriptionPlanList();
}
}, []);
const classes = useStyles();
let { message } = props;
const [openDialog, setOpenDialog] = React.useState(false);
// const [virtualCapitalError, setVirtualCapitalError] = React.useState(false);
const [someValueChanged, setSomeValueChanged] = React.useState(false);
const updateValueChanged = () => {
setSomeValueChanged(true);
};
const [open, setOpen] = React.useState(false);
const handleClose = () => {
setOpen(false);
};
React.useEffect(() => {
console.log('useEffect+_+_+_+_+_+_+_+_+_+_+_+_+_+_');
if (message !== null) {
setOpenDialog(true);
}
}, [message]);
const { isErrorSubscriptionPlan, resetErrorCreateSubscription, errorSubscription } = props;
// const [loader,setLoader] = React.useState(false)
// // React.useEffect(() => {
// // setSomeValueChanged(false);
// // setLoader(false);
// // });
const [shouldDisable, setShouldDisable] = React.useState(true);
const [subscriptionObject, setSubscriptionObject] = React.useState({
tradingType: null,
tradingDuration: null,
tradingTime: null,
tradingScrip: null,
subSegment: null
});
const checkError = () => {
if (subscriptionObject.tradingType && subscriptionObject.tradingDuration && subscriptionObject.tradingTime) {
if (subscriptionObject.tradingType === 'Options' || subscriptionObject.tradingType === 'Future') {
if (subscriptionObject.tradingScrip) {
setShouldDisable(false);
} else {
setShouldDisable(true);
}
} else {
setShouldDisable(false);
}
console.log(subscriptionObject.tradingType);
} else {
setShouldDisable(true);
}
// if(tradingDuration.filter(t => t.isSelected === true)>0){
// setShouldDisable(true)
// }
// if(tradingTime.filter(t => t.isSelected === true)>0){
// setShouldDisable(true)
// }
// if(tradingType.filter(t => t.isSelected===true))
};
React.useEffect(() => {
checkError();
}, [subscriptionObject]);
const defaultType = [
{ text: 'Intraday', isSelected: false, value: 'INTRADAY' },
{ text: 'Positional', isSelected: false, value: 'DELIVERY' }
];
const defaultTypeForInvestment = [{ text: 'Positional', isSelected: false, value: 'DELIVERY' }];
const defaultTime = [
{ text: '1 Day', isSelected: false, value: 1 },
{ text: '1 Week', isSelected: false, value: 7 },
{ text: '1 Month', isSelected: false, value: 30 },
{ text: '3 Months', isSelected: false, value: 90 }
];
const defaultTimeForInvestment = [
{ text: '1 Month', isSelected: false, value: 30 },
{ text: '3 Months', isSelected: false, value: 90 },
{ text: '6 Months', isSelected: false, value: 180 },
{ text: '12 Months', isSelected: false, value: 360 }
];
const [tradingType, setTradingType] = React.useState([
{ id: 0, text: 'Cash', isSelected: false, value: 'EQUITY' },
{ id: 1, text: 'Options', isSelected: false, value: 'OPTIONS' },
{ id: 2, text: 'Future', isSelected: false, value: 'FUTURES' },
{ id: 3, text: 'Investment', isSelected: false, value: 'INVESTMENT' }
]);
const [tradingDuration, setTradingDuration] = React.useState([
{ text: '1 Day', isSelected: false, value: 1 },
{ text: '1 Week', isSelected: false, value: 7 },
{ text: '1 Month', isSelected: false, value: 30 },
{ text: '3 Months', isSelected: false, value: 90 },
{ text: '6 Months', isSelected: false, value: 180 },
{ text: '12 Months', isSelected: false, value: 365 }
]);
const [tradingTime, setTradingTime] = React.useState([
{ text: 'Intraday', isSelected: false, value: 'INTRADAY' },
{ text: 'Positional', isSelected: false, value: 'DELIVERY' }
]);
const [tradingScrip, setTradingScrip] = React.useState([
{ text: 'NIFTY', isSelected: false, value: 'NF' },
{ text: 'BANK NIFTY', isSelected: false, value: 'BNF' },
// { text: 'EQUITY', isSelected: false, value: 'EQ' }
{ text: 'ALL SCRIPS', isSelected: false, value: 'ALL' }
]);
const handleChangeTradingType = text => {
console.log('text', text);
let newArr = tradingType;
newArr = newArr.map(item => {
if (item.text === text) {
setSubscriptionObject({
...subscriptionObject,
tradingType: item.value,
tradingScrip: text === 'Investment' || text === 'Cash' ? null : subscriptionObject.tradingScrip
});
console.log(item.value);
return { ...item, isSelected: true };
} else {
return { ...item, isSelected: false };
}
});
setTradingType(newArr);
if (text === 'Investment') {
setTradingTime(defaultTypeForInvestment);
setTradingDuration(defaultTimeForInvestment);
setSubscriptionObject(draft => ({ ...draft, tradingTime: null, tradingDuration: null }));
} else {
setTradingTime(defaultType);
setTradingDuration(defaultTime);
setSubscriptionObject(draft => ({ ...draft, tradingTime: null, tradingDuration: null }));
}
};
const handleChangeTradingDuration = text => {
let newArr = tradingDuration;
newArr = newArr.map(item => {
if (item.text === text) {
setSubscriptionObject({ ...subscriptionObject, tradingDuration: item.value });
return { ...item, isSelected: true };
} else {
return { ...item, isSelected: false };
}
});
setTradingDuration(newArr);
};
const handleChangeTradingTime = text => {
let newArr = tradingTime;
console.log(newArr);
newArr = newArr.map(item => {
console.log(item);
if (item.text === text) {
console.log(item);
setSubscriptionObject({ ...subscriptionObject, tradingTime: item.value });
return { ...item, isSelected: true };
} else {
return { ...item, isSelected: false };
}
});
console.log(newArr);
setTradingTime(newArr);
};
const handleChangeTradingScrip = text => {
let newArr = tradingScrip;
newArr = newArr.map(item => {
if (item.text === text) {
setSubscriptionObject({ ...subscriptionObject, tradingScrip: item.value });
return { ...item, isSelected: true };
} else {
return { ...item, isSelected: false };
}
});
setTradingScrip(newArr);
};
let selectedType = tradingType.filter(x => x.id === 1 || x.id === 2);
selectedType = selectedType.filter(x => x.isSelected === true);
console.log('selectedType...', subscriptionObject);
// console.log('here!!!!!!!!!!!!!')
// const [state, setState] = React.useState({ education: '', tradingExperience: '', certification: '' })
// const handleChange = (e, variable) => {
// console.log(e, variable)
// }
// console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@', props, subscriptionObject);
return (
<>
<Zoom in={true} timeout={500}>
<div>
<Header
someValueChanged={someValueChanged}
title={`Analyst Create Subscription Plan`}
backButton
backTo={() => props.history.push('/')}
/>
<Dialog
onClose={handleClose}
aria-labelledby='simple-dialog-title'
open={open}
fullWidth={true}
TransitionComponent={Grow}
transitionDuration={500}
>
<DialogContent>
<div className='p-3'>
<div className='text-center' style={{ fontSize: '1rem', fontWeight: '600', color: '#2962ff' }}>
Your Subscription Plans
</div>
{props.subscriptionPlan && props.subscriptionPlan.map(data => <SubscribedItem data={data} />)}
</div>
</DialogContent>
<DialogContent>
{!props.subscriptionPlan ||
(props.subscriptionPlan && props.subscriptionPlan.length === 0 && (
<p className='text-secondary'>No Subscription Plan Found</p>
))}
</DialogContent>
<DialogActions>
<Button
onClick={() => {
setOpen(false);
// props.history.push('/analyst-profile');
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
{/* <DialogActions style={{ display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleClose} color="primary">
Okay
</Button>
</DialogActions> */}
</Dialog>
<div style={{ padding: '10px', marginTop: '20px' }}>
{/* <Typography variant="caption" style={{ color: 'gray' }} align="left">
Pricing
</Typography> */}
<Formik
initialValues={{
pricing: ''
// ,
// password: '',
// select: 'none',
// tags: [],
// rememberMe: true,
}}
validate={values => {
const errors = {};
if (someValueChanged === false) {
updateValueChanged();
}
if (tradingType.filter(f => f.isSelected === true) > 0) {
errors.segment = 'Select a value first!';
}
if (!values.pricing) {
errors.pricing = 'Please enter a price value';
} else if (!/^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/i.test(values.pricing)) {
errors.pricing = 'Please enter numbers only';
}
return errors;
}}
handleChanged={(e, values) => {
console.log(e.target);
values.pricing = e.target.value;
}}
onSubmit={(values, { setSubmitting }) => {
setSubmitting(false);
// if (
// props.analystDetails &&
// props.analystDetails.capital_required &&
// props.analystDetails.capital_required > 0 &&
// props.analystDetails.segment_list &&
// props.analystDetails.segment_list.length > 0
// ) {
let subscriptionObj = {
pricing: parseInt(values.pricing),
tradingType: subscriptionObject.tradingType,
tradingDuration: tradingDuration.filter(t => t.isSelected === true)[0]
? tradingDuration.filter(t => t.isSelected === true)[0].value
: null,
tradingTime: tradingTime.filter(t => t.isSelected === true)[0]
? tradingTime.filter(t => t.isSelected === true)[0].text
: null,
tradingScrip: tradingScrip.filter(t => t.isSelected === true)[0]
? tradingScrip.filter(t => t.isSelected === true)[0].text
: null,
subSegment: tradingType.filter(t => t.isSelected === true)[0]
? tradingType.filter(t => t.isSelected === true)[0].text.toUpperCase()
: null
};
let date = new Date();
props.createSubscriptionPlan({
segment_name: subscriptionObj.tradingType,
amount: subscriptionObj.pricing,
days: subscriptionObj.tradingDuration.toString(),
from_date: moment(date).format('DD/MM/YYYY'),
//"end_date":'10/12/2020'
end_date: moment(date.addDays(subscriptionObj.tradingDuration)).format('DD/MM/YYYY'),
trade_type: subscriptionObj.tradingTime,
script: subscriptionObject.tradingScrip,
sub_segment_name: subscriptionObj.subSegment
});
// } else {
// setVirtualCapitalError(true);
// }
// setLoader(true)
// let date = new Date()
// console.log('end_date: ',date.addDays(subscriptionObj.tradingDuration*30))
// console.log(`duration: `,subscriptionObj.tradingDuration)
// console.log(`tradingType: `,tradingType.filter(t => t.isSelected===true)[0].text)
// console.log(`tradingDuration: `,tradingDuration.filter(t => t.isSelected===true)[0].text)
// console.log(`values: ${JSON.stringify(values, null, 2).pricing}`)
// console.log(`values: ${JSON.stringify(values, null, 2)}`)
// setTimeout(() => {
// console.log(`Data to send to API: ${subscriptionObj}`)
// console.log(`Data to send to API: ${subscriptionObj.pricing}`)
// console.log(`Data to send to API: ${subscriptionObj.tradingType}`)
// console.log(`Data to send to API: ${subscriptionObj.tradingDuration}`)
// console.log(`Data to send to API: ${subscriptionObj.tradingTime}`)
// console.log(`Data to send to API: ${subscriptionObj.tradingScrip}`)
// }, 500);
}}
render={({ submitForm, isSubmitting, values, errors, setFieldValue, handleChanged }) => (
<Form>
<Typography variant='caption' style={{ color: 'gray' }} align='left'>
Segment
</Typography>
<Row>
{tradingType.map(t => (
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '5px' }}>
<Box
allowed='true'
isSelected={t.isSelected}
text={t.text}
handleChange={handleChangeTradingType}
/>
</Col>
))}
{subscriptionObject.tradingType ? null : <p className='error-text'>* mandatory</p>}
{/* <Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={true} text={`Cash`}/>
</Col>
<Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={false} text={`Options`}/>
</Col>
<Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={false} text={`Future`}/>
</Col>
<Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={false} text={`Investment`}/>
</Col> */}
</Row>
<Typography variant='caption' style={{ color: 'gray' }} align='left'>
Subscription Period
</Typography>
<Row>
{tradingDuration.map(t => (
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '5px' }}>
<Box
allowed='true'
isSelected={t.isSelected}
text={t.text}
handleChange={handleChangeTradingDuration}
/>
</Col>
))}
{subscriptionObject.tradingDuration ? null : <p className='error-text'>* mandatory</p>}
</Row>
<Typography variant='caption' style={{ color: 'gray' }} align='left'>
Trade Type
</Typography>
<Row>
{tradingTime.map(t => (
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '5px' }}>
<Box
allowed='true'
isSelected={t.isSelected}
text={t.text}
handleChange={handleChangeTradingTime}
/>
</Col>
))}
{subscriptionObject.tradingTime ? null : (
<Col lg={12} md={12} sm={12} xs={12}>
<p className='error-text'>* mandatory</p>
</Col>
)}
{/* <Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={true} text={`Intraday`}/>
</Col>
<Col lg={6} md={6} sm={6} xs={6} style={{padding:'5px'}}>
<Box allowed="true" isSelected={false} text={`Positional`}/>
</Col> */}
</Row>
{selectedType && selectedType.length > 0 ? (
<div>
<Typography variant='caption' style={{ color: 'gray' }} align='left'>
Scrip
</Typography>
<Row>
{tradingScrip.map(t => (
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '5px' }}>
<Box
allowed='true'
isSelected={t.isSelected}
text={t.text}
handleChange={handleChangeTradingScrip}
/>
</Col>
))}
</Row>
{subscriptionObject.tradingScrip ? null : <p className='error-text'>* mandatory</p>}
</div>
) : null}
<div style={{ backgroundColor: '#F1F1F1', padding: '20px 20px 1px 20px', marginTop: '20px' }}>
<Field label='Fees' name='pricing' type='number' min='1' component={TextField} />
<p className='input-helper'>In rupees</p>
</div>
<Row style={{ display: 'flex', justifyContent: 'center', padding: '20px 0px' }}>
{/* {console.log('isSubmitting',isSubmitting)} */}
{props.loader ? (
<CircularProgress name='circle' color='primary' />
) : (
<Button
variant='contained'
color='primary'
className={classes.button}
disabled={shouldDisable || (props.subscriptionPlan && props.subscriptionPlan.length >= 8)}
onClick={submitForm}
>
Add Subscription
</Button>
)}
{props.subscriptionPlan && props.subscriptionPlan.length >= 8 && (
<p
style={{
fontSize: '12px',
color: '#f44336',
opacity: '0.8',
marginTop: '1rem',
paddingLeft: '3rem',
paddingRight: '3rem'
}}
>
You can Add maximum 8 subscription plan. Delete plans to add more.
</p>
)}
</Row>
{/* <Row style={{ display: 'flex', justifyContent: 'center', padding: '20px 0px' }}>
<Button
variant="contained"
color="primary"
className={classes.button}
disabled={isSubmitting}
onClick={submitForm}
>
Add Subscription
</Button>
</Row> */}
</Form>
)}
/>
{/* <TextField
//label="IFSC Code"
defaultValue="3500"
className={classes.textField}
margin="normal"
// type="password"
/> */}
<Row style={{ display: 'flex', justifyContent: 'center', padding: '0px 20px', marginBottom: '100px' }}>
<Typography
variant='caption'
style={{ color: '#2962ff', textDecoration: 'underline', cursor: 'pointer' }}
align='center'
onClick={() => setOpen(true)}
>
View my subscriptions
</Typography>
</Row>
</div>
<Dialog
open={openDialog}
onClose={() => setOpenDialog(false)}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>{props.message}</DialogTitle>
<DialogActions>
<Button
onClick={() => {
props.setMessage(null);
setSomeValueChanged(false);
setOpenDialog(false);
setOpen(true);
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
</Dialog>
{/* <Dialog
open={virtualCapitalError}
onClose={() => setVirtualCapitalError(false)}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>Kindly Allocate your trade first!</DialogTitle>
<DialogActions>
<Button
onClick={() => {
setVirtualCapitalError(false);
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
</Dialog> */}
</div>
</Zoom>
<BasicNavigator />
</>
);
};
const mapStateToProps = state => ({
signinData: state.auth.signinData,
errorSubscription: state.auth.errorSubscription,
isErrorSubscriptionPlan: state.auth.isErrorSubscriptionPlan,
loader: state.auth.loader,
subscriptionPlan: state.analyst.subscriptionPlan,
message: state.auth.message,
analystDetails: state.analyst.analystDetails
});
const mapDispatchToProps = dispatch => ({
createSubscriptionPlan: params => dispatch(actions.createSubscriptionPlan(params)),
// resetErrorCreateSubscription: message => dispatch(actions.resetErrorCreateSubscription(message)),
setMessage: message => dispatch(actions.setMessage(message)),
getSubscriptionPlanList: token => dispatch(actions.getSubscriptionPlanList(token))
});
export default connect(mapStateToProps, mapDispatchToProps)(CreateSubscriptionPlan);
|
import RestfulDomainModel from '../base/RestfulDomainModel'
class Model extends RestfulDomainModel {
async pageNoAuth(pageNo, pageSize, filter, sort) {
return await this.post(`${this.baseUrl}/pageNoAuth`, { pageNo, pageSize, filter, sort })
}
}
export default new Model([
{ id: { name: 'ID', dataOnly: true }},
{ name: { name: '品牌名称' }},
{ tenantId: { name: '租户', dataOnly: true }},
{ description: { name: '品牌描述' }},
{ logo: { name: 'LOGO', dataOnly: true }},
{ url: { name: '品牌链接' }},
{ deleted: { name: '是否删除', dataOnly: true }},
{ ctime: { name: '创建时间' }},
{ mtime: { name: '更新时间', dataOnly: true }}
], '/ecommerse/brand')
|
import React from 'react';
import styled from 'styled-components'
import Searcher from '../searcher'
import backgroundImage from '../../images/hero-background.svg'
const HeroStyled = styled.div`
.Container__Hero {
max-width: 100%;
height: 100vh;
background: url(${backgroundImage});
background-repeat: no-repeat;
background-size: cover;
background-position: center;
margin-bottom: 1em;
}
.Hero {
text-align: center;
padding: var(--padding__container);
}
.Container__Hero {
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.Container__Hero .Hero__texts {
margin: auto auto;
}
.Container__Hero .Hero__texts h1 {
font-size: 2.5em;
color: #fff;
font-weight: bold;
margin-bottom: 0.3em;
}
.Container__Hero .Hero__texts p {
font-size: var(--font-size-paragrah);
margin-bottom: 1em;
color: var(--colorBlue);
}
`
function Hero () {
return (
<HeroStyled>
<section className="Container__Hero">
<div className="Hero">
<div className="Hero__texts">
<h1>Busca Apps y recursos educativos</h1>
<p>La mejor plataforma de recursos educativos online</p>
</div>
<Searcher/>
</div>
</section>
</HeroStyled>
)
}
export default Hero |
'use strict';
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let UsersRepository = require('../api/repositories/UsersRepository');
let EntityNotFoundError = require('../api/errors/EntityNotFoundError');
let bcrypt = require('bcrypt');
let AuthError = require('../api/errors/AuthError');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
UsersRepository
.findOne({id: id})
.then(userFound => done(null, userFound))
.catch(err => done(err));
});
passport.use(new LocalStrategy(
function(email, password, done) {
UsersRepository
.findOne({email: email})
.then(userFound => {
if (userFound.isCorrectPassword(password)) {
done(null, userFound);
} else {
done(new AuthError('La contraseña es incorrecta'));
}
})
.catch(EntityNotFoundError, done);
}
)); |
import { homeTemplate } from "./homeTemplate.js";
let _router = undefined;
let _renderer = undefined;
function initialize(router, renderer) {
_router = router;
_renderer = renderer;
}
async function getView() {
let templateResult = homeTemplate();
_renderer(templateResult);
}
export default {
initialize,
getView
} |
import React, { Component } from 'react'
import FlipkartLogo from './FlipkartLogo'
import { Link } from 'react-router-dom'
import { increment, decrement, userLogin, cartItems, addToCartApi, getCartItems } from '../action/getUser'
import { connect } from 'react-redux'
import OrderCartFooter from './OrderCartFooter'
import CartPage from './CartPage'
import CartItemsComp from './CartItemsComp'
import PriceDetailPage from './PriceDetailPage'
import LoginSignupComponent from './LoginSignupComponent'
import LogoutComponent from './LogoutComponent'
import SearchComponent from './SearchComponent'
let custId
let dispQty = 1
let product
class ShoppingCart extends Component {
constructor(props) {
super(props)
this.state = {
product: {},
tot_amt: 0,
status: false,
isLoggedIn: false
}
this.incrementCount = this.incrementCount.bind(this)
this.decrementCount = this.decrementCount.bind(this)
custId = localStorage.getItem('custId')
if(custId === null){
custId = 0
}else{
custId = custId
}
}
static getDerivedStateFromProps(nextProps){
console.log(nextProps)
return{
product: nextProps.cartProduct
}
}
componentDidMount(){
const token = localStorage.getItem('token')
if(token !== null){
this.props.userLogin(true)
}
this.props.getCartItems({custId: custId})
}
incrementCount = () => {
this.props.addToCartApi({prodId:this.props.location.state.prodId, custId, val: 'incr'})
}
decrementCount = (e) => {
if(dispQty > 0){
this.props.addToCartApi({prodId:this.props.location.state.prodId, custId, val: 'decr'})
}
}
render() {
if(this.props.cartProduct.length > 0 ){
localStorage.setItem('itemsInCart', this.props.cartProduct.length)
}
product = this.props.cartProduct
let rediLink = '/login-before-buy'
return (
product.length > 0 ?
<div id="container">
<div className="_3ybBIU">
<div className="_1tz-RS">
<div className="_1S7OK2"></div>
<div className="_3pNZKl">
<FlipkartLogo />
<SearchComponent />
{
this.props.isLoggedIn ? <LogoutComponent /> : <LoginSignupComponent />
}
</div>
<div className="_1S7OK2"></div>
</div>
<div className="_2hlh_L"></div>
</div>
<div className="t-0M7P _27IFdQ">
<div className="_1VV5Cf _1QHAXj">
<div className="_1SFos- " style={{transform: "scaleX(1)"}}></div>
</div>
<div className="_3e7xtJ">
<div className="_1HmYoV hCUpcT col-12-12">
<div className="_1HmYoV _35HD7C" style={{flexGrow: 1, overflow: "visible"}}>
<div className="_1HmYoV _35HD7C col-12-12" style={{boxShadow: "rgba(0, 0, 0, 0.2) 0px 1px 2px 0px"}}>
<div className="_1HmYoV hCUpcT col-12-12" style={{backgroundColor: "rgb(255, 255, 255)"}}>
<div className="bhgxx2 col-3-12">
<div className="_2EoEbp">
<div className="_1lBhq8">My Cart ({localStorage.getItem('itemsInCart')})</div>
<div></div>
</div>
</div>
<div className="bhgxx2 col-9-12" style={{margin: "5px 10px 0px 0px"}}>
<div className="_2KHWIh _3yhhU7 _1nhGgC" style={{float: "right"}}>
<div className="_29cQtz">
<img alt="" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48ZWxsaXBzZSBjeD0iOSIgY3k9IjE0LjQ3OCIgZmlsbD0iI0ZGRTExQiIgcng9IjkiIHJ5PSIzLjUyMiIvPjxwYXRoIGZpbGw9IiMyODc0RjAiIGQ9Ik04LjYwOSA3LjAxYy0xLjA4IDAtMS45NTctLjgyNi0xLjk1Ny0xLjg0NSAwLS40ODkuMjA2LS45NTguNTczLTEuMzA0YTIuMDIgMi4wMiAwIDAgMSAxLjM4NC0uNTRjMS4wOCAwIDEuOTU2LjgyNSAxLjk1NiAxLjg0NCAwIC40OS0uMjA2Ljk1OS0uNTczIDEuMzA1cy0uODY0LjU0LTEuMzgzLjU0ek0zLjEzIDUuMTY1YzAgMy44NzQgNS40NzkgOC45MjIgNS40NzkgOC45MjJzNS40NzgtNS4wNDggNS40NzgtOC45MjJDMTQuMDg3IDIuMzEzIDExLjYzNCAwIDguNjA5IDAgNS41ODMgMCAzLjEzIDIuMzEzIDMuMTMgNS4xNjV6Ii8+PC9nPjwvc3ZnPg==" className="_3KEg0q" />
<span className="_1nBnpg">Deliver to</span>
</div>
<div className="_2FexNG OmFqo5">
<input type="text" placeholder="Enter delivery pincode"
value="" maxLength="6" className="_20PCkk" readOnly/>
<span className="_2m9c-p _3PnL67">Check</span>
</div>
</div>
</div>
</div>
{
product.length > 0 &&
product.map((prod, i) => {
return <CartItemsComp product={prod} key={i}/>
})
}
<div className="bhgxx2 col-12-12 _3KsTU0">
<div className="_31gTpz _1RLi8m">
<Link to={rediLink}>
<button className="_2AkmmA iwYpF9 _7UHT_c">
<span>Place Order</span>
</button>
</Link>
</div>
</div>
</div>
</div>
{
product.length > 0 ? <PriceDetailPage product={product}/> : ''
}
</div>
<OrderCartFooter />
</div>
</div>
</div> : <CartPage />
)
}
}
const mapStateToProps = state => {
return {
quantity: state.quantity,
isLoggedIn: state.isLoggedIn,
prodId: state.prodId,
cartProduct: state.cartProduct
}
}
const mapDispatchToProps = dispatch => {
return {
increment: (count) => dispatch(increment(count)),
decrement: (count) => dispatch(decrement(count)),
userLogin: (bool) => dispatch(userLogin(bool)),
cartItems: (count) => dispatch(cartItems(count)),
addToCartApi: (prodId, custId, quantity, param) => dispatch(addToCartApi(prodId, custId, quantity, param)),
getCartItems: (id) => dispatch(getCartItems(id))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ShoppingCart)
|
import { Meteor } from 'meteor/meteor';
import {Games} from '/imports/api/links';
Meteor.startup(() => {
Meteor.methods({
buzzer(game_id, side) {
Streamy.broadcast(game_id, {side: side}, []);
return null;
},
toGame(game_id, command){
Streamy.broadcast(game_id + "toGame", {command: command}, []);
return null;
},
toController(game_id, command){
Streamy.broadcast(game_id + "toControl", {command: command}, []);
return null;
},
toTimer(game_id, command){
Streamy.broadcast(game_id+"toTimer", {command: command}, []);
},
async join_questions(game_id) {
const pipeline = [
{$match: {_id: game_id}},
{$unwind: "$regular_questions"},
{
$lookup: {
from: 'questions',
localField: 'regular_questions',
foreignField: '_id',
as: 'question'
}
},
{
$addFields: {
question: {$arrayElemAt: ["$question", 0]},
}
},
{
$group: {
_id: {_id: "$_id", title: "$title", fast_money: "$fast_money_questions"},
questions: {$push: "$question"}
}
},
{$unwind: "$_id.fast_money"},
{
$lookup: {
from: 'questions',
localField: '_id.fast_money',
foreignField: '_id',
as: 'fast_money'
}
},
{
$addFields: {
fast_money: {$arrayElemAt: ["$fast_money", 0]},
}
},
{
$group: {
_id: {_id: "$_id._id", questions: "$questions", title: "$_id.title"},
fast_money: {$push: "$fast_money"}
}
},
{
$project: {
_id: "$_id._id",
title: "$_id.title",
fast_money: 1,
questions: "$_id.questions"
}
}
];
return await Games.rawCollection().aggregate(
pipeline
).toArray(); // get first element
}
});
});
// {$sort: {_id: -1}}
|
(function() {var implementors = {};
implementors['toml'] = ["impl <a class='trait' href='rustc_serialize/serialize/trait.Encodable.html' title='rustc_serialize::serialize::Encodable'>Encodable</a> for <a class='enum' href='toml/enum.Value.html' title='toml::Value'>Value</a>",];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
|
import React from 'react';
const ApplicationContext = React.createContext(null);
export default ApplicationContext; |
/* First, we need to create the XMLHttpRequest object using the new operator.
Save this object in a const called xhr, it is a common practice to name this object xhr.*/
const xhr = new XMLHttpRequest;
/*Next, save the following URL to a const called url.
Make sure the URL is wrapped in quotes so that it is a string.*/
const url = "https://api-to-call.com/endpoint";
/*Set the responseType property of the xhr object to equal 'json'. */
xhr.responseType = 'json';
/*Set the xhr.onreadystatechange event handler equal to an anonymous arrow function.*/
xhr.onreadystatechange = () => {
/*The purpose of this conditional statement checks to see if the request has finished. */
if (xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
/*.open() creates a new request and the arguments passed in determine the type and URL of the request. */
xhr.open('GET', url);
xhr.send();
}
/* AJAX POST request using an XMLHttpRequest object.*/
const xhr = new XMLHttpRequest();
const url = 'https://api-to-call.com/endpoint';
/*JSON.stringify() will convert a value to a JSON string. By converting the value to a string, we can then send the data to a server. */
const data = JSON.stringify({id: '200'});
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE){
return xhr.response;
}
}
xhr.open('POST', url);
xhr.send(data);
|
"use strict";
const
express = require('express'),
request = require('request'),
config = require('config'),
crypto = require('crypto'),
util = require('util');
let router = express.Router();
router.get('/', (req, res, next) => {
console.log(req.params);
res.json(req.params);
});
module.exports = router; |
import Events from '../Events/index'
class Service extends Events {
constructor(settings = {}, options = {}) {
super(...arguments)
this.settings = settings
this.options = options
}
get validSettings() { return [
'url',
'method',
'mode',
'cache',
'credentials',
'headers',
'parameters',
'redirect',
'referrerPolicy',
'body',
'files',
] }
get settings() { return this._settings }
set settings(settings) {
this._settings = settings
this.validSettings.forEach((validSetting) => {
if(settings[validSetting]) this[validSetting] = settings[validSetting]
})
}
get options() {
if(!this._options) this._options = {}
return this._options
}
set options(options) { this._options = options }
get url() {
if(this.parameters) {
return this._url.concat(this.queryString)
} else {
return this._url
}
}
set url(url) { this._url = url }
get queryString() {
let queryString = ''
if(this.parameters) {
let parameterString = Object.entries(this.parameters)
.reduce((parameterStrings, [parameterKey, parameterValue]) => {
let parameterString = parameterKey.concat('=', parameterValue)
parameterStrings.push(parameterString)
return parameterStrings
}, [])
.join('&')
queryString = '?'.concat(parameterString)
}
return queryString
}
get method() { return this._method }
set method(method) { this._method = method }
get mode() { return this._mode }
set mode(mode) { this._mode = mode }
get cache() { return this._cache }
set cache(cache) { this._cache = cache }
get credentials() { return this._credentials }
set credentials(credentials) { this._credentials = credentials }
get headers() { return this._headers }
set headers(headers) { this._headers = headers }
get redirect() { return this._redirect }
set redirect(redirect) { this._redirect = redirect }
get referrerPolicy() { return this._referrerPolicy }
set referrerPolicy(referrerPolicy) { this._referrerPolicy = referrerPolicy }
get body() { return this._body }
set body(body) { this._body = body }
get files() { return this._files }
set files(files) { this._files = files }
get parameters() { return this._parameters || null }
set parameters(parameters) { this._parameters = parameters }
get previousAbortController() {
return this._previousAbortController
}
set previousAbortController(previousAbortController) { this._previousAbortController = previousAbortController }
get abortController() {
if(!this._abortController) {
this.previousAbortController = this._abortController
}
this._abortController = new AbortController()
return this._abortController
}
get response() { return this._response }
set response(response) { this._response = response }
get responseData() { return this._responseData }
set responseData(responseData) { this._responseData = responseData }
abort() {
this.abortController.abort()
return this
}
fetch() {
const fetchOptions = this.validSettings.reduce((_fetchOptions, fetchOptionName) => {
if(this[fetchOptionName]) _fetchOptions[fetchOptionName] = this[fetchOptionName]
return _fetchOptions
}, {})
fetchOptions.signal = this.abortController.signal
if(this.previousAbortController) this.previousAbortController.abort()
return fetch(this.url, fetchOptions)
.then((response) => {
this.response = response
return response.json()
})
.then((data) => {
this.emit(
'ready',
data,
this,
)
return data
})
.catch((error) => {
this.emit(
'error',
{
message: error,
},
this,
)
return error
})
}
async fetchSync() {
const fetchOptions = this.validSettings.reduce((_fetchOptions, fetchOptionName) => {
if(this[fetchOptionName]) _fetchOptions[fetchOptionName] = this[fetchOptionName]
return _fetchOptions
}, {})
fetchOptions.signal = this.abortController.signal
if(this.previousAbortController) this.previousAbortController.abort()
this.response = await fetch(this.url, fetchOptions)
this.responseData = await this.response.json()
if(
this.responseData.code >= 400 &&
this.responseData.code <= 499
) {
this.emit(
'error',
this.responseData,
this,
)
throw this.responseData
} else {
this.emit(
'ready',
this.responseData,
this,
)
}
return this.responseData
}
}
export default Service
|
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert(
"Animals",
[
{
name: "Piper",
type: "dog",
size: "medium",
age: "adult",
gender: "female",
status: "available",
breed: "Brown Australian Kelpie and German Shepherd Dog",
photo: "/images/piper.jpg",
description:
"Hey there! My name is Piper I'm a 2 year old, 57#, Australian Kelpie/Australian Shepherd mix. I am a young, spunky, and playful doggie. I would do best in an active home I am a very smart dog who can shake, sit and lay down. I will be a very loyal dog, who may have some guardy behavior once I know you're my person. I am very affectionate and LOVE to be close to people. Please come spend some time with me!",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Maggie",
type: "dog",
size: "large",
age: "adult",
gender: "female",
status: "available",
breed: "black and tan German Shepherd Dog mix",
description:
"Hi I'm Maggie! I am a 65#, 2 year old spayed female shepherd mix! I was transferred to Colorado with my 3 puppies and man, did we luck out! My babies all found homes so now it's my turn! I am a COMPLETE love! I lean in for cuddles, walk great on a leash, meet new people very easily, and I am just the best. I'd move into your life and heart seamlessly. Come meet me!",
photo: "/images/maggie.jpg",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Hershey",
type: "dog",
size: "medium",
age: "puppy",
gender: "male",
status: "available",
breed: "Rottweiler",
description:
"I am just 8 weeks old and ready for a home of my own. All of my siblings have found home, so it's my turn now. Come meet me!",
photo: "/images/hershey.jpg",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Romeo",
type: "dog",
size: "small",
age: "adult",
gender: "male",
status: "available",
breed: "Chihuahua - Smooth Coated",
description:
"Why hello, I'm Romeo! I'm a 2.5 year old, 8#, neutered, Chihuahua. I was transferred here from a shelter in Kansas to find a family as sweet as I am! I am reported to be good with dogs, cats, and children…and just love affection and attention. I do like to burrow and hide in blankets, under beds, or in a kennel to feel safe so if you can't find me, I'm probably taking a nap. Will you be my new person?",
photo: "/images/romeo.jpg",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Larry",
type: "cat",
size: "medium",
age: "adult",
gender: "male",
status: "available",
breed: "orange and white Domestic Longhair",
description:
"Hi! My name is Larry and I am a super affectionate long haired neutered male cat. I'll need to live with someone who is cat-savvy as I can be a testy one. I looooove affection and to be close, but on my terms. I am energetic and like to be the life of the party. I've made great progress with my other feline friends - I tolerate them now. Please come spend some time with me...I am really a good boy!",
photo: "/images/larry.jpg",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Zara",
type: "cat",
size: "small",
age: "adult",
gender: "female",
status: "available",
breed: "white and gray Domestic Mediumhair",
description:
"Meow! My name is Zara and I am a 7 year old domestic long haired beauty! I am a petite spayed female who loves to be in your lap. I am okay with other friendly cats, but because of a previous attack from a dog, I might be happiest without a stress of being around a dog. Please come spend some time with me! I was just transferred from a shelter in Craig, CO and cannot wait to find myself in a loving home. Maybe yours?",
photo: "/images/zara.jpg",
createdAt: new Date(),
updatedAt: new Date()
},
{
name: "Devon",
type: "cat",
size: "medium",
age: "young",
gender: "male",
status: "available",
breed: "gray tab Domestic Shorthair",
description:
"Hi there. I'm Devon. I am a neutered male kitten who was found as a stray elsewhere in Colorado. I am reserved and it will take me some time to warm up to you. But if you're a patient person, I will surely learn to trust you! And what's better than earning the trust of an insecure kitty?? Not much! Please take me home with you and let me learn to be the playful kitten I deserve to be!",
photo: "/images/devon.jpg",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("Animals", null, {});
}
};
|
import React, { Component } from 'react';
import classnames from 'classnames';
import { connect } from 'react-redux';
import { forgetPass } from '../../store/actions/authActions';
import Spinner from '../common/Spinner';
import { Link } from 'react-router-dom';
class ForgetPass extends Component {
constructor(props) {
super(props);
this.state = {
phone: '',
errors: {},
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.errors) {
return { errors: nextProps.errors};
}
if (nextProps.sendPassStatus) {
nextProps.history.push('/sendPassSuccess');
}
return null;
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.sendPassStatus) {
prevProps.history.push('/sendPassSuccess');
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit = (e) => {
e.preventDefault();
this.props.forgetPass(this.state.phone);
}
render() {
const { errors } = this.state;
const { loading } = this.props.auth;
return (
<div className="landing">
<div className="dark-overlay landing-inner text-light">
<div className="forgotPass">
<div className="container">
<div className="row">
<div className="col-md-5 m-auto" style={{ marginLeft:830}}>
<h2 style={{ marginBottom:30}}>Quên mật khẩu</h2>
<form noValidate onSubmit={this.onSubmit}>
<div className="form-group">
<input
type="text"
style={{width:"100%", borderRadius:25}}
className={classnames('form-control form-control-lg', {
'is-invalid': errors.message2
})}
placeholder="Số điện thoại của bạn"
name="phone"
value={this.state.phone}
onChange={this.onChange}
/>
{errors.message2 && (
<div className="invalid-feedback">{errors.message2}</div>
)}
</div>
{ loading ? <Spinner /> :
<input type="submit" style={{width:"100%", borderRadius:25}} className="btn-lg btn-warning btn-block mt-4" value="Gửi mật khẩu về điện thoại"/>}
<div className="form-group" style={{color:'white',marginTop:20, marginLeft:10}}><Link style={{color:'white', fontSize: 20}} to="/login">Quay lại</Link></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors,
sendPassStatus: state.sendCodeBySMS.messageSendCode.status
});
export default connect(mapStateToProps, { forgetPass })(ForgetPass); |
function audioAddUploadedFile(options) {
var obj = GET_OBJ(G_UPLOAD_OBJID);
if (options.list.length > 0) {
waitbarShow();
$.ajax({
data: {
fn: 'reg_uploaded_files',
session: G_SERVER_SESSION,
user: G_SERVER_USERID,
docid: G_EDITOR_INFO['id'],
list: options.list,
type: OBJECT_TYPE_AUDIO
},
type: 'POST',
url: 'app/media.php',
success: function (response) {
var audioData = $(obj).IObject('getData', OBJECT_TYPE_AUDIO);
waitbarHide();
if (!response.success) {
var msg = MESSAGEERR[response.msg];
if (response.errdata) msg += " (" + response.errdata + ')';
alert(msg);
return;
}
$.each(response.data.list, function (idx, val) {
audioData.list.push({
name: val['name'],
type: val['type']
});
});
$(obj).IObject('setData', OBJECT_TYPE_AUDIO, audioData);
$(obj).trigger(EVT_REDRAW);
$(obj).trigger(EVT_UPDATE);
},
error: function (data, status, err) {
waitbarHide();
alert(MESSAGEERR['SERV0001']);
}
});
}
G_UPLOAD_FILE_CNT = 0;
G_UPLOAD_FILE_MAX = 0;
G_UPLOAD_OBJID = false;
G_UPLOAD_SUCCESS_LIST = false;
G_UPLOAD_TYPE = false;
}
|
export default function normalizeISODateString(dateString) {
return dateString.replace(/\.\d+/, '');
}
|
function myMessage() {
console.log('This is the myMessage Function');
}
function add(x,y) {
var result;
result = x + y;
console.log(result);
}
function add2(x, y) {
var total = x + y;
return total;
}
add2result = add2(10, 36);
function cardFlip(element) {
$(element).hide();
}
var result = add2(add2(5, 10), add2(20, 30)); |
import React from 'react';
import styled from 'styled-components';
const StyledPictures = styled.div`
flex: 1 1 60%;
background-color: #ececec;
`;
const Pictures = () => (
<StyledPictures>pictures</StyledPictures>
);
export default Pictures;
|
class GenericService {
Model = null;
constructor(Model) {
this.Model = Model;
}
find = async (data = {}) => {
var list = await this.Model.find(data).lean();
return list;
};
findOne = async (data) => {
var result = await this.Model.findOne(data).lean();
return result;
};
findById = async (data) => {
var result = await this.Model.findById(data);
return result;
};
findByIdAndUpdate = async (id, data) => {
var result = await this.Model.findByIdAndUpdate(id, data);
return result;
};
findOneAndUpdate = async (id, data) => {
var result = await this.Model.findOneAndUpdate(id, data);
return result;
};
findByIdAndRemove = async (_id) => {
var result = await this.Model.findByIdAndRemove(_id);
return result;
};
findOneAndRemove = async (data) => {
var result = await this.Model.findOneAndRemove(data);
return result;
};
save = async (result) => {
var s = new this.Model(result);
s = await s.save();
result = s;
// console.log({ id: s._id, fixed: s.fixed });
// console.log(s.fixed);
return result;
};
countDocuments = async () => {
var result = this.Model.countDocuments();
return result;
};
findAndPopulate = async (data = {}, onPopulate, condition, option) => {
const result = await this.Model.find(data).populate(
onPopulate,
null,
condition
);
return result;
};
findAndSelect = async (data = {}, select) => {
const result = await this.Model.find(data).select(select).lean();
return result;
};
findOneAndSelect = async (data = {}, select) => {
const result = await this.Model.findOne(data).select(select).lean();
return result;
};
}
module.exports = GenericService;
|
import { Vector3, Object3D } from 'three';
import GLTFLoader from 'three-gltf-loader';
import MODEL from './flag.gltf';
import config from '../../config.json';
export default class Flag extends Object3D {
constructor(lat, long, country, instrument) {
super();
this.name = 'flag';
this.country = country;
this.instrument = instrument;
const location = this.spherePositionSet(lat, long);
const loader = new GLTFLoader();
loader.load(MODEL, (gltf) => {
this.add(gltf.scene);
}, (xhr) => {
console.log(`${( xhr.loaded / xhr.total * 100 )}% loaded`);
}, (error) => {
console.error('Error:', error);
});
this.scale.set(2, 2, 2);
this.lookAt(new Vector3(location.x, location.y, location.z));
this.rotateX(0.5*Math.PI);
this.position.set(location.x, location.y, location.z);
}
/**
* Sets position of flag on sphere (earth)
* @param { Number } lat the latitude of the location
* @param { Number } long the longitude of the location
* @returns { Object } x, y, z of flag
*/
spherePositionSet(lat, long) {
const radius = 350; //config.earthRadius;
lat *= Math.PI/180;
long *= Math.PI/180;
const x = radius * Math.cos(lat) * Math.cos(long);
const y = radius * Math.cos(lat) * Math.sin(long);
const z = radius * Math.sin(lat);
return {x, y, z};
}
} |
const fs = require('fs');
const moment = require('moment');
const puppeteer = require('puppeteer');
const PushBullet = require('pushbullet');
const PUSHBULLET_ACCESS_TOKEN = process.env['PUSHBULLET_ACCESS_TOKEN'];
const pusher = new PushBullet(PUSHBULLET_ACCESS_TOKEN);
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
const rows = await page.$$eval(
".athing .storylink",
(anchors) => anchors.map(
(anchor) => Object({
href: anchor.href,
title: anchor.textContent,
})
),
);
await browser.close();
let now = moment().format('YYYY-MM-DD HH:mm 기준');
let title = `Hacker News\n${now}\n`;
let body = '';
for ([idx, row] of rows.entries()) {
body += `${idx+1}. ${row.href}\n`;
}
pusher.note(process.env['PUSHBULLET_IDEN'], title, body, (err, res) => {
console.log(res);
});
})(); |
"use strict";
"use warning";
var GameScene = new function() {
var INSTANCE = this;
// Image
var iframe;
var stage_title;
var stage_num;
var movePos = 0;
var moveCnt = 0;
this.load = function(onload) {
var onloadCnt = 0;
var checkOnload = function () {
onloadCnt++;
if (onloadCnt == 2) {
onload();
}
};
if (GameEngine.getGameMode() == GAME_MODE_DEFENCE) {
setResource(checkOnload);
} else if (GameEngine.getGameMode() == GAME_MODE_RAID) {
setResourceForRaid(checkOnload);
}
POPUP.POP_SKILLEFFECT.getInstance().setResource(checkOnload);
};
var setResourceForRaid = function(onload) {
var stageFrame = "world/" + UnitManager.getStageName();
var imgParam = [
[iframe = new Image(), ROOT_IFRAME + stageFrame + EXT_IFRAME],
[stage_title = new Image(), ROOT_IMG + "game/etc/stage_raid_0" + EXT_PNG],
[stage_num = new Image(), ROOT_IMG + "game/etc/stage_num_1" + EXT_PNG],
];
ResourceMgr.makeImageList(imgParam, function() {
imgParam = null;
PlayResManager.setResourceForDefence(HeroManager.getMyHeroInfo(), UnitManager.getEnUnitInfo(), function() {
GameEngine.setResource(onload);
});
}, function(err) {
appMgr.openDisconnectPopup("GameScene setResource Fail!!");
onload();
});
};
var setResource = function(onload) {
var stageNum = 0;
if (UnitManager.getStageNum() < 3) {
stageNum = 0;
}
var stageFrame = "world/" + UnitManager.getStageName();
var imgParam = [
[iframe = new Image(), ROOT_IFRAME + stageFrame + EXT_IFRAME],
[stage_title = new Image(), ROOT_IMG + "game/etc/stage_title_" + UnitManager.getStageArea() + EXT_PNG],
[stage_num = new Image(), ROOT_IMG + "game/etc/stage_num_" + UnitManager.getStageNum() + EXT_PNG],
];
ResourceMgr.makeImageList(imgParam, function() {
imgParam = null;
PlayResManager.setResourceForDefence(HeroManager.getMyHeroInfo(), UnitManager.getEnUnitInfo(), function() {
GameEngine.setResource(onload);
});
}, function(err) {
appMgr.openDisconnectPopup("GameScene setResource Fail!!");
onload();
});
};
var fps = 0;
return {
toString: function() {
return "GameScene";
},
init: function(onload, loadData) {
fps = 12;
UIMgr.setFPS(fps);
onload();
},
start: function() {
// appMgr.loopNetSound(ROOT_SOUND + "stage_" + UnitManager.getStageArea() + EXT_MP3);
},
run: function() {
moveCnt++;
GameEngine.update();
UIMgr.repaint();
},
paint: function() {
if (UnitManager.getIsFireSkill()) {
if (moveCnt % 2 == 0) {
movePos+=10;
} else {
movePos-=10;
}
g.drawImage(iframe, 0 + movePos, 0);
} else {
g.drawImage(iframe, 0, 0);
}
g.drawImage(stage_title, 15, 13);
if (GameEngine.getGameMode() == GAME_MODE_DEFENCE) {
g.drawImage(stage_num, stage_title.width + 14, 14);
}
GameEngine.render(g);
},
dispose: function() {
},
stop: function() {
iframe = null;
stage_title = null;
stage_num = null;
appMgr.stopSound();
GameEngine.stop();
POPUP.POP_SKILLEFFECT.getInstance().clear();
},
onKeyPressed: function(key) {
GameEngine.keyAction(key);
},
onKeyReleased: function(key) {
},
getInstance: function() {
return INSTANCE;
}
};
}; |
/**
* Created by irek on 01/05/2016.
*/
'use strict';
angular.module('myApp', [
"ngRoute",
'ngAnimate',
'ngMaterial',
'ui.materialize',
'ui.router',
'ngResource',
'ui.bootstrap'
])
.config(function($provide,
$routeProvider,
$locationProvider,
$httpProvider,
$urlRouterProvider,
$stateProvider
){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'components/home/home.tpl.html',
controller: 'homeController'
})
.state('/about', {
url: '/about',
templateUrl: 'components/about/about.tpl.html',
controller: 'aboutController'
})
.state('/customers', {
url: '/customers',
templateUrl: 'components/customer/customer.tpl.html',
controller: 'customerController'
})
.state('/products', {
url: '/products',
templateUrl: 'components/products/product.tpl.html',
controller: 'productController'
});
$locationProvider.html5Mode({enabled: true });
}).filter('startFrom', function(){
return function(data, start){
return data.slice(start)
}
});
|
import React, { useEffect } from 'react';
//import './BasicDetail.scss';
import { Row, Col } from 'react-bootstrap';
import Header from '../components/Header/customHeader';
import TextField from '@material-ui/core/TextField';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import NativeSelect from '@material-ui/core/NativeSelect';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Paper from '@material-ui/core/Paper';
import BasicNavigator from '../components/BottomNavigator';
import { Formik } from 'formik';
import { connect } from 'react-redux';
import * as actions from '../../redux/actions/index';
import { Typography } from '@material-ui/core';
import { Link } from 'react-router-dom';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import Loading from '../Loading/Loading';
// import DialogContentText from '@material-ui/core/DialogContentText';
import Slide from '@material-ui/core/Slide';
import Zoom from '@material-ui/core/Zoom';
import DialogTitle from '@material-ui/core/DialogTitle';
import PublishIcon from '@material-ui/icons/Publish';
import CircularProgress from '@material-ui/core/CircularProgress';
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
root: {
padding: theme.spacing(3, 2),
width: '100%'
},
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200
},
button: {
width: 224,
textTransform: 'none',
fontWeight: 'normal'
}
}));
const BasicDetail = props => {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const [files, setFiles] = React.useState(null);
const [fileCounter, setFileCounter] = React.useState(0);
const [documentUpload, setdocumentUpload] = React.useState(false);
let { message, getBankDetails, bankAccountDetails, analystDetails } = props;
const [openDialog, setOpenDialog] = React.useState(false);
const [documentRequired, setDocumentRequired] = React.useState(false);
React.useEffect(() => {
if (message !== null) {
setOpenDialog(true);
}
}, [message]);
useEffect(() => {
getBankDetails();
props.isDocumentUpdated(false);
}, []);
const [state, setState] = React.useState({
qualification: analystDetails ? analystDetails.education : null,
tradingExperience: analystDetails ? analystDetails.trading_experience : 0,
certification: ''
});
const handleStateChange = (e, variable) => {
if (variable === 'qualification') {
setState({ ...state, qualification: e.target.value });
}
if (variable === 'tradingExperience') {
setState({ ...state, tradingExperience: e.target.value });
}
//console.log(e.target.value, variable)
};
const [someValueChanged, setSomeValueChanged] = React.useState(false);
const updateValueChanged = () => {
setSomeValueChanged(true);
};
React.useEffect(() => {
if (props.documentUpdated) {
setFileCounter(0);
setFiles(null);
}
}, [props.documentUpdated]);
const handleInputFile = e => {
console.log('asdf', e.target.files);
console.log('file0', e.target.files[0]);
setFiles(e.target.files[0]);
// for(let i=0;i<e.target.files.length;i++){
// setFiles(draft => [...draft,e.target.files[i]])
// }
setFileCounter(e.target.files.length);
};
const handleClose = () => {
setOpen(false);
};
// const handleCertifiacteUpload = e => {
// console.log('certificate: ', e.target.files);
// };
const shouldDisable = value => {
if (
state.qualification === 'SEBI RIA' ||
state.qualification === 'SEBI Research Analyst' ||
state.qualification === 'NISM Research Analyst'
) {
if (!documentUpload || !props.documentUpdated) {
return true;
}
return false;
}
return false;
};
console.log('@@@@@@@@@@@@@', props, state);
return (
// <Slide direction='down' in={true} timeout={500} mountOnEnter unmountOnExit>
<>
<Zoom in={true} timeout={500}>
<div>
<Header
someValueChanged={someValueChanged}
backButton
backTo={() => props.history.push('/')}
title={`Personal Details`}
/>
<Dialog onClose={handleClose} aria-labelledby='simple-dialog-title' open={open}>
<DialogTitle id='simple-dialog-title'>Delete My Account</DialogTitle>
<DialogContent>
Your account will be permanently deleted and you will not be able to use the same phone number or email to
sign up again. Are you sure?
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color='primary'>
Cancel
</Button>
<Button onClick={handleClose} color='primary'>
Ok, Delete
</Button>
</DialogActions>
</Dialog>
<div style={{ padding: '10px', marginTop: '20px' }}>
<Paper className={classes.root}>
<Formik
initialValues={{
firstname:
props.signinData &&
props.signinData.user &&
props.signinData.user.UserAttributes &&
props.signinData.user.UserAttributes.filter(item => item.Name === 'name').length > 0
? props.signinData.user.UserAttributes.filter(item => item.Name === 'name')[0].Value.split(' ')[0]
: '',
lastname:
props.signinData &&
props.signinData.user &&
props.signinData.user.UserAttributes &&
props.signinData.user.UserAttributes.filter(item => item.Name === 'name').length > 0
? props.signinData.user.UserAttributes.filter(item => item.Name === 'name')[0].Value.split(' ')[1]
? props.signinData.user.UserAttributes.filter(item => item.Name === 'name')[0].Value.split(
' '
)[1]
: ''
: '',
email:
props.signinData &&
props.signinData.user &&
props.signinData.user.UserAttributes &&
props.signinData.user.UserAttributes.filter(item => item.Name === 'email').length > 0
? props.signinData.user.UserAttributes.filter(item => item.Name === 'email')[0].Value
: ''
}}
validate={values => {
const errors = {};
if (someValueChanged === false) {
updateValueChanged();
}
if (!values.firstname) {
errors.firstname = 'Enter your first name';
}
if (!values.lastname) {
errors.lastname = 'Enter your last name';
}
if (state.qualification === null || state.qualification === '') {
errors.qualification = 'Qualification is necessary';
}
// if (!values.email) {
// errors.email = 'Enter your email';
// }
// if (!values.password) {
// errors.password = 'Enter your new password';
// }
// if (!values.confirmPassword) {
// errors.confirmPassword = 'Repeat your new password';
// }
// if (values.password !== values.confirmPassword) {
// errors.confirmPassword = "New passwords do not match!";
// }
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
setSubmitting(false);
if (!shouldDisable()) {
console.log(state.education);
props.updateAnalystBasicDetails({
trading_experience: state.tradingExperience,
capital_required:
props.analystDetails && props.analystDetails.capital_required
? props.analystDetails.capital_required
: 0,
education: state.qualification,
user: {
first_name: values.firstname,
last_name: values.lastname
// email: values.email
}
});
} else {
setDocumentRequired(true);
}
// setSubmitting(false)
// // let submitData = {
// // ifscCode: values.password,
// // accountNumber: values.confirm
// // }
// props.changePassword({
// "accesstoken": props.signinData.token.AuthenticationResult.AccessToken,
// "PreviousPassword": values.oldPassword,
// "ProposedPassword": values.password,
// "nextUrl": '/analyst-home'
// })
// console.log('password: ', values.password)
// console.log('CONFRIMpassword: ', values.confirmPassword)
// console.log('oldpassword: ', values.oldPassword)
}}
render={({
submitForm,
isSubmitting,
errors,
touched,
handleChange,
values,
handleSubmit,
setFieldValue
}) => (
<form onSubmit={handleSubmit}>
<Row>
<FormControl className={classes.formControl}>
<TextField
name='firstname'
helperText={touched.firstname ? errors.firstname : ''}
error={Boolean(errors.firstname)}
label='First Name'
//type="password"
value={values.firstname}
onChange={handleChange}
//fullWidth
/>
{errors.firstname && touched.firstname}
</FormControl>
</Row>
<Row style={{ marginTop: '10px' }}>
<FormControl className={classes.formControl}>
<TextField
name='lastname'
helperText={touched.lastname ? errors.lastname : ''}
error={Boolean(errors.lastname)}
label='Last Name'
//type="password"
value={values.lastname}
onChange={handleChange}
//fullWidth
/>
{errors.lastname && touched.lastname}
</FormControl>
</Row>
{/* <Row style={{ marginTop: '10px' }}>
<FormControl className={classes.formControl}>
<TextField
name='email'
helperText={touched.email ? errors.email : ''}
error={Boolean(errors.email)}
label='Email'
//type="password"
value={values.email}
onChange={handleChange}
//fullWidth
/>
{errors.email && touched.email}
</FormControl>
</Row> */}
<Row style={{ marginTop: '20px' }}>
<FormControl className={classes.formControl}>
<InputLabel shrink htmlFor='age-native-label-placeholder'>
Qualification
</InputLabel>
<NativeSelect
value={state.qualification}
//name="education"
helperText={touched.qualification ? errors.qualification : ''}
onChange={e => handleStateChange(e, 'qualification')}
>
<option value=''>Select</option>
{/* <option value={`Graduate`}>Graduate</option>
<option value={`Post graduation`}>Post graduation</option>
<option value={`Graduate & SEBI RIA`}>{`Graduate & SEBI RIA`}</option>
<option value={`Post Graduate & SEBI RIA`}>{`Post Graduate & SEBI RIA`}</option> */}
<option value={`Graduate/PG (No SEBI Certification)`}>
Graduate/PG (No SEBI Certification)
</option>
<option value={`SEBI RIA`}>{`SEBI RIA`}</option>
<option value={`SEBI Research Analyst`}>{`SEBI Research Analyst`}</option>
<option value={`NISM Research Analyst`}>{`NISM Research Analyst`}</option>
<option value={`CFA/CMT/FRM`}>CFA/CMT/FRM</option>
</NativeSelect>
<span style={{ color: '#f44336', fontSize: '0.75rem' }}>
{state.qualification === '' || state.qualification === null ? errors.qualification : ''}
</span>
{/* <FormHelperText>"Problem"</FormHelperText> */}
</FormControl>
</Row>
<Row style={{ marginTop: '20px', display: 'flex', justifyContent: 'space-between' }}>
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '0px' }}>
<FormControl className={classes.formControl}>
<InputLabel shrink htmlFor='id-trading-experience' style={{ color: '#616161' }}>
Trading Exp.
</InputLabel>
<NativeSelect
value={state.tradingExperience}
onChange={e => handleStateChange(e, 'tradingExperience')}
style={{ width: '90%' }}
inputProps={{
name: 'tradingExperience',
id: 'id-trading-experience'
}}
>
<option value={0}>0 years</option>
<option value={1}>1 year</option>
<option value={2}>2 years</option>
<option value={3}>3 years</option>
<option value={4}>4 years</option>
<option value={5}>5 years</option>
<option value={6}>6 years</option>
<option value={7}>7 years</option>
<option value={8}>8 years</option>
<option value={9}>9 years</option>
<option value={10}>10 years</option>
<option value={11}>11 years</option>
<option value={12}>12 years</option>
<option value={13}>13 years</option>
<option value={14}>14 years</option>
<option value={15}>15 years</option>
<option value={16}>16 years</option>
<option value={17}>17 years</option>
<option value={18}>18 years</option>
<option value={19}>19 years</option>
<option value={20}>20 years</option>
<option value={21}>21 years</option>
<option value={22}>22 years</option>
<option value={23}>23 years</option>
<option value={24}>24 years</option>
<option value={25}>25 years</option>
<option value={26}>26 years</option>
<option value={27}>27 years</option>
<option value={28}>28 years</option>
<option value={29}>29 years</option>
<option value={30}>30+ years</option>
</NativeSelect>
</FormControl>
</Col>
<Col lg={6} md={6} sm={6} xs={6} style={{ padding: '0px', alignSelf: 'flex-end' }}>
<FormControl className={classes.formControl}>
<InputLabel shrink htmlFor='certificate'>
Certification
</InputLabel>
<div className='file' id='certificate' style={{ marginBottom: '0px', paddingBottom: '32px' }}>
<label for='file' style={{ cursor: 'pointer' }}>
{fileCounter > 0 ? 'Files Selected' : 'Choose File'}
</label>
<Input type='file' name='file' id='file' onChange={handleInputFile} />
<PublishIcon
onClick={() => {
if (files !== null) {
var formData = new FormData();
console.log('!!!!!!!!!!!!!', files);
formData.append('field_name', 'certificate');
formData.append('certificate', files);
props.uploadDocument({
payload: formData
});
setdocumentUpload(true);
}
}}
className='icon'
style={{ fontSize: '19px', cursor: fileCounter > 0 ? 'pointer' : 'default' }}
/>
{fileCounter > 0 ? <div className='counter'>{fileCounter}</div> : null}
</div>
{shouldDisable() && !documentUpload && <p className='error-text'>Add Certification</p>}
</FormControl>
</Col>
</Row>
<Row style={{ display: 'flex', justifyContent: 'center', padding: '20px 0px' }}>
{props.loader ? (
<CircularProgress name='circle' color='primary' />
) : (
<Button
variant='contained'
color='primary'
className={classes.button}
disabled={isSubmitting}
type='submit'
>
Save Details
</Button>
)}
</Row>
</form>
)}
/>
</Paper>
<Paper className={classes.root} style={{ marginTop: '20px', marginBottom: '3rem' }}>
<div className='d-flex justify-content-between'>
<Typography variant='h6' style={{ marginBottom: '15px' }}>
Bank Account Details
</Typography>
<Link className='mt-1' style={{ fontSize: '1rem' }} to='/account-detail'>
Edit
</Link>
</div>
<Typography variant='body1' align='center' style={{ marginBottom: '15px' }}>
{bankAccountDetails && bankAccountDetails.name}
</Typography>
<Typography variant='body1' align='center' style={{ marginBottom: '15px' }}>
{bankAccountDetails && bankAccountDetails.bank.name}
</Typography>
<Typography variant='body1' align='center' style={{ marginBottom: '15px' }}>
{bankAccountDetails && `${bankAccountDetails.ifsc_code}, ${bankAccountDetails.type}`}
</Typography>
</Paper>
{/* <Row style={{ display: 'flex', justifyContent: 'center', padding: '40px 50px', marginBottom: '30px' }}>
<a href='#' style={{ color: 'red', textDecoration: 'underline' }} onClick={() => setOpen(true)}>
Delete My Account
</a>
</Row> */}
</div>
<Loading open={props.loading} popover />
<Dialog
open={openDialog}
onClose={() => setOpenDialog(false)}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>{props.message}</DialogTitle>
<DialogActions>
<Button
onClick={() => {
props.setMessage(null);
setOpenDialog(false);
setSomeValueChanged(false);
// props.history.push('/analyst-home');
props.changeHomeState(3);
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
</Dialog>
<Dialog
open={documentRequired}
onClose={() => setDocumentRequired(false)}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>
for {state.qualification} kindly add your certification first
</DialogTitle>
<DialogActions>
<Button
onClick={() => {
setDocumentRequired(false);
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
</Dialog>
</div>
{/* </Slide> */}
</Zoom>
<BasicNavigator />
</>
);
};
const mapStateToProps = state => ({
signinData: state.auth.signinData,
loader: state.auth.loader,
message: state.auth.message,
bankAccountDetails: state.auth.bankAccountDetails,
analystDetails: state.analyst.analystDetails,
documentUpdated: state.analyst.documentUpdated,
loading: state.analyst.loading
});
const mapDispatchToProps = dispatch => ({
// changePassword: params => dispatch(actions.changePassword(params)),
setMessage: message => dispatch(actions.setMessage(message)),
uploadDocument: data => dispatch(actions.uploadDocument(data)),
getBankDetails: token => dispatch(actions.getBankDetails(token)),
updateAnalystBasicDetails: payload => dispatch(actions.updateAnalystBasicDetails(payload)),
isDocumentUpdated: payload => dispatch(actions.documentUpdated(payload)),
changeHomeState: params => dispatch(actions.changeHomeState(params))
});
export default connect(mapStateToProps, mapDispatchToProps)(BasicDetail);
|
var utility = require('../service/utility');
var chatRooms = require('../models/chatRooms');
var chatMessages = require('../models/chatMessages');
var arrayGroup = require('group-array');
var Chat = function () {
this.messageHistory = function (room_id, callback) {
var condition = {
chat_room_id: room_id
};
chatRooms.findOne(condition, function (err, room) {
if (room) {
chatMessages.find(condition, null, {
sort: {
datetime: 1
}
}, function (err, messages) {
if (err) {
console.log(err);
return false;
}
callback(messages);
});
} else {
var Rooms = new chatRooms({
chat_room_id: room_id,
name: utility.uniqid(),
datetime: new Date()
});
Rooms.save(callback([]));
}
});
};
this.addMessage = function (data, callback) {
var chat = {
message_id: utility.uniqid(),
chat_room_id: data.room_id,
user_from_id: data.user_from_id,
user_to_id: data.user_to_id,
message: data.message,
status: 'UR',
datetime: new Date()
};
var message = new chatMessages(chat);
message.save(function (err) {
if (err) return console.log(err);
callback(chat);
});
};
this.readMessage = function (message_id, callback) {
var condition = {
message_id: message_id
};
chatMessages.findOne(condition, function (err, message) {
message.status = "R";
message.save(callback);
});
};
this.getNotify = function (user, callback) {
chatMessages.find({
user_to_id: user,
status: 'UR'
}, function (err, messages) {
if (err) {
return console.log(err);
}
var data = arrayGroup(messages, "user_from_id");
callback(data);
});
};
};
module.exports = new Chat(); |
/* eslint-disable react/require-default-props */
/* eslint-disable class-methods-use-this */
/* eslint-disable react/prop-types */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { ToastContainer, toast } from 'react-toastify';
import LandingPage from '../components/LandingPage';
import LoginAction from '../actions/LoginAction';
const jwt = require('jsonwebtoken');
// eslint-disable-next-line react/prefer-stateless-function
export class Home extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.loginState.user) {
this.handleSuccess(nextProps.loginState);
}
if (!nextProps.loginState.user) {
this.handleErrors(nextProps);
}
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
handleSubmit(e) {
e.preventDefault();
// eslint-disable-next-line react/destructuring-assignment
this.props.LoginAction(this.state);
}
handleSuccess(loginState) {
if (loginState.user.token) {
toast.success(
<p className="text-white">
Login Successful
</p>,
);
const { token } = loginState.user;
const decoded = jwt.decode(token);
if (decoded.roles[0] === 'Admin') {
setTimeout(() => window.location.assign('/admindashboard'), 2000);
} else {
setTimeout(() => window.location.assign('/attendantdashboard'), 2000);
}
}
}
handleErrors(props) {
if (props.loginState.error) {
toast.error(
<p>
{props.loginState.error.message}
</p>,
);
}
}
render() {
return (
<div>
<LandingPage onChange={this.handleChange} onSubmit={this.handleSubmit} />
<ToastContainer />
</div>
);
}
}
Home.propTypes = {
LoginAction: PropTypes.func,
};
const mapStateToProps = state => ({
username: state.LoginReducer.username,
password: state.LoginReducer.password,
loginState: state.LoginReducer,
});
export default connect(mapStateToProps, { LoginAction })(Home);
|
import React from 'react'
import Notepad from '../components/Notepad'
import { handleSingleClick, handleLinkDblClick } from '../utils/functions'
const ProjectFolder = (props) => {
return (
<div id="singleProjectContainer">
<div
id="goBack"
className=" hover:bg-gray-400 flex items-center sm:p-4 "
onClick={(event) => {
return handleSingleClick(event, document.getElementById('singleProjectContainer'))
}}
onDoubleClick={props.goBack}
>
<img className="w-8 m-2" src="./images/icons/folderopened_yellow.ico"></img>
<span>. . </span>
</div>
<div
id="liveSite"
searchterm="Live Site"
className="searchAble hover:bg-gray-400 sm:p-4 "
onClick={(event) => {
return handleSingleClick(event, document.getElementById('singleProjectContainer'))
}}
onDoubleClick={() => {
handleLinkDblClick(props.selectedProject.link)
}}
>
<div className="flex items-center">
<img className="w-8 m-2 sm:w-8 sm:text-md" src="./images/tech/chrome.png"></img>
<span>Live Site</span>
</div>
</div>
<div
id="code"
searchterm="code"
className="searchAble hover:bg-gray-400 sm:p-4 "
onClick={(event) => {
return handleSingleClick(event, document.getElementById('singleProjectContainer'))
}}
onDoubleClick={() => {
handleLinkDblClick(props.selectedProject.code)
}}
>
<div className="flex items-center">
<img className="w-8 m-2 sm:w-8 sm:text-md" src="./images/githubLight.png"></img>
<span>Code</span>
</div>
</div>
<button
type="button"
id="description"
searchterm="Description"
className="searchAble hover:bg-gray-400 sm:p-4 w-full border-0 focus:outline-none"
onClick={(event) => {
return handleSingleClick(event, document.getElementById('singleProjectContainer'))
}}
onDoubleClick={(event) => {
props.setShowDescription(event)
}}
>
<div className="flex items-center">
<img className="w-8 m-2 sm:w-8 sm:text-md" src="./images/icons/notepad.ico"></img>
<span>Description</span>
</div>
</button>
{props.showDescription ? (
<Notepad setShowDescription={props.setShowDescription} project={props.selectedProject} />
) : (
''
)}
</div>
)
}
export default ProjectFolder
|
module.exports = function(app) {
require('dotenv').load();
var express = require('express');
var fs = require('fs');
var async = require('async');
var discogsRouter = express.Router();
var Discogs = require('disconnect').Client;
var discogsToken = process.env.DISCOGS_API_TOKEN;
var albumsJSON = __dirname+'/../data/albums-07212015.json';
var artistsJSON = __dirname+'/../data/artists-07212015.json';
function getDiscogsAlbum(artist, title, cb) {
var DiscogsQuery = new Discogs({userToken: discogsToken}).database();
DiscogsQuery.search(title, { type: 'release', artist: artist, release_title: title, per_page: 1, page: 1 }, function(err, data) {
if(err || typeof data === undefined || data.results.length === 0) {
return typeof (data === undefined || data.results.length === 0) ? cb('[DISCOGS_API] Release Search Error: '+err) : cb('[DISCOGS_API] Release Search Error: No Results');
}
DiscogsQuery.release(data.results[0].id, function(err, release) {
if(err) return cb('[DISCOGS_API] Initial Release Retrival Error: '+err);
DiscogsQuery.master(release.master_id, function(err, master) {
if(err) return cb('[DISCOGS_API] Master Release Retrieval Error: '+err);
if(master.main_release === release.id) {
return cb(null, release);
}
DiscogsQuery.release(master.main_release, function(err, mainRelease) {
if(err) return cb('[DISCOGS_API] Main Release Retrieval Error: '+err);
return cb(null, mainRelease);
});
});
});
});
}
function getDiscogsArtist(artist, cb) {
var DiscogsQuery = new Discogs({ userToken: discogsToken}).database();
var searchResult;
var resources = ['artist', 'release', 'master'];
var resultWithArtist;
function searchDiscogs(query, resource, _cb) {
DiscogsQuery.search(query, {type: resource}, function(err, data) {
return _cb(data);
});
}
function getResult(result, _cb) {
DiscogsQuery[result.type](result.id, function(err, release) {
if(err) return _cb(err);
if(typeof release !== undefined && Array.isArray(release.artists)) {
return _cb(null, release);
} else {
return _cb('Not found');
}
});
}
async.eachSeries(resources, function(resource, next) {
searchDiscogs(artist, resource, function(response) {
if(response && response.results.length > 2) {
searchResult = response.results;
}
next();
});
}, function() {
if(!searchResult) {
return cb('Not found.');
}
async.eachSeries(searchResult, function(result, next) {
if(!resultWithArtist) {
DiscogsQuery[result.type](result.id, function(err, release) {
/* artist.id 194 is Discog's "various artists" id, returns no page on lookup */
if(typeof release.artists !== undefined && Array.isArray(release.artists) && release.artists[0].id !== 194) {
resultWithArtist = release;
}
next();
});
} else {
next();
}
}, function() {
if(resultWithArtist) {
console.log(resultWithArtist.artists[0].id);
DiscogsQuery.artist(resultWithArtist.artists[0].id, function(err, artistResult) {
if(err) return cb('[DISCOGS_API] Error retrieving artist: '+err);
return cb(null, artistResult);
});
} else {
return cb('Not found.');
}
});
});
}
function readJSON(json, cb) {
fs.readFile(json, function(err, file) {
if(err) {
console.log('Error reading file: '+err);
return cb(err);
}
return cb(null, JSON.parse(file));
});
}
function getAlbum(id, cb) {
readJSON(albumsJSON, function(err, albums) {
while(albums.length) {
var album = albums.shift();
if(album.id === id) {
return cb(null, album);
}
if(albums.length === 0) {
console.log('Album not found.');
return cb('Album '+id+' not found.');
}
};
});
}
function getArtist(id, cb) {
readJSON(artistsJSON, function(err, artists) {
while(artists.length) {
var artist = artists.shift();
if(parseInt(artist.id) === parseInt(id)) {
return cb(null, artist);
}
if(artists.length === 0) {
console.log('Artist not found.');
return cb('Artist '+id+' not found.');
}
};
});
}
discogsRouter.get('/?', function(req, res) {
if(req.query.artist) {
getArtist(req.query.artist, function(err, artist) {
getDiscogsArtist(artist.name, function(err, discogsArtist) {
if(err) {
console.log('******* ERROR *******');
console.log(err);
return res.send({ discogs: [{id: 1, error: err }]});
}
res.send({ discogs: [discogsArtist] });
});
});
} else {
res.send({ discogs: []});
}
});
discogsRouter.post('/', function(req, res) {
res.status(201).end();
});
discogsRouter.get('/:id', function(req, res) {
getAlbum(req.params.id, function(err, album) {
getArtist(album.artist, function(err, artist) {
getDiscogsAlbum(artist.name, album.title, function(err, discogsAlbum) {
if(err) {
console.log('******* ERROR *******');
console.log(err);
return res.send({ discog: { id: 1, error: err } });
}
res.send({ discog: discogsAlbum });
});
});
});
});
discogsRouter.put('/:id', function(req, res) {
res.send({
'discogs': {
id: req.params.id
}
});
});
discogsRouter.delete('/:id', function(req, res) {
res.status(204).end();
});
app.use('/api/discogs', discogsRouter);
};
|
import React, {Component} from "react"
import {Layout, Carousel} from "element-react"
import "element-theme-default";
import echarts from "echarts"
import MyFetch from "../../../../components/global/myFetch"
import {sentimentApi} from "../../../../components/global/apiGroup"
import "./SliderBar.scss"
const navItem = [
{name: "实时数据", indexTab: 0},
{name: "累计数据", indexTab: 1}
]
const weather = [
{key: "温度", value: "21℃"},
{key: "湿度", value: "45%"},
{key: "风向", value: "西北方向"},
{key: "风力", value: "四到五级"},
{key: "首要污染物", value: "PM2.5"},
{key: "空气质量", value: "良"},
]
const weather_date = [
{key: "PM2.5", value: 53},
{key: "PM10", value: 58},
{key: "SO2", value: 16},
{key: "CO", value: 1.1},
{key: "NO2", value: 42},
{key: "O3", value: 72}
]
const city_point = [
{name: "国控点"},
{name: "市控点"},
{name: "科研站"},
{name: "气站"}
]
const title = ["排名", "监测点", "空气质量等级", "AQI", "首要污染物"]
class Sliderbar extends Component {
constructor(props) {
super(props)
this.state = {
activeTab: 0,
data: {},
isDrawer: true,
city_rank:[]
}
}
silderTab(indexTab) {
this.setState({
activeTab: indexTab
})
}
toggleWeather(flag) {
this.setState({
style: flag ? {"left": "0.3rem"} : {"left": "-5.5rem"},
style1: flag ? {"opacity": 0} : {"opacity": 1}
})
}
componentDidMount() {
this.getData();
window.addEventListener("resize", this.handleResize);
fetch("./data/data.json").then(function (res) {
return res.json();
}).then(function (data) {
this.setState({
city_rank:data.data
})
}.bind(this))
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
getData = () => {
let data = {
complainSum: 63,
transactSum: 19
}
this.setState({data}, () => {
this.drawChart(this.echarts1, "e1")
this.drawChart(this.echarts2, "e2")
this.drawChart(this.echarts3, "e3")
this.drawChart(this.echarts4, "e4")
this.drawChart(this.echarts5, "e5")
this.drawChart(this.echarts6, "e6")
});
}
drawChart(dom, echart) {
if (!dom) return
const {complainSum = 1, transactSum = 0} = this.state.data
const percentageOfDone = (transactSum / complainSum * 100).toFixed(0)
const percentageOfPending = 100 - percentageOfDone
let myChart = echarts.init(dom);
let option = {
series: [
{
name: "受理率",
type: "pie",
radius: ["68%", "80%"],
// center: ["40%", "52%"],
color: ["#00a3ff", "#7AB3E6"],
hoverAnimation: false,
label: {
normal: {
show: false,
position: "center",
textStyle: {
fontSize: "14"
}
}
},
data: [
{value: percentageOfDone, name: `${percentageOfDone}%\n受理率`},
{value: percentageOfPending, name: ""}
]
}
]
};
if(echart == "e2"){
option.series.color = ["#00a3ff", "#36DB7D"]
}
myChart.setOption(option);
this[echart] = myChart;
}
handleResize = () => {
// this.echart && this.echart.resize()
this.e1 && this.e1.resize()
this.e2 && this.e2.resize()
this.e3 && this.e3.resize()
this.e4 && this.e4.resize()
this.e5 && this.e5.resize()
this.e6 && this.e6.resize()
}
selectItem(val){
var longitude = val.x;
var latitude = val.y;
var name = val.name;
var desc = val.desc;
if(this.props.onInfoClick){
this.props.onInfoClick({longitude,latitude,name,desc})
}
}
weather() {
return (
<div className="weather_date">
<div className="date_left">
<p>通心岭</p>
<img src={require("../../../../image/env/weather/31.png")}/>
<p className="dateCalender">2018-09-01</p>
</div>
<div className="date_right">
{
weather.map(item => {
return (
<p key={item.key} className="">
<span>{item.key}</span>
<span>{item.value}</span>
</p>
)
})
}
</div>
</div>
)
}
render() {
const {complainSum, transactSum} = this.state.data
const percentageOfDone = ((transactSum || 0) / (complainSum || 1) * 100).toFixed(1);
return (
<div>
<div className="sliderbar" style={this.state.style}>
<div className="nav" id="page-nav">
{
navItem.map((item, index) => {
return (
<div
className={item.indexTab === this.state.activeTab ? "nav-item active" : "nav-item"}
key={index}
onClick={() => this.silderTab(item.indexTab)}
>
<span>{item.name}</span>
<div
className={item.indexTab === this.state.activeTab ? "nav-arrows" : ""}></div>
</div>
)
})
}
<img
className="img_out"
src={require("../../../../image/env/weather/in.png")}
onClick={() => this.toggleWeather(false)}
/>
</div>
<Carousel
trigger="click"
className="carousel"
autoplay={false}
>
<Carousel.Item>
{this.weather()}
<div>
<div className="petition-handling-container">
{complainSum
? <div className="content">
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts1 = dom
}}></div>
<div className="percentage">
{percentageOfDone}%
</div>
<p>小时AQI</p>
</div>
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts2 = dom
}}></div>
<div className="percentage">
{percentageOfDone}%
</div>
<p>当天AQI</p>
</div>
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts3 = dom
}}></div>
<div className="percentage">
{percentageOfDone}%
</div>
<p>小时综合指数</p>
</div>
</div>
: <div className="content">
<div className="nodata-tip">暂无数据</div>
</div>
}
</div>
</div>
<div className="weather_data">
{
weather_date.map((item, index) => {
return (
<div className="date_item" key={index}>
<p>{item.key}</p>
<p>{item.value}</p>
</div>
)
})
}
</div>
<div>
<div className="petition-handling-container">
{complainSum
? <div className="content">
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts4 = dom
}}></div>
<div className="percentage">
<p>{percentageOfDone}%</p>
</div>
<p>日排名</p>
</div>
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts5 = dom
}}></div>
<div className="percentage">
<p>{percentageOfDone}%</p>
</div>
<p>月排名</p>
</div>
<div id="echarts-wrap">
<div id="petition-handling-chart" ref={(dom) => {
this.echarts6 = dom
}}></div>
<div className="percentage">
<p>{percentageOfDone}%</p>
</div>
<p>年排名</p>
</div>
</div>
: <div className="content">
<div className="nodata-tip">暂无数据</div>
</div>
}
</div>
</div>
</Carousel.Item>
<Carousel.Item>
{this.weather()}
<div className="tabcontainer">
<ul className="city_point">
{
city_point.map((item, index) => {
return (
<li key={index}>{item.name}</li>
)
})
}
</ul>
<div className="cityPoint_more">
<i className="el-icon-more"></i>
</div>
</div>
<ul className="title title-color">
{
title.map((item, index) => {
return (
<li key={index}>{item}</li>
)
})
}
</ul>
<div className="scroll">
{this.state.city_rank.map((item, index) => {
return (
<ul className="title" key={index} onClick={this.selectItem.bind(this,item)}>
<li>{item.NO}</li>
<li>{item.name}</li>
<li>{item.quality}</li>
<li>{item.AQI}</li>
<li>{item.program}</li>
</ul>
)
})
}
</div>
</Carousel.Item>
</Carousel>
</div>
<div className="img_in_container"
style={this.state.style1}
onClick={() => this.toggleWeather(true)}
>
<img
className="img_in"
src={require("../../../../image/env/weather/out.png")}
/>
</div>
</div>
)
}
}
export default Sliderbar |
import React from "react";
import ContentHeader from "./helpers/content-header";
import SkillCard from "./helpers/skill-card";
function Skills() {
const skills = [
{ name: "JavaScript", value: 70 },
{ name: "ReactJs", value: 75 },
{ name: "Redux", value: 70 },
{ name: "Cascading Style Sheets", value: 75 },
{ name: "HTML", value: 90 },
{ name: "GitHub", value: 75 },
{ name: "DBMS", value: 70 },
{ name: "SQL", value: 70 },
{ name: "Data Structures and Algorithms", value: 75 },
{ name: "MS Office Suite", value: 90 },
{ name: "Problem Solving", value: 80 }
];
return (
<div className="ui segments box-shadow-none margin-no margin-five-bottom">
<ContentHeader title="Skills & Competences" />
<div className="ui segment box-shadow-none padding-vs-horizontal">
<div className="ui grid margin-no">
{skills.map((skill, i) => (
<SkillCard key={i} data={skill} />
))}
</div>
</div>
</div>
);
}
export default Skills;
|
const lines = [
"2016-09-15 20:59:57.421 0.351s",
"2016-09-15 20:59:58.233 1.181s",
"2016-09-15 20:59:58.299 0.8s",
"2016-09-15 20:59:58.688 1.041s",
"2016-09-15 20:59:59.591 1.412s",
"2016-09-15 21:00:00.464 1.466s",
"2016-09-15 21:00:00.741 1.581s",
"2016-09-15 21:00:00.748 2.31s",
"2016-09-15 21:00:00.966 0.381s",
"2016-09-15 21:00:02.066 2.62s",
];
const solution = (lines) => {
let answer = 0;
const arr = [];
const logPointArr = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].split(" ");
const edSec =
Number(line[1].substring(0, 2)) * 3600 +
Number(line[1].substring(3, 5)) * 60 +
Number(line[1].substring(6, 12));
const duration = Number(line[2].substring(0, line[2].length - 1));
const stSec = edSec - duration + 0.001;
arr.push([stSec, edSec, duration]);
logPointArr.push(stSec, edSec);
}
logPointArr.sort();
console.log(logPointArr);
for (let i = 0; i < logPointArr.length; i++) {
const beginRange = logPointArr[i];
const endRange = logPointArr[i] + 1;
let count = 0;
for (let j = 0; j < arr.length; j++) {
let stPoint = arr[j][0];
let edPoint = arr[j][1];
if (
(stPoint >= beginRange && stPoint < endRange) ||
(edPoint >= beginRange && edPoint < endRange) ||
(stPoint <= beginRange && edPoint >= endRange)
) {
count++;
}
}
if (count > answer) {
answer = count;
}
}
return answer;
};
console.log(solution(lines));
|
import { Auth0Provider } from "@auth0/auth0-react";
function MyApp({ Component, pageProps }) {
return (
<Auth0Provider
domain="DOMAIN"
clientId="CLIENT_ID"
redirectUri="http://localhost:3000/login-success"
>
<Component {...pageProps}/>
</Auth0Provider>
)
}
export default MyApp |
angular.module('starter')
.service('AutorizacionServicio',function($q,$http,USER_ROLES){
var LOCAL_TOKEN_KEY="";
var usuario = "";
var isAutenticado = false;
var perfil = "";
var authtoken;
function storeUserCredentials(token){
window.localStorage.setItem(LOCAL_TOKEN_KEY,token);
userCredentials(token);
}
function userCredentials(token){
usuario = token.split('.')[0];
isAutenticado = true;
authtoken = token;
role = USER_ROLES
}
var login = function (pUsuario) {
usuario = pUsuario;
}
return{
login : login,
logout : logout,
isAutenticado : isAutenticado,
isaAutorizado : function(){return isAutenticado;},
usuario : function(){return usuario;},
role : function(){ return perfil;}
};
}) |
/* @flow */
import React from 'react'
const tdCx = {
fontSize: '0px',
lineHeight: '0',
paddingTop: '12px',
paddingBottom: '12px',
textAlign: 'left'
}
const lineCx = {
borderTopColor: '#e5e5e5',
borderTopStyle: 'solid',
borderTopWidth: '1px',
fontSize: '0px',
lineHeight: '0px'
}
type spacingType = {
line: bool
}
const Spacing = ({ line }: spacingType): React.Element => {
const lineTable = <table style={lineCx} width='100%' cellPadding='0' cellSpacing='0'>
<tbody>
<tr>
<td style={{textAlign: 'left'}} align='left'>
</td>
</tr>
</tbody>
</table>
return <table width='100%' cellPadding='0' cellSpacing='0'>
<tbody>
<tr>
<td style={tdCx} align='left'>
{line ? lineTable : ' '}
</td>
</tr>
</tbody>
</table>
}
export default Spacing
|
import whatis from "./assets/images/whatis.png";
import started from "./assets/images/started.png";
import using from "./assets/images/using.png";
import dataimg from "./assets/images/data.png";
export const data = [
{
id: 0,
header: "What is Latana?",
sub: ["How does Latana work?", "Why choose Latana?", "What does Latana cost?"],
src: whatis,
href: "",
},
{
id: 1,
header: "Getting Started",
sub: ["What is MRP?", "How do you gather data?", "What is a margin of error?"],
src: started,
href: "",
},
{
id: 2,
header: "Using Latana",
sub: ["How to use Latana?", "What is the Brand Funnel?", "How to interpret Brand Tracking Data?"],
src: using,
href: "",
},
{
id: 3,
header: "Data Collection & Methodology",
sub: ["What is MRP?", "How do you gather data?", "What is a margin of error?"],
src: dataimg,
href: "",
},
{
id: 4,
header: "Success",
sub: ["What is MRP?", "How do you gather data?", "What is a margin of error?"],
src: using,
href: "",
},
];
|
const {expect} = require('chai');
const combineMediaQueries = require('../lib/combine-media-queries');
const input = `
<!doctype html>
<html>
<head>
<style>
@media (min-width: 100px) {
.one {
color: red;
}
}
@media (min-width: 100px) {
.two {
color: green;
}
}
@media (min-width: 200px) {
.three {
color: blue;
}
}
</style>
</head>
<body></body>
</html>
`;
describe('combineMediaQueries()', () => {
it('combines CSS from identical media queries into one block', () => {
const output = combineMediaQueries(input, '', {
compress: true
});
const mediaQueries = output.match(/@media \(min-width: \d{3}px\)/g);
expect(mediaQueries).to.eql([
'@media (min-width: 100px)',
'@media (min-width: 200px)'
]);
});
it('does not combine media queries if the `compress` option is `false`', () => {
const output = combineMediaQueries(input, '', {
compress: false
});
const mediaQueries = output.match(/@media \(min-width: \d{3}px\)/g);
expect(mediaQueries).to.eql([
'@media (min-width: 100px)',
'@media (min-width: 100px)',
'@media (min-width: 200px)'
]);
});
});
|
// alert("It's working!")
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.strokeStyle="salmon";
ctx.moveTo(150,0);
ctx.lineTo(300,300);
ctx.lineTo(0,300)
ctx.closePath();
ctx.stroke();
ctx.fillStyle= "green";
ctx.fill()
var c2=document.getElementById("myCanvas2");
var ctx2=c2.getContext("2d");
ctx2.beginPath();
ctx2.strokeStyle="blue";
ctx2.moveTo(150,0);
ctx2.lineTo(300,150);
ctx2.lineTo(150,300);
ctx2.lineTo(0,150)
ctx2.closePath();
ctx2.stroke();
ctx2.fillStyle= "blue"
ctx2.fill()
var c3=document.getElementById("myCanvas3");
var ctx3=c3.getContext("2d");
ctx3.beginPath()
ctx3.strokeStyle="blue";
ctx3.moveTo(0,0);
ctx3.lineTo(150,150);
ctx3.lineTo(300,0);
ctx3.lineTo(300,300);
ctx3.lineTo(150,150);
ctx3.lineTo(0,300);
ctx3.closePath();
ctx3.stroke();
ctx3.fillStyle= "blue"
ctx3.fill()
var c4=document.getElementById("myCanvas4");
var ctx4=c4.getContext("2d");
ctx4.beginPath();
ctx4.strokeStyle="blue";
ctx4.moveTo(0,0);
ctx4.lineTo(0,150);
ctx4.lineTo(150,150);
ctx4.lineTo(150,0);
ctx4.lineTo(300,0);
ctx4.lineTo(150,150);
ctx4.lineTo(300,150);
ctx4.lineTo(300,300);
ctx4.lineTo(150,150);
ctx4.lineTo(150,300);
ctx4.lineTo(0,300);
ctx4.lineTo(150,150);
ctx4.closePath();
ctx4.stroke();
ctx4.fillStyle = "blue"
ctx4.fill();
var c5=document.getElementById("myCanvas5");
var ctx5=c5.getContext("2d");
ctx5.beginPath();
ctx5.strokeStyle="brown"
ctx5.arc(150,150,150,0,6.28)
ctx5.moveTo(80,80)
ctx5.fillStyle = "red"
ctx5.fill();
ctx5.arc(80,80,40,0,6.28)
ctx.fillStyle = "blue"
ctx5.fill();
ctx5.moveTo(220,80)
ctx5.fillStyle = "red"
ctx5.fill();
ctx5.arc(220,80,40,0,6.28)
ctx.fillStyle = "blue"
ctx5.moveTo(50,200)
ctx5.lineTo(200,200)
ctx5.arc(150,200,100,0,3.14)
ctx5.moveTo(125,200)
ctx5.lineTo(175,200)
ctx5.arc(150,200,50,0,3.14)
//Arc: X-Coordinate, Y-Coordinate, Radius(Size), Start Angle, End Angle
ctx5.closePath();
ctx5.stroke();
|
import React, { useState } from "react";
import "../styles/contact.css";
import Button from "@material-ui/core/Button";
import Footer from "./Footer";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import CircularProgress from "@material-ui/core/CircularProgress";
// import axios from "axios";
import CheckCircleOutlineIcon from "@material-ui/icons/CheckCircleOutline";
import CancelIcon from "@material-ui/icons/Cancel";
import Snackbar from "@material-ui/core/Snackbar";
// import {CONTACTAPI} from "../api/api";
function Contact() {
const [dialog, setDialoag] = useState(false);
const [contactData, setContactdata] = useState({
name: "",
email: "",
phone: "",
address: "",
district: "",
message: "",
});
const [alert, setAlert] = useState({ showSnackbar: false, message: "" });
const [successDialouge, setSuccessDialouge] = useState(false);
const closeDialog = () => {
setDialoag(false);
};
const closeSuccessDialouge = () => {
setSuccessDialouge(false);
};
const closeSnack = () => {
setAlert({
showSnackbar: false,
});
};
const submitContact = async (e) => {
e.preventDefault();
if (contactData.name === "") {
setAlert({
showSnackbar: true,
message: "Please enter your name",
});
} else if (contactData.email === "") {
setAlert({
showSnackbar: true,
message: "Please enter your email",
});
} else if (contactData.phone === "") {
setAlert({
showSnackbar: true,
message: "Please enter your phone number",
});
} else if (contactData.district === "") {
setAlert({
showSnackbar: true,
message: "Please enter your district",
});
} else if (contactData.message === "") {
setAlert({
showSnackbar: true,
message: "Please enter your message",
});
} else {
setDialoag(true);
const res = await fetch("/user/contact", {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
body: JSON.stringify(contactData),
});
const data = await res.json();
// console.log(data);
if (res.status === 422 || !data) {
window.alert("Oops something went wrong");
} else {
setDialoag(false);
setSuccessDialouge(true);
setContactdata({
name: "",
email: "",
phone: "",
address: "",
district: "",
message: "",
});
}
}
};
return (
<div className="contact">
<h2>Feel free to reach us</h2>
<form className="contact_from">
<input
type="text"
className="name"
placeholder="Enter your name"
value={contactData.name}
onChange={(e) =>
setContactdata({ ...contactData, name: e.target.value })
}
/>
<input
type="email"
className="email"
placeholder="Enter your email"
value={contactData.email}
onChange={(e) =>
setContactdata({ ...contactData, email: e.target.value })
}
/>
<input
type="phone"
className="phone"
placeholder="Enter your phone "
value={contactData.phone}
onChange={(e) =>
setContactdata({ ...contactData, phone: e.target.value })
}
/>
<input
type="text"
className="address"
placeholder="Enter your Address "
value={contactData.address}
onChange={(e) =>
setContactdata({ ...contactData, address: e.target.value })
}
/>
<input
type="text"
className="dist"
placeholder="Enter your District "
value={contactData.district}
onChange={(e) =>
setContactdata({ ...contactData, district: e.target.value })
}
/>
<textarea
className="message"
placeholder="Type your Message "
value={contactData.message}
onChange={(e) =>
setContactdata({ ...contactData, message: e.target.value })
}
/>
<Button
variant="contained"
color="secondary"
id="submit_btn"
onClick={submitContact}
>
Submit
</Button>
</form>
<Snackbar
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
open={alert.showSnackbar}
message={alert.message}
autoHideDuration={3000}
onClose={closeSnack}
/>
<Dialog open={dialog} onClose={closeDialog}>
<DialogContent>
<DialogContentText id="alert-dialog-description">
<CircularProgress color="secondary" />
<p style={{ fontFamily: "cursive", color: "blue" }}>Wait..</p>
</DialogContentText>
</DialogContent>
</Dialog>
<Dialog open={successDialouge}>
<DialogContent color="black">
<DialogContentText id="alert-dialog-description">
<CancelIcon
style={{
marginLeft: "12vw",
fontSize: "1.8rem",
marginBottom: "1vh",
}}
onClick={closeSuccessDialouge}
/>
<p
style={{
fontFamily: "cursive",
color: "blue",
fontSize: "1.1rem",
}}
>
Request sent Successfylly
<br />
We will get back to you shortly
</p>
<CheckCircleOutlineIcon
style={{
fontSize: "3rem",
color: "blue",
marginLeft: "5.5vw",
marginTop: "1.5vh",
}}
/>
</DialogContentText>
</DialogContent>
</Dialog>
<Footer />
</div>
);
}
export default Contact;
|
let content = document.getElementById('content');
let gallery = document.getElementById('gallery');
let searchReq;
let requestedPhotos = [];
const SEARCH_ADDRESS = ' https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key';
const API_KEY = '...'; //removed key, requests wont work without it. create and use own key for testing
let searchWord = getRequestedName();
searchForPhotos(searchWord);
/**
* Retreives searched by user word string from page adress.
* @returns text searched by user
*/
function getRequestedName() {
let searched = window.location.search;
searched = searched.substr(searched.indexOf('=') + 1);
return searched;
}
/**
* When search form is submited this method runs search for photos on Flickr.
* @param {string} word - is searched word that will be queried on Flickr
*/
function searchForPhotos(word) {
if (!word) {
gallery.innerHTML = 'Could not retreive any photos from Flickr.';
return;
} else {
gallery.innerHTML = 'Loading...';
}
let request = `${SEARCH_ADDRESS}=${API_KEY}&text=${word}&format=json&nojsoncallback=1&extras=url_s`;
searchReq = new XMLHttpRequest();
searchReq.onreadystatechange = function () { onSearchDone(searchReq) };
searchReq.open('GET', request, true);
searchReq.send();
}
/**
* When XMLHttpRequest for list of photos has been fullfilled this method checks
* the result. If result is OK then a gallery of found photos will be shown to user.
* @param {XMLHttpRequest} xmlhttpr - is search request to be checked for status
*/
function onSearchDone(xmlhttpr) {
if (xmlhttpr.readyState == XMLHttpRequest.DONE) {
if (xmlhttpr.status == 200) {
this.requestedPhotos = decodeJSONPhotos(xmlhttpr.responseText);
displayPhotos(this.requestedPhotos);
}
else {
alert('Error, could not retreive list of photos: status ' + xmlhttpr.status);
}
}
}
/**
* Decodes jsonString result from Flickr gallery search request to array of Photo objects
* which is then returned.
* @param {string} jsonString - is string formatted photo gallery response from Flickr server
* @returns an array of Photo objects to be shown to user in gallery
*/
function decodeJSONPhotos(jsonString) {
let jsonObj = JSON.parse(jsonString);
let photoArray = jsonObj.photos.photo;
let photos = [];
if (photoArray) {
for (let i in photoArray) {
let jsonPhoto = photoArray[i];
let id = jsonPhoto.id;
let urlS = jsonPhoto.url_s;
if (id && urlS) {
let photo = new Photo(id, urlS);
photo.img = createImgElement('', '', photo.urlS, id);
photos.push(photo);
}
}
}
return photos;
}
/**
* Takes list of Photo objects and displays them to user by appending child
* elements with photos. If list is empty user will be informed that there
* are no photos to show.
* @param {array} photos - list of Photo objects to be shown
*/
function displayPhotos(photos) {
gallery.innerHTML = '';
if (photos.length < 1) {
gallery.innerHTML = 'No photos were found for ' + searchWord;
return;
}
for (let photo of photos) {
gallery.appendChild(photo.img);
}
}
/**
* Class Photo is used as container of photo information to be
* shown to user.
* @constructor
* @param {string} id is photos id on Flickr
* @param {string} urlS is photos url on Flickr
*/
class Photo {
constructor(id, urlS) {
this.urlS = urlS;
this.id = id;
this.img = null;
this.urlO = null;
}
toString() {
return `id: ${this.id}, urlS: ${this.urlS}, urlO:${this.urlO}, a: ${this.img} `;
}
}
/**
* Creates img element contained in div and a elements which enable prettier
* display of that element in DOM.
* @param {string} text - is thext to be added in node
* @param {string} alt - is alternative text to picture
* @param {string} refUrl - is url to photo to be used by img
* @returns returns div element containing a element with img element in it
*/
function createImgElement(text, alt, refUrl, id) {
let img = new Image();
let linkText = document.createTextNode(text);
img.appendChild(linkText);
img.alt = alt;
img.src = refUrl;
let a = document.createElement('a');
a.href = 'editor.html?search=' + id;
a.appendChild(img);
let div = document.createElement('div');
div.className = 'photo';
div.appendChild(a);
return div;
}
|
import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import NavBar from './NavBar.js';
import Footer from './Footer.js';
import NewsUserContainer from './containers/NewsUserContainer.js';
import ArticleDetails from './components/ArticleDetails.js';
import './App.css';
class App extends Component {
render() {
return (
<Router>
<React.Fragment>
<NavBar/>
<Switch>
<Route exact path="/home" component ={NewsUserContainer} />
<Route exact path="/articles/:id" render = {(props) => {
const url = "/articles/" + props.match.params.id;
return <ArticleDetails url={url} />
}}/>
<Route exact path="/articles/category/:category" render = {(props) => {
const url = props.match.url
return <ArticleDetails url={url} />
}}/>
</Switch>
<Footer/>
</React.Fragment>
</Router>
)
}
}
export default App;
|
let ism = prompt("Ismingizni kiriting :");
let conf = confirm(` Assalomu alaykum ${ism} ! \n Siz 0 dan 20 gacha bo'lgan sonlarni kiritishigiz kerak va siz o'yagan son \n men o'ylagan songa teng bo'lsa g'olib bo'lasiz \n O'yinni boshlashga tayyormisiz ?`);
let sonlar_toplami = [];
let kiritilgan_sonlar;
let oyna = document.querySelector("#son");
let urinish = document.querySelector("#urinishlar");
let random = Math.floor(Math.random() * 20 + 1);
let a = 5;
for (let i = 0; i < 20; i++) {
kiritilgan_sonlar = Number(prompt("O`ylagan soningizni kiriting: "));
sonlar_toplami.push(kiritilgan_sonlar);
if (random === kiritilgan_sonlar || kiritilgan_sonlar === a) {
alert(
`Siz g'olibsiz, siz ${sonlar_toplami.length} chi urunishda meni mag'lub etdingiz `
);
break;
} else if(random > kiritilgan_sonlar){
alert("Men o`ylagan son bundan kattaroq edi, qayta urinib ko`ring");
} else if (random < kiritilgan_sonlar){
alert("Men o`ylagan son bundan kichikroq edi, qayta urinib ko`ring");
}
// console.log(sonlar_toplami);
// console.log(sonlar_toplami.length);
}
oyna.textContent = sonlar_toplami;
urinish.textContent = sonlar_toplami.length; |
module.exports = {
rootDir: 'src',
testEnvironment: 'jsdom',
transform: {
'^.+\\.(j|t)sx?$': 'babel-jest',
},
moduleNameMapper: {
'\\.(css)$': 'identity-obj-proxy',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.ts',
'single-spa-react/parcel': 'single-spa-react/lib/cjs/parcel.cjs',
},
setupFilesAfterEnv: ['@testing-library/jest-dom'],
};
|
import {create} from '../gl-mat3/create'
import {from_mat3} from './from_mat3.js'
import {normalize} from './normalize.js'
var matr = create()
/**
* Sets the specified quaternion with values corresponding to the given
* axes. Each axis is a vec3 and is expected to be unit length and
* perpendicular to all other specified axes.
*
* @param {vec3} view the vector representing the viewing direction
* @param {vec3} right the vector representing the local "right" direction
* @param {vec3} up the vector representing the local "up" direction
* @returns {quat} out
*/
export function set_axes (out, view, right, up) {
matr[0] = right[0]
matr[3] = right[1]
matr[6] = right[2]
matr[1] = up[0]
matr[4] = up[1]
matr[7] = up[2]
matr[2] = -view[0]
matr[5] = -view[1]
matr[8] = -view[2]
return normalize(out, from_mat3(out, matr))
}
|
function say (name){
console.log('hello '+name);
}
function excute(fun,value){
fun(value);
}
excute(say,"Jully");
|
import React from 'react';
const success = () => {
return (
<div className="text-center">
<p className="center-block">
<h3>Congratulations! You are now registered for the Crawfish Cup Pickleball Tournament.</h3> <br />
<h3>You should expect to receive an emailed receipt shortly confirming your registration. </h3> <br />
<h3>If you do not receive an emailed receipt you may email kyle.savant@outlook.com for confirmation. </h3> <br />
<h3>Thank you and we look forward to seeing you on the courts!</h3>
</p>
</div>
);
}
export default success; |
import React, { Fragment } from 'react'
import { compose } from 'recompose'
import { connect } from 'react-redux'
import { Helmet } from 'react-helmet'
import { NavLink, Link, withRouter } from 'react-router-dom'
import { Icon, Button } from 'semantic-ui-react'
import Panel from './../../components/Panel'
import './InsightsLayout.css'
const isShowedNewInsightsButton = (history, isLogin) => (
isLogin &&
(!history.location.pathname.startsWith('/insights/new') ||
history.location.pathname === '/insights/newest')
)
const NewInsightBtn = ({history, disabled}) => (
<Button
disabled={disabled}
color='green'
onClick={() => history.push('/insights/new')}>
<Icon name='plus' />New insight
</Button>
)
const InsightsLayout = ({
isLogin = false,
title = 'SANbase: Insights',
sidebar = null,
loginModalRequest,
history,
children,
hasUsername
}) => (
<div className='page event-votes insights-page'>
<Helmet>
<title>{title}</title>
</Helmet>
<div className='insights-page-rows'>
<div className='insights-page-navs'>
<h2>Insights</h2>
<div className='event-votes-navs-list'>
{isLogin && <NavLink
to={'/insights/my'}>
My Insights
</NavLink>}
<NavLink
to={'/insights'}>
All Insights
</NavLink>
<br />
{isShowedNewInsightsButton(history, isLogin) &&
<NewInsightBtn
isLogin={isLogin}
loginModalRequest={loginModalRequest}
history={history}
disabled={!hasUsername}
/>}
</div>
</div>
<div className='insights-page-content'>
{children}
</div>
<div className='insights-page-sidebar'>
{sidebar && sidebar}
{!sidebar &&
<Fragment>
{isLogin && <div className='insights-page-sidebar-highlights'>
<div>
<Link to={'/insights/33'}>How to use Insights: Traders/Investors</Link>
</div>
<div>
<Link to={'/insights/34'}>How to use Insights: Researchers</Link>
</div>
</div>}
<Panel>
<div className='cta-subscription'>
<span className=''>Get new signals/insights about crypto in your inbox, every day</span>
<div id='mc_embed_signup'>
<form action='//santiment.us14.list-manage.com/subscribe/post?u=122a728fd98df22b204fa533c&id=80b55fcb45' method='post' id='mc-embedded-subscribe-form' name='mc-embedded-subscribe-form' className='validate' target='_blank'>
<div id='mc_embed_signup_scroll'>
<input type='email' defaultValue='' name='EMAIL' className='email' id='mce-EMAIL' placeholder='Your email address' required />
<div className='hidden-xs-up' aria-hidden='true'>
<input type='text' name='b_122a728fd98df22b204fa533c_80b55fcb45' tabIndex='-1' value='' />
</div>
<div className='clear'>
<input type='submit' value='Subscribe' name='subscribe' id='mc-embedded-subscribe' className='button' />
</div>
</div>
</form>
</div>
</div>
</Panel>
</Fragment>}
</div>
</div>
</div>
)
const mapStateToProps = state => ({
hasUsername: !!state.user.data.username
})
const mapDispatchToProps = dispatch => {
return {
loginModalRequest: () => {
dispatch({
type: 'TOGGLE_LOGIN_REQUEST_MODAL'
})
}
}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
withRouter
)(InsightsLayout)
|
import Reflux from 'reflux';
const OrgActions = Reflux.createActions([
'loadRepos',
'stopPolling'
]);
export default OrgActions;
|
import Request from './_request'
const req = new Request('/gcfsUserInfo/')
//用户列表
async function list(param) {
return await req.post('listPage', param)
}
//用户详情
async function detail(param) {
return await req.post('listPage', param)
}
//保存用户
async function save(param) {
return await req.post('listPage', param)
}
//更新用户
async function update(param) {
return await req.post('listPage', param)
}
export default {
list,
detail,
save,
update
} |
import CheckInButton from "./CheckInButton";
import locale from "./locale";
import "./CheckIn.css";
const CheckIn = ({ onAddCheckIn, areCheckInsVisible, onToggleCheckIns }) => (
<div className="checkIn">
<h1>{locale.checkInHeading()}</h1>
<p className="howAreYouFeeling">{locale.checkInSubheading()}</p>
<div>
<CheckInButton mood={1} emoji="😢" onClick={() => onAddCheckIn(1)} />
<CheckInButton mood={2} emoji="🙁" onClick={() => onAddCheckIn(2)} />
<CheckInButton mood={3} emoji="😐" onClick={() => onAddCheckIn(3)} />
<CheckInButton mood={4} emoji="😊" onClick={() => onAddCheckIn(4)} />
<CheckInButton mood={5} emoji="🤩" onClick={() => onAddCheckIn(5)} />
</div>
{areCheckInsVisible ? (
<button
data-test-id="hideCheckIns"
className="toggleCheckIns"
onClick={onToggleCheckIns}
>
{locale.hideCheckIns()}
</button>
) : (
<button
data-test-id="showCheckIns"
className="toggleCheckIns"
onClick={onToggleCheckIns}
>
{locale.showCheckIns()}
</button>
)}
</div>
);
export default CheckIn;
|
#!/usr/bin/env node
'use strict';
process.env.NODE_PATH = __dirname + './../node_modules/';
const program = require('commander');
const updateNotifier = require('update-notifier');
const chalk = require('chalk');
const pkg = require('../package.json');
// 新版本更新提醒
updateNotifier({ pkg, updateCheckInterval: 0 }).notify();
// 定义当前版本
program.version(pkg.version);
// 定义使用方法
program.usage('<command>');
program
.command('add')
.description('添加一个新模板到扩展库')
.alias('a')
.action(() => {
require('../command/add')();
});
program
.command('-l')
.description('展示模板列表')
.alias('l')
.action(() => {
require('../command/list')();
});
program
.command('init')
.description('创建一个基于模板的项目')
.alias('i')
.action(() => {
require('../command/init')();
});
program
.command('delete')
.description('删除一个扩展库模板')
.alias('d')
.action(() => {
require('../command/delete')();
});
program
.command('start')
.description('运行项目')
.action(() => {
require('../command/start')();
});
program
.command('build')
.description('打包项目')
.option('-d, --debug <key>')
.option('-a, --archive [name]', '打包', './../command/build.js')
.action(() => {
require('../command/build')();
});
program
.command('test')
.description('测试')
.action(() => {
require('../command/test')();
});
program.on('--help', function() {
console.log('');
console.log('');
console.log(chalk.yellow('使用规则:'));
console.log('');
console.log(chalk.grey(' #添加一个新模板到扩展库'));
console.log(chalk.green(' $omycli add 或者使用快捷方式 $omycli a'));
console.log('');
console.log(chalk.grey(' #展示模板列表'));
console.log(chalk.green(' $omycli list 或者使用快捷方式 $omycli l'));
console.log('');
console.log(chalk.grey(' #创建一个基于模板的项目'));
console.log(chalk.green(' $omycli init 或者使用快捷方式 $omycli i'));
console.log('');
console.log(chalk.grey(' #查看 output 配置项'));
console.log(chalk.green(' $omycli build -d "output"'));
console.log('');
console.log(chalk.grey(' #查看整个配置'));
console.log(chalk.green(' $omycli build -d "."'));
console.log('');
console.log(chalk.grey(' #生成 dist.zip'));
console.log(chalk.green(' $omycli build -a'));
console.log('');
console.log(chalk.grey(' #生成 build.tar'));
console.log(chalk.green(' $omycli build -a build.tar'));
console.log('');
console.log('-------------------------');
console.log(chalk.red(' 慎用!!!'));
console.log(chalk.grey(' #删除一个扩展库模板'));
console.log(chalk.green(' $omycli delete 或者使用快捷方式 $omycli d'));
console.log('-------------------------');
console.log('');
});
program.parse(process.argv);
if (!program.runningCommand && !program.args[0]) {
console.log('');
console.log(' 未知的命令: ' + program.args.join(' '));
console.log('');
console.log(' 查看命令帮助,请输入:`omycli --help`');
console.log('');
return false
}
|
const CCDCaseField = require('./CCDCaseField');
const configTemplate = {
'id': 'FR_solicitorCreate',
'name': 'EXUI Test CaseType',
'description': 'Create an application for EXUI Test Casetype 1',
'case_id': null,
'case_fields': [],
'event_token': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJpcTlxNWs5NW85cWllNTk5NnU1MmEyNGhqYiIsInN1YiI6IjQxYTkwYzM5LWQ3NTYtNGViYS04ZTg1LTViNWJmNTZiMzFmNSIsImlhdCI6MTU5NjU0NzA2NSwiZXZlbnQtaWQiOiJGUl9zb2xpY2l0b3JDcmVhdGUiLCJjYXNlLXR5cGUtaWQiOiJGaW5hbmNpYWxSZW1lZHlDb250ZXN0ZWQiLCJqdXJpc2RpY3Rpb24taWQiOiJESVZPUkNFIiwiY2FzZS12ZXJzaW9uIjoiYmYyMWE5ZThmYmM1YTM4NDZmYjA1YjRmYTA4NTllMDkxN2IyMjAyZiJ9.QXtddQWsWbl8H8tKvM-SViK-E9JrFeU6bS0wlt5eJ0o',
'wizard_pages': [],
'show_summary': true,
'show_event_notes': false,
'end_button_label': null,
'can_save_draft': null,
'_links': {
'self': {
'href': 'http://gateway-ccd.aat.platform.hmcts.net/internal/case-types/FinancialRemedyContested/event-triggers/FR_solicitorCreate?ignore-warning=false'
}
}
};
const wizardPageTemplate = {
'id': 'page1',
'label': null,
'order': 1,
'wizard_page_fields': [],
'show_condition': null,
'callback_url_mid_event': 'http://finrem-cos-aat.service.core-compute-aat.internal/case-orchestration/contested/set-defaults',
'retries_timeout_mid_event': []
};
class CCDCaseConfig extends CCDCaseField {
caseConfigTemplate = JSON.parse(JSON.stringify(configTemplate));
constructor(id, name, description) {
super();
this.caseConfigTemplate.id = id;
this.caseConfigTemplate.name = name;
this.caseConfigTemplate.description = description;
this.currentWizardPage = null;
this.currentCaseField = null;
this.currentComplexField = null;
this.currentCollectionField = null;
}
addWizardPage(id, label) {
let wizardPage = JSON.parse(JSON.stringify(wizardPageTemplate));
wizardPage.id = id;
wizardPage.label = label;
wizardPage.order = this.caseConfigTemplate.wizard_pages.length;
this.caseConfigTemplate.wizard_pages.push(wizardPage);
this.currentWizardPage = wizardPage;
this.currentCaseField = null;
return this;
}
addCCDFieldToPage(wizardPage, fieldConfig) {
const ccdField = this.getCCDFieldTemplateCopy(fieldConfig);
this.caseConfigTemplate.case_fields.push(ccdField);
wizardPage.wizard_page_fields.push({
'case_field_id': fieldConfig.id,
'order': wizardPage.wizard_page_fields.length,
'page_column_no': 1,
'complex_field_overrides': []
});
return ccdField;
};
addCaseField(fieldConfig) {
if (!this.currentWizardPage) {
throw new Error('No wizard page added. Add a wizard page before adding case field');
}
const ccdField = this.getCCDFieldTemplateCopy(fieldConfig);
if (ccdField.field_type.type === 'Complex') {
ccdField.display_context = 'COMPLEX';
this.currentComplexField = ccdField;
this.currentCollectionField = null;
} else if (ccdField.field_type.type === 'Collection') {
this.currentComplexField = null;
this.currentCollectionField = ccdField;
} else {
this.currentComplexField = null;
this.currentCollectionField = null;
}
this.caseConfigTemplate.case_fields.push(ccdField);
this.currentWizardPage.wizard_page_fields.push({
'case_field_id': ccdField.id,
'order': this.currentWizardPage.wizard_page_fields.length,
'page_column_no': 1,
'complex_field_overrides': []
});
this.currentCaseField = ccdField;
return this;
}
setComplexField(fieldConfig) {
this.currentComplexField.field_type.complex_fields.push(his.getCCDFieldTemplateCopy(fieldConfig));
return this;
}
setEventProps(fieldprops) {
this.setObjectProps(this.caseConfigTemplate, fieldprops);
return this;
}
updateEventProps(fieldprops) {
this.setObjectProps(this.caseConfigTemplate, fieldprops);
return this;
}
setFieldProps(fieldprops) {
this.checkPageAndFiedlSet();
this.setObjectProps(this.currentCaseField, fieldprops);
return this;
}
setFieldPropsForField(fieldConfig, fieldprops) {
this.setObjectProps(fieldConfig, fieldprops);
return this;
}
updateFieldProps(fieldId, fieldprops) {
const fieldStructure = fieldId.split('.');
let fieldConfig = this.getCaseFieldConfig(fieldStructure[0]);
for (let i = 1; i < fieldStructure.length; i++) {
if (fieldConfig.field_type.type === 'Complex') {
for (let complexFieldCtr = 0; complexFieldCtr < fieldConfig.field_type.complex_fields.length; complexFieldCtr++) {
let complexFieldElement = fieldConfig.field_type.complex_fields[complexFieldCtr];
if (complexFieldElement.id === fieldStructure[i]) {
fieldConfig = complexFieldElement;
break;
}
}
} else if (fieldConfig.field_type.type === 'Collection') {
fieldConfig = fieldConfig.field_type.collection_field_type;
}
};
this.setObjectProps(fieldConfig, fieldprops);
return this;
}
setFieldTypeProps(fieldTypeprops) {
this.checkPageAndFiedlSet();
this.setObjectProps(this.currentCaseField.field_type, fieldTypeprops);
return this;
}
updateFieldTypeProps(fieldId, fieldTypeprops) {
const fieldStructure = fieldId.split('.');
let fieldConfig = this.getCaseFieldConfig(fieldStructure[0]);
for (let i = 1; i < fieldStructure.length; i++) {
if (fieldConfig.field_type.type === 'Complex') {
for (let complexFieldCtr = 0; complexFieldCtr < fieldConfig.field_type.complex_fields.length; complexFieldCtr++) {
let complexFieldElement = fieldConfig.field_type.complex_fields[complexFieldCtr];
if (complexFieldElement.id === fieldStructure[i]) {
fieldConfig = complexFieldElement;
break;
}
}
} else if (fieldConfig.field_type.type === 'Collection') {
fieldConfig = fieldConfig.field_type.collection_field_type;
}
};
this.setObjectProps(fieldConfig.field_type, fieldTypeprops);
return this;
}
setFixedListItems(fieldId, fieldListItems) {
const fieldStructure = fieldId.split('.');
let fieldConfig = this.getCaseFieldConfig(fieldStructure[0]);
for (let i = 1; i < fieldStructure.length; i++) {
if (fieldConfig.field_type.type === 'Complex') {
for (let complexFieldCtr = 0; complexFieldCtr < fieldConfig.field_type.complex_fields.length; complexFieldCtr++) {
let complexFieldElement = fieldConfig.field_type.complex_fields[complexFieldCtr];
if (complexFieldElement.id === fieldStructure[i]) {
fieldConfig = complexFieldElement;
break;
}
}
} else if (fieldConfig.field_type.type === 'Collection') {
fieldConfig = fieldConfig.field_type.collection_field_type;
}
};
fieldConfig.field_type.fixed_list_items = fieldListItems;
return this;
}
checkPageAndFiedlSet() {
if (!this.currentWizardPage) {
throw new Error('No wizard page added.');
}
if (!this.currentCaseField) {
throw new Error('No case field added.');
}
}
getCase() {
return this.caseConfigTemplate;
}
getWizardPageConfig(pageId) {
return this.caseConfigTemplate.wizard_pages.filter((wizardpage) => wizardpage.id === pageId)[0];
}
getCaseFieldConfig(caseFieldId) {
const fields = this.caseConfigTemplate.case_fields.filter((caseField) => caseField.id === caseFieldId);
if (fields.length === 0) {
const fieldsIds = this.caseConfigTemplate.case_fields.map((caseField) => caseField.id);
throw new Error(`Fields with id ${caseFieldId} not found in case event config fields: ${JSON.stringify(fieldsIds)}`);
}
return fields[0];
}
addComplexFieldOverridesToCaseField(caseFieldId, overrides) {
this.caseConfigTemplate.wizard_pages;
for (let i = 0; i < this.caseConfigTemplate.wizard_pages.length; i++) {
const wizardPage = this.caseConfigTemplate.wizard_pages[i];
for (let j = 0; j < wizardPage.wizard_page_fields.length; j++) {
const caseField = wizardPage.wizard_page_fields[j];
if (caseField.case_field_id === caseFieldId) {
for (let overridesCtr = 0; overridesCtr < overrides.length; overridesCtr++) {
let complexFieldOverride = {
'complex_field_element_id': '',
'display_context': '',
'label': null,
'hint_text': null,
'show_condition': '',
'retain_hidden_value': null
};
this.setObjectProps(complexFieldOverride, overrides[overridesCtr]);
caseField.complex_field_overrides.push(complexFieldOverride);
}
}
}
}
}
setCaseFieldValue(fieldId, value) {
const fieldStructure = fieldId.split('.');
let fieldConfig = this.getCaseFieldConfig(fieldStructure[0]);
let caseFieldValue = fieldConfig.value;
let fieldValTracker = caseFieldValue;
if (fieldStructure.length === 1) {
fieldConfig.value = value;
} else {
}
for (let i = 1; i < fieldStructure.length; i++) {
fieldConfig = fieldConfig.field_type.complex_fields.filter((complexField) => complexField.id === fieldStructure[i])[0];
if (fieldConfig.field_type.type === 'Complex') {
fieldValTracker = fieldValTracker[fieldStructure[i]];
} else if (fieldConfig.field_type.type === 'Collection') {
var myRegexp = /(?:^|\s)[(.*?)(?:\n|$)]/g;
var match = myRegexp.exec(fieldStructure[i]);
while (fieldValTracker.length === parseInt(match) + 1) {
const collectionFieldType = { id: '', label: '', field_type: fieldConfig.field_type.collection_field_type };
fieldValTracker.push(this.getFieldValue(collectionFieldType));
}
fieldValTracker = fieldValTracker[parseInt(match)];
fieldConfig = collectionFieldType;
} else {
fieldValTracker[fieldStructure[i]] = value;
}
}
}
getCaseFieldDefaultValue(fieldId) {
const fieldConfig = this.getCaseFieldConfig(fieldId);
return this.getFieldValue(fieldConfig);
}
getFieldValue(fieldConfig) {
let fieldVal = null;
if (fieldConfig.field_type.type === 'Collection') {
fieldVal = [];
const collectionFieldType = { id: '', label: '', field_type: fieldConfig.field_type.collection_field_type };
fieldVal.push(this.getFieldValue(collectionFieldType));
}
if (fieldConfig.field_type.type === 'Complex') {
fieldVal = {};
const complexFields = fieldConfig.field_type.complex_fields;
for (let i = 0; i < complexFields.length; i++) {
fieldVal[complexFields[i].id] = this.getFieldValue(complexFields[i]);
}
} else {
fieldVal = this.getFieldTypeMockValue(fieldConfig);
}
return fieldVal;
}
getFieldTypeMockValue(fieldConfig) {
let value = null;
switch (fieldConfig.field_type.type) {
case 'Text':
case 'TextArea':
value = 'test ' + fieldConfig.label;
break;
case 'Postcode':
value = 'SW1 2AB';
break;
case 'Number':
value = 10;
break;
case 'YesOrNo':
value = true;
break;
case 'Email':
value = fieldConfig.id + '.test@test.com';
break;
case 'PhoneUK':
value = '07123456789';
break;
case 'Date':
case 'DateTime':
value = '2021-04-15T22:21:30.000Z';
break;
case 'MoneyGBP':
value = 10000;
break;
case 'DynamicList':
value = { value: this.getDummyListItems()[0], list_items: this.getDummyListItems() };
break;
case 'FixedList':
case 'FixedRadioList':
value = fieldConfig.field_type.fixed_list_items[0];
break;
case 'MultiSelectList':
value = [fieldConfig.field_type.fixed_list_items[0], fieldConfig.field_type.fixed_list_items[1]];
break;
case 'Document':
value = {};
break;
}
return value;
}
getDummyListItems() {
const listItems = [];
listItems.push({ code: 'item1', value: 'Item 1' });
listItems.push({ code: 'item2', value: 'Item 2' });
listItems.push({ code: 'item3', value: 'Item 3' });
return listItems;
}
getInputFieldConfig(caseFieldConfig, inputFieldPathArr) {
let fieldConfig = caseFieldConfig;
for (let i = 1; i < inputFieldPathArr.length; i++) {
let childFieldId = inputFieldPathArr[i];
let thisFieldType = fieldConfig.field_type ? fieldConfig.field_type.type : fieldConfig.type;
if (thisFieldType === 'Complex') {
let complexFields = fieldConfig.field_type ? fieldConfig.field_type.complex_fields : fieldConfig.complex_fields;
fieldConfig = complexFields.filter((complexField) => complexField.id === childFieldId)[0];
} else if (thisFieldType === 'Collection') {
let colletionField = fieldConfig.field_type ? fieldConfig.field_type.collection_field_type : fieldConfig.collection_field_type;
fieldConfig = colletionField;
} else {
fieldConfig = fieldConfig;
}
}
return fieldConfig;
}
}
module.exports = CCDCaseConfig;
|
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';
import path from 'path';
import classNames from 'classnames';
var ROOT_PATH = path.resolve(__dirname);
class Photo extends React.Component {
constructor(props) {
super(props);
this.state = {actived: false};
}
handleClick(){
this.setState({actived: !this.state.actived});
}
render() {
return (
<div className='photo'>
<img src={this.props.src} className={this.state.actived? 'picactive' : this.props.fileName} onClick={this.handleClick.bind(this)}/>
</div>);
}
}
class PhotoGallery extends React.Component {
render() {
var photos = this.props.photos.map(function(photo,index) {
return <Photo key={index} src={photo.url} fileName={photo.fileName}/>
});
return (
<div className='photo-gallery'>
{photos}
</div>);
}
}
var data = [
{
fileName : 'pic1',
url:'image/1.jpg',
caption: 'Hong Kong!'
},
{
fileName : 'pic2',
url: 'image/2.jpg',
caption: 'Cows'
},
{
fileName : 'pic3',
url: 'image/3.jpg',
caption: 'Scooters'
},
{
fileName : 'pic4',
url: 'image/4.jpg',
caption: 'Scooters'
},
{
fileName : 'pic5',
url: 'image/5.jpg',
caption: 'Scooters'
},
{
fileName : 'pic6',
url: 'image/6.jpg',
caption: 'Scooters'
},
{
fileName : 'pic7',
url: 'image/7.jpg',
caption: 'Scooters'
},
{
fileName : 'pic8',
url: 'image/8.jpg',
caption: 'Scooters'
},
{
fileName : 'pic9',
url: 'image/9.jpg',
caption: 'Scooters'
},
{
fileName : 'pic10',
url: 'image/10.jpg',
caption: 'Scooters'
}
];
ReactDOM.render(<PhotoGallery photos={data} />, document.getElementById ('content')); |
import { setOwner } from '@ember/application';
import { lastObject } from '../../util/array';
import { oncePromise } from '../../util/once';
export default class File {
constructor(owner, { files, name, type }) {
setOwner(this, owner);
let components = name.split('/');
this.files = files;
this.name = name;
this.type = type;
this.filename = lastObject(components);
this.directory = components.slice(0, -1).join('/');
}
_load() {}
_metadata() {}
@oncePromise
async load() {
await this.files._loadModel(this);
return this;
}
}
|
$(document).ready(function(){
$("#dev-img").click(function(){
$("#dev-img").toggle();
$("#development").toggle();
});
$("#development").click(function(){
$("#development").slideUp();
$("#dev-img").slideDown();
});
});
$(document).ready(function(){
$("#design-img").click(function(){
$("#design-img").slideToggle();
$("#design").slideToggle();
});
$("#design").click(function(){
$("#design").slideUp();
$("#design-img").slideDown();
});
});
$(document).ready(function(){
$("#product-img").click(function(){
$("#product-img").toggle();
$("#product").toggle();
});
$("#product").click(function(){
$("#product").slideUp();
$("#product-img").slideDown();
});
});
$(document).ready(function(){
$('#contact form').submit(function (){
let name = $('input#name').val();
let email = $('input#email').val()
let message = $('input#message').val()
alert('Hello ' + name + ' we have received your message thank you for reaching out')
});
}) |
/**
* @doc function
* @name angularApp.controller:MainCtrl
*
* @decription Controller used to handle index view
*/
'use strict'
bankAppControllers.controller('MainCtrl', [function() {
var self = this;
self.test = true;
}]); |
import React, {PropTypes} from 'react';
import OrgContainer from '../components/org/orgContainer.jsx';
const Org = ({params}) => (
<div>
<OrgContainer params={params} />
</div>
);
Org.propTypes = {
params: PropTypes.object.isRequired
};
export default Org;
|
/*
* @akoenig/website
*
* Copyright(c) 2017 André König <andre.koenig@gmail.com>
* MIT Licensed
*
*/
/**
* @author André König <andre.koenig@gmail.com>
*
*/
import React from "react";
import Link from "gatsby-link";
import styled from "styled-components";
import { Github as GitHubIcon, Twitter as TwitterIcon } from "react-feather";
import { Email } from "../../shared/Email";
import { Social, SocialIcon, SocialLink } from "./Social";
const Wrapper = styled.footer`
background: #fff;
border-top: 1px solid rgba(0, 0, 0, 0.03);
font-size: 80%;
padding: 0.4em 0;
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
`;
const Content = styled.section`
align-items: center;
display: flex;
flex-direction: row;
justify-content: space-between;
margin: 0 auto;
max-width: 740px;
padding: 0 0.8rem;
`;
const Title = styled.section`
align-items: center;
display: flex;
margin: 0;
padding: 0;
`;
const Me = styled.strong`
font-size: 80%;
font-weight: 600;
display: inline-block;
margin-right: 0.4em;
align-self: flex-start;
`;
const Claim = styled.small``;
const Hire = styled.span`
border: 1px solid #f44336;
border-radius: 3px;
color: #f44336;
cursor: pointer;
font-size: 70%;
margin-left: 0.4rem;
padding: 0.2rem 0.4rem;
transition: background 0.2s ease-in-out, color 0.3s ease-in-out;
text-decoration: none;
&:hover {
background: #f44336;
color: #fff;
text-decoration: none;
}
@media (max-width: 390px) {
display: block;
background: #f44336;
color: #fff;
font-size: 0.8rem;
padding: 0.1rem 0;
margin: 0;
text-align: center;
}
`;
const Footer = () => (
<Wrapper>
<Content>
<Title>
<Me>André König</Me>
<Claim>
Freelance Software Architect & Engineer
<Email>
<Hire>Let's work together!</Hire>
</Email>
</Claim>
</Title>
<Social>
<SocialIcon>
<SocialLink href="https://github.com/akoenig">GitHub</SocialLink>
</SocialIcon>
<SocialIcon>
<SocialLink href="https://twitter.com/binarycereals">
Twitter
</SocialLink>
</SocialIcon>
<SocialIcon>
<SocialLink href="https://www.xing.com/profile/Andre_Koenig23/cv">
XING
</SocialLink>
</SocialIcon>
<SocialIcon>
<Link
to="/imprint"
style={{
color: "rgba(0, 0, 0, 0.3)",
outline: "none",
textDecoration: "none"
}}
activeStyle={{
color: "#f44336"
}}
>
Imprint
</Link>
</SocialIcon>
</Social>
</Content>
</Wrapper>
);
export { Footer };
|
import React, { memo, useState, useRef, useEffect } from 'react';
import Button from '@material-ui/core/Button';
import Input from '@material-ui/core/Input';
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
import User from '../user/user';
import './users.css';
import users from './users.json';
const Row = ({ index, style, userList, onClick, selectedUser }) => {
const [userId, { name, displayName }] = userList[index];
return (
<div
onClick={() => onClick({ userId, name, displayName })}
className={`${index % 2 ? 'listItemOdd' : 'listItemEven'} ${selectedUser && selectedUser.userId === userId ? 'isSelected' : ''}`}
style={style}
>
<div className='user'>
{displayName}<div className='userDetails'>({name}, {userId})</div>
</div>
</div>
);
};
const Users = memo(({ onGzFileClick }) => {
const userListRef = useRef();
const [selectedUser, setSelectedUser] = useState(null);
const [filter, setFilter] = useState('');
const userList = Object.entries(users)
.filter(([ userId, { name, displayName } ]) => {
return `${userId}${name}${displayName}`.toLowerCase().indexOf(filter) !== -1;
});
const _setFilter = (event) => {
setFilter(event.target.value);
};
const _onUserClick = (user) => {
setSelectedUser(user);
}
const _selectRandomuser = () => {
const index = Math.floor(Math.random() * userList.length);
const [userId, { name, displayName }] = userList[index]
setSelectedUser({ userId, name, displayName });
}
useEffect(() => {
if (selectedUser) {
userListRef.current.scrollTop = 0;
}
}, [selectedUser])
return (
<div className='userContainer'>
{selectedUser && (
<div ref={userListRef} style={{ width: '350px', maxHeight: '95vh', overflow: 'scroll' }}>
<Button
variant='outlined'
onClick={() => setSelectedUser(null)}
>
Close
</Button>
<User
userId={selectedUser.userId}
name={selectedUser.name}
displayName={selectedUser.displayName}
onClick={onGzFileClick}
/>
</div>
)}
<div style={{ width: '250px' }}>
<div className='filterInput'>
<Input placeholder='Filter users' onChange={_setFilter} value={filter} />
<Button
variant='outlined'
onClick={_selectRandomuser}
>
Random
</Button>
</div>
<AutoSizer>
{({ height }) => (
<FixedSizeList
className='userList'
width={250}
height={height - 55}
itemCount={userList.length}
itemSize={35}
>
{({ index, style }) => Row({ index, style, userList, onClick: _onUserClick, selectedUser })}
</FixedSizeList>
)}
</AutoSizer>
</div>
</div>
);
});
export default Users;
|
let warned = {};
function log(message, logLevel = 'warn') {
console[logLevel](message); // eslint-disable-line no-console
}
/**
* Custom prop type that logs a warning that a prop is being deprecated
* @param {propType} propType
* @param {string} message
*/
function deprecate(propType, message, logLevel = 'warn') {
function validate(props, propName, componentName, ...rest) {
if (props[propName] != null && process.env.NODE_ENV !== 'production') {
const warning = `Matchbox: Deprecated prop "${propName}" of "${componentName}"\n${message}`;
if (!warned[warning]) {
warned[warning] = true;
log(warning, logLevel);
return;
}
}
return propType(props, propName, componentName, ...rest);
}
validate.isRequired = propType.isRequired; // Fixes react-docgen false positive
return validate;
}
function resetWarned() {
warned = {};
}
deprecate.resetWarned = resetWarned;
export { deprecate };
|
import Vue from "vue";
import Router from "vue-router";
import Index from "./views/Index.vue";
import Landing from "./views/Landing.vue";
import Login from "./views/Login.vue";
import MainNavbar from "./layout/MainNavbar.vue";
import MainFooter from "./layout/MainFooter.vue";
import AdminNavbar from "./layout/AdminNavbar.vue";
import Admin from "./views/Admin.vue";
import Home from "./views/pages/Home.vue";
import Profile from "./views/pages/Profile.vue";
Vue.use(Router);
const router = new Router({
mode: "history",
routes: [
{
path: "/index",
name: "index",
components: { default: Index, header: MainNavbar, footer: MainFooter },
props: {
header: { colorOnScroll: 400 },
footer: { backgroundColor: "black" }
}
},
{
path: "/",
name: "admin",
redirect: "/home",
components: { default: Admin, header: AdminNavbar, footer: MainFooter },
props: {
header: { colorOnScroll: 400 },
footer: { backgroundColor: "black" }
},
children: [
{
path: "/home",
name: "home",
component: Home
},
{
path: "/profile",
name: "profile",
component: Profile
}
]
},
{
path: "/landing",
name: "landing",
components: { default: Landing, header: MainNavbar, footer: MainFooter },
props: {
header: { colorOnScroll: 400 },
footer: { backgroundColor: "black" }
}
},
{
path: "/login",
name: "login",
components: { default: Login, header: "", footer: MainFooter },
props: {
header: { colorOnScroll: 400 }
}
},
//redirect jika route tidak di temukan
{
path: "*",
redirect: "/login"
}
],
scrollBehavior: to => {
if (to.hash) {
return { selector: to.hash };
} else {
return { x: 0, y: 0 };
}
}
});
router.beforeEach((to, from, next) => {
if (to.name !== "login" && !localStorage.getItem("user"))
next({ name: "login" });
else if (to.name === "login" && localStorage.getItem("user"))
next({ name: "admin" });
else next();
});
export default router;
|
import { NOTIFICATION_CHAT } from '../constants';
const ActionNotificationChat = state => {
return {
type: NOTIFICATION_CHAT,
payload:state
};
};
export default ActionNotificationChat; |
$(()=>{
// afficherListePays();
// afficherInfoEtudiant();
});
function afficherInfoEtudiant(){
$('#natio_etudiant').css('display','none');
$.ajax({
url: '/',
type: 'POST',
data: {
action: 'get_etudiant'
},
success: function(response) {
$('#etudiant_date').attr("name","dateNaissanceaRenvoyer");
jsonToForm($('#formulaire_etudiant'), response);
$('#select_pays_etudiant option[value="'+$('#natio_etudiant').val()+'"]').attr('selected','selected');
},
error: function(e) {
console.log(e.message);
}
});
$('#etudiant_date').attr("name","dateNaissance");
};
$("#sauvegarder").on('click',function(){
$('input').css('border-color', '');
$('#error_nb_etud').css('display', 'none');
$('#error_tel').css('display', 'none');
$('#error_compte').css('display', 'none');
$('#success_save_etud').css('display', 'none');
$('#error_save_etud').css('display', 'none');
$('#error_code').css('display', 'none');
$('#error_nb_etud').text('Erreur format numérique : ');
$('#etudiant_date').attr("name","dateNaissance");
let nationalite = $('#select_pays_etudiant option:selected').val();
$('#natio_etudiant').val(""+nationalite+"");
let date_naissance = $('#formulaire_etudiant input[name=dateNaissance]').val();
let adresse = $('#formulaire_etudiant input[name=adresse]').val();
let tel = $('#formulaire_etudiant input[name=tel]').val();
let sexe = $('#formulaire_etudiant input[name=sexe_etudiant]:checked').val();
let statut = $('#formulaire_etudiant input[name=statut_etudiant]:checked').val();
let nbr_annee_etudes = $('#formulaire_etudiant input[name=nbrAnneesEtudes]').val();
let num_compte_bancaire = $('#formulaire_etudiant input[name=numCompteBancaire]').val();
let titulaire_compte = $('#formulaire_etudiant input[name=titulaireCompte]').val();
let banque = $('#formulaire_etudiant input[name=nomBanque]').val();
let code_bic = $('#formulaire_etudiant input[name=codeBic]').val();
let departement = $('#formulaire_etudiant input[name=departement]').val();
let numero = $('#formulaire_etudiant input[name=numero]').val();
let code_postal = $('#formulaire_etudiant input[name=codePostal]').val();
let stop = false;
let etud={statut:statut,adresse:adresse,sexe:sexe,
numCompteBancaire:num_compte_bancaire,titulaireCompte:titulaire_compte,nomBanque:banque,codeBic:code_bic,departement:departement,codePostal:code_postal,nationalite:nationalite};
try{
if(nbr_annee_etudes === '' || nbr_annee_etudes < 0){
throw 'error_nb';
}
etud.nbrAnneesEtudes = nbr_annee_etudes;
}
catch(error){
if(error === "error_nb"){
$("#formulaire_etudiant input[name=nbrAnneesEtudes]").css("border-color", "red");
$('#error_nb_etud').css('display', 'block');
$('#error_nb_etud').append('Nombre années d\'études | ');
}
stop = true;
}
try{
if(numero === '' || numero < 0){
throw 'error_num';
}
etud.numero = numero;
}
catch(error){
if(error === "error_num"){
$("#formulaire_etudiant input[name=numero]").css("border-color", "red");
$('#error_nb_etud').css('display', 'block');
$('#error_nb_etud').append('Numéro');
}
stop = true;
}
try{
console.log('tel'+tel);
if(!tel.match(eval('/^[+]?\\d{9,10}$/')) && tel !== ''){
throw 'error_tel';
}
etud.tel = tel;
}
catch(error){
if(error === "error_tel"){
$("#formulaire_etudiant input[name=tel]").css("border-color", "red");
$('#error_tel').css('display', 'block');
}
stop = true;
}
try{
console.log(num_compte_bancaire);
if(!num_compte_bancaire.match(eval('/^[A-Z]{2}[0-9]{2}\\s?[0-9]{4}\\s?[0-9]{4}\\s?[0-9]{4}$/')) && num_compte_bancaire != ''){
throw 'error_compte';
}
}
catch(error){
if(error === "error_tel"){
$("#formulaire_etudiant input[name=tel]").css("border-color", "red");
$('#error_tel').css('display', 'block');
}
stop = true;
}
try{
if(!code_bic.match(eval('/^[A-Z]{8}$/')) && code_bic !== ''){
throw 'error_code';
}
}
catch(error){
if(error === 'error_code'){
$("#formulaire_etudiant input[name=codeBic]").css("border-color", "red");
$('#error_code').css('display', 'block');
}
stop = true;
}
if(stop){
return;
}
let json=JSON.stringify(etud);
$.ajax({
url: '/',
type: 'POST',
data: {
action: 'save_info',
json:json,
date_naissance: date_naissance
},
success: function(response) {
afficherInfoEtudiant();
$('#success_save_etud').css('background-color', 'green');
$('#success_save_etud').css('display', 'block');
},
error: function(error) {
if(error.responseText === 'ko_save_etud'){
$('#error_save_etud').css('display', 'block');
}
}
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.