text stringlengths 7 3.69M |
|---|
import AppCore from 'comptechsoft-app-starter'
export default {
methods: {
init()
{
this.dt = new AppCore.DatatableManager('dt-teams', this.model, this)
this.dt.addFilter('company_id', {
value: this.company.id,
where: 'teams.company_id = [value]'
})
this.dt.populate()
this.fm = new AppCore.ActionFormManager('team-form', this)
}
},
mounted() {
let i = setInterval(() => {
if( this.company )
{
clearInterval(i)
this.init()
}
}, 10)
},
} |
import React, { Component } from 'react';
import Intro from './Intro'
class Intros extends Component {
state = {
intros:[{background:'firstIntro',
title:'Who are We?',
intro:'Ever since its inception in 2015, with a commitment to deliver value-based technology consulting & software development services, CodeBlock Technologies has gained momentum to emerge as a driving force in all of its target market We pride in having an exquisite bench strength with the right combination of seasoned IT professionals to deliver best-in-class enterprise-grade software.',
body:'firstIntroBody',
},{background:'secondIntro',
title:'Technology Partners',
intro:'Over the years, we’ve set benchmark standards in cloud technologies and serverless architecture that helps us optimise Infrastructure cost and maximise process ROI.',
body:'secondIntroBody',
}]
}
render() {
return (
<React.Fragment>
<div className='intr'>
{this.state.intros.map(intro=>(
<Intro intro={intro} />
))}
</div>
</React.Fragment>
);
}
}
export default Intros; |
import React from "react";
import {
Flex,
Button,
FormControl,
FormLabel,
Input,
Heading,
Image,
Text,
Spinner,
useMediaQuery,
} from "@chakra-ui/react";
import { useHistory } from "react-router-dom";
import { Link } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHome } from "@fortawesome/free-solid-svg-icons";
import { register } from "../data/api";
import applicationColors from "../style/colors";
const Register = () => {
let history = useHistory();
const [name, setName] = React.useState("");
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState(null);
// Media Queries
const [breakpoint1400] = useMediaQuery("(max-width: 1200px)");
const [breakpoint1200] = useMediaQuery("(max-width: 1200px)");
const [breakpoint1000] = useMediaQuery("(max-width: 1000px)");
const [breakpoint800] = useMediaQuery("(max-width: 850px)");
const [breakpoint600] = useMediaQuery("(max-width: 600px)");
const [breakpoint400] = useMediaQuery("(max-width: 400px)");
// Set title
React.useEffect(() => {
window.document.title = "ClockOn | Register";
}, []);
const onSubmit = (e) => {
e.preventDefault();
setLoading(true);
setError(null);
register({ name, email, password })
.then((data) => {
if (data.token) {
// Set token and redirect
sessionStorage.setItem("token", data.token);
setTimeout(() => {
history.push("/dashboard");
}, 1000);
}
if (data.error) {
// Display errors
setError(data.error);
setLoading(false);
}
})
.catch((err) => console.error(err));
};
return (
<Flex h="100%" w="100%" align="center" justify="center">
<Flex
color="gray.600"
align="center"
justify="center"
h={breakpoint800 ? "90%" : "75%"}
w={
breakpoint400
? "95%"
: breakpoint600
? "80%"
: breakpoint800
? "60%"
: breakpoint1000
? "90%"
: "80%"
}
maxWidth="1200px"
border="3px solid #8eaedd"
borderRadius="20px"
boxShadow="3px 3px 10px 2px rgba(0, 0, 0, .2)"
position="relative"
>
<Link to="/">
<FontAwesomeIcon
size="2x"
icon={faHome}
color="8eaedd"
style={{
position: "absolute",
left: "20px",
top: "20px",
}}
/>
</Link>
<form onSubmit={onSubmit} flex="1" p="30px" data-testid="form">
<Heading as="h1" size="lg" mb="30px">
Get Started
</Heading>
<Flex direction="column" align="center">
<FormControl isRequired mb="10px">
<FormLabel>First Name:</FormLabel>
<Input
data-cy="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</FormControl>
<FormControl isRequired mb="10px">
<FormLabel>Email:</FormLabel>
<Input
data-cy="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</FormControl>
<FormControl isRequired mb="10px">
<FormLabel>Password:</FormLabel>
<Input
data-cy="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</FormControl>
</Flex>
<Button
bg="#8eaedd"
_hover={{ bg: "#B6CBE8" }}
color="white"
type="submit"
mt="15px"
w="100%"
data-cy="submit"
>
{loading ? <Spinner /> : "Register"}
</Button>
{/* Single error */}
{error && error.length === 1 && (
<Text
mt="10px"
color={applicationColors.ERROR_COLOR}
data-cy="error"
>
{/* Display more meaningful error message if name validation fails */}
{error[0] === "Name is invalid"
? "Name can only contain alphabet characters"
: error[0]}
</Text>
)}
{/* Multiple errors */}
{error && error.length > 1 && (
<ul style={{ marginTop: "10px" }}>
{error.map((e, index) => (
<li
key={index}
style={{ color: applicationColors.ERROR_COLOR }}
>
{e === "Name is invalid"
? "Name can only contain alphabet characters"
: e}
</li>
))}
</ul>
)}
</form>
{breakpoint800 ? null : (
<Image
ml="30px"
w="50%"
maxWidth={
breakpoint1200 ? "400px" : breakpoint1400 ? "450px" : "600px"
}
src="./assets/register.jpg"
alt="vector image of freelancer"
flex="1"
/>
)}
</Flex>
</Flex>
);
};
export default Register;
|
import React from 'react';
import {Text, StyleSheet, View, FlatList} from 'react-native';
const ListScreen = () =>
{
const friends = [
{name: "Friend #1", key: "01", age: "20"},
{name: "Friend #2", key: "02", age: "35"},
{name: "Friend #3", key: "03", age: "18"},
{name: "Friend #4", key: "04", age: "42"},
{name: "Friend #5", key: "05", age: "31"},
{name: "Friend #6", key: "06", age: "30"},
{name: "Friend #7", key: "07", age: "55"},
];
return(
<FlatList
keyExtractor={friend=> friend.name}
data={friends}
renderItem={({item}) => {
return <View>
<Text style={styles.textStyle} >{item.name} - {item.age}</Text>
</View>
}}
/>
);
}
const styles = StyleSheet.create({
textStyle: {
marginVertical: 50
}
});
export default ListScreen; |
/* --------------------------- INTUIT CONFIDENTIAL ---------------------------
overview.js
Written by Date
Jason Harris 10/19/09
Revised by Date Summary of changes
Lane Roathe 06/22/10 [DE1411] check window.viewController usage to fix deferred printing
(Some reports do not have a viewController or attached method)
Lane Roathe 01/20/11 Update position calculations to use true offest (not absolute positions)
Copyright 2009-2010 Intuit, Inc All rights reserved. Unauthorized
reproduction is a violation of applicable law. This material contains
certain confidential and proprietary information and trade secrets of
Intuit, Inc.
RESTRICTED RIGHTS LEGEND
Use, duplication, or disclosure by the Government is subject to
restrictions as set forth in subdivision (b) (3) (ii) of the Rights in
Technical Data and Computer Software clause at 52.227-7013.
Intuit, Inc
P.O. Box 7850
Mountain View, CA 94039-7850
----------------------------- INTUIT CONFIDENTIAL ------------------------- */
function OverviewInit()
{
$(".accountList").accountsExpander();
// position the horizontal today marker
var todayRows = $("#upcomingBillsTable .today");
var outers = $(".hTodayMarkerOuter");
var inners = $(".hTodayMarkerInner");
if (!todayRows.length)
{
outers.hide();
inners.hide();
}
else
{
var todayRow = todayRows[0]; // get individual elements so we can get true offset data
var inner = inners[0];
var outer = outers[0];
var top = todayRow.offsetTop - 15;
todayRows.hide();
var topoffset = top + outer.offsetTop;
outers.css('top', topoffset + 'px');
topoffset = top + inner.offsetTop;
inners.css('top', topoffset + 'px');
inners.html(todayRows.html());
}
$(".updateAllBtn").click(function() {
if( window.viewController )
window.viewController.UpdateAllAccounts();
return false;
});
SpendingTrendsInit("", "");
UpcomingTransactionsInit();
QuickZoomTransactionsInit();
BudgetGoalsInit();
CurrencyMenuInit();
}
function ExploreCategory(quickenIDs)
{
if (0 == quickenIDs.length)
quickenIDs = "__other__";
if( window.viewController )
window.viewController.ExploreCategoryWithQuickenIDs(quickenIDs);
}
function DisplayAccount(quickenID)
{
if( window.viewController )
window.viewController.DisplayAccountWithQuickenID(quickenID);
return false;
}
function ShowAssistant(identifier)
{
if( window.viewController )
window.viewController.ShowAssistant(identifier);
return false;
}
function ShowCategoryExplorer()
{
if( window.viewController )
window.viewController.ShowCategoryExplorer();
return false;
}
|
import React ,{Component} from 'react';
import { queryApi } from "../../../utils/queryApi";
import { useApi } from "../../../hooks/useApi";
import { Link } from "react-router-dom";
import Header from'../Header';
export default function Learn({match}) {
const id = match.params.id;
const [courses, err, reload] = useApi("course");
const course =useApi("course/detail/"+id,null,"GET")[0];
const usercours =useApi("usercourse/learncourse/"+id,null,"GET")[0];
const siwar="e";
const addtogoogleDrive=(f)=>async()=>{
var file={
File:f
}
const [inscriptio, err] = await queryApi("course/googledrive",file, "POST",false);
if (err) {
console.log(err);
} else console.log(inscriptio);
}
return (
<div> <Header />
<div style={{width:"1050px",marginLeft:"339px",marginTop:"-10px"}}>
<br/><br/><br/><br/>
<div class="course-layouts" >
<div class="course-content " >
<div class="course-header" style={{backgroundColor:"#0cb9c1"}} >
<h4 class="text-white"> {usercours?.CourseId.Name} </h4>
<div>
<a href="#" class="btn-back" uk-toggle="target: .course-layouts; cls: course-sidebar-collapse">
<i class="icon-feather-chevron-left"></i>
</a>
</div>
</div>
<div class="course-content-inner">
{usercours?.CourseId.Module?.map((mod, index) => (
<ul id={mod?.Name} class="uk-switcher" style={{touchAction:"pan-y pinch-zoom"}}>
{mod?.Section.map((sec, ind) => (
<li class="" >
<div>
{sec?.Type=="pdf"?(
<div class="video-responsive" >
<h1 class="uk-heading-line uk-text-center" style={{marginTop:"-220px"}}>{sec?.Name}</h1>
<p uk-responsive="" class="uk-responsive-width">{sec?.Description}</p>
{/* <iframe src="https://www.youtube.com/embed/9gTw2EDkaDQ?enablejsapi=1" frameborder="0" uk-video="automute: true" allowfullscreen="" uk-responsive="" class="uk-responsive-width"></iframe>**/}
<a href={ "https://3aweni.netlify.app/assets/uploads/" + sec?.ContentInformation} download target="_blank">
<button >
<i class="icon-feather-folder .icon-tiny"/>
Download File
</button>
<br/>
</a>
<button onClick={addtogoogleDrive(sec?.ContentInformation)}>add this file to google drive</button>
</div>
):(
<div>
<h1 class="uk-heading-line uk-text-center" >{sec?.Name}</h1>
<iframe src={"https://3aweni.netlify.app/assets/uploads/" + sec?.ContentInformation} frameborder="0" uk-video="automute: true" allowfullscreen="" uk-responsive="" class="uk-responsive-width" style={{width:"1000px",height:"500px"}}></iframe>
</div>
)}
</div>
</li>
))}
{/**Quiz */}
<li class="" >
{/** <!-- to autoplay video uk-video="automute: true" -->*/}
<div class="video-responsive" >
<div style={{marginBottom:"220px",marginRight:"320px"}}>
<p uk-responsive="" class="uk-responsive-width" style={{fontSize:"9px"}}>QUIZ FOR PRACTICE</p>
<h3 >{mod?.Quiz.Name}</h3>
<br/><br/><br/><br/><br/>
{/**Submit assignment */}
<div class="rc-CoverPageRow" >
<div class="rc-CoverPageRow__left-side-view">
<label style={{display:"inline-block", verticalAlign: "middle",marginLeft:"50px"}}>Submit your assignment</label>
<Link to={`/quiz/${usercours?._id}/${index}`} class="flex items-center justify-center h-9 px-5 rounded-md bg-blue-600 text-white space-x-1.5" style={{width:"50px",height:"20px" ,display:"inline-block",marginLeft:"100px"}} >
<span>Show</span>
</Link>
<hr style={{width:"100%",textAlign:"left",marginLeft:"0"}}/>
</div>
</div>
{/**Recieve a Mark */}
<div class="rc-CoverPageRow" >
<div class="rc-CoverPageRow__left-side-view">
{usercours?.PassQuiz.map((passqui, indq) =>
(
<div >
{passqui.Index==index?
( <div> <label style={{display:"inline-block", verticalAlign: "middle",marginLeft:"50px"}}>Your mark is</label> <p style={{display:"inline-block", verticalAlign: "middle",marginLeft:"150px"}}>{passqui.Note}/{mod?.Quiz.Questions.length} </p> <hr style={{width:"100%",textAlign:"left",marginLeft:"0"}}/> </div>
)
:
( <div> </div>
)}
</div>
))
}
</div>
</div>
{/* <iframe src="https://www.youtube.com/embed/9gTw2EDkaDQ?enablejsapi=1" frameborder="0" uk-video="automute: true" allowfullscreen="" uk-responsive="" class="uk-responsive-width"></iframe>**/}
</div>
</div>
</li>
<li class="" >
{/** <!-- to autoplay video uk-video="automute: true" -->*/}
<div class="video-responsive" >
<p uk-responsive="" class="uk-responsive-width" ></p>
{/* <iframe src="https://www.youtube.com/embed/9gTw2EDkaDQ?enablejsapi=1" frameborder="0" uk-video="automute: true" allowfullscreen="" uk-responsive="" class="uk-responsive-width"></iframe>**/}
</div>
</li>
</ul>
))}
</div>
</div>
{/** <!-- course sidebar --> */}
<div class="course-sidebar"
>
<div class="course-sidebar-title">
<h3> Table of Contents </h3>
</div>
<div class="course-sidebar-container" data-simplebar="init"><div class="simplebar-wrapper" ><div class="simplebar-height-auto-observer-wrapper"><div class="simplebar-height-auto-observer"></div></div><div class="simplebar-mask"><div class="simplebar-offset" style={{left: "-17px",bottom: "-17px"}}><div class="simplebar-content" style={{padding: "0px", height: "100%", overflow: "scroll"}}>
<ul class="course-video-list-section uk-accordion" uk-accordion="">
{/**display Module */}
{usercours?.CourseId.Module?.map((mod, index) => (
<li class="">
<a class="uk-accordion-title" href="#"> {mod?.Name} </a>
<div class="uk-accordion-content" aria-hidden="true" hidden="">
{/** <!-- course-video-list -->*/}
<ul class="course-video-list highlight-watched" uk-switcher= {"connect:#" + `${mod?.Name}`+" ; animation: uk-animation-slide-right-small, uk-animation-slide-left-medium"}>
{mod?.Section.map((sec, ind) => (
<li class="watched" id="h"> <a href="#" aria-expanded="false"> { `${sec?.Type} ` + ":" + `${sec?.Name} `} <span>{sec?.Duration} min </span> </a>
</li>
))}
<li class="watched" id="h"> <a href="#" aria-expanded="false"> { "Quiz" + + `${index +1} `} <span> {mod?.Quiz.Duration} min </span> </a>
</li>
<li id="h"> <a href="#" aria-expanded="false"> Close<span> </span> </a>
</li>
</ul>
</div>
</li>
))}
</ul>
</div></div></div>
</div></div>
</div>
</div>
</div>
</div>
)
}
|
export class CSS {
constructor (name = undefined) {
this.name = name;
}
get vars () {
let prefix = '';
const { name } = this;
if (name) {
prefix = `${name}-`;
}
return Object.entries(this).reduce((res, [key, t]) => {
if (key === 'name' || key === 'cssVars' || key === 'template') {
return res;
}
if (t.toCSSVars) {
t.toCSSVars(`${prefix}${key}`, res);
} else {
res[`--${prefix}${key}`] = t.valueOf();
}
return res;
}, {});
}
}
export function css (name = undefined) {
return new CSS(name);
}
|
import GlobalStyle from "../GlobalStyle";
import { library } from "@fortawesome/fontawesome-svg-core";
import { fab } from "@fortawesome/free-brands-svg-icons";
import styled from "styled-components";
import Meta from "./Meta";
//import Header from './Header';
//import Footer from './Footer';
library.add(fab);
const Wrapper = styled.div`
display: grid;
place-items: center;
min-height: 100vh;
width: 100%;
`;
const Page = props => (
<div>
<Meta />
<GlobalStyle />
<Wrapper>
{/* <Header /> */}
{props.children}
{/* <Footer /> */}
</Wrapper>
</div>
);
export default Page; |
jQuery("#simulation")
.on("click", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .click", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Panel_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/752e7899-846b-4d9e-be3b-145d0cdea8d4"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_27")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "logedin"
},"com" ]
},
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/4504737a-6c18-4cad-a80e-09b3bc3ee603"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "logedin"
},"user" ]
},
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/c7028ed6-9829-4728-a08e-2f8f76d492c9"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_28")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "logedin" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/752e7899-846b-4d9e-be3b-145d0cdea8d4"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_2")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_3")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/752e7899-846b-4d9e-be3b-145d0cdea8d4"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_4")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/5efaa79a-cf60-4586-b825-3f5042bab117"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-signed")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimAnd",
"parameter": [ {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "logedin"
},"0" ]
},{
"action": "jimNot",
"parameter": [ {
"datatype": "property",
"target": "#s-comoruser",
"property": "jimIsVisible"
} ]
} ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-comoruser" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-signup_1","#s-wrong_2","#s-wrong_1" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": {
"action": "jimAnd",
"parameter": [ {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "logedin"
},"0" ]
},{
"action": "jimOr",
"parameter": [ {
"action": "jimOr",
"parameter": [ {
"action": "jimOr",
"parameter": [ {
"datatype": "property",
"target": "#s-comoruser",
"property": "jimIsVisible"
},{
"datatype": "property",
"target": "#s-signup_1",
"property": "jimIsVisible"
} ]
},{
"datatype": "property",
"target": "#s-comsignin_1",
"property": "jimIsVisible"
} ]
},{
"datatype": "property",
"target": "#s-usersignin_1",
"property": "jimIsVisible"
} ]
} ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-sign" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": {
"datatype": "property",
"target": "#s-Panel_9",
"property": "jimIsVisible"
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_7" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_7" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_18")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-comoruser","#s-usersignin_1","#s-comsignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-signup_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-wrong_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_17")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimAnd",
"parameter": [ {
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_10",
"property": "jimGetValue"
},"group8" ]
},{
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_11",
"property": "jimGetValue"
},"g8user" ]
} ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-sign" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "logedin" ],
"value": "user"
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-wrong_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_14")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-usersignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_20")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimAnd",
"parameter": [ {
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_13",
"property": "jimGetValue"
},"g8company" ]
},{
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_12",
"property": "jimGetValue"
},"group8" ]
} ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "logedin" ],
"value": "com"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-sign" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-wrong_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_15")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-comsignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_17")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-signup_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_2")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-usersignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-signup_1","#s-comoruser","#s-comsignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_3")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-comsignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-signup_1","#s-comoruser","#s-usersignin_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_18")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-comoruser" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_7" ],
"transition": {
"type": "slideleft",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_6")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_8" ],
"transition": {
"type": "slideright",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_8")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_8" ],
"transition": {
"type": "slideleft",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_9")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_6" ],
"transition": {
"type": "slideright",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_11")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_6" ],
"transition": {
"type": "slideleft",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_12")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Panel_7" ],
"transition": {
"type": "slideright",
"duration": 700
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseup", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseup", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Rectangle_18")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18 > .backgroundLayer": {
"attributes": {
"background-color": "#282828"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18": {
"attributes-ie": {
"-pie-background": "#282828",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_17")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17 > .backgroundLayer": {
"attributes": {
"background-color": "#282828"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17": {
"attributes-ie": {
"-pie-background": "#282828",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_20")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20 > .backgroundLayer": {
"attributes": {
"background-color": "#282828"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20": {
"attributes-ie": {
"-pie-background": "#282828",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_22")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22 > .backgroundLayer": {
"attributes": {
"background-color": "#282828"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22": {
"attributes-ie": {
"-pie-background": "#282828",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mousedown", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mousedown", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Rectangle_18")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18 > .backgroundLayer": {
"attributes": {
"background-color": "#999999"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18": {
"attributes-ie": {
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_17")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17 > .backgroundLayer": {
"attributes": {
"background-color": "#999999"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17": {
"attributes-ie": {
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_20")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20 > .backgroundLayer": {
"attributes": {
"background-color": "#999999"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20": {
"attributes-ie": {
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_22")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22 > .backgroundLayer": {
"attributes": {
"background-color": "#999999"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22": {
"attributes-ie": {
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("click", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .toggle", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Rectangle_23")) {
if(jFirer.data("jimHasToggle")) {
jFirer.removeData("jimHasToggle");
jEvent.undoCases(jFirer);
} else {
jFirer.data("jimHasToggle", true);
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_16" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
}
}
})
.on("mouseenter dragenter", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Text_2") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_2 > .backgroundLayer": {
"attributes": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_2": {
"attributes": {
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_2 span": {
"attributes": {
"font-family": "'Arial',Arial",
"font-style": "normal",
"font-weight": "700"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_2": {
"attributes-ie": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_3") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_3 > .backgroundLayer": {
"attributes": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_3": {
"attributes": {
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_3 span": {
"attributes": {
"font-family": "'Arial',Arial",
"font-style": "normal",
"font-weight": "700"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_3": {
"attributes-ie": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_4") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_4 > .backgroundLayer": {
"attributes": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_4": {
"attributes": {
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_4 span": {
"attributes": {
"font-family": "'Arial',Arial",
"font-style": "normal",
"font-weight": "700"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_4": {
"attributes-ie": {
"border-top-color": "#EEEEEE",
"border-right-color": "#EEEEEE",
"border-bottom-color": "#EEEEEE",
"border-left-color": "#EEEEEE"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_18") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18 > .backgroundLayer": {
"attributes": {
"background-color": "#5E5E5E"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_18": {
"attributes-ie": {
"-pie-background": "#5E5E5E",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_17") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17 > .backgroundLayer": {
"attributes": {
"background-color": "#5E5E5E"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_17": {
"attributes-ie": {
"-pie-background": "#5E5E5E",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_20") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20 > .backgroundLayer": {
"attributes": {
"background-color": "#5E5E5E"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_20": {
"attributes-ie": {
"-pie-background": "#5E5E5E",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_22") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22 > .backgroundLayer": {
"attributes": {
"background-color": "#5E5E5E"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_22": {
"attributes-ie": {
"-pie-background": "#5E5E5E",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_5") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_8": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_8": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_8": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_6") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_9": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_9": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_9": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_8") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_11": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_11": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_11": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_9") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_12": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_12": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_12": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_11") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_14": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_14": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_14": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_12") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_15": {
"attributes": {
"opacity": "1.0"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_15": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_15": {
"attributes-ie8lte": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)",
"filter": "alpha(opacity=100)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
}
})
.on("mouseleave dragleave", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseleave", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Text_2")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_3")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_4")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Rectangle_18")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Rectangle_17")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Rectangle_20")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Rectangle_22")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_5")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_6")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_8")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_9")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_11")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_12")) {
jEvent.undoCases(jFirer);
}
}); |
import React from 'react'
import Image from '../assets/img/doguito404.svg';
import '../assets/css/404.css';
const NotFound = () => {
return (
<main className="container flex flex--center flex--column">
<img src={Image} alt="" className="doguito-imagem"/>
<p className="naoencontrado-texto">Ops! Page Not Found!</p>
</main>
);
}
export default NotFound |
({
getSuggestedUnits : function(component, event, helper) {
var unit = component.get("c.getUnitRecords");
unit.setParams({
leadID : component.get("v.recordId")
});
unit.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS" && response.getReturnValue().length > 0) {
var unitList = response.getReturnValue();
component.set("v.units", unitList);
console.log("unitList : ", JSON.parse(JSON.stringify(unitList)));
component.set("v.displayedUnitList", JSON.parse(JSON.stringify(unitList)));
if(response.getReturnValue().length > 0){
component.set("v.hasMatchingUnit","true");
}else{
component.set("v.hasMatchingUnit","false");
}
} else if (state === "ERROR") {
console.log("No suggested properties");
}
});
$A.enqueueAction(unit);
}
}) |
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { editUser } from "../action/authAction";
import { useHistory } from "react-router-dom";
const Admin = () => {
const history = useHistory();
const dispatch = useDispatch();
const user = useSelector((state) => state.UserNow);
const auth = useSelector((state) => state.AuthReducer);
const [messages, setMessages] = useState([]);
useEffect(() => {
setMessages(user.msg);
}, []);
const filterMsg = (e) => {
dispatch(editUser({ msg: messages.filter((el) => el.id != e.target.id) }));
setMessages(messages.filter((el) => el.id != e.target.id));
};
return (
<div className="container-fluid">
<div className="jumbotron">
<h1 className="text-primary p-2 rounded m-auto border shadow text-center">
Feedback
</h1>
<div className="d-flex flex-wrap justify-content-center vh-100 overflow-auto ">
{messages.length ? (
messages.map((el, i) => (
<div
key={i}
className="border m-5 p-2 alert-dark border border-dark shadow "
style={{
minWidth: "300px",
borderRadius: "20px",
maxHeight: "250px",
}}
>
<p
className="font-weight-bold overflow-auto"
style={{ margin: "5px" }}
>
{el.email}
</p>
<p
className="border p-2 font-italic alert-success "
style={{
margin: "auto",
overflow: "auto",
height: "130px",
maxWidth: "250px",
fontSize: "15px",
borderRadius: "15px",
}}
>
{el.message}
</p>
<span className="float-right">
<i
class="fas fa-times removeMSG"
title="remove"
id={el.id}
onClick={filterMsg}
></i>
<a href={`mailto:${el.email}`} title="répondre">
<i class="fas fa-reply "></i>
</a>
</span>
</div>
))
) : (
<h1 className="text-danger">Pas des messages</h1>
)}
</div>
</div>
</div>
);
};
export default Admin;
|
const {Op} = require('sequelize');
const Notice = require('../entity/Notices');
const Author = require('../entity/Author');
const AuthorRepository = require('../repository/AuthorRepository');
async function insertNotice(req) {
let authorId = await AuthorRepository.insertAuthor(req.authorName)
await Notice.create({title: req.title, text: req.text, author_id: authorId});
}
function selectAllNotices() {
return Notice.findAll({
attributes: ['title', 'text','author_id'],
include: [{
model: Author,
required: true,
attributes: ['name','id']
}]
});
}
async function updateNotice(req) {
await Notice.update({title: req.title, text: req.text}, {
where: {
title: req.oldTitle,
text: req.oldText
}
});
}
async function deleteNotice(req) {
await Notice.destroy({
where: {
title: req.title,
text: req.text
}
});
}
async function getAllLike(req) {
return await Notice.findAll({
where: {
title: { [Op.like]: '%' + req.search + '%' }
}
});
}
module.exports = {insertNotice,selectAllNotices,deleteNotice,updateNotice,getAllLike};
|
'use strict';
(function () {
window.initializeScale = function (scale, data, callBack) {
var buttonDec = document.querySelector('.upload-resize-controls-button-dec');
var buttonInc = document.querySelector('.upload-resize-controls-button-inc');
function onClickResize(evt) {
if (evt.target === buttonDec) {
data.scale = Math.max(scale.min, data.scale - scale.step);
} else if (evt.target === buttonInc) {
data.scale = Math.min(scale.max, data.scale + scale.step);
}
if (typeof callBack === 'function') {
callBack(data.scale);
}
}
document.querySelector('.upload-resize-controls').addEventListener('click', onClickResize);
};
})();
|
import {StyleSheet} from 'react-native';
const styles = StyleSheet.create ({
headerContainer: {
padding: 25,
backgroundColor: '#5784BA',
borderBottomStartRadius: 20,
borderBottomEndRadius: 20,
paddingBottom: 35
},
headerName: {
fontFamily: 'Kanit-Medium',
color: '#F9F9F9',
fontSize: 33
},
headerCreate: {
fontFamily: 'Kanit-Medium',
color: '#F9F9F9',
fontSize: 23
},
senderName: {
fontFamily: 'Kanit-Regular',
fontSize: 20
},
senderMessage: {
fontFamily: 'Kanit-Regular',
fontSize: 14,
color: '#787878'
},
});
export default styles |
//getRoom(id)
//addRoom(id, type, key, admin)
//removeRoom(id)
class Rooms{
constructor(){
this.rooms = [];
}
addRoom(id, type, key, admin, activeUser){
var room = {id, type, key, admin, activeUser};
this.rooms.push(room);
return room;
}
getRoom(id){
return this.rooms.filter((room)=> room.id===id)[0];
}
removeRoom(id){
var room = this.getRoom(id);
if(room){
this.rooms = this.rooms.filter((room)=> room.id!==id);
}
return room;
}
}
module.exports = {Rooms}
|
import React from "react";
import { Consumer } from "../../context";
const RightArrow = () => {
let n = 12;
const goForward = dispatch => {
n++;
dispatch({ type: "GO_FORWARD", payload: n });
};
return (
<Consumer>
{value => {
const { dispatch } = value;
return (
<div className="panel-right" onClick={goForward.bind(this, dispatch)}>
<div className="nav-text">
<div>F</div>
<div>O</div>
<div>R</div>
<div>W</div>
<div>A</div>
<div>R</div>
<div>D</div>
</div>
<i className="fas fa-caret-right fa-2x"></i>
</div>
);
}}
</Consumer>
);
};
export default RightArrow;
|
class Element {
constructor(type, props, children) {
this.type = type
this.props = props
this.children = children
}
}
function createElement(type, props, children) {
return new Element(type, props, children)
}
// 设置属性
function setAttr(dom, key, value) {
switch (key) {
case 'value': // dom是一个input或者textarea
if (dom.tagName.toUpperCase() === 'INPUT' || dom.tagName.toUpperCase() === 'TEXTAREA') {
dom.value = value
} else {
dom.setAttribute(key, value)
}
break
case 'style':
dom.style.cssText = value
break
default:
dom.setAttribute(key, value)
break
}
}
function render(vdom) {
let dom = document.createElement(vdom.type)
for (const key in vdom.props) {
setAttr(dom, key, vdom.props[key])
}
vdom.children.forEach(child => {
child = child instanceof Element ? render(child) : document.createTextNode(child)
dom.appendChild(child)
})
return dom
}
function renderDom(dom, container) {
container.appendChild(dom)
}
export { Element, createElement, setAttr, render, renderDom }
|
/**
* Created with JetBrains WebStorm.
* User: ty
* Date: 14-5-21
* Time: 上午9:07
* To change this template use File | Settings | File Templates.
*/
/**
* Created with JetBrains WebStorm.
* User: ty
* Date: 14-2-22
* Time: 上午9:43
* To change this template use File | Settings | File Templates.
*/
var chargeMgr=(function(config){
/**
* 创建datatable
* @returns {*|jQuery}
*/
function createTable(){
var ownTable=$("#chargeTable").dataTable({
"bServerSide": true,
"sAjaxSource": config.ajaxUrls.getAllCharge,
"bInfo":true,
"bLengthChange": false,
"bFilter": false,
"bSort":false,
"bAutoWidth": false,
"iDisplayLength":config.perLoadCount.table,
"sPaginationType":"full_numbers",
"oLanguage": {
"sUrl":"js/de_DE.txt"
},
"aoColumns": [
{ "mDataProp": "packName"},
{ "mDataProp": "fullname"},
{ "mDataProp": "mobile"},
{ "mDataProp": "quota"}
] ,
"fnServerParams": function ( aoData ) {
aoData.push({
"name": "content",
"value": $("#searchContent").val()
});
},
"fnServerData": function(sSource, aoData, fnCallback) {
//回调函数
$.ajax({
"dataType":'json',
"type":"get",
"url":sSource,
"data":aoData,
"success": function (response) {
if(response.success===false){
config.ajaxReturnErrorHandler(response);
}else{
fnCallback(response);
}
}
});
},
"fnFormatNumber":function(iIn){
return iIn;
}
});
return ownTable;
}
return {
ownTable:null,
createTable:function(){
this.ownTable=createTable();
},
tableRedraw:function(){
this.ownTable.fnSettings()._iDisplayStart=0;
this.ownTable.fnDraw();
}
}
})(config);
$(document).ready(function(){
chargeMgr.createTable();
$("#searchContent").keydown(function(e){
if(e.which==13){
chargeMgr.tableRedraw();
//$(this).val("");
}
});
});
|
var searchData=
[
['values_2eh_46',['values.h',['../values_8h.html',1,'']]],
['visualisation_5fmode_47',['visualisation_mode',['../_main_8c.html#a2dec2fc8ae5940a371ea303bd698b071',1,'visualisation_mode(): Main.c'],['../values_8h.html#a2dec2fc8ae5940a371ea303bd698b071',1,'visualisation_mode(): Main.c']]],
['visualization_5fmode_5favailable_48',['visualization_mode_available',['../values_8h.html#a52cfe38b233b1bb9c3b76b5a6a8c272e',1,'values.h']]]
];
|
import React,{Component} from 'react'
import { Route, Switch, NavLink } from "react-router-dom";
import * as api from '../../config/api.js'
import { Tabs,Pagination, DatePicker,Modal ,Button,Icon,Popover} from 'antd'
import Information from '../../common/model/index'
import ConfirmedPopup from '../../common/model/querEnModel'
import UnreservedPopup from '../../common/model/weiyuyuemodel'
import ReservedPopup from '../../common/model/yiyuyueModel'
import UpdataPopup from '../../common/model/updateImageModel'
import Detail from '../detail/index'
const { RangePicker } = DatePicker;
const TabPane = Tabs.TabPane;
function callback(key) {
console.log(key);
}
class Administration extends Component{
/**
* 构造函数
* @param {*} props
*/
constructor(props) {
// location.reload(()=>{window.history.back()} )
// history.go(0)
super(props);
this.state = ({
oder:'新单核保体检',
queryRecord:[], //全部列表数据
//queryRecord1:[], //未预约列表数据
//queryRecord2:[], //已预约列表数据
//queryRecord5:[], //已确认列表数据
//queryRecord7:[], //已体检列表数据
//queryRecord8:[], //报告回齐列表数据
//queryRecord9:[], //录入完成列表数据
//queryRecord10:[], //已撤销列表数据
pagenum:1, //当前页数
cityList:[], //城市列表
hospitalList:[], //体检机构列表
//查询请求参数
healthOderCode:'', //预约号
orderType:'', //预约类型
cityCode:'', //城市代码
checkupDates:'', //体检日期
personName:'', //客户姓名
partyCode:'', //体检机构 name
hospitalCode:'', //体检机构 code
//分页控制
totalPage:0, //总页数
pageSize:0, //一页数据的大小
totalCount:0, //总记录数
// currentPage:'', //后台当前页数
//操作按钮,弹框控制
operateHistory:[],
queryRecord3:[],
informOpt:false, //预约信息的visible
//全部
unreserveOpt:false, //未预约的visible
reservedOpt:false, //已预约的cisible
confirmedOpt:false, //已确认的visible
//已体检的visible
//报告回齐的visible
entryOpt:false, //录入完成
rescindedOpt:false, //已撤销
updataOpt:false, //影像上传
//详情接口请求传参
reserveNum:'', //预约号
healthState:'', //预约状态/体检状态
})
}
componentWillMount() {
//城市列表查询
api.cityLoad().then(res=>{this.setState({cityList:res.cityList})} );
//初始调查询接口,取全部数据
var param={
pageno:this.state.pagenum,
healthOderCode:this.state.healthOderCode,
orderType:this.state.orderType,
cityCode:this.state.cityCode,
checkupDates:this.state.checkupDates,
personName:this.state.personName,
partyCode:this.state.partyCode,
hospitalCode:this.state.hospitalCode,
}
api.selectQuery(param).then(res=>{this.setState({
queryRecord:res.pagerList==undefined?[]:res.pagerList.pageItems,
totalCount:res.pagerList==undefined?0:res.pagerList.totalCount,
pagenum:res.pagerList==undefined?1:res.pagerList.currentPage,
totalPage:res.pagerList==undefined?0:res.pagerList.totalPage,
pageSize:res.pagerList==undefined?0:res.pagerList.pageSize
})} ).catch();
//预约详情,调试
// var num ={
// healthOderCode:'WX001',
// }
// api.detailedQuery(num).then();
// api.statusQuery();
}
componentDidMount() {
// api.cityLoad().then(res=>{this.setState({cityList:res.cityList})} );
// var status ={
// healthStatus:'1', //1:未预约2:已预约3:已邮件4:已预约取消5:已确认6:已确认取7:已体检8:资料回齐9:录入完成10:已撤销
// }
// api.statusQuery();
}
OrgCode(value){
console.log(value);
this.setState({hospitalCode:value})
}
//按钮点击事件,触发弹框
popup(code,num){
var param2={
healthOderCode:code,
healthStatus:num,
}
api.detailedQuery(param2).then(res=>{this.setState({
operateHistory:res.operateHistory,
queryRecord3:res.queryRecord
})});
switch(num){
case '1':
this.setState({unreserveOpt:true});
break;
case '2':
this.setState({reservedOpt:true});
break;
case '4':
this.setState({unreserveOpt:true});
break;
case '5':
this.setState({confirmedOpt:true});
break;
case '6':
this.setState({unreserveOpt:true});
break;
case '7':
this.setState({updataOpt:true});
break;
case '8':
this.setState({updataOpt:true});
break;
}
console.log(code+'-'+num)
}
//详情接口
detailQuery(){
api.detailedQuery().then();
}
//预约状态,预约类型code转汉字,及预约状态对应操作按钮arr返回,供循环render
listTrans(type,value,numb){
switch(type){
case 'healthStatus': //1:未预约 2:已预约 3:已邮件 4:已预约取消 5:已确认 6:已确认取消 7:已体检 8:资料回齐 9:录入完成 10:已撤销
switch(value){
case '1':
return '未预约'
break;
case '2':
return '已预约'
break;
case '3':
return '已邮件' //后台筛选,不传
break;
case '4':
return '未预约' //'已预约取消'
break;
case '5':
return '已确认'
break;
case '6':
return '未预约' //'已确认取消'
break;
case '7':
return '已体检'
break;
case '8':
return '资料回齐'
break;
case '9':
return '录入完成'
break;
case '10':
return '已撤销'
break;
};
break;
case 'bookingType': //0.新单核保体检
switch(value){
case '0':
return '新单核保体检'
break;
}
break;
case 'operation': //1:未预约 2:已预约 5:已确认 7:已体检 8:资料回齐 9:录入完成 10:已撤销
//按钮操作加numb预约号,为循环的a按钮点击事件 取值 做接口传参用,
switch(value){
case '1':
return [{numb:numb,code:value,name:'预约'},]
break;
case '2':
return [{numb:numb,code:value,name:'修改'},{numb:numb,code:value,name:'预约确认'},{numb:numb,code:value,name:'预约取消'}]
break;
case '3':
return [{numb:numb,code:value,name:''}]
break;
case '4':
return [{numb:numb,code:value,name:'预约'}]
break;
case '5':
return [{numb:numb,code:value,name:'修改'},{numb:numb,code:value,name:'预约取消'}]
break;
case '6':
return [{numb:numb,code:value,name:'预约'}]
break;
case '7':
return [{numb:numb,code:value,name:'取消预约'},{numb:numb,code:value,name:'修改预约'}]
break;
case '8':
return [{numb:numb,code:value,}]
break;
case '9':
return [{numb:numb,code:value,}]
break;
case '10':
return [{numb:numb,code:value,}]
break;
};
break;
}
}
//快捷弹框<>
showConfirm(value) {
Modal.confirm({
title: '预约体检',
content: '预约体检',
okText: '确认',
okType: 'danger',
cancelText: '取消',
bodyStyle:{width:'500px',height:'500px',},
width:'1000px',
height:'800px',
onOk() {
console.log('确认');
},
onCancel() {
console.log('取消');
},
});
console.log(value)
}
//取城市列表数据,及相应体检机构数据获取
cityQuery(id){
var city ={
cityCode:id, //界面加载时,若不向后台传递城市code参数,则后台只向前台返回城市,不返回城市对应的体检机构
}
api.cityLoad(city).then(res=>{this.setState({hospitalList:res.hospitalList})} );
}
//预约状态查询数据,数据1-10,8,9,10暂无数据,tabs无3,4,6,7,
statuQuery(statu,pages){
if(statu!='0'){
var status={
healthStatus:statu,
pageno:pages,
healthOderCode:this.state.healthOderCode,
orderType:this.state.orderType,
cityCode:this.state.cityCode,
checkupDates:this.state.checkupDates,
personName:this.state.personName,
hospitalCode:this.state.partyCode,
partyCode:this.state.partyCode,
}
console.log(status)
api.selectQuery(status).then(res=>{this.setState({
queryRecord:res.pagerList==undefined?[]:res.pagerList.pageItems,
totalCount:res.pagerList==undefined?0:res.pagerList.totalCount,
pagenum:res.pagerList==undefined?1:res.pagerList.currentPage,
totalPage:res.pagerList==undefined?0:res.pagerList.totalPage,
pageSize:res.pagerList==undefined?0:res.pagerList.pageSize
})} ).catch();
}else{
this.query(1);
}
}
//查询按钮,
query(num){
var param={
pageno:num,
healthOderCode:this.state.healthOderCode,
orderType:this.state.orderType,
cityCode:this.state.cityCode,
checkupDates:this.state.checkupDates,
personName:this.state.personName,
hospitalCode:this.state.partyCode,
partyCode:this.state.partyCode,
}
console.log(param)
// api.food(param);
api.selectQuery(param).then(res=>{this.setState({
queryRecord:res.pagerList==undefined?[]:res.pagerList.pageItems,
totalCount:res.pagerList==undefined?0:res.pagerList.totalCount,
pagenum:res.pagerList==undefined?1:res.pagerList.currentPage,
totalPage:res.pagerList==undefined?0:res.pagerList.totalPage,
pageSize:res.pagerList==undefined?0:res.pagerList.pageSize
})} ).catch();
}
render(){
return (
<div className="content-right">
<div className="tab">
体检管理 / <span> 体检管理</span>
</div>
<div className="main1">
<div className="box2">
<div className="clearfix"></div>
<ul className="clearfix chaxunlist">
<li className="col-mod-3">
<label className="fl" >体检预约号</label>
<input type="text" className="tl fl width20" placeholder="例:YY233432" value={this.state.healthOderCode} data-input-clear="5" onChange={(e)=>this.setState({healthOderCode:e.target.value})}/>
</li>
<li className="col-mod-3">
<label className="fl" >体检城市</label>
<select className="fl-none fl width20" name="choose" id="choose" value={this.state.cityCode} onChange={(e)=>{this.setState({cityCode:e.target.value}); this.cityQuery(e.target.value) }} >
<option value="请选择" >请选择</option>
{this.state.cityList==undefined?[]:this.state.cityList.map((item,index)=>{
return(
<option key={index} value={item.note} onClick={
(e)=>this.cityQuery(e.target.value)
}>{item.province}</option>
)
})}
</select>
</li>
<li className="col-mod-3">
<label className="fl" >体检机构</label>
<select className="fl-none fl width20" name="choose" id="choose" value={this.state.partyCode} onChange={(e)=>this.setState({partyCode:e.target.value})}>
<option value="请选择" >请选择</option>
{this.state.hospitalList.map((item,index)=>{
return(
<option key={index} value={item.hospitalCode} >{item.hospitalName}</option>
)
})}
</select>
</li>
<li className="col-mod-3">
<label className="fl" >体检日期</label>
<DatePicker placeholder='' onChange={(date,dateString)=>{this.setState({checkupDates:dateString})} }/>
{/* <select className="fl-none fl width20" name="choose" id="choose">
<option value="请选择" selected>请选择</option>
<option value="请选择1">请选择1</option>
<option value="请选择2">请选择2</option>
</select> */}
</li>
<li className="col-mod-3">
<label className="fl" >客户姓名</label>
<input type="text" className="tl fl width20" value={this.state.personName} data-input-clear="5" onChange={(e)=>this.setState({personName:e.target.value})}/>
</li>
<li className="col-mod-3">
<label className="fl" >预约类型</label>
<select className="fl-none fl width20" name="choose" id="choose" value={this.state.oder} onChange={(e)=>this.setState({orderType:e.target.value})}>
<option value="请选择" >请选择</option>
{/* <option value="请选择" >新单核保体检</option> */}
{/* {this.state.hospitalList.map((item,index)=>{
return(
<option key={index} value={item.id}>{item.hospitalName}</option>
)
})} */}
</select>
</li>
<div className="title-add" style={{}}><a className="add-data fr" data-reveal-id="edIt" onClick={()=>{this.query()}}>查询</a></div>
<div className="title-add"><a className="add-data fr" data-reveal-id="edIt" onClick={(e)=>this.setState({informOpt:true})}>预约体检</a></div>
{/* <div className="wraper clearfix">
<div className="title-add">
<a className="reset" data-reveal-id="edIt">重置</a>
<a className="confirm" data-reveal-id="edIt">确认</a>
</div>
</div> */}
</ul>
</div>
</div>
<div className="clear"></div>
<div className="main1 content" id="myTab2_2Content0">
{/* <div className="title-add"><a href="javaScript:;" className="add-data" data-reveal-id="edIt">+新增</a></div> */}
{/* <ul className="clearfix header-table"> */}
{/* <li>未预约</li>
<li>已预约</li>
<li>已确认</li>
<li>已体检</li>
<li>报告回齐</li>
<li>录入完成</li>
<li>已撤回</li> */}
<Tabs defaultActiveKey="0" onChange={(key)=>{callback(key);this.statuQuery(key);this.setState({key:key})}} className="clearfix header-table">
{/* 1:未预约 2:已预约 3:已邮件 4:已预约取消 5:已确认 6:已确认取消 7:已体检 8:资料回齐 9:录入完成 10:已撤销 */}
<TabPane tab="全部" key="0">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>预约号</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>体检项目</th>
<th>预约类型</th>
<th>预约状态</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{this.state.queryRecord==undefined?'':index+1}</td>
{/* index=(currentPage-1)*pageSize //序号*/}
<td >{item.healthName}</td>
<td >{item.healthOderCode}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >{this.listTrans('healthStatus',item.healthStatus)}</td>
<td >{item.taskSource}</td>
<td >
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation',item.healthStatus,item.healthOderCode)==undefined?[]:this.listTrans('operation',item.healthStatus,item.healthOderCode).map((item,index)=>{
return(
<span>
<a key={index} value={this.props.data} onClick={(e)=>this.popup(item.numb,item.code)}>{item.name}</a>
<br style={item.name==undefined?{display:'none'}:{display:'block'}}/>
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation',item.healthStatus,item.healthOderCode)==undefined?[]:this.listTrans('operation',item.healthStatus,item.healthOderCode).map((item,index)=>{
return(
<a key={index} value={this.props.data} onClick={(e)=>this.popup(item.numb,item.code)}>{item.name}</a>
)})} */}
{/* {this.listTrans('operation',item.healthStatus)} */}
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
{/* <ul className="mui-pagination mui-pagination-lg tr">
<span className="totle">共45条</span>
<li className="mui-previous">
<a >
<
</a>
</li>
<li>
<a className="active">
1
</a>
</li>
<li>
<a >
2
</a>
</li>
<li>
<a >
3
</a>
</li>
<li>
<a >
4
</a>
</li>
<li className="mui-active">
<a >
5
</a>
</li>
<li className="mui-next">
<a >
>
</a>
</li>
<li className="mui-next">
<a >
25条/页<i></i>
</a>
</li>
<span>
跳至
</span>
<li className="mui-next">
<a >
5
</a>
</li>
<span>
页
</span>
</ul> */}
{this.state.queryRecord==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={this.state.queryRecord==undefined?true:false}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
console.log(this.state.pagenum) //setState设置后,不能立马获取到改变后state
this.query(page); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="未预约" key="1">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>预约号</th>
<th>营销员</th>
<th>营销员电话</th>
<th>预约类型</th>
<th>任务来源</th>
<th>任务生成时间</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{this.state.queryRecord==undefined?[]:index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >{item.taskSource}</td>
<td >{item.taskGenerationTime}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','1',item.healthOderCode).map((item,index)=>{
return(
<span>
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/>
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// this.listTrans('operation','1',item.healthOderCode).map((item,index)=>{
// return(
// <a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
// )})
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','1',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
console.log(page)
this.setState({pagenum:page})
this.statusQuery('1',page); //调预约状态接口,状态写死
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="已预约" key="2">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>预约号</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>体检项目</th>
<th>预约类型</th>
<th>体检时间</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOderCode}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >{item.healthOrderTime}</td>
<td >{item.taskSource}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','2',item.healthOderCode).map((item,index)=>{
return(
<span>
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/>
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','2',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="已确认" key="5">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>预约号</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>体检项目</th>
<th>预约类型</th>
<th>体检时间</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOderCode}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >{item.healthOrderTime}</td>
<td >{item.taskSource}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','5',item.healthOderCode).map((item,index)=>{
return(
<span>
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/>
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','5',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="已体检" key="7">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>预约号</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>体检项目</th>
<th>预约类型</th>
<th>体检时间</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOderCode}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >{item.healthOrderTime}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','7',item.healthOderCode).map((item,index)=>{
return(
<span>
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/>
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','7',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right",display:this.state.queryRecord==undefined?"none":"block"}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="报告回齐" key="8">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>预约类型</th>
<th>体检项目</th>
<th>影像上传时间</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >{item.imageUploadTime}</td>
<td >{item.taskSource}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','8',item.healthOderCode).map((item,index)=>{
return(
<span>
{/* <a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/> */}
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','8',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
<TabPane tab="录入完成" key="9">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>预约类型</th>
<th>体检项目</th>
<th>体检时间</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >2018.7.13</td>
<td >{item.taskSource}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','9',item.healthOderCode).map((item,index)=>{
return(
<span>
{/* <a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/> */}
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','9',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
<Pagination style={{float:"right",display:this.state.queryRecord1==undefined?'none':'block'}}
// hideOnSinglePage={true}
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
</TabPane>
<TabPane tab="已撤回" key="10">
<div className="box1 table-overflow m-b-2">
<table width="100%" border="0" className="table1">
<tbody>
<tr>
<th>序号</th>
<th>体检人姓名</th>
<th>体检机构</th>
<th>营销员</th>
<th>营销员电话</th>
<th>预约类型</th>
<th>体检项目</th>
<th>体检时间</th>
<th>任务来源</th>
<th>操作</th>
</tr>
{this.state.queryRecord==undefined?[]:this.state.queryRecord.map((item,index)=>{
return(
<tr key={index} value={item.id}>
<td >{index+1}</td>
<td >{item.healthName}</td>
<td >{item.healthOrgName}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contact}</td>
<td >{item.healthCheckupRecord==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1]==undefined?'':item.healthCheckupRecord[item.healthCheckupRecord.length-1].contactphone}</td>
<td >{this.listTrans('bookingType',item.bookingType)}</td>
<td >
{item.healthProject.map((item,index)=>{
return(
<span key={index} value={item.id} onClick={(e)=>alert(item.id+item.projectName)}>{item.projectName}</span>
)
})}
</td>
<td >2018.7.13</td>
<td >{item.taskSource}</td>
<td>
<Popover placement="bottomRight" content={
<div>
{this.listTrans('operation','10',item.healthOderCode).map((item,index)=>{
return(
<span>
{/* <a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
<br/> */}
</span>
)})
}
<NavLink to={{pathname:'/index/Detail',code:item.healthStatus,numb:item.healthOderCode}} isActive={false}>查看</NavLink>
</div>
} trigger="click"
// title={
// }
onConfirm={true} >
<Icon type="ellipsis" theme="outlined" />
</Popover>
{/* {this.listTrans('operation','10',item.healthOderCode).map((item,index)=>{
return(
<a key={index} onClick={(e)=>this.popup(item.num,item.code)}>{item.name}</a>
)})} */}
</td>
{/* <td><a data-reveal-id="edIt">修改</a><a data-reveal-id="addalldata">删除</a><a data-reveal-id="contectM">关联项目</a></td> */}
</tr>
)
})}
</tbody>
</table>
</div>
{this.state.queryRecord1==undefined?'':
<Pagination style={{float:"right"}}
// hideOnSinglePage={true} s
// defaultCurrent={1}
current={this.state.pagenum}
showTotal={function showTotal(total) {
return '共'+total+'条';
}}
total={this.state.totalCount} //总记录数
onChange={
(page,pageSize)=>{
console.log(page)
this.setState({pagenum:page})
this.query(); //tab全部,调全部查询接口
}}
pageSize={10} //总数%每页条数=页数
showSizeChanger={false}
showQuickJumper
/>
}
</TabPane>
</Tabs>
<Modal
// title="Basic Modal"
cancelText="取消"
okText="确认"
visible={this.state.informOpt}
onOk={(e)=>this.setState({informOpt:false})}
onCancel={(e)=>this.setState({informOpt:false})}
width={700}
mask={true}
>
<Information data={this.state.queryRecord3[0]}></Information>
</Modal>
<Modal
// title="Basic Modal"
cancelText="取消"
okText="确认"
visible={this.state.confirmedOpt}
onOk={(e)=>this.setState({confirmedOpt:false})}
onCancel={(e)=>this.setState({confirmedOpt:false})}
width={700}
mask={true}
>
<ConfirmedPopup data={this.state.queryRecord3[0]}></ConfirmedPopup>
</Modal>
<Modal
// title="Basic Modal"
cancelText="取消"
okText="确认"
visible={this.state.unreserveOpt}
onOk={(e)=>this.setState({unreserveOpt:false})}
onCancel={(e)=>this.setState({unreserveOpt:false})}
width={700}
mask={true}
>
<UnreservedPopup data={this.state.queryRecord3[0]}></UnreservedPopup>
</Modal>
<Modal
// title="Basic Modal"
cancelText="取消"
okText="确认"
visible={this.state.reservedOpt}
onOk={(e)=>this.setState({reservedOpt:false})}
onCancel={(e)=>this.setState({reservedOpt:false})}
width={700}
mask={true}
>
<ReservedPopup data={this.state.queryRecord3[0]}></ReservedPopup>
</Modal>
<Modal
// title="Basic Modal"
cancelText="取消"
okText="确认"
visible={this.state.updataOpt}
onOk={(e)=>this.setState({updatadOpt:false})}
onCancel={(e)=>this.setState({updataOpt:false})}
width={700}
mask={true}
>
<UpdataPopup data={this.state.queryRecord3[0]}></UpdataPopup>
</Modal>
</div>
<Switch>
<Route path="/index/Detail" component={Detail} />
</Switch>
</div>
)
}
}
export default Administration; |
module.exports = {
GetAllCategories: require("./GetAllCategories"),
CreateCategory: require("./CreateCategory"),
GetCategory: require("./GetCategory"),
UpdateCategory: require("./UpdateCategory"),
DeleteCategory: require("./DeleteCategory"),
OrderCategory: require("./OrderCategory")
};
|
// Load plugins
var gulp = require( 'gulp' ),
changed = require( 'gulp-changed' ),
chmod = require( 'gulp-chmod' ),
imagemin = require( 'gulp-imagemin' ),
notify = require( 'gulp-notify' ),
plumber = require( 'gulp-plumber' ),
// Load config file
config = require( '../gulp-tasks/config' ).images,
size = config.size;
gulp.task( 'images', function() {
return gulp.src( config.src )
.pipe( plumber( {
errorHandler: config.onError
} ) )
.pipe( size.s )
.pipe( size.sg )
.pipe( changed( config.dest ) )
.pipe( imagemin( config.imagemin ) )
.pipe( chmod( 644 ) )
.pipe( gulp.dest( config.dest ) )
.pipe( notify( {
title: config.notifyOnSucess.title,
message: function( ) {
return config.notifyOnSucess.message + ' ' + size.totalSizeMessage + ' ' + size.s.prettySize + ' ' + size.gzipMessage + ' ' + size.sg.prettySize;
},
onLast: true
} ) );
} );
|
class TerreScene {
constructor() {
this.scene = new THREE.Scene();
this.actif = true;
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.5, 4000);
this.name = "Terre";
this.IsDefine = false;
}
DefineScene() {
this.scene.background = new THREE.CubeTextureLoader()
.setPath('Texture/BackgroundEarth/')
.load([
'bluecloud_ft.jpg',
'bluecloud_bk.jpg',
'bluecloud_up.jpg',
'bluecloud_dn.jpg',
'bluecloud_rt.jpg',
'bluecloud_lf.jpg'
]);;
// Add light
var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(400, 300, 400);
this.scene.add(directionalLight);
var TextureTerrains = new THREE.MeshStandardMaterial({ map: grass });
//var newMaterial = new THREE.MeshStandardMaterial({color: 0xff0000});
Terrains.traverse ( ( o ) => {
if ( o.isMesh ) if (o.isMesh) o.material = TextureTerrains
});
//Terrains.traverse ( (o) => { console.log(o)})
this.scene.add(Terrains);
Terrains.scale.set(.5,.5,.5);
this.water = new BestWater(this.scene, this.camera, directionalLight);
// positionnement de la caméra
this.PingouinJoueur = new Pingouin(0, 30, 0);
this.scene.add(this.PingouinJoueur.getModel());
//Penguin.scale.set(0.01, 0.01, 0.01);
var manetteControls = new THREE.GamepadControls(this.PingouinJoueur.getModel());
this.PingouinJoueur.getModel().add(this.camera);
//this.PingouinJoueur.getModel().add(new THREE.AxesHelper(1000))
this.camera.position.y = 100;
this.camera.position.z = 150;
//this.camera.rotateX(.5 *Math.PI);
this.camera.lookAt(this.PingouinJoueur.getCamera());
/*
var controls = new THREE.OrbitControls(this.camera, renderer.domElement);
controls.minDistance = 2;
controls.maxDistance = 1200;
*/
this.IsDefine = true;
}
animate() {
var delta = clock.getDelta();
this.water.update();
//this.PingouinJoueur.animate(delta);
if (this.actif)
requestAnimationFrame(this.animate.bind(this));
renderer.render(this.scene, this.camera);
}
disabled() {
this.actif = false;
}
active() {
this.actif = true;
}
} |
import h, { render } from '@kuba/h'
import router from '@kuba/router'
router('/login', async function logIn () {
const { default: LogIn } = await import('./auth' /* webpackChunkName: "logIn" */)
render(document.body, <LogIn />)
})
|
var config = {
username: process.env.BOT_USERNAME,
/* Be sure to update the .env file with your API keys.
See how to get them: https://botwiki.org/tutorials/how-to-create-a-twitter-app */
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
},
Twit = require('twit'),
T = new Twit(config),
helpers = require(__dirname + '/helpers.js'),
util = require('util');
module.exports = {
twit: T,
tweet: function(text, cb){
T.post('statuses/update', { status: text }, function(err, data, response) {
if (cb){
cb(err, data, response);
}
});
},
retweet: function(tweet_id, cb){
T.post('statuses/retweet/:id', { id: tweet_id }, function (err, data, response) {
if (cb){
cb(err, data, response);
}
})
},
reply: function(tweet_id, status, cb){
T.post('statuses/update',{
in_reply_to_status_id: tweet_id,
auto_populate_reply_metadata: true,
status: status
}, function(err, data, response) {
if (cb){
cb(err);
}
});
},
send_dm: function(user_id, text, cb){
console.log('sending DM...');
T.post('direct_messages/indicate_typing', {
'recipient_id': user_id
}, function(err, data, response) {
if (err){
console.log('ERROR:\n', err);
}
T.post('direct_messages/events/new', {
'event': {
'type': 'message_create',
'message_create': {
'target': {
'recipient_id': user_id
},
'message_data': {
'text': text,
}
}
}
}, function(err, data, response) {
if (err){
console.log('ERROR:\n', err);
}
if (cb){
cb(err, data, response);
}
});
});
},
post_image: function(text, image_base64, cb) {
T.post('media/upload', { media_data: image_base64 }, function (err, data, response) {
if (err){
console.log('ERROR:\n', err);
}
if (cb){
cb(err);
}
else{
console.log('tweeting the image...');
T.post('statuses/update', {
status: text,
media_ids: new Array(data.media_id_string)
},
function(err, data, response) {
if (err){
console.log('ERROR:\n', err);
if (cb){
cb(err);
}
}
else{
console.log('tweeted');
if (cb){
cb(null);
}
}
});
}
});
},
update_profile_image: function(image_base64, cb) {
console.log('updating profile image...');
T.post('account/update_profile_image', {
image: image_base64
},
function(err, data, response) {
if (err){
console.log('ERROR:\n', err);
if (cb){
cb(err);
}
}
else{
if (cb){
cb(null);
}
}
});
},
delete_last_tweet: function(cb){
console.log('deleting last tweet...');
T.get('statuses/user_timeline', { screen_name: process.env.BOT_USERNAME }, function(err, data, response) {
if (err){
if (cb){
cb(err, data);
}
return false;
}
if (data && data.length > 0){
var last_tweet_id = data[0].id_str;
T.post(`statuses/destroy/${last_tweet_id}`, { id: last_tweet_id }, function(err, data, response) {
if (cb){
cb(err, data);
}
});
} else {
if (cb){
cb(err, data);
}
}
});
},
bot_behavior: [],
on: function(event, event_handler){
if (this.bot_behavior[event]){
this.bot_behavior[event].push(event_handler);
}
else{
this.bot_behavior[event] = [event_handler];
}
},
handle_event: function(event){
var bot_behavior = this.bot_behavior;
// console.log(util.inspect(event, false, null));
if (event.direct_message_indicate_typing_events){
event.direct_message_indicate_typing_events.forEach(function(typing_event){
var user_typing = event.users[typing_event.sender_id].screen_name;
if (user_typing !== process.env.BOT_USERNAME){
console.log(`@${user_typing} is typing...`);
if (bot_behavior['direct_message_indicate_typing_events']){
bot_behavior['direct_message_indicate_typing_events'].forEach(function(fn){
fn(event);
});
}
}
});
}
if (event.direct_message_events){
event.direct_message_events.forEach(function(dm_event){
var dm_sender = event.users[dm_event.message_create.sender_id].screen_name;
if (dm_sender !== process.env.BOT_USERNAME){
console.log(`received new DM from @${dm_sender}...`);
if (bot_behavior['direct_message_events']){
bot_behavior['direct_message_events'].forEach(function(fn){
fn(dm_event.message_create);
});
}
}
});
}
if (event.follow_events){
event.follow_events.forEach(function(follow_event){
var new_follower = follow_event.source.screen_name;
if (new_follower !== process.env.BOT_USERNAME){
console.log(`@${new_follower} started following...`);
if (bot_behavior['follow_events']){
bot_behavior['follow_events'].forEach(function(fn){
fn(follow_event.source);
});
}
}
});
}
if (event.tweet_create_events){
event.tweet_create_events.forEach(function(tweet_create_event){
var tweet_from_screen_name = tweet_create_event.user.screen_name;
if (tweet_from_screen_name !== process.env.BOT_USERNAME){
console.log(`new tweet from @${tweet_from_screen_name}...`);
if (bot_behavior['tweet_create_events']){
bot_behavior['tweet_create_events'].forEach(function(fn){
fn(tweet_create_event);
});
}
}
});
}
if (event.favorite_events){
event.favorite_events.forEach(function(favorite_event){
// console.log(util.inspect(favorite_event, false, null));
var favorite_event_user_screen_name = favorite_event.user.screen_name;
if (favorite_event_user_screen_name !== process.env.BOT_USERNAME){
console.log(`@${favorite_event_user_screen_name} favorited a tweet...`);
if (bot_behavior['favorite_events']){
bot_behavior['favorite_events'].forEach(function(fn){
fn(favorite_event.favorited_status, favorite_event.user);
});
}
}
});
}
if (event.block_events){
event.block_events.forEach(function(block_event){
// console.log(util.inspect(block_event, false, null));
var block_event_user_screen_name = block_event.user.screen_name;
if (block_event_user_screen_name !== process.env.BOT_USERNAME){
console.log(`@${block_event_user_screen_name} favorited a tweet...`);
if (bot_behavior['block_events']){
bot_behavior['block_events'].forEach(function(fn){
fn(block_event.user);
});
}
}
});
}
if (event.direct_message_mark_read_events){
// console.log(util.inspect(event, false, null));
event.direct_message_mark_read_events.forEach(function(direct_message_mark_read_event){
var direct_message_mark_read_event_user_screen_name = event.users[direct_message_mark_read_event.sender_id].screen_name;
if (direct_message_mark_read_event_user_screen_name !== process.env.BOT_USERNAME){
if (bot_behavior['direct_message_mark_read_events']){
bot_behavior['direct_message_mark_read_events'].forEach(function(fn){
fn(direct_message_mark_read_event.favorited_status, direct_message_mark_read_event.user);
});
}
}
});
}
}
};
|
// Adapted from https://gist.github.com/electricg/4372563
// global variables
let startTime = 0;
let lapTime = 0;
let timer = 0;
const clockElement = document.querySelector('.clock');
function formatTime(time) {
// Define many variables in one line!
let h = m = s = ms = 0;
let newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
// could teach string interpolation here as well
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function pad(value, size) {
// Implement for/while loops here!
let resultStr = String(value);
let counter = size - resultStr.length;
while (counter > 0) {
counter -= 1;
resultStr = '0' + resultStr;
}
return resultStr;
}
function start() {
timer = setInterval(update, 1);
// teach about ternary operator
startTime = startTime ? startTime : getTimeNow();
}
function stop() {
// Writing in if else conditional here
if (startTime) {
lapTime = lapTime + getTimeNow() - startTime;
}
// remember to clear the interval we set
clearInterval(timer);
startTime = 0;
}
function update() {
clockElement.innerHTML = formatTime(stopwatchTime());
}
function reset() {
// if running, don't do anything
if (!startTime) {
startTime = lapTime = 0;
update();
}
}
function stopwatchTime() {
if (startTime) {
return lapTime + getTimeNow() - startTime;
} else {
return lapTime;
}
}
function getTimeNow() {
return Date.now();
} |
const day = "25-04-2018";
module.exports = {
day,
intervals: [
{
begin: "08:00",
end: "09:00",
sessions: [require("../breakfasts")[day][0]],
},
{
begin: "09:00",
end: "10:00",
sessions: [require("../presentations/ken-wheeler")],
},
{
begin: "10:00",
end: "11:00",
sessions: [require("../presentations/kasia-jastrzebska")],
},
{
begin: "11:00",
end: "11:30",
sessions: [
{
title: "Four lightning talks",
},
require("../presentations/varya-stepanova"),
],
},
{
begin: "11:30",
end: "12:30",
sessions: [require("../lunches")[day][0]],
},
{
begin: "12:30",
end: "13:00",
sessions: [require("../panels")[day][0]],
},
{
begin: "13:00",
end: "14:00",
sessions: [require("../presentations/christian-alfoni")],
},
{
begin: "14:00",
end: "15:00",
sessions: [require("../presentations/sia-karamalegos")],
},
{
begin: "15:00",
end: "15:45",
sessions: [require("../presentations/sara-vieira")],
},
{
begin: "15:45",
end: "16:30",
sessions: [require("../presentations/rotem-mizrachi-meidan")],
},
{
begin: "16:30",
end: "17:00",
sessions: [require("../coffee-breaks")[day][0]],
},
{
begin: "17:00",
end: "17:30",
sessions: [
{
title: "Four lightning talks",
},
],
},
{
begin: "17:30",
end: "18:00",
sessions: [require("../panels")[day][1]],
},
],
};
|
// import * as home from './home'
// import * as message from './message'
// import * as messageUI from './messageUI'
// import * as topic from './topic'
// import * as topicUI from './topicUI'
// import * as user from './user'
// import * as userUI from './userUI'
// import * as utils from './utils'
// import { combineReducers } from 'redux'
//
// export default combineReducers({
// home,
// message,
// messageUI,
// topic,
// topicUI,
// user,
// userUI,
// utils
// })
import { combineReducers } from 'redux'
import home from './home'
import user from './user'
import userUI from './userUI'
import utils from './utils'
import message from './message'
import messageUI from './messageUI'
import topic from './topic'
import topicUI from './topicUI'
export default combineReducers({
home,
user,
userUI,
utils,
message,
messageUI,
topic,
topicUI
})
|
const shuffle = module.exports = list => {
let r, t
for (let i = list.length - 1; i >= 0; i--) {
r = Math.floor(Math.random() * (i + 1)) // 在 i 的基础上 +1,是因为 random() 包含下限0不含上限1
t = list[i]
list[i] = list[r]
list[r] = t
// console.log(`i=${i}, r=${r}`)
// console.log(list.map((v, y) => y === i || y === r ? '[' + v + ']' : v).join(' '))
}
}
const list = [5, 31, 67, 3, 2, 4, 6, 89, 2, 10, 0]
shuffle(list)
console.log(list) |
// map 在 lodash 和 lodash/fp 中也是不一样得
const _ = require('lodash')
const fp = require('lodash/fp')
console.log(_.map(['23', '8', '10'], parseInt)); // [ 23, NaN, 2 ]
// 输出结果不是我们想要得原因分析
/*
迭代时,将三个参数传入 parseInt (value, index|key, array)
可是 parseInt 得参数得意义分别是:值,进制
parseInt ('23', 0, array) 0 表示 10 进制
parseInt ('8', 1, array) 1 识别不出来
parseInt ('10', 2, array) 2 表示 2 进制
用 fp.map 可以避免上述问题
*/
console.log(fp.map(parseInt, ['23', '8', '10'])); // [ 23, 8, 10 ]
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { listMonthly, updateMonthly, deleteExpense } from '../../api/remote';
import Input from '../common/Input';
export default class MonthlyBalance extends Component {
constructor(props) {
super(props);
this.state = {
budget: 0,
income: 0,
expenses: []
};
this.onChangeHandler = this.onChangeHandler.bind(this);
this.onSubmitHandler = this.onSubmitHandler.bind(this);
this.deleteExpenses = this.deleteExpenses.bind(this);
}
async getData(year, month) {
const data = await listMonthly(year, month)
this.setState(data);
}
async deleteExpenses(id) {
try {
const res = await deleteExpense(id);
console.log(res)
} catch (e) {
console.log(e)
}
const year = Number(this.props.match.params.year)
const month = Number(this.props.match.params.month)
this.getData(year, month);
}
componentDidMount() {
const year = Number(this.props.match.params.year)
const month = Number(this.props.match.params.month)
this.getData(year, month)
.then(() => {
console.log(this.state)
})
}
onChangeHandler(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmitHandler(e) {
e.preventDefault();
const year = Number(this.props.match.params.year)
const month = Number(this.props.match.params.month)
const newIncome = Number(this.state.income)
const newBudget = Number(this.state.budget)
updateMonthly(year, month, newIncome, newBudget)
.then(res => {
console.log(res)
if (res.success) {
this.props.history.push(`/plan/${year}`); // redirects to yearly balance
} else {
console.log('Enter data again');
}
})
}
render() {
let monthMap = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
const year = Number(this.props.match.params.year)
const month = Number(this.props.match.params.month)
return (
<main>
<div className="container">
<div className="row space-top">
<div className="col-md-12">
<h1>Welcome to Budget Planner</h1>
</div>
</div>
<div className="row space-top ">
<div className="col-md-12 ">
<div className="card bg-secondary">
<div className="card-body">
<blockquote className="card-blockquote">
<h2 id="month">{monthMap[month]} {year}</h2>
<div className="row">
<div className="col-md-3 space-top">
<h4>Planner</h4>
<form onSubmit={this.onSubmitHandler}>
<div className="form-group">
<Input
name="income"
type="number"
value={this.state.income}
onChange={this.onChangeHandler}
label="Income:"
/>
</div>
<div className="form-group">
<Input
name="budget"
type="number"
value={this.state.budget}
onChange={this.onChangeHandler}
label="Budget:"
/>
</div>
<input type="submit" className="btn btn-secondary" value="Save" />
</form>
</div>
<div className="col-md-8 space-top">
<div className="row">
<h4 className="col-md-9">Expenses</h4>
<Link to={`/plan/${year}/${month}/expence`} className="btn btn-secondary ml-2 mb-2">Add expenses</Link>
</div>
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Cost</th>
<th>Payment Date</th>
<th></th>
</tr>
</thead>
<tbody>
{this.state.expenses.map(exp => {
return (
<tr key={exp.id}>
<td>{exp.name}</td>
<td>{exp.category}</td>
<td>{parseFloat(Math.round(exp.amount * 100) / 100).toFixed(2)}</td>
<td>{exp.date}-{exp.month}-{exp.year}</td>
<td>
<a href="javascript:void(0)" onClick={() => this.deleteExpenses(exp.id)} className="btn btn-secondary">Delete</a>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</blockquote>
</div>
</div>
</div>
</div>
</div>
</main>
);
}
} |
import React, { Component, PropTypes } from 'react';
import DisqusThread from './DisqusThread';
import { Well } from 'react-bootstrap';
export default class Comments extends Component {
static propTypes = {
item: PropTypes.object
}
render() {
const { item } = this.props;
return (
<Well>
<DisqusThread
id={item._id}
title={item.name}
path={`/blog/post/${item.key}/${item._id}`}
/>
</Well>
);
}
}
|
/*
Copyright 2016 - $Date $ by PeopleWare n.v.
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.
*/
define(["dojo/_base/declare", "./PpwCodeObject", "ppwcode-util-oddsAndEnds/js", "module"],
function(declare, PpwCodeObject, js, module) {
var IdentifiableObject = declare([PpwCodeObject], {
// summary:
// IdentifiableObjects are PpwCodeObjects that feature a method `getKey()`.
_c_invar: [
function() {return js.typeOf(this.getTypeDescription()) === "string";}
],
getKey: function() {
// summary:
// A (business) key (String) that uniquely identifies
// the object represented by this (if we all keep to the rules).
// description:
// There is no default, but implementations are advised to return
// `this.getTypeDescription() + "@" + id`, where `id` is a String uniquely
// and durably identifying the instance within the type.
// If it is impossible to return a unique key (in border conditions),
// the function should return falsy.
// tags
// protected extension
this._c_ABSTRACT();
}
});
IdentifiableObject.mid = module.id;
return IdentifiableObject;
}
);
|
import React from 'react'
import {Box, Link, Flex,List, Text,Spacer} from '@chakra-ui/react'
import SideBar from './SideBar'
import MenuOptions from './Menu'
const MainNavBar = () => {
return (
<Box bg='red.300'color='white' py={3}>
<List>
<Flex>
{/* <SideBar/> */}
<Text pl={10} pt={1} > Gina's Daily Blog</Text>
<Spacer/>
<Flex pr={8}>
<Box pt={1}>
<Link href='/signup' >Sign Up</Link>
<Link href='/login' ml={5}>Login</Link>
</Box>
<MenuOptions/>
</Flex>
</Flex>
</List>
</Box>
)
}
export default MainNavBar
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _server = require('./server');
var _server2 = _interopRequireDefault(_server);
var _route = require('./route');
var _route2 = _interopRequireDefault(_route);
var _require = require('./require');
var _require2 = _interopRequireDefault(_require);
var _db = require('./db');
var _db2 = _interopRequireDefault(_db);
var _table = require('./table');
var _table2 = _interopRequireDefault(_table);
var _types = require('./types');
var _types2 = _interopRequireDefault(_types);
exports['default'] = {
Server: _server2['default'],
Route: _route2['default'],
Require: _require2['default'],
Database: _db2['default'],
Table: _table2['default'],
Types: _types2['default']
};
module.exports = exports['default']; |
import React from 'react';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { withRouter } from "react-router";
import { Layout, Icon, Button } from 'antd'
import SiderMenu from './SiderMenu'
import Routes from "./routes";
import { toggleSiderMenu } from "../modules/layout";
import './routes/utils';
import './app.css';
const { Sider, Content, Header } = Layout
const App = ({ toggleSiderMenu, history }) => (
<Layout className="app">
<Header className="app__header">
<h2 className="app__logo">
IDP-Ant Design
</h2>
</Header>
<Layout className="app__content">
<Sider breakpoint="sm" collapsible
onCollapse={ collapsed => toggleSiderMenu(collapsed) }>
<SiderMenu />
</Sider>
<Layout>
<Content>
<Routes />
</Content>
</Layout>
</Layout>
</Layout>
);
const mapStateToProps = state => ({
isCollapsed: state.layout.isCollapsed
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ toggleSiderMenu }, dispatch);
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(App)
);
|
export { default as auth } from './auth'
export { default as user } from './user'
export { default as ticket } from './ticket'
export { default as typeUser } from './typeUser'
|
var express = require('express');
// var pug = require ('pug');
var app = express();
var port = 3008;
app.set('view engine', 'pug');
app.set('views', './');
var arr_ten = [
{id: 1, name: 'nhi'},
{id: 2, name: 'thương'},
{id: 3, name: 'gái'}
];
app.get('/', function(request, response) {
response.send('hello co ba');
});
app.get('/ten', function(req, res) {
res.render('data.pug',{
ten: arr_ten
})
});
app.get('/ten/search', function(req, res) {
var q = req.query.q;
var find_q = arr_ten.filter(function(item){
return item.name.indexOf(q) != -1;
})
res.render('data.pug', {
ten:find_q
})
})
app.listen(port, function() {
console.log('da tao port '+port);
}) |
import React, {useEffect, useState} from "react";
import Layout from "../../components/layout/layout";
import {Container, Paper, Tab, Tabs} from "@material-ui/core";
import {makeStyles} from "@material-ui/styles";
import {useDispatch, useSelector} from "react-redux";
import {getOrders} from "../../redux/orders/order-action-creators";
import {green, grey, red} from "@material-ui/core/colors";
import BankLoginsPurchased from "../../components/shared/bank-logins-purchased";
import CCDumpsPinsPurchased from "../../components/shared/cc-dumps-pins-purchased";
import {useSnackbar} from "notistack";
const OrdersPage = () => {
const useStyles = makeStyles(theme => {
return {
container: {
paddingTop: 32
},
divider: {
marginTop: 16,
marginBottom: 16
},
title: {
textTransform: 'uppercase'
},
box: {
marginBottom: 32
},
editIcon: {
color: grey['300'],
cursor: 'pointer'
},
viewIcon: {
color: green['600'],
cursor: 'pointer'
},
deleteIcon: {
color: red['600'],
cursor: 'pointer'
},
pending: {
color: grey['600'],
},
completed: {
color: green['600'],
},
cancelled: {
color: red['600'],
},
}
});
const classes = useStyles();
const dispatch = useDispatch();
const {enqueueSnackbar} = useSnackbar();
const {token, user} = useSelector(state => state.auth);
const query = `user=${user._id}`;
useEffect(() => {
const showNotification = (message, options) => {
enqueueSnackbar(message, options);
}
dispatch(getOrders(token, query, showNotification));
}, [dispatch, enqueueSnackbar, query, token])
const [currentTabIndex, setCurrentTabIndex] = useState('logins');
const handleTabChange = (event, index) => {
setCurrentTabIndex(index);
}
const getCurrentTabContent = index => {
switch (index) {
case 'logins':
return <BankLoginsPurchased/>;
case 'dumps':
return <CCDumpsPinsPurchased/>;
default:
return <BankLoginsPurchased/>;
}
}
return (
<Layout>
<Container className={classes.container}>
<Tabs component={Paper} value={currentTabIndex} onChange={handleTabChange} variant="fullWidth">
<Tab value="logins" label="Bank Logins"/>
<Tab value="dumps" label="CC Dumps+ Pins"/>
</Tabs>
{getCurrentTabContent(currentTabIndex)}
</Container>
</Layout>
)
}
export default OrdersPage;
|
// from data.js
var tableData = data;
// YOUR CODE HERE!
// Using the UFO dataset provided in the form of an array of JavaScript objects, write code that appends a
// table to your web page and then adds new rows of data for each UFO sighting.
var table = d3.select('tbody')
function tableCreate(data) {
table.html("");
data.forEach((dataRows) => {
var row = table.append('tr');
Object.values(dataRows).forEach((value) => {
var cell = row.append('td');
cell.text(value);
});
});
}
// Make sure you have a column for date/time, city, state, country, shape, and comment at the very least.
tableCreate(tableData)
// Use a date form in your HTML document and write JavaScript code that will listen for events and search through
// the date/time column to find rows that match user input.
function filterClicker(){
var date = d3.select('#datetime').property('value');
var filterData = tableData;
if (date){
filterData = filterData.filter(row => row.datetime===date);
}
tableCreate(filterData)
}
d3.selectAll("#filter-btn").on('click',filterClicker)
|
sap.ui.define([
"com/delfi/salesprocessing/controller/BaseController"
], function (BaseController) {
"use strict";
return BaseController.extend("com.delfi.salesprocessing.controller.StockUpdate", {
onInit: function () {
var oThisController = this;
// oThisController.fnInitializeView();
oThisController.getRouter().getRoute("nStockUpdate").attachPatternMatched(function () {
$(".pageStockUpdate").css("visibility", "None");
if (oThisController.getAttribute("uid")) {
//Valid Session exists
oThisController.fnSetTimeout(function () {
$(".pageStockUpdate").css("visibility", "visible");
oThisController.fnInitializeView();
}, 100);
} else {
oThisController.getRouter().navTo("nLogin", {}, true);
}
});
//To prevent change in input value on scroll
var oInput1 = oThisController.byId("idStockIn");
var oInput2 = oThisController.byId("idStockOut");
oInput1.attachBrowserEvent("mousewheel", function (oEvent) {
oEvent.preventDefault();
});
oInput2.attachBrowserEvent("mousewheel", function (oEvent) {
oEvent.preventDefault();
});
},
onAfterRendering: function () {
this.fnSetNumberRestrictions();
},
fnInitializeView: function () {
var oThisController = this;
var oMdlApp = oThisController.getParentModel("mApp");
var oSelCustomer = (oThisController.getAttribute("oSelCustomer")) ? JSON.parse(oThisController.getAttribute("oSelCustomer")) : {};
/*if(!oSelCustomer.hasOwnProperty()){
oThisController.showMessage("Invalid customer","E",function(){
oThisController.getRouter().navTo("nDashboard", {}, true);
});
return;
}*/
oThisController.fnSetSelCustomer(oSelCustomer);
// var oSelCust = JSON.parse(oThisController.getAttribute("oSelCustomer"));
// oThisController.fnSetSelCustomer(oSelCust);
// var oSelShipTo = JSON.parse(oThisController.getAttribute("oSelShipTo"));
// oThisController.fnSetShipTo(oSelShipTo);
var oDataStockUpdate = {
"stockList": [],
"prevHist": {
"material": "",
"st1Date": "",
"st2Date": "",
"st3Date": "",
"units1": "",
"units2": "",
"units3": ""
},
"uiOnly": {
"createDraftVisible": false,
"updateButtonVisible": true
}
};
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
if (oMdlStockUpdate) {
oMdlStockUpdate.setData(oDataStockUpdate);
} else {
oMdlStockUpdate = new sap.ui.model.json.JSONModel(oDataStockUpdate);
oThisController.getView().setModel(oMdlStockUpdate, "mStockUpdate");
}
oMdlApp.setProperty("/uiOnly/homeIconVisible", true);
oThisController.getStockList();
},
//Fn to get stock details
getStockList: function () {
var oThisController = this;
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
var oMdlApp = this.getParentModel("mApp");
var vUserId = oMdlApp.getProperty("/userDetails/uid");
var customerId = oMdlApp.getProperty("/selCustomer/custId");
var date;
var dataToTransfer;
if (oMdlApp.getProperty("/selCustomer/isPrimary")) {
dataToTransfer = {
"salesRep": vUserId,
"customerId": customerId,
"shippingToAddress": oMdlApp.getProperty("/selShipTo/shipToId")
};
} else {
dataToTransfer = {
"salesRep": vUserId,
"customerId": customerId
};
}
$.ajax({
type: "POST",
url: "/delfi/stock/getStockDetails",
data: JSON.stringify(dataToTransfer),
crossDomain: true,
xhrFields: {
withCredentials: true
},
headers: {
"Authorization": "Basic " + oThisController._oCommon._a,
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
beforeSend: function (xhr) {
oThisController.openBusyDialog();
},
complete: function (xhr, status) {
if (xhr.responseJSON) {
if (status === "success") {
if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.length) {
var aStockList = [];
$.each(xhr.responseJSON.data, function (index, row) {
var aDuplicateMaterials = $.grep(aStockList, function (gRow) {
return gRow.matId === row.matId && gRow.uom === row.uom;
});
if (!aDuplicateMaterials.length) {
row["totalQuantityStockUpdate"] = Number(row.stockIn) + Number(row.stockOut);
row["units"] = Number(row.stockIn) + Number(row.stockOut);
//Add Stok-in and stock-out to get total quantity
var prevLength = row.listOfPreviousTransaction.length;
for (var i = prevLength; i <= 3; i++) {
row.listOfPreviousTransaction.push({
"stockIn": 0,
"stockOut": 0
});
}
$.each(row.listOfPreviousTransaction, function (indexPrevTran, rowPrevTran) {
if (rowPrevTran.transactionDate) {
date = new Date(rowPrevTran.transactionDate);
rowPrevTran.transactionDate = oThisController.formatter.toDateString(date);
}
rowPrevTran.stockIn = Number(rowPrevTran.stockIn);
rowPrevTran.stockIn = isNaN(rowPrevTran.stockIn) ? "" : rowPrevTran.stockIn;
rowPrevTran.stockOut = Number(rowPrevTran.stockOut);
rowPrevTran.stockOut = isNaN(rowPrevTran.stockOut) ? "" : rowPrevTran.stockOut;
rowPrevTran["units"] = Number(rowPrevTran.stockIn) + Number(rowPrevTran.stockOut);
});
aStockList.push(row);
}
});
/*$.each(aStockList, function(index, row) {
row["totalQuantityStockUpdate"] = Number(row.stockIn) + Number(row.stockOut);
row["units"] = Number(row.stockIn) + Number(row.stockOut);
//Add Stok-in and stock-out to get total quantity
$.each(row.listOfPreviousTransaction, function(innerIndex, innerRow) {
innerRow["units"] = Number(innerRow.stockIn) + Number(innerRow.stockOut);
});
});*/
oMdlStockUpdate.setProperty("/stockList", aStockList);
if (aStockList.length > 30) {
oMdlStockUpdate.setProperty("/uiOnly/createDraftVisible", true);
oMdlStockUpdate.setProperty("/uiOnly/updateButtonVisible", false);
} else if (aStockList.length <= 30) {
oMdlStockUpdate.setProperty("/uiOnly/createDraftVisible", false);
oMdlStockUpdate.setProperty("/uiOnly/updateButtonVisible", true);
}
oMdlStockUpdate.setProperty("/bckUpStockList", $.extend(true, [], aStockList));
oThisController._oCommon["fromStockUpdate"] = aStockList;
oThisController.fnSetTimeout(function () {
oThisController.fnSetNumberRestrictions();
}, 2000);
}
} else {
oThisController.showMessage(xhr.responseJSON.message, "E");
}
} else {
oThisController.showMessage(oThisController.getMessage("msg.noDataFound"));
}
oThisController.closeBusyDialog();
}
});
},
//Fn to add new line item to stock table
fnAddNewMaterials: function (aMaterials) {
var oThisController = this;
var uomSel = true;
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
var aStockList = $.extend(true, [], oMdlStockUpdate.getProperty("/stockList"));
var aDuplicateMaterials = [],
sMessage = "";
$.each(aMaterials, function (index, row) {
if (!row.uom) {
uomSel = false;
return false;
} else {
aDuplicateMaterials = $.grep(aStockList, function (gRow) {
return gRow.matId === row.matId && gRow.uom === row.uom;
});
if (!aDuplicateMaterials.length) {
if (!row.listOfPreviousTransaction) {
row.listOfPreviousTransaction = [];
}
var prevLength = row.listOfPreviousTransaction.length;
for (var i = prevLength; i <= 3; i++) {
row.listOfPreviousTransaction.push({
"stockIn": 0,
"stockOut": 0
});
}
$.each(row.listOfPreviousTransaction, function (indexPrevTran, rowPrevTran) {
rowPrevTran.stockIn = Number(rowPrevTran.stockIn);
rowPrevTran.stockIn = isNaN(rowPrevTran.stockIn) ? "" : rowPrevTran.stockIn;
rowPrevTran.stockOut = Number(rowPrevTran.stockOut);
rowPrevTran.stockOut = isNaN(rowPrevTran.stockOut) ? "" : rowPrevTran.stockOut;
});
/* new material should be top */
//aStockList.push(row);
aStockList.splice(0, 0, row);
} else {
//List out material and UOM that are duplicate
if (!sMessage) {
sMessage = oThisController.getMessage("msg.duplicateMaterial");
}
sMessage += ("\n " + row.matId + " - " + row.uom);
}
}
});
if (!uomSel) {
oThisController.showMessage("Please select UOM!", "E");
return;
}
oMdlStockUpdate.setProperty("/stockList", aStockList);
oMdlStockUpdate.refresh();
oThisController.onCloseMultipleMaterials();
if (sMessage) {
sMessage += "\n Please update the quantity accordingly.";
oThisController.showMessage(sMessage, "I");
}
if (aStockList.length > 30) {
oMdlStockUpdate.setProperty("/uiOnly/createDraftVisible", true);
oMdlStockUpdate.setProperty("/uiOnly/updateButtonVisible", false);
} else if (aStockList.length <= 30) {
oMdlStockUpdate.setProperty("/uiOnly/createDraftVisible", false);
oMdlStockUpdate.setProperty("/uiOnly/updateButtonVisible", true);
}
},
onCreateDraft: function () {
var oThisController = this;
var oMdlApp = this.getParentModel("mApp");
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
var addedStockList = oMdlStockUpdate.getProperty("/stockList");
var oSelCustomer = oMdlApp.getProperty("/selCustomer");
var oUserDet = oMdlApp.getProperty("/userDetails");
var aMat = [];
oThisController.onSubmit(false, false);
$.each(addedStockList, function (index, row) {
aMat.push({
"matId": row.matId,
"price": row.netPrice,
"units": "1",
"uom": row.uom,
"isFree": false,
"itemCategory": row.itemCategory,
"matDesc": row.matDesc
});
});
var oDataToSend = {
"customerId": oSelCustomer.custId,
"salesRep": oUserDet.uid,
"totalPrice": "",
"createdBy": oUserDet.uid,
"creditLimit": oSelCustomer.custCreditLimit,
"orderPlacementDate": new Date().getTime(),
"requestedDeliveryDate": "",
"isDraft": true,
"listOfItems": aMat,
"draftId": "",
"salesOrderID": "",
"currency": oMdlApp.getProperty("/uiOnly/currency"),
"poDate": "",
"poNumber": "",
"shippingText": "",
"comments": "",
"guaranteeDate": "",
"shippingToAddress": oMdlApp.getProperty("/shipToAddress"),
"shippingToId": oMdlApp.getProperty("/shipToId"),
"soldToCustId": oSelCustomer.spCustId,
"terms": oSelCustomer.terms
};
$.ajax({
async: false,
type: "POST",
url: "/delfi/order/createOrder",
data: JSON.stringify(oDataToSend),
crossDomain: true,
xhrFields: {
withCredentials: true
},
headers: {
"Authorization": "Basic " + oThisController._oCommon._a,
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
beforeSend: function (xhr) {
oThisController.openBusyDialog();
},
complete: function (xhr, status) {
oThisController.showMessage("Saved as Draft with ID's '" + xhr.responseJSON.data.draftIdList + "'", "I", function (sAction) {
if (sAction === "OK") {
oThisController.getRouter().navTo("nDashboard");
}
});
oThisController.closeBusyDialog();
}
});
},
//Fn to add stock in and stock out
onLiveStockChange: function (oEvent) {
var oThisController = this;
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
var spath = oEvent.getSource().getBindingContext("mStockUpdate").getPath();
var totQuantity = 0;
var stockin = Number(oMdlStockUpdate.getProperty(spath + "/stockIn"));
var stockout = Number(oMdlStockUpdate.getProperty(spath + "/stockOut"));
if (isNaN(stockin)) {
stockin = 0;
}
if (isNaN(stockout)) {
stockout = 0;
}
totQuantity = stockin + stockout;
oMdlStockUpdate.setProperty(spath + "/totalQuantityStockUpdate", totQuantity);
},
//Fn to navigate to slaesorder in case of primary customer and to add new stock for secondary customer
onNext: function (oEvent) {
var oThisController = this;
var oMdlApp = oThisController.getParentModel("mApp");
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
var date = new Date();
date = oThisController.formatter.toDateString(date);
var listMatId = [];
var prevTransDate;
var oMat, aSoMat = [];
/*var aValidStockDetails = $.grep(oMdlStockUpdate.getProperty("/stockList"), function(gRow) {
return (Number(gRow.totalQuantityStockUpdate) > 0);
});*/
var aValidStockDetails = $.extend(true, [], oMdlStockUpdate.getProperty("/stockList"));
$.each(aValidStockDetails, function (index, row) {
if (listMatId.indexOf(row.matId) === -1) {
listMatId.push(row.matId);
}
});
var oDeferred = $.Deferred();
oThisController.getAllMatDetsByIds(oDeferred, listMatId);
oDeferred.done(function (aMaterials) {
$.each(listMatId, function (property, value) {
var aTempMat = $.grep(aMaterials, function (gRow) {
return gRow.matId === value;
});
var aTempMatUom = $.grep(aValidStockDetails, function (gRow) {
return gRow.matId === value;
});
aTempMatUom = aTempMatUom.uniqueByStrProp("matId", "uom");
if (aTempMat && aTempMat.length) {
oMat = aTempMat[0];
}
$.each(aTempMatUom, function (index, row) {
var aNewTemp = $.grep(oMat.listMatUomDto, function (gRow) {
return gRow.altUnit === row.uom;
});
oMdlApp.setProperty("/uiOnly/currency", aNewTemp[0].currency);
$.each(aNewTemp[0].previousTransactionList, function (prevIndex, prevRow) {
prevTransDate = new Date(prevRow.transactionDate);
prevRow.transactionDate = oThisController.formatter.toDateString(prevTransDate);
prevRow.units = prevRow.stockIn + prevRow.stockOut;
});
aSoMat.push({
"matId": oMat.matId,
"uom": aNewTemp[0].altUnit,
"unitPrice": aNewTemp[0].unitPrice,
"tax": aNewTemp[0].tax,
"discount1": aNewTemp[0].discount1,
"discount2": aNewTemp[0].discount2,
"discount3": aNewTemp[0].discount3,
"netPrice": aNewTemp[0].netPrice,
"discount1Type": aNewTemp[0].discount1Type,
"discount2Type": aNewTemp[0].discount2Type,
"discount3Type": aNewTemp[0].discount3Type,
"availableQuantity": aNewTemp[0].availableQuantity,
"listOfPreviousTransaction": aNewTemp[0].previousTransactionList
});
});
});
if (!aValidStockDetails.length) {
oThisController.showMessage("No Stock has been updated!", "E");
return;
}
if (oMdlApp.getProperty("/selCustomer/isPrimary") === true) {
oThisController.confirmUserAction("Do you want to create sales order after updating stock?", "I", function (sAction) {
if (sAction === "OK") {
oThisController._oCommon["fromDraftList"] = [];
oThisController._oCommon["fromStockUpdate"] = aValidStockDetails;
// oThisController.getRouter().navTo("nSalesOrder");
oThisController.onUpdate(oEvent, true, false);
}
/*else if (sAction === "CANCEL"){
oThisController.onUpdate(oEvent);
}*/
});
} else {
// var oDeferred = $.Deferred();
// oThisController.onSubmit(oDeferred);
// oDeferred.done(function(){
oThisController.confirmUserAction("Do you want to update stock for another customer after updating this?", "I", function (
sAction) {
if (sAction === "OK") {
oThisController._userAction = "Stock Update";
oThisController._oCommon._fNextSecCustomer = true;
oThisController._oCommon._oControllerStockUpdate = oThisController;
oThisController.onUpdate(oEvent, false, true);
}
});
// oThisController.closeBusyDialog();
// });
}
});
},
onUpdate: function (oEvent, fNavToSO, fNxtSecCust) {
var oThisController = this;
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
oThisController._aStockUpdate = $.extend(true, [], oMdlStockUpdate.getProperty("/stockList"));
//TODO Confirm whats the use of the following code
/*var matIdList = [],
uomList = [];
$.each(oMdlStockUpdate.getProperty("/stockList"), function(index, row) {
matIdList.push(row.matId);
uomList.push(row.uom);
});
for (var i = 0; i < oMdlStockUpdate.getProperty("/stockList").length; i++) {
if (oMdlStockUpdate.getProperty("/stockList")[i].matId === matIdList[i]) {
if (oMdlStockUpdate.getProperty("/stockList")[i].matId === uomList[i]) {
oThisController.showMessage(oThisController.getMessage("msg.duplicateMaterial"), "E");
}
}
}*/
if (!oThisController._aStockUpdate.length) {
oThisController.confirmUserAction("No stock has been updated", "E");
return;
}
/*var aValidStockUpdate = $.grep(oThisController._aStockUpdate, function(gRow) {
return Number(gRow.totalQuantityStockUpdate) > 0;
});
if (!aValidStockUpdate.length) {
oThisController.confirmUserAction("No stock has been updated", "E");
return;
} else {
oMdlStockUpdate.setProperty("/stockList", aValidStockUpdate);
oThisController.onSubmit(fNavToSO, fNxtSecCust);
}*/
oThisController.onSubmit(fNavToSO, fNxtSecCust);
},
//on click of update the stockin stockout values are set to zero
setQtyToZero: function () {
var oThisController = this;
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
oThisController._oCommon["fromStockUpdate"] = $.extend(true, [], oMdlStockUpdate.getProperty("/stockList"));
for (var i = 0; i < oMdlStockUpdate.getProperty("/stockList").length; i++) {
oMdlStockUpdate.setProperty("/stockList/" + i + "/stockIn", 0);
oMdlStockUpdate.setProperty("/stockList/" + i + "/stockOut", 0);
oMdlStockUpdate.setProperty("/stockList/" + i + "/totalQuantityStockUpdate", 0);
}
},
//post stock update
onSubmit: function (fNavToSO, fNxtSecCust) {
var oThisController = this;
var oMdlApp = this.getParentModel("mApp");
var vUserId = oMdlApp.getProperty("/userDetails/uid");
var oSelCust = oMdlApp.getProperty("/selCustomer");
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
var oSelShipTo = oMdlApp.getProperty("/selShipTo");
var aStockList = [];
$.each(oMdlStockUpdate.getProperty("/stockList"), function (index, row) {
aStockList.push({
"matId": row.matId.toUpperCase(),
"uom": row.uom,
"unitPrice": row.unitPrice,
"stockIn": row.stockIn,
"stockOut": row.stockOut,
"netPrice": row.netPrice,
"matDesc" : row.matDesc,
"brand" : row.brand,
"category": row.category
});
});
var dataToTransfer = {
"salesRep": vUserId,
"customerId": oSelCust.custId,
"stockDate": new Date(), //TODO Check what format is accepted
"shippingToAddress": oSelShipTo.shipToId, //TODO Check what needs to be mapped
"listOfStockLineItems": aStockList,
};
if (oSelCust.isPrimary === true) {
dataToTransfer.isSecondary = false;
} else {
dataToTransfer.isSecondary = true;
}
var sUrl = "/delfi/stock";
$.ajax({
type: "POST",
url: sUrl,
crossDomain: true,
xhrFields: {
withCredentials: true
},
data: JSON.stringify(dataToTransfer),
headers: {
"Authorization": "Basic " + oThisController._oCommon._a,
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
},
beforeSend: function (xhr) {
if (!fNavToSO) {
oThisController.openBusyDialog();
}
},
complete: function (xhr, status) {
if (xhr.responseJSON) {
if (status === "success") {
oThisController.showMessage(oThisController.getMessage("msg.stockUpdSuccess", [oSelCust.custName]), "I",
function (sAction) {
if (fNavToSO) {
oThisController.getRouter().navTo("nSalesOrder");
} else if (fNxtSecCust) {
oMdlStockUpdate.setProperty("/stockList", []);
oMdlStockUpdate.refresh();
if (!oThisController._oCommon._custSelDlg) {
oThisController._oCommon._custSelDlg = sap.ui.xmlfragment("com.delfi.salesprocessing.fragments.customerDetails",
oThisController);
}
oThisController.getView().addDependent(oThisController._oCommon._custSelDlg);
oThisController._oCommon._custSelDlg.open();
} else {
// oThisController.setQtyToZero();
oThisController.fnInitializeView();
// oThisController.closeBusyDialog();
}
});
} else {
oThisController.showMessage(xhr.responseJSON.message, "E");
oThisController.closeBusyDialog();
}
}
}
});
},
onPrevHistory: function (oEvent) {
var oLink = oEvent.getSource();
var oBindContext = (oLink) ? oLink.getBindingContext("mStockUpdate") : "";
var sPath = (oBindContext) ? oBindContext.getPath() : "";
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
var selMat, units1, units2, units3;
if (sPath) {
selMat = oMdlStockUpdate.getProperty(sPath);
oMdlStockUpdate.setProperty("/prevHist/material", selMat.matId);
oMdlStockUpdate.setProperty("/prevHist/st1Date", selMat.listOfPreviousTransaction[0].transactionDate);
oMdlStockUpdate.setProperty("/prevHist/st2Date", selMat.listOfPreviousTransaction[1].transactionDate);
oMdlStockUpdate.setProperty("/prevHist/st3Date", selMat.listOfPreviousTransaction[2].transactionDate);
units1 = oMdlStockUpdate.getProperty(sPath + "/listOfPreviousTransaction/0/stockIn") + oMdlStockUpdate.getProperty(sPath +
"/listOfPreviousTransaction/0/stockOut");
units2 = oMdlStockUpdate.getProperty(sPath + "/listOfPreviousTransaction/1/stockIn") + oMdlStockUpdate.getProperty(sPath +
"/listOfPreviousTransaction/1/stockOut");
units3 = oMdlStockUpdate.getProperty(sPath + "/listOfPreviousTransaction/2/stockIn") + oMdlStockUpdate.getProperty(sPath +
"/listOfPreviousTransaction/2/stockOut");
oMdlStockUpdate.setProperty("/prevHist/units1", units1);
oMdlStockUpdate.setProperty("/prevHist/units2", units2);
oMdlStockUpdate.setProperty("/prevHist/units3", units3);
if (!this._oPopoverExceedLimit) {
this._oPopoverExceedLimit = sap.ui.xmlfragment("com.delfi.salesprocessing.fragments.previousStockUpdate", this);
this.getView().addDependent(this._oPopoverExceedLimit);
}
this._oPopoverExceedLimit.openBy(oEvent.getSource());
//TODO open dialog
}
},
//Fn to delete stock
onDeleteStockUpdate: function (oEvent) {
var oThisController = this;
var sPath = oEvent.getSource().getBindingContext("mStockUpdate").getPath();
var oMdlStockUpdate = this.getView().getModel("mStockUpdate");
var index = Number(sPath.split("/stockList/")[1]);
oThisController.confirmUserAction(oThisController.getMessage("msg.confirmDraftDelete"), "W", function (sAction) {
if (sAction === "OK") {
oMdlStockUpdate.getProperty("/stockList").splice(index, 1);
oMdlStockUpdate.refresh();
}
});
},
onHome: function (oEvent) {
var oThisController = this;
var oMdlStockUpdate = oThisController.getView().getModel("mStockUpdate");
var oDataStock = $.extend(true, {}, oMdlStockUpdate.getData());
if (JSON.stringify(oDataStock.bckUpStockList) !== JSON.stringify(oDataStock.stockList)) {
oThisController.confirmUserAction("Unsaved changes will be lost. Do you wnat to continue?", "W", function (sAction) {
if (sAction === "OK") {
oThisController.getRouter().navTo("nDashboard", {}, true);
}
});
} else {
oThisController.getRouter().navTo("nDashboard", {}, true);
}
}
});
}); |
const parser = require('@typescript-eslint/parser');
module.exports = {
* extractRegexesFromSource(content, filename) {
// options https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/types/src/parser-options.ts
const tree = parser.parse(content, {
ecmaFeatures: {
jsx: true
},
comment: false,
ecmaVersion: 2020,
errorOnTypeScriptSyntacticAndSemanticIssues: false,
errorOnUnknownASTType: false,
range: true,
loc: true,
filename,
});
yield* this.walkASTForRegexes(tree);
},
* walkASTForRegexes(tree) {
if (!tree) {
return;
}
if (tree.regex) {
yield {
'pattern': tree.regex.pattern,
'flags': tree.regex.flags,
'lineno': tree.loc.start.line,
}
return;
}
if (
(tree.type == 'NewExpression' || tree.type == 'CallExpression') &&
tree.callee && tree.callee.name == 'RegExp' && tree.arguments && tree.arguments[0].type == 'Literal'
) {
yield {
'pattern': tree.arguments[0].value,
'flags': tree.arguments.length > 1 && tree.arguments[1].type == 'Literal' ? tree.arguments[1].value : '',
'lineno': tree.loc.start.line,
}
return;
}
for (const element of Object.values(tree)) {
if (element && typeof element == 'object') {
yield* this.walkASTForRegexes(element);
}
}
}
}
|
import React from "react"
import styled from "styled-components"
import Img from "gatsby-image"
const Container = styled.div`
padding: 3rem;
border-radius: 10px;
height: 100%;
background-color: rgba(19, 20, 24, 0.75);
display: flex;
flex-direction: column;
align-items: center;
position: relative;
overflow: hidden;
`
const Image = styled(Img)`
border-radius: 50%;
height: 20rem;
width: 20rem;
margin-bottom: 3rem;
`
const Header = styled.h4`
font-size: 2.5rem;
@media only screen and (max-width: 41em) {
font-size: 2rem;
}
`
const Secondary = styled.span`
font-size: 2rem;
font-style: oblique;
margin-bottom: 3rem;
@media only screen and (max-width: 41em) {
font-size: 1.8rem;
}
`
const Email = styled.a`
transition: all 0.3s;
:link,
:visited {
font-size: 1.8rem;
align-self: flex-end;
color: #0074b8;
text-decoration: none;
@media only screen and (max-width: 41em) {
font-size: 1.6rem;
}
}
:active,
:hover {
color: #efefef;
}
`
const Details = styled.span`
font-size: 1.8rem;
@media only screen and (max-width: 41em) {
font-size: 1.6rem;
}
`
const PersonCard = ({ name, title, image, email, children }) => (
<Container>
<Image fixed={image.childImageSharp.fixed} />
<Header>{name}</Header>
<Secondary>{title}</Secondary>
<Details>{children}</Details>
<Email href={"mailto:" + email}>{email}</Email>
</Container>
)
export default PersonCard
|
var audio = document.getElementById("my_audio");
var song_list = []
var no = -1;
var list = document.getElementById("song_list");
var table = document.getElementById("my_order");
function main() {
audio.addEventListener("ended", function() {
next_song();
});
init_song_list();
make_list();
song_list = shuffle(song_list);
make_table();
}
function init_song_list() {
song_list[0] = {
name: "Overture",
id: 0
}
song_list[1] = {
name: "Act I Marie and Fritz",
id: 1
}
song_list[2] = {
name: "Act I March",
id: 2
}
song_list[3] = {
name: "Act I Father-Daughter Dance",
id: 3
}
song_list[4] = {
name: "Act I Herr Drosselmeier's Arrival",
id: 4
}
song_list[5] = {
name: "Act I Herr Drosselmeier's Gifts",
id: 5
}
song_list[6] = {
name: "Act I Grandfather's Dance",
id: 6
}
song_list[7] = {
name: "Act I Guest's Depart",
id: 7
}
song_list[8] = {
name: "Act I Marie's Dream",
id: 8
}
song_list[9] = {
name: "Act I The Battle",
id: 9
}
song_list[10] = {
name: "Act I Pine Forest",
id: 10
}
song_list[11] = {
name: "Act I Waltz of the Snowflakes",
id: 11
}
song_list[12] = {
name: "Act II Sugarplum Fairy",
id: 12
}
song_list[13] = {
name: "Act II Hot Chocolate",
id: 13
}
song_list[14] = {
name: "Act II Coffee",
id: 14
}
song_list[15] = {
name: "Act II Tea",
id: 15
}
song_list[16] = {
name: "Act II Candy Cane",
id: 16
}
song_list[17] = {
name: "Act II Marzipan",
id: 17
}
song_list[18] = {
name: "Act II Mother Ginger",
id: 18
}
song_list[19] = {
name: "Act II Waltz of the Flowers",
id: 19
}
song_list[20] = {
name: "Act II Cavalier Pas de Deux",
id: 20
}
song_list[21] = {
name: "Act II Finale",
id: 21
}
}
function next_song() {
no++;
if(no >= song_list.length) {
no = 0;
}
change_music("songs/" + song_list[no].name + ".mp3");
}
function change_music(music) {
audio.pause();
audio.setAttribute('src', music);
audio.load();
audio.play();
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function make_list() {
//adds a caption to the table
list.createCaption().innerHTML = "<b>Soundtrack List</b>"
var row = list.createTHead().insertRow(0);
row.insertCell(0).innerHTML = "<b>Track Number</b>";
row.insertCell(1).innerHTML = "<b>Song Title</b>";
for(var i = 1; i <= song_list.length; i++) {
var row = list.insertRow(i);
row.insertCell(0).innerHTML = i;
row.insertCell(1).innerHTML = song_list[i-1].name;
const NAME = song_list[i-1].name;
row.onclick = function () {
makeChoice(NAME);
}
}
}
function checkAnswers() {
var count = 0;
table.rows[0].insertCell(2).innerHTML = "<b>Correct Solution</b>"
for(var i = 1; i <= song_list.length; i++) {
var row = table.rows[i];
var cell = row.cells[1];
var sol = row.insertCell(2);
sol.innerHTML = song_list[i-1].name;
if(cell.innerHTML===song_list[i-1].name) {
cell.style.backgroundColor = "lightgreen";
count++;
} else {
cell.style.backgroundColor = "red";
}
sol.style.backgroundColor = "lightblue";
}
document.getElementById("song_list").style.display = "none";
document.getElementById("check_answers").style.display = "none";
document.getElementById("next_song").style.display = "none";
makePercentWheel(Math.round(count/song_list.length*100));
}
function makeChoice(name) {
if(no > -1) {
var table = document.getElementById("my_order");
row = (table.rows[no+1]);
row.deleteCell(1);
row.insertCell(1).innerHTML = name;
}
}
function make_table() {
//adds a caption to the table
table.createCaption().innerHTML = "<b>Nutcracker Songs</b>"
var row = table.createTHead().insertRow(0);
row.insertCell(0).innerHTML = "<b>ID Number</b>";
row.insertCell(1).innerHTML = "<b>Your Guess</b>";
for(var i = 1; i <= song_list.length; i++) {
var row = table.insertRow(i);
row.insertCell(0).innerHTML = i;
row.insertCell(1).innerHTML = "not guessed";
}
}
function makePercentWheel(percent) {
var svg = document.createElement("svg");
svg.setAttribute("viewbox", "0 0 36 36");
svg.setAttribute("class", "circular-chart green");
var pathbg = document.createElement("path");
pathbg.setAttribute("class", "circle-bg");
pathbg.setAttribute("d", "M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831");
svg.appendChild(pathbg);
var path = document.createElement("path");
path.setAttribute("class", "circle");
var dasharray = percent + ", 100";
path.setAttribute("stroke-dasharray", dasharray);
path.setAttribute("d", "M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831");
svg.appendChild(path);
var txt = document.createElement("text");
txt.setAttribute("x", "18");
txt.setAttribute("y", "20.35");
txt.setAttribute("class", "percentage");
txt.innerHTML = percent + "%";
svg.appendChild(txt);
document.getElementById("container").appendChild(svg);
document.getElementById("container").innerHTML += "";
}
main(); |
// Filename: views/bound-view
define([
'jquery',
'underscore',
'backbone',
'rivets',
'marionette',
'views/bound-view',
'adapters',
'formatters'
], function($, _, Backbone, rivets, Marionette, BoundView){
var BoundView = Marionette.LayoutView.extend({
binding: null, // used for rivets
template: null, // HTML for template
render: function(){
this.$el.html( this.template );
this.binding = rivets.bind(this.$el, { view: this, model: this.model });
},
remove: function() {
this.binding.unbind();
}
});
return BoundView;
});
|
function toDash(string) {
return string.replace(/([A-Z])/g, function(char) {
return "-" + char.toLowerCase();
});
}
function stringify(object) {
var array = Object.keys(object).map(function(cssAttribute) {
if (typeof object[cssAttribute] === "object") {
return (
toDash(cssAttribute) + " { " + stringify(object[cssAttribute]) + " } "
);
}
return toDash(cssAttribute) + ": " + object[cssAttribute] + "; ";
});
return array.join("");
}
module.exports = stringify;
|
var chance = 2;
var status = "Waiting...";
var fail = true;
var falhas = 0;
var resourceCount = 0;
var isEnglish = true;
function simulate() {
// se já deu sucesso, não simula mais.
if (!fail) {
return;
}
const n1 = Math.floor((Math.random() * 100) + 1);
const n2 = Math.floor((Math.random() * 99) + 0);
var randomNumber = Number.parseFloat(n1 + '.' + n2);
console.log(randomNumber)
if (randomNumber > chance) {
fail = true;
status = isEnglish ? "Failed!" : "Falhou!";
chance += 0.2;
falhas++;
} else {
fail = false;
status = isEnglish ? "Success!" : "Sucesso!"
}
resourceCount++;
sChance = Number.parseFloat(chance).toFixed(2);
document.getElementById("chance").innerHTML = sChance + "%";
document.getElementById("status").innerHTML = status;
document.getElementById("falhas").innerHTML = falhas;
document.getElementById("recurso").innerHTML = resourceCount;
}
function reset() {
fail = true;
chance = 2;
falhas = 0;
status = isEnglish ? "Waiting..." : "Aguardando...";
document.getElementById("chance").innerHTML = chance + "%";
document.getElementById("status").innerHTML = status;
document.getElementById("falhas").innerHTML = falhas;
document.getElementById("recurso").innerHTML = resourceCount;
}
function resetResources() {
resourceCount = 0;
reset();
}
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
function toEnglish() {
isEnglish = true;
document.getElementById("title").innerHTML = "+14 Reblath FailStack Simulator";
document.getElementById("status").innerHTML = status.startsWith("F") ? "Failed!" : status.startsWith("S") ? "Success!" : "Waiting...";
document.getElementById("failed-label").innerHTML = "Failed";
document.getElementById("btnEnhance").innerHTML = "Enhance";
document.getElementById("btnNewItem").innerHTML = "New Item";
document.getElementById("btnReset").innerHTML = "Reset";
}
function toPortuguese() {
isEnglish = false;
document.getElementById("title").innerHTML = "Simulador +14 Reblath FailStack";
document.getElementById("status").innerHTML = status.startsWith("F") ? "Falhou!" : status.startsWith("S") ? "Sucesso!" : "Aguardando...";
document.getElementById("failed-label").innerHTML = "Falhou";
document.getElementById("btnEnhance").innerHTML = "Aprimorar";
document.getElementById("btnNewItem").innerHTML = "Novo Item";
document.getElementById("btnReset").innerHTML = "Reset";
} |
angular.module('alert-me', [])
/**
* At start check if element is
* in the document body
*/
.run(function($log, $document, $templateCache, AlertMe) {
var mainTmpl = '<div class="notify-container {{posV}} {{posH}}">'+
'<ul class="notify-nav" >'+
'<alert-message ng-repeat="message in messages" message="message"></alert-message>'+
'</ul>'+
'</div>';
var listTmpl = '<li class="notify-message" ng-click="onClick($event)">' +
'<div class="notify-message-inner {{message.className}}" ng-class="{dismissable: message.dismissButton}">' +
'<div ng-if="message.icon" class="notify-icon">' +
'<img ng-src="{{message.icon}}" title="{{message.title}}" />' +
'</div>' +
'<div ng-show="message.count > 1" class="count" ng-bind="message.count"></div>' +
'<div class="notify-content">' +
'<span ng-if="message.title" class="notify-title" ng-bind="message.title"></span>' +
'<span ng-if="message.isTrustedHtml" class="notify-message" ng-bind-html="message.content"></span>' +
'<span ng-if="!message.isTrustedHtml" class="notify-message" ng-bind="message.content"></span>' +
'</div>' +
'<span ng-if="message.dismissButton" class="close" ng-click="closeAlert()">X</span>' +
'</div>' +
'</li>';
$templateCache.put('alert-me/container-template.html', mainTmpl);
$templateCache.put('alert-me/message-template.html', listTmpl);
// If global default notification
// init main directive and exit
if( !AlertMe.defaults.desktop ) {
return AlertMe.$$init();
}
// If Notification is not available fallback to default method
if( !window.Notification || typeof window.Notification === 'undefined' ) {
// Alert the user (or developer)
$log.warn('angular-alert-me: Notifications are not supported in your browser.');
// Remove global option
AlertMe.defaults.desktop = false;
// Init directive
AlertMe.$$init();
}
});
|
Template.thanksForShare.onCreated(function helloOnCreated() {
// counter starts at 0
// alert('hello world');
this.counter = new ReactiveVar(0);
document.body.style.backgroundColor = '#fff';
//document.body.style.color = ' #00827f !important';
});
|
seajs.use(["template"],
function(a) {
var f, g, h, i, j, k, b = !1,
c = "http://misc.360buyimg.com/vip/skin/2013/i/tks.jpg",
d = "http://misc.360buyimg.com/vip/skin/2013/i/e-i2.png"; !
function() {
var h, i, b = $(".item .p-img a").children(),
e = {
list: []
},
f = [],
g = {};
$.each(b,
function() {
var c = {
href: "",
src: $(this).attr("src").replace(/\/n3\//g, "/n4/"),
id: $(this).parent().attr("itemid"),
title: $(this).attr("title")
};
f.push(c)
}),
h = {
href: "",
src: c,
id: "",
title: "谢谢参与"
},
i = {
href: "",
src: d,
id: "",
title: "京东抽奖"
},
f.push(h),
f.unshift(i),
g.content = f,
e.list.push(g, g, g),
$(".draw-box>div.d-list").append(a("draw_box_content", e))
} (),
f = function(a, c) {
function q(a, b) {
1 == b && (Math.abs(d) >= i - h && (a.css("marginTop", 0), d = 0), d += h, a.animate({
marginTop: -d
},
120)),
2 == b && (Math.abs(e) >= i - h && (a.css("marginTop", 0), e = 0), e += h, a.animate({
marginTop: -e
},
100)),
3 == b && (Math.abs(f) >= i - h && (a.css("marginTop", 0), f = 0), f += h, a.animate({
marginTop: -f
},
80))
}
function r(a) {
m.stop(!0),
clearInterval(j),
m.animate({
marginTop: -h * a[0]
},
"slow",
function() {
n.stop(!0),
clearInterval(k),
n.animate({
marginTop: -h * a[1]
},
"slow",
function() {
o.stop(!0),
clearInterval(l),
o.animate({
marginTop: -h * a[2]
},
"slow",
function() {
c(),
b = !1,
$(".d-list em").css("z-index", 1),
$(".draw-box span").hide(),
vipFN.beanFresh(),
s(a[2])
})
})
})
}
function s(a) {
for (var b = parseInt(m.css("marginTop"), 10), c = parseInt(n.css("marginTop"), 10), d = parseInt(o.css("marginTop"), 10); b != c || b != d || c != d;) m.css("marginTop", -h * a),
m.css("marginTop", -h * a),
m.css("marginTop", -h * a),
b = parseInt(m.css("marginTop"), 10),
c = parseInt(n.css("marginTop"), 10),
d = parseInt(o.css("marginTop"), 10)
}
var j, k, l, d = 0,
e = 0,
f = 0,
g = 0,
h = 0,
i = 0,
m = $("#solt-item-1 ul"),
n = $("#solt-item-2 ul"),
o = $("#solt-item-3 ul"),
p = function() {
var b = $("#solt-item-1 ul li:first");
g = $("#solt-item-1 ul li").length,
h = b.outerHeight(),
i = (g + 1) * h,
j = setInterval(function() {
q(m, 1)
},
70),
k = setInterval(function() {
q(n, 2)
},
70),
l = setInterval(function() {
q(o, 3)
},
70),
setTimeout(function() {
r(a)
},
5e3)
};
p()
},
g = function() {
var b = "谢谢参与",
c = $("#solt-item-1 li").index($("#solt-item-1 li[title= " + b + "]"));
return [c, c, c]
},
h = function(a, c, d) {
a = $("#payPWD").val(),
c = $("#verifyCode").val(),
i(),
$(".draw-box span").show(),
$.ajax({
type: "get",
url: "http://vip.jd.com/index.php?mod=Vip.MemberLottery&action=lottery",
data: {
payPwd: a || "",
authCode: c || "",
acid: d || ""
},
timeout: 12e3,
dataType: "jsonp",
success: function(a) {
var i, c = a.success && a.result.prizeInfo.id || 0,
d = $("#solt-item-1 ul li").index($("#" + c)),
e = [d, d, d],
h = $(".list-wrap li").length;
e = a.success && e || g(h),
i = function() {
switch (b = !1, +a.resultCode) {
case 1:
case 2:
case 5:
case 11:
$.jdThickBox(k.errorAction),
$(".draw-box span").hide();
break;
case 21:
$.jdThickBox(k.exceptionPayAction),
$(".draw-box span").hide();
break;
case 22:
$.jdThickBox(k.exceptionCodeAction(a.result.acid)),
$(".draw-box span").hide();
break;
case 23:
$.jdThickBox(k.exceptionPayAction),
$(".draw-box span").hide(),
$(".msg-error").show();
break;
case 24:
$.jdThickBox(k.exceptionCodeAction(a.result.acid)),
$(".draw-box span").hide(),
$(".msg-error").show();
break;
case 25:
$.jdThickBox(k.exceptionNoPayAction),
$(".draw-box span").hide();
break;
case 26:
$.jdThickBox(k.exceptionPayAction),
$(".draw-box span").hide(),
$(".msg-error-lock").show();
break;
case 3:
$.jdThickBox(k.insufficientAction),
$(".draw-box span").hide();
break;
case 4:
b = !0,
f(e,
function() {
$.jdThickBox(k.failAction)
}),
$(".my-beans .num").text( + $(".my-beans .num").text() - 20);
break;
case 6:
$.jdThickBox(k.nonStartAction),
$(".draw-box span").hide()
}
if (a.success) {
switch (b = !0, a.result.prizeInfo.type) {
case 1:
f(e,
function() {
$.jdThickBox(k.successSkuAction(a.result.prizeInfo.skuName, a.result.prizeInfo.couponBatchNum))
});
break;
case 2:
f(e,
function() {
$.jdThickBox(k.successAction(a.result.prizeInfo.skuName))
});
break;
case 3:
f(e,
function() {
var b = +a.result.prizeInfo.jdPrice,
c = 200 !== b ? k.successBeanAction(a.result.prizeInfo.skuName) : k.succeeBeanTicketAction;
$.jdThickBox(c)
})
}
$(".my-beans .num").text( + $(".my-beans .num").text() - 20)
}
} ()
},
error: function() {
$.jdThickBox(k.ajaxErrorAction)
}
})
},
i = function() {
$(".thickclose").click()
},
window.drawAction = h,
window.jdThickBoxclose = i,
window.refreshCode = function() {
var a = document.getElementById("JD_Verification");
j = j || a.src,
a.src = j + "?" + Math.random()
},
k = {
ajaxErrorAction: {
type: "text",
width: 400,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>抽奖失败,请稍后重试哦~</h3></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
nonStartAction: {
type: "text",
width: 400,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>京豆抽奖即将开启,敬请期待哦~</h3></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
startAction: {
type: "text",
width: 360,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>您确定要用20京豆抽奖吗?</h3><div class='op-btns'><a href='javascript:;' onclick='drawAction()' class='btn gray-btn m-btn'>确定</a><a href='javascript:;' onclick='jdThickBoxclose()' class='btn gray-btn m-btn del-btn'>取消</a></div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
insufficientAction: {
type: "text",
width: 420,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>您的京豆不够哦,快去赚京豆吧~</h3></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
errorAction: {
type: "text",
width: 360,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>系统异常!</h3></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
successSkuAction: function(a, b) {
return {
type: "text",
width: 548,
height: 110,
source: "<div class='tip-box succ-box'><h3 class='font-green'>恭喜您!您抽中了" + a + "。</h3><div class='box-cont'>购买此商品时,使用优惠券:" + b + " 即可0元购买,优惠券已放入您的<a href='http://quan.jd.com/user_quan.action' target='_blank'>我的京东>优惠券</a>中。</div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
}
},
successAction: function(a) {
return {
type: "text",
width: 548,
height: 110,
source: "<div class='tip-box succ-box'><h3 class='font-green'>恭喜您!您抽中了" + a + "。</h3><div class='box-cont'>优惠券已经发放到您的账户中,请到<a href='http://quan.jd.com/user_quan.action' target='_blank'>我的京东>优惠券</a>中查看。</div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
}
},
successBeanAction: function(a) {
return {
type: "text",
width: 548,
height: 110,
source: "<div class='tip-box succ-box'><h3 class='font-green'>恭喜您!您抽中了" + a + "。</h3><div class='box-cont'>没有收到奖品?<a href='#lottery_rule' onclick='jdThickBoxclose();'>点击这里查看抽奖规则</a></div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
}
},
succeeBeanTicketAction: {
type: "text",
width: 548,
height: 110,
source: "<div class='tip-box succ-box'><h3 class='font-green'>恭喜您!您抽中了200个京豆。</h3><div class='box-cont'>您的手气太好了~ 趁热<a href='http://caipiao.jd.com/' target='_blank' clstag='homepage|keycount|julebu|shouyeguanggao3'>去买张彩票</a>吧,说不定能中大大大奖哦~</div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
failAction: {
type: "text",
width: 420,
height: 110,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>谢谢参与!<br/> 还差一点点就抽到了,继续加油哦~</h3></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
exceptionPayAction: {
type: "text",
width: 473,
height: 200,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>亲爱的用户,为了保证您的京豆安全,请输入支付密码后再抽奖哦!</h3><div class='form'><div class='item'><span class='label'>支付密码:</span><div class='fl'><input type='password' class='itxt' id='payPWD'/><a href='http://safe.jd.com/validate/payPwd/updatePayPwd.action' class='link' target='_blank'>忘记支付密码?</a><div class='msg-error'>支付密码错误</div><div class='msg-error-lock'>抱歉,您的支付密码已错误6次,将锁定2小时</div></div><div class='clr'></div></div><div class='item'><span class='label'></span><div class='fl'><div class='op-btns'><a href='javascript:;' clstag='homepage|keycount|julebu|qiandaozhifumima' class='btn gray-btn m-btn' onclick='drawAction(\"\", \"\", \"\")'>确定</a><a href='javascript:;' class='btn gray-btn m-btn del-btn' onclick='jdThickBoxclose()'>取消</a></div></div><div class='clr'></div></div></div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
exceptionNoPayAction: {
type: "text",
width: 430,
height: 120,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>为保障您的账户京豆安全,请先开启支付密码后再继续抽奖哦~!</h3><a href='http://safe.jd.com/user/paymentpassword/safetyCenter.action' class='link startCode' target='_blank'>开启付密码</a></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
},
exceptionCodeAction: function(a) {
return {
type: "text",
width: 580,
height: 188,
source: "<div class='tip-box warn-box'><h3 class='font-yellow'>抽奖机偷懒了,需要您输入以下验证码来唤醒它哦!</h3><div class='form'><div class='item'><span class='label'>输入验证码:</span><div class='fl'><input type='text' class='itxt' id='verifyCode'/><img id='JD_Verification' onclick='refreshCode()' src= \"http://authcode.jd.com/verify/image?acid=" + a + "\" width='115' height='30'/><a href='javascript:;' class='link' onclick=\"setTimeout(function(){ $('#JD_Verification').click()},50);\">换一张</a><div class='msg-error'>验证码错误</div></div><div class='clr'></div></div><div class='item'><span class='label'></span><div class='fl'><div class='op-btns'><a href='javascript:;' class='btn gray-btn m-btn' clstag='homepage|keycount|julebu|qiandaoyanzhengma' onclick='drawAction(\"\", \"\", \"" + a + "\")'>确定</a><a href='javascript:;' class='btn gray-btn m-btn del-btn' onclick='jdThickBoxclose()'>取消</a></div></div><div class='clr'></div></div></div></div>",
title: "提示",
_close_val: "×",
_titleOn: !0
}
}
},
$(".draw-box>a").bind("mousedown mouseup click",
function(a) { + $("#userLogin").val() &&
function(c) {
var d = $(".d-list em"),
e = +$(".my-beans .num").text();
"mousedown" == a.type && ~
function() {
d.css("z-index", 2),
$(c).addClass("drawed-btn")
} (),
"mouseup" == a.type && ~
function() {
$(c).removeClass("drawed-btn")
} (),
"click" == a.type && ~
function() {
20 > e ? $.jdThickBox(k.insufficientAction) : !b && $.jdThickBox(k.startAction)
} ()
} (this)
}),
$("#winner-list").imgScroll({
width: 120,
height: 160,
visible: 6,
speed: 300,
step: 1,
showNavItem: !0,
autoTime: 1500,
loop: !0,
next: "#next",
prev: "#prev"
})
}),
function(a) {
var b = {
init: function() {
var b = this;
a(".draw-box a").bind("click",
function() {
b.checkLogin(function() { ! +a("#userLogin").val() && (window.location.href = window.location.href)
})
})
},
checkLogin: function(b) {
a.login({
modal: !0,
complete: function(a) {
a && a.IsAuthenticated && b && b.call()
}
}),
a.extend(jdModelCallCenter.settings, {
fn: b
})
}
};
b.init(),
!!+a(".list-wrap").attr("cls") && a(".no-draw").show()
} ($); |
import React, { useContext } from 'react';
import { Button, Container, FormControl, FormHelperText, Grid, Input, InputLabel, makeStyles, TextField } from '@material-ui/core';
import { useState } from 'react';
import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from '../../firebaseConfig';
import LoginWithOther from '../loginWithOthers/LoginWithOther';
import { useHistory, useLocation } from "react-router-dom";
import { UserContext } from '../../App';
import LoginForm from '../LoginForm/LoginForm';
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app();
}
const useStyles = makeStyles((theme) => ({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: '60ch',
},
},
container: {
marginTop: 20,
paddingTop: 20,
paddingBottom: 60,
backgroundColor: 'white',
borderRadius: 5
},
btn: {
background: "#FF6E40",
textTransform: 'capitalize',
color: 'white',
width: "95%",
borderRadius: 0
},
errormsg: {
color: 'red'
},
msg: {
color: 'green'
},
}));
const Login = () => {
const classes = useStyles();
const [newUser, setNewUser] = useState(true);
const [createdNew, setNewCreated] = useState(false);
const [loggedInUser, setLoggedInUser] = useContext(UserContext);
const [errorMessage, setErrorMessage] = useState('');
const [loginErrorMessage, setLoginErrorMessage] = useState('');
const [successMessage, setSucessMessage] = useState('');
const history = useHistory();
const location = useLocation();
let { from } = location.state || { from: { pathname: "/" } };
const [currentPassword, setPasswordcheck] = useState('');
const [user, setUser] = useState({
isSignedIn: false,
displayName: '',
email: '',
password: '',
photoURL: ''
})
const handleSubmit = (e) => {
if (newUser && user.email && user.password) {
firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
.then(res => {
const newUserInfo = { ...user };
setUser(newUserInfo);
setNewCreated(createdNew);
setSucessMessage("Account has been made, please try to login");
updateUserInfo(res.displayName);
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
setErrorMessage(errorMessage);
console.log(errorMessage, errorCode);
});
}
if (!newUser && user.email && user.password) {
firebase.auth().signInWithEmailAndPassword(user.email, user.password)
.then(res => {
const newUserInfo = { ...user };
newUserInfo.isSignedIn = true;
setUser(newUserInfo);
setLoggedInUser(newUserInfo);
history.replace(from);
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
setLoginErrorMessage(error.message);
});
}
e.preventDefault();
}
const handleBlur = (e) => {
let isFieldValid = false;
console.log(isFieldValid);
if (e.target.name === 'displayName') {
if (e.target.value === '') {
isFieldValid = false;
}
else { isFieldValid = true; }
console.log("display", isFieldValid);
}
if (e.target.name === 'email') {
isFieldValid = /\S+@\S+\.\S+/.test(e.target.value);
}
if (e.target.name === 'password') {
isFieldValid = e.target.value.length > 6;
setPasswordcheck(e.target.value);
console.log(currentPassword);
}
if (e.target.name === 'confirmPassword') {
if (e.target.value === currentPassword) {
isFieldValid = true;
console.log("check", currentPassword);
}
else if (e.target.value === '') {
isFieldValid = false;
console.log("wrong:", currentPassword);
}
else {
isFieldValid = false;
}
console.log("con:", isFieldValid);
}
if (isFieldValid === true) {
console.log("last", isFieldValid);
const newUserInfo = { ...user };
newUserInfo[e.target.name] = e.target.value;
setUser(newUserInfo);
}
}
const updateUserInfo = name => {
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: name
}).then(function () {
console.log("Update successful");
}).catch(function (error) {
console.log("An error happened");
});
}
return (
<Container maxWidth="sm" className={classes.container}>
<Grid container spacing={0}>
<Grid item xs={6} sm={12}>
<div id='alert'> {errorMessage && (
<p className={classes.errormsg}> {errorMessage} </p>
)}
{successMessage && (
<p className={classes.msg}> {successMessage} </p>
)}
</div>
{newUser && !createdNew && <div>
<h2>Create an account</h2>
<form onSubmit={handleSubmit} className={classes.root} noValidate autoComplete="off">
<TextField
onBlur={handleBlur}
id="standard-name-input"
label="Name"
type="text"
name="displayName"
required
helperText="Put your Full name here"
/>
<TextField
onBlur={handleBlur}
id="standard-email-input"
label="Username or Email"
type="text"
name='email'
required
helperText="example@example.com"
/>
<TextField
onBlur={handleBlur}
id="standard-password-input"
label="Password"
type="password"
autoComplete="current-password"
name="password"
required
helperText="more than 6 letters/digits"
/>
<TextField
onBlur={handleBlur}
id="standard-confirm-password-input"
label="Confirm Password"
type="password"
autoComplete="current-password"
name="confirmPassword"
required
/>
<Button type='submit' variant="contained" className={classes.btn}>
Create an account
</Button>
</form>
<p style={{ textAlign: 'center' }}>Already have an account? <Button onClick={() => setNewUser(!newUser)} style={{
color: '#FF6E40',
textTransform: 'capitalize',
}}>Login</Button></p>
</div>}
</Grid>
{!newUser &&
<LoginForm handleSubmit={handleSubmit} error={loginErrorMessage} handleBlur={handleBlur} />}
<LoginWithOther user={user} />
</Grid>
</Container>
);
};
export default Login; |
import { combineReducers } from "redux";
import { articleReducer } from "./slices/articleSlice";
import { boardReducer } from "./slices/boardSlice";
import { commentReducer } from "./slices/commentSlice";
import { codeReducer } from "./slices/codeSlice";
const rootReducer = combineReducers({ articleReducer, boardReducer, commentReducer, codeReducer }); // reducer 합치는 곳
export default rootReducer; |
import React from 'react';
import ReactDOM from 'react-dom';
import FileBase64 from 'react-file-base64';
class App extends React.Component {
constructor() {
super()
this.state = {
files: []
}
}
// Callback~
getFiles(files){
this.setState({ files: files })
}
render() {
return (
<FileBase64
multiple={ true }
onDone={ this.getFiles.bind(this) } />
)
}
}
ReactDOM.render(<App />, document.getElementById("app")) |
/*
* blz模块声明
*/
;(function(fn){
'use strict';
/* jshint ignore:start */
if (typeof define === 'function' && define.amd) {
define(['jQuery'],function () {
return fn(window.Zepto||window.jQuery);
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = fn(window.Zepto||window.jQuery);
}else{
fn(window.Zepto||window.jQuery);
}
/* jshint ignore:end */
}(function($){
'use strict';
var w=window,
d=document;
$.blz={
// 空函数
emptyFn:function(){},
// 获取数据类型
getDataType:function(data){
return Object.prototype.toString.call(data).slice(8,-1).toLowerCase();
},
// 获取用户代理ios 或 android
isAndroid:/Android/gi.test(navigator.userAgent),
// 检测动画属性transition的支持情况
checkTransition:function(){
var o=d.createElement('div');
var a=[['','transition',''],['webkit','Transition','-'],['ms','Transition','-'],['Moz','Transition','-'],['O','Transition','-']];
for(var i=0;i<a.length;i++){
if(a[i][0]+a[i][1] in o.style){
return a[i][2]+a[i][0].toLowerCase()+a[i][2];
}else if(i===0){
return false;
}
}
},
// 动画帧函数的兼容处理
requestAnimationFrame:function(){
if (!w.requestAnimationFrame) {
w.requestAnimationFrame=w.webkitRequestAnimationFrame||w.mozRequestAnimationFrame||w.oRequestAnimationFrame ||w.msRequestAnimationFrame||function(callback) {
w.setTimeout(callback, 1000/60);
};
return w.requestAnimationFrame;
}else{
return w.requestAnimationFrame;
}
},
// 自定义事件
customEvent:function(elem,name,data){
var event = d.createEvent('CustomEvent');
event.initCustomEvent(name,true,false,data);
elem.dispatchEvent(event);
},
// 转换成字面量
toString:function(val){
return val == null? '': typeof val === 'object'? JSON.stringify(val, null, 2): String(val);
},
/*
* 动画相关
*/
// webGl初始化
initWebGl:function(canvas){
var context3d=null;
try{
context3d=canvas.getContext('webgl')||canvas.getContext('experimental-webgl');
}catch(e){
throw new Error('你的浏览器不支持WebGl');
}
return context3d;
}
};
return $;
}));
/*
* weui对话框
*/
;((function(fn){
'use strict';
/* jshint ignore:start */
if (typeof define === 'function' && define.amd){
define(['jQuery'],function (empty){
return fn(window.jQuery);
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = fn(window.jQuery);
}else{
fn(window.jQuery);
}
/* jshint ignore:end */
})(function($){
'use strict';
$.weui={};
var modelAlert={
model:'',
hidden:true,
cache:[],
config:{
title:'',
article:''
}
},
modelConfirm={
model:'',
hidden:true,
cache:[],
config:{
title:'',
article:'',
sureText:'确定',
cancelText:'取消',
sureHref:'javascript:void(0);',
cancelHref:'javascript:void(0);',
cancelCallback:null,
sureCallback:null
}
},
modelWarn={
model:'',
cache:[]
},
loading='',
modelTip={
model:'',
hidden:true,
cache:[]
};
// 缓存的弹窗数据处理
function bindCache(model,cache,callback,time){
time=time||0;
model.on('click.blz',function(){
setTimeout(function(){
callback(cache[0]);
cache.shift();
if(cache.length<=0){
model.off('click.blz');
}
},time);
});
}
$.weui.alert=function(obj){
var model=modelAlert.model;
obj=$.extend({},modelAlert.config,obj||{});
if(model!==''&&model.css('display')!=='none'){
var cache=modelAlert.cache;
// 假如弹窗已存在,将弹窗数据缓存;
cache[cache.length]=obj;
model.off('click.blz');
bindCache(model,cache,$.weui.alert,300);
return model;
}else if(model!==''){
model.find('.weui_dialog_title').html(obj.title);
model.find('.weui_dialog_bd').html(obj.article);
model.fadeIn(300);
}else{
model='<div id="weui_dialog_alert" class="weui_dialog_alert" style="position:fixed;top:0;bottom:0;left:0;right:0;z-index:9999">'+
'<div class="weui_mask"></div>'+
'<div class="weui_dialog">'+
'<div class="weui_dialog_hd">'+
'<strong class="weui_dialog_title">'+obj.title+'</strong>'+
'</div>'+
'<div class="weui_dialog_bd">'+obj.article+'</div>'+
'<div class="weui_dialog_ft">'+
'<a href="javascript:void(0);" class="weui_btn_dialog primary" data-blz-dismiss="#weui_dialog_alert">确定</a>'+
'</div>'+
'</div>'+
'</div>';
modelAlert.model=model=$(model).appendTo(document.body);
}
if(obj.sureCallback){
model.find('.weui_btn_dialog').on('click.blz',function(){
obj.sureCallback();
$(this).off('click.blz');
});
}
return model;
};
$.weui.confirm=function(obj){
var model=modelConfirm.model;
obj=$.extend({},modelConfirm.config,obj||{});
if(model!==''&&model.css('display')!=='none'){
var cache=modelConfirm.cache;
// 假如弹窗已存在,将弹窗数据缓存;
cache[cache.length]=obj;
model.off('click.blz');
bindCache(model,cache,$.weui.confirm,300);
return model;
}else if(model!==''){
model.find('.weui_dialog_title').html(obj.title);
model.find('.weui_dialog_bd').html(obj.article);
model.find('.weui_btn_dialog.default').html(obj.cancelText).attr('href',obj.cancelHref);
model.find('.weui_btn_dialog.primary').html(obj.sureText).attr('href',obj.sureHref);
model.fadeIn(300);
}else{
model='<div id="weui_dialog_confirm" class="weui_dialog_confirm" style="position:fixed;top:0;bottom:0;left:0;right:0;z-index:9999">'+
'<div class="weui_mask"></div>'+
'<div class="weui_dialog">'+
'<div class="weui_dialog_hd">'+
'<strong class="weui_dialog_title">'+obj.title+'</strong>'+
'</div>'+
'<div class="weui_dialog_bd">'+obj.article+'</div>'+
'<div class="weui_dialog_ft">'+
'<a href="'+obj.cancelHref+'" class="weui_btn_dialog default" data-blz-dismiss="#weui_dialog_confirm" data-blz-option="cancell">'+obj.cancelText+'</a>'+
'<a href="'+obj.sureHref+'" class="weui_btn_dialog primary" data-blz-dismiss="#weui_dialog_confirm" data-blz-option="sure">'+obj.sureText+'</a>'+
'</div>'+
'</div>'+
'</div>';
modelConfirm.model=model=$(model).appendTo(document.body);
}
if(obj.cancelCallback){
$(document).on('clickBlzOptioncancel',function(e){
obj.cancelCallback(e);
$(document).off('clickBlzOptionsure clickBlzOptioncancel click.sure.cancel');
});
}
if(obj.sureCallback){
$(document).on('clickBlzOptionsure',function(e){
obj.sureCallback(e);
$(document).off('clickBlzOptionsure clickBlzOptioncancel click.sure.cancel');
});
}
// 确定取消按钮
$(document).on('click.sure.cancel',function(e){
var $target=$(e.target),
data=$target.data('blz-option')?$target.data('blz-option'):$target.closest('.weui_btn_dialog').data('blz-option');
data=data?data:'cancel';
setTimeout(function(){
$(document).trigger('clickBlzOption'+data);
},30);
});
return model;
};
$.weui.loading=function(string){
if(!navigator.onLine){
$.weui.tip('无网络');
return null;
}
string=string||'数据加载中';
if(loading!==''){
loading.css('display','block').find('.weui_toast_content').html(string);
}else{
loading='<div id="loadingToast" class="weui_loading_toast" style="display: none;">'+
'<div class="weui_mask_transparent"></div>'+
'<div class="weui_toast">'+
'<i class="weui_loading weui_icon_toast"></i>'+
'<p class="weui_toast_content">'+string+'</p>'+
'</div>'+
'</div>';
loading=$(loading).appendTo(document.body).css('display','block');
}
return loading;
};
$.weui.partLoading=function(elem,string){
if(!navigator.onLine){
$.weui.tip('无网络');
return false;
}
string=string||'数据加载中';
string='<div class="weui_toast model-part-loading">'+
'<i class="weui_loading weui_icon_toast"></i>'+
'<p class="weui_toast_content">'+string+'</p>'+
'</div>';
return $(string).appendTo(elem);
};
$.weui.warn=function(obj){
var model=modelWarn.model;
var cache=modelWarn.cache;
obj.article=obj.article||'';
obj.title=obj.title||'警告';
if(model!==''&&model.css('display')!=='none'){
// 假如弹窗已存在,将弹窗数据缓存;
cache[cache.length]=obj;
return model;
}else if(model!==''){
model.html(obj.title+':'+obj.article).fadeIn();
}else {
model='<div class="weui_toptips weui_warn js_tooltips">'+obj.title+':'+obj.article+'</div>';
modelWarn.model=model=$(model).appendTo(document.body).fadeIn();
}
setTimeout(function(){
model.fadeOut(0);
// 小于零则关闭warn弹窗的反复调用大于0则开启
if(cache.length>0){
$.weui.warn(cache[0]);
cache.shift();
}
},3000);
return model;
};
$.weui.tip=function(string){
var model=modelTip.model;
var cache=modelTip.cache;
string=string||'';
if(model!==''&&model.css('display')!=='none'){
// 假如弹窗已存在,将弹窗数据缓存;
cache[cache.length]=string;
return model;
}else if(model!==''){
model.html(string).fadeIn();
}else {
model='<div class="glb_weui_toast weui_toast" style="padding-top:1em;">'+string+'</div>';
modelTip.model=model=$(model).appendTo(document.body);
}
setTimeout(function(){
$(model).fadeOut(0);
// 小于零则关闭tip弹窗的反复调用大于0则开启
if(cache.length>0){
$.weui.tip(cache[0]);
cache.shift();
}
},3000);
return model;
};
// dismiss交互
$(document).on('click.blz.dismiss','[data-blz-dismiss]',function(){
var target=$(this).data('blz-dismiss');
$(target).fadeOut(0);
});
// show交互
$(document).on('click.blz.show','[data-blz-show]',function(){
var target=$(this).data('blz-show');
$(target).fadeIn(300);
});
// 组件卸载
$.weuiOff=function(){
$.weui=null;
$(document).off('click.blz.dismiss click.blz.show');
if(modelAlert.model!==''){modelAlert.model.remove();}
if(modelConfirm.model!==''){modelConfirm.model.remove();}
if(modelWarn.model!==''){modelWarn.model.remove();}
if(loading!==''){loading.remove();}
if(modelTip.model!==''){modelTip.model.remove();}
$.weuiOff=null;
};
return $;
})); |
var latexit = "http://latex.codecogs.com/svg.latex?";
var arr;
$(document).ready(function () {
"use strict";
var variables = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var jsav = new JSAV("av");
var arrow = String.fromCharCode(8594),
lastRow, // index of the last visible row (the empty row)
//arr, // the grammar
backup = null, // a copy of the original grammar (as a string) before it is transformed
m, // the grammar table
tGrammar, // transformed grammar
derivationTable, // the derivation table shown during brute-force parsing
parseTableDisplay, // the parse table
parseTree, // parse tree shown during parsing slideshows
parseTable, // parse table used for pasing
conflictTable, // used for SLR parsing conflicts
ffTable, // table for FIRST and FOLLOW sets
arrayStep, // the position of FIRST or FOLLOW cells
selectedNode, // used for FA/graph editing
modelDFA, // DFA used to build SLR parse table
builtDFA, // DFA created by the user
type = $("h1").attr('id'), // type of parsing, can be bf, ll, slr
grammars, // stores grammar exercises, xml
currentExercise = 0,// current exercise index
multiple = false, // if multiple grammar editing is enabled
fi, // input box for matrix
row, // row number for input box
col; // column number for input box
var parenthesis = "(";
var lambda = String.fromCharCode(955),
epsilon = String.fromCharCode(949),
square = String.fromCharCode(9633),
dot = String.fromCharCode(183),
emptystring = lambda;
/*
If there is a grammar in local storage, load that grammar.
This is used to import grammars from certain proofs.
*/
//do not look at the storage if the editor is for an exercise
if (type == null && localStorage["grammar"]) {
arr = JSON.parse(localStorage.getItem("grammar"));
lastRow = arr.length;
// add an empty row for editing purposes (clicking the empty row allows the user to add productions)
//arr.push(["S", arrow, "jZ"]);
arr.push(["", arrow, ""]);
// clear the grammar from local storage to prevent it from being loaded by other grammar tests
localStorage.removeItem('grammar');
} else {
arr = new Array(20); // arbitrary array size
for (var i = 0; i < arr.length; i++) {
arr[i] = ["", arrow, ""];
}
lastRow = 0;
}
// Function to initialize/reinitialize the grammar display
var init = function () {
if (m) {
m.clear();
}
var m2 = jsav.ds.matrix(arr, {style: "table"});
// hide all of the empty rows
for (var i = lastRow+1; i < arr.length; i++) {
m2._arrays[i].hide();
}
layoutTable(m2, 2);
if(type !== "transformation")
m2.on('click', matrixClickHandler);
return m2;
};
// fired when document is clicked
// saves current fi input value
function defocus(e) {
if ($(e.target).hasClass("jsavvaluelabel")) return;
if ($(e.target).attr('id') == "firstinput") return;
if (!fi || !fi.is(':visible')) return;
var input = fi.val();
var regex = new RegExp(emptystring, g);
input = input.replace(regex, "");
input = input.replace(regex, "!");
if (input == "" && col == 2) {
input = emptystring;
}
if (input === "" && col === 0) {
//alert('Invalid left-hand side.');
fi.remove();
return;
}
if (col == 2 && _.find(arr, function(x) { return x[0] == arr[row][0] && x[2] == input && arr.indexOf(x) !== row;})) {
alert('This production already exists.');
return;
}
fi.remove();
m.value(row, col, input);
arr[row][col] = input;
layoutTable(m, 2);
}
// LL(1) parsing
var llParse = function () {
if(checkLHSVariables()){
alert('Your production is unrestricted on the left hand side');
return;
}
var firsts = {};
var follows = {};
var productions = _.map(_.filter(arr, function(x) { return x[0]}), function(x) {return x.slice();});
if (productions.length === 0) {
alert('No grammar.');
return;
}
var pDict = {}; // a dictionary mapping left sides to right sides
for (var i = 0; i < productions.length; i++) {
if (!(productions[i][0] in pDict)) {
pDict[productions[i][0]] = [];
}
pDict[productions[i][0]].push(productions[i][2]);
}
var derivers = {}; // variables that derive lambda
var counter = 0;
while (removeLambdaHelper(derivers, productions)) {
counter++;
if (counter > 500) {
console.log(counter);
break;
}
};
// variables
var v = {};
// terminals
var t = {};
for (var i = 0; i < productions.length; i++) {
var x = productions[i];
v[x[0]] = true;
for (var j = 0; j < x[2].length; j++) {
if (variables.indexOf(x[2][j]) !== -1) {
v[x[2][j]] = true;
} else if (x[2][j] !== emptystring) {
t[x[2][j]] = true;
}
}
}
v = Object.keys(v);
v.sort();
t = Object.keys(t);
t.sort();
t.push('$');
// populate firsts and follows sets
for (var i = 0; i < v.length; i++) {
firsts[v[i]] = first(v[i], pDict, derivers).sort();
}
for (var i = 0; i < v.length; i++) {
follows[v[i]] = follow(v[i], productions, pDict, derivers).sort();
}
/*
parseTable is the parse table, while parseTableDisplay is the matrix displayed to the user.
parseTableDisplay includes the row/column headers (which are ignored by the click handler).
*/
parseTable = [];
for (var i = 0; i < v.length; i++) {
var a = [];
for (var j = 0; j < t.length; j++) {
a.push("");
}
parseTable.push(a);
}
// fill in parseTable
for (var i = 0; i < productions.length; i++) {
var pFirst = first(productions[i][2], pDict, derivers);
var vi = v.indexOf(productions[i][0]);
for (var j = 0; j < pFirst.length; j++) {
var ti = t.indexOf(pFirst[j]);
if (pFirst[j] !== emptystring && ti !== -1) {
// exit parsing if a parse table conflict is found
if (parseTable[vi][ti] && parseTable[vi][ti] !== productions[i][2]) {
alert('This grammar is not LL(1)!');
return;
}
parseTable[vi][ti] = productions[i][2];
}
}
if (pFirst.indexOf(emptystring) !== -1) {
var pFollow = follows[productions[i][0]];
for (var j = 0; j < pFollow.length; j++) {
var ti = t.indexOf(pFollow[j]);
if (pFollow[j] !== emptystring && ti !== -1) {
// exit parsing if a parse table conflict is found
if (parseTable[vi][ti] && parseTable[vi][ti] !== productions[i][2]) {
alert('This grammar is not LL(1)!');
return;
}
parseTable[vi][ti] = productions[i][2];
}
}
}
}
startParse();
$('#followbutton').show();
$('.jsavcontrols').hide();
$(m.element).css("margin-left", "auto");
// $(m.element).css('position', 'absolute');
// create the table for FIRST and FOLLOW sets
var ffDisplay = [];
ffDisplay.push(["", "FIRST", "FOLLOW"]);
for (var i = 0; i < v.length; i++) {
var vv = v[i];
ffDisplay.push([vv, "", ""]);
}
jsav.umsg('Define FIRST sets. ! is '+emptystring+'.');
ffTable = new jsav.ds.matrix(ffDisplay);
// ffTable = new jsav.ds.matrix(ffDisplay, {left: "30px", relativeTo: m, anchor: "right top", myAnchor: "left top"});
arrayStep = 1;
ffTable.click(firstFollowHandler);
$('#followbutton').click(function () {
var check = continueToFollow(firsts, follows);
if (check) {
$('#parsetablebutton').show();
}
});
// Function to check FOLLOW set and transition to parse table editing
var continueToParseTable = function () {
$('#firstinput').remove();
var incorrect = checkTable(firsts, follows);
// provide option to complete FOLLOW sets automatically
if (incorrect.length > 0) {
var confirmed = confirm('The following sets are incorrect: ' + incorrect + '.\nFix automatically?');
if (confirmed) {
for (var i = 1; i < ffTable._arrays.length; i++) {
var a = ffTable._arrays[i].value(0);
ffTable.value(i, 2, follows[a]);
}
layoutTable(ffTable);
} else {
return;
}
}
$(ffTable.element).off();
$('#parsetablebutton').hide();
$('#parsereadybutton').show();
jsav.umsg('Fill entries in parse table. ! is '+emptystring+'.');
var pTableDisplay = [];
pTableDisplay.push([""].concat(t));
for (var i = 0; i < v.length; i++) {
var toPush = [v[i]];
for (var j = 0; j < parseTable[i].length; j++) {
toPush.push('');
}
pTableDisplay.push(toPush);
}
parseTableDisplay = new jsav.ds.matrix(pTableDisplay);
parseTableDisplay.addClass("parseTableDisplay");
parseTableDisplay.click(llparseTableHandler);
};
$('#parsetablebutton').click(continueToParseTable);
$('#parsereadybutton').click(function() {
checkllParseTable(parseTableDisplay, parseTable);
});
// do the parsing
var continueParse = function () {
var inputString = prompt('Input string');
if (inputString === null) {
return;
}
startParse();
$(m.element).css("margin-left", "auto");
//$(m.element).css('position', 'absolute');
var pTableDisplay = [];
pTableDisplay.push([""].concat(t));
for (var i = 0; i < v.length; i++) {
pTableDisplay.push([v[i]].concat(parseTable[i]));
}
//jsav.label('Grammar', {relativeTo: m, anchor: "center top", myAnchor: "center bottom"});
parseTableDisplay = new jsav.ds.matrix(pTableDisplay);
layoutTable(parseTableDisplay);
//parseTableDisplay = new jsav.ds.matrix(pTableDisplay, {left: "30px", relativeTo: m, anchor: "right top", myAnchor: "left top"});
var remainingInput = inputString + '$';
// display remaining input and the parse stack
updateSLRDisplay('<mark>' + remainingInput[0] + '</mark>' + remainingInput.substring(1) , ' <mark>' + productions[0][0] + '</mark>');
jsav.displayInit();
parseTree = new jsav.ds.tree();
var next;
var parseStack = [parseTree.root(productions[0][0])];
updateSLRDisplay('<mark>' + remainingInput[0] + '</mark>' + remainingInput.substring(1), "");
var accept = true;
parseTree.layout();
counter = 0;
while (true) {
counter++;
if (counter > 500) {
console.warn(counter);
break;
}
next = parseStack.pop();
if (!next) {
break;
}
var vi = v.indexOf(next.value());
var ti = t.indexOf(remainingInput[0])
// if the terminal on the stack and the next terminal in the input do not match, the string is rejected
if (vi === -1 && next.value() !== remainingInput[0]) {
accept = false;
break;
}
jsav.step();
// if terminal:
if (vi !== -1) {
var toAdd = parseTable[vi][ti];
if (!toAdd) {
accept = false;
break;
}
for (var j = 0; j < parseTableDisplay._arrays.length; j++) {
parseTableDisplay._arrays[j].unhighlight();
}
// highlight the relevant cell in the parse table (offset by 1 due to row/column headers)
parseTableDisplay.highlight(vi + 1, ti + 1);
var temp = [];
// create parse tree nodes
for (var i = 0 ; i < toAdd.length; i++) {
// note: .child(x, y) creates a child node but returns the parent
var n = next.child(i, toAdd[i]).child(i);
if (v.indexOf(toAdd[i]) === -1) {
n.addClass('terminal');
}
if (toAdd[i] !== emptystring) {
temp.unshift(n);
}
}
parseStack = parseStack.concat(temp);
parseTree.layout();
} else if (next.value() === remainingInput[0]) {
remainingInput = remainingInput.substring(1);
}
updateSLRDisplay('<mark>' + remainingInput[0] + '</mark>' + remainingInput.substring(1),
_.map(parseStack, function(x, k) {
if (k === parseStack.length - 1) {return '<mark>'+x.value()+'</mark>';} return x.value();}));
}
jsav.step();
if (accept && remainingInput[0] === '$' && !next) {
jsav.umsg('"' + inputString + '" accepted');
} else {
jsav.umsg('"' + inputString + '" rejected');
}
for (var j = 0; j < parseTableDisplay._arrays.length; j++) {
parseTableDisplay._arrays[j].unhighlight();
}
jsav.recorded();
};
// allow user to parse repeatedly with different inputs
$('#parsebutton').click(continueParse);
};
// SLR(1) parsing helpers:
// click handler for the nodes of the DFA being built
var dfaHandler = function (e) {
if (selectedNode) {
selectedNode.unhighlight();
}
if ($('.jsavgraph').hasClass('addfinals')) {
this.toggleClass('final');
}
else {
this.highlight();
// if node clicked is the toNode for the new edge
// check for goto set
if(selectedNode && localStorage['slrdfareturn']) {
var newItemSet = localStorage['slrdfareturn'].replace(/,/g, '<br>');
if (this.stateLabel() === newItemSet) {
builtDFA.addEdge(selectedNode, this, {weight: localStorage['slrdfasymbol']});
builtDFA.layout();
jsav.umsg("Build the DFA: Click a state.");
selectedNode.unhighlight();
this.unhighlight();
selectedNode = null;
return;
} else {
alert('Incorrect.');
this.unhighlight();
return;
}
}
// if node clicked is fromNode
var pr = prompt('Grammar symbol for the transition?');
if (!pr) {
this.unhighlight();
return;
}
var bEdges = this.getOutgoing();
for (var i = 0; i < bEdges.length; i++) {
if (bEdges[i].weight().split('<br>').indexOf(pr) !== -1) {
alert('Transition already created.');
this.unhighlight();
return;
}
}
selectedNode = this;
var nodes = modelDFA.nodes();
var checkNode;
for (var next = nodes.next(); next; next = nodes.next()) {
// get state label of the hidden node:
var modelItems = next._stateLabel.element[0].innerHTML.split('<br>');
// get state label of the visible node:
var builtItems = this.stateLabel().split('<br>');
// find the model node corresponding to the selected node:
var inter = _.intersection(modelItems, builtItems);
if (inter.length === modelItems.length && inter.length === builtItems.length) {
checkNode = next;
break;
}
}
// find model edge corresponding to transition to be built
var edges = checkNode.getOutgoing();
for (var i = 0; i < edges.length; i++) {
var w = edges[i].weight().split('<br>');
if (w.indexOf(pr) !== -1) {
// open goto window for user to fill out the item set
var productions = _.filter(arr, function(x) {return x[0];});
localStorage['slrdfaproductions'] = ["S'" + arrow + productions[0][0]].concat(_.map(productions, function(x) {return x.join('');}));
localStorage['slrdfaitemset'] = this.stateLabel().split('<br>');
localStorage['slrdfasymbol'] = pr;
window.open('slrGoTo.html', '', 'width = 800, height = 750, screenX = 300, screenY = 25');
jsav.umsg('Place the new node.');
break;
}
}
e.stopPropagation();
}
};
//Multiple Brute Force Parsing
function mbfParse(productions){
var productions = _.filter(arr, function(x) {return x[0];});
localStorage['grammars'] = JSON.stringify(productions);
window.open("./MBFParse.html");
};
/*
SLR(1) parsing
Does not check to see if the grammar is correct format.
*/
var slrParse = function () {
if(checkLHSVariables()){
alert('Your production is unrestricted on the left hand side');
return;
}
var productions = _.map(_.filter(arr, function(x) { return x[0]}), function(x) {return x.slice();});
if (productions.length === 0) {
alert('No grammar.');
return;
}
// variables:
var v = {};
// terminals:
var t = {};
for (var i = 0; i < productions.length; i++) {
var x = productions[i];
v[x[0]] = true;
for (var j = 0; j < x[2].length; j++) {
if (variables.indexOf(x[2][j]) !== -1) {
v[x[2][j]] = true;
} else if (x[2][j] !== emptystring) {
t[x[2][j]] = true;
}
}
}
v = Object.keys(v);
v.sort();
t = Object.keys(t);
t.sort();
t.push('$');
// terminals + variables:
var tv = t.concat(v);
// variables + terminals:
var vt = v.concat(t);
parseTable = [];
for (var i = 0; i < productions.length; i++) {
var a = [];
for (var j = 0; j < tv.length; j++) {
a.push("");
}
parseTable.push(a);
}
startParse();
$(m.element).css("margin-left", "auto");
// $(m.element).css('position', 'absolute');
var slrM = [[0, "S'", arrow, productions[0][0]]];
for (var i = 0; i < productions.length; i++) {
var prod = productions[i];
slrM.push([i+1, prod[0], prod[1], prod[2]]);
}
if (m) {
m.clear();
}
m = jsav.ds.matrix(slrM, {style: "table"});
layoutTable(m);
var ffDisplay = [];
ffDisplay.push(["", "FIRST", "FOLLOW"]);
for (var i = 0; i < v.length; i++) {
var vv = v[i];
ffDisplay.push([vv, "", ""]);
}
jsav.umsg('Define FIRST sets. ! is '+emptystring+'.');
ffTable = new jsav.ds.matrix(ffDisplay);
// ffTable = new jsav.ds.matrix(ffDisplay, {left: "30px", relativeTo: m, anchor: "right top", myAnchor: "left top"});
arrayStep = 1;
// build DFA to model the parsing stack
modelDFA = jsav.ds.FA({width: '90%', height: 440, layout: 'automatic'});
var sNode = modelDFA.addNode();
modelDFA.makeInitial(sNode);
sNode.stateLabel("S'"+arrow+dot+productions[0][0]);
var nodeStack = [sNode];
while (nodeStack.length > 0) {
var nextNode = nodeStack.pop();
nextNode.addClass('slrvisited');
var items = addClosure(nextNode.stateLabel().split('<br>'), productions);
nextNode.stateLabel(items.join('<br>'));
for (var i = 0; i < vt.length; i++) {
var symbol = vt[i];
var nextItems = addClosure(goTo(items, symbol), productions);
if (nextItems.length > 0) {
var nodes = modelDFA.nodes();
var toNode = null;
// check if node has already been created
for (var next = nodes.next(); next; next = nodes.next()) {
var curItems = next.stateLabel().split('<br>');
var inter = _.intersection(curItems, nextItems);
if (inter.length === curItems.length && inter.length === nextItems.length) {
toNode = next;
}
}
if (!toNode) {
toNode = modelDFA.addNode();
toNode.stateLabel(nextItems.join('<br>'));
}
modelDFA.addEdge(nextNode, toNode, {weight: symbol});
if (!toNode.hasClass('slrvisited')) {
nodeStack.push(toNode);
}
}
}
}
// add final states
var nodes = modelDFA.nodes();
for (var next = nodes.next(); next; next = nodes.next()) {
var items = next.stateLabel().split('<br>');
for (var i = 0; i < items.length; i++) {
var r = items[i];
if (r[r.length - 1] === dot) {
next.addClass('final');
break;
}
}
}
modelDFA.layout();
// use DFA to generate the parse table
var pDict = {}; // a dictionary mapping left sides to right sides
for (var i = 0; i < productions.length; i++) {
if (!(productions[i][0] in pDict)) {
pDict[productions[i][0]] = [];
}
pDict[productions[i][0]].push(productions[i][2]);
}
var derivers = {}; // variables that derive lambda
var counter = 0;
while (removeLambdaHelper(derivers, productions)) {
counter++;
if (counter > 500) {
console.log(counter);
break;
}
};
// get FIRSTs and FOLLOWs
var firsts = {};
for (var i = 0; i < v.length; i++) {
firsts[v[i]] = first(v[i], pDict, derivers).sort();
}
var follows = {};
for (var i = 0; i < v.length; i++) {
follows[v[i]] = follow(v[i], productions, pDict, derivers).sort();
}
// add the extra S' -> S production
pDict["S'"] = productions[0][0];
if (productions[0][0] in derivers) {
derivers["S'"] = true;
}
productions.unshift(["S'", arrow, productions[0][0]]);
// Create parse table using the DFA
nodes.reset();
var index = 0;
conflictTable = [];
for (var next = nodes.next(); next; next = nodes.next()) {
var row = [];
var conflictRow = [];
for (var j = 0; j < tv.length; j++) {
row.push("");
conflictRow.push([]);
}
parseTable.push(row);
conflictTable.push(conflictRow);
var edges = next.getOutgoing();
for (var i = 0; i < edges.length; i++) {
var w = edges[i].weight().split('<br>');
for (var j = 0; j < w.length; j++) {
var ti = t.indexOf(w[j]);
if (ti !== -1) {
var entry = 's' + edges[i].end().value().substring(1);
parseTable[index][ti] = entry;
conflictTable[index][ti].push(entry);
} else {
var vi = tv.indexOf(w[j]);
parseTable[index][vi] = edges[i].end().value().substring(1);
}
}
}
if (next.hasClass('final')) {
var l = next.stateLabel().split('<br>');
var rItem = null;
var rk = [];
for (var i = 0; i < l.length; i++){
if (l[i].indexOf(dot) === l[i].length - 1) {
rItem = l[i].substring(0, l[i].length-1);
if (!rItem.split(arrow)[1]) {
rItem = rItem + emptystring;
}
break;
}
}
if (rItem.substr(0, 2) === "S'") {
var ti = tv.indexOf('$');
parseTable[index][ti] = 'acc';
} else {
for (var i = 0; i < productions.length; i++) {
if (productions[i].join('') === rItem) {
rk.push(i);
}
}
for (var j = 0; j < rk.length; j++) {
var followSet = follows[productions[rk[j]][0]];
for (var i = 0; i < followSet.length; i++) {
var ti = tv.indexOf(followSet[i]);
parseTable[index][ti] = 'r' + rk[j];
conflictTable[index][ti].push('r' + rk[j]);
}
}
}
}
index++;
}
// var conflict = _.filter(conflictTable, function(row) {return _.filter(row, function(entry) {return entry.length > 1;});});
var conflict = _.filter(conflictTable, function() {
for (var r = 0; r < conflictTable.length; r++) {
for (var c = 0; c < conflictTable[r].length; c++) {
if (conflictTable[r][c].length > 1){
return true;
}
}
}
return false;
});
console.log(conflict);
modelDFA.hide();
$('#followbutton').show();
$('.jsavcontrols').hide();
if (conflict.length > 0) {
console.log("conflict.length: " + conflict.length);
var contin = confirm("This grammar is not SLR(1)\nContinue?");
if (!contin) {
$('#backbutton').click();
return;
}
}
// interactable FIRST/FOLLOW, same as LL parsing
ffTable.click(firstFollowHandler);
$('#followbutton').click(function () {
var check = continueToFollow(firsts, follows);
if (check) {
$('#slrdfabutton').show();
}
});
// Function to check FOLLOW sets and initialize the DFA
var continueToDFA = function () {
$('#firstinput').remove();
var incorrect = checkTable(firsts, follows);
// provide option to complete the FOLLOW sets automatically
if (incorrect.length > 0) {
var confirmed = confirm('The following sets are incorrect: ' + incorrect + '.\nFix automatically?');
if (confirmed) {
for (var i = 1; i < ffTable._arrays.length; i++) {
var a = ffTable._arrays[i].value(0);
ffTable.value(i, 2, follows[a]);
}
layoutTable(ffTable);
} else {
return;
}
}
$(ffTable.element).off();
$('#slrdfabutton').hide();
$('#parsetablebutton').show();
jsav.umsg('Build the DFA: Click a state.');
// create the DFA
builtDFA = jsav.ds.FA({width: '90%', height: 440});
builtDFA.enableDragging();
builtDFA.click(dfaHandler);
$('.jsavgraph').click(graphHandler);
$('#av').append($('#dfabuttons'));
$('#dfabuttons').show();
var pr = confirm("Would you like to define the initial set yourself?");
if (pr) {
// user fills out the initial set in the goTo window and adds the initial node to the graph manually
localStorage['slrdfaproductions'] = _.map(productions, function(x) {return x.join('');});
localStorage['slrdfasymbol'] = 'initial';
window.open('slrGoTo.html', '', 'width = 800, height = 750, screenX = 300, screenY = 25');
jsav.umsg("Add the initial node.");
} else {
// initial state is added automatically
var builtInitial = builtDFA.addNode({left: 50, top: 50});
builtDFA.makeInitial(builtInitial);
builtInitial.stateLabel(modelDFA.initial._stateLabel.element[0].innerHTML);
builtDFA.layout();
}
};
$('#slrdfabutton').click(continueToDFA);
// Function to check the DFA and transition to the parse table
var continueToParseTable = function () {
var edges1 = modelDFA.edges();
var edges2 = builtDFA.edges();
var tCount1 = 0,
tCount2 = 0,
correctFinals = true;
for (var next = edges1.next(); next; next = edges1.next()) {
tCount1 = tCount1 + next.weight().split('<br>').length;
}
for (var next = edges2.next(); next; next = edges2.next()) {
tCount2 = tCount2 + next.weight().split('<br>').length;
}
var bNodes = builtDFA.nodes();
for (var next = bNodes.next(); next; next = bNodes.next()) {
var nis = next.stateLabel().split('<br>');
var ff = _.find(nis, function(x) {return x[x.length - 1] === dot; });
if (ff && !next.hasClass('final')) {
correctFinals = false;
break;
}
if (!ff && next.hasClass('final')) {
correctFinals = false;
break;
}
}
// if the number of transitions and number of nodes match, and final nodes are correct
if (tCount1 !== tCount2 || modelDFA.nodeCount() !== builtDFA.nodeCount() || !correctFinals) {
var confirmed = confirm('Not finished!\nFinish automatically?');
// "finish automatically" = displaying the model DFA. This changes the layout.
if (confirmed) {
builtDFA.clear();
modelDFA.show();
} else {
return;
}
}
$('#dfabuttons').hide();
$('#parsetablebutton').hide();
$('#parsereadybutton').show();
jsav.umsg('Fill entries in parse table. ! is '+emptystring+'.');
// initialize parse table display
var pTableDisplay = [];
pTableDisplay.push([""].concat(tv));
for (var i = 0; i < modelDFA.nodeCount(); i++) {
var toPush = [i];
for (var j = 0; j < parseTable[i].length; j++) {
toPush.push('');
}
pTableDisplay.push(toPush);
}
//jsav.label('Grammar', {relativeTo: m, anchor: "center top", myAnchor: "center bottom"});
parseTableDisplay = new jsav.ds.matrix(pTableDisplay);
parseTableDisplay.click(slrparseTableHandler);
};
$('#parsetablebutton').click(continueToParseTable);
$('#parsereadybutton').click(function() {
checkslrParseTable(parseTableDisplay, parseTable);
});
// do the parsing
var continueParse = function () {
$('#buttons').prepend($('#parsebutton'));
var inputString = prompt('Input string');
if (inputString === null) {
return;
}
startParse();
var slrM = [];
for (var i = 0; i < productions.length; i++) {
var prod = productions[i];
slrM.push([i, prod[0], prod[1], prod[2]]);
}
if (m) {
m.clear();
}
m = jsav.ds.matrix(slrM, {style: "table"});
layoutTable(m);
var pTableDisplay = [];
pTableDisplay.push([""].concat(tv));
for (var i = 0; i < modelDFA.nodeCount(); i++) {
pTableDisplay.push([i].concat(parseTable[i]));
}
//parseTableDisplay = new jsav.ds.matrix(pTableDisplay, {left: "30px", relativeTo: m, anchor: "right top", myAnchor: "left top"});
$(m.element).css("margin-left", "auto");
$(m.element).css("margin-top", "0px");
parseTableDisplay = new jsav.ds.matrix(pTableDisplay);
layoutTable(parseTableDisplay);
// The parse 'tree' is a directed graph with layered output. This allows the tree to be built bottom up
parseTree = new jsav.ds.graph({layout: "layered", directed: true});
parseTree.element.addClass('parsetree');
var remainingInput = inputString + '$';
var parseStack = [0];
var currentRow = 0;
var accept = false;
var displayOrder = [];
updateSLRDisplay(remainingInput, productions[1][0]);
$('.jsavcontrols').insertAfter($('.jsavmatrix:eq(1)'));
$('.jsavoutput').insertAfter($('.jsavcontrols'));
var container = document.getElementById("container");
container.scrollTop = container.scrollHeight;
jsav.displayInit();
// m.hide();
// parseTableDisplay.hide();
updateSLRDisplay(remainingInput ,"");
counter = 0;
while (true) {
counter++;
if (counter > 500) {
console.warn(counter);
break;
}
// index of the lookahead
var lookAhead = tv.indexOf(remainingInput[0]);
// parse table entry to be processed
var entry = parseTable[currentRow][lookAhead];
for (var j = 0; j < m._arrays.length; j++) {
m.unhighlight(j);
}
for (var j = 0; j < parseTableDisplay._arrays.length; j++) {
parseTableDisplay.unhighlight(j);
}
parseTableDisplay.highlight(currentRow+1, lookAhead+1);
if (!entry) {
break;
}
if (entry === 'acc') {
accept = true;
jsav.step();
break;
}
if (entry[0] === 's') { // shift
// add parse tree node, and add items to the stack
var term = parseTree.addNode(remainingInput[0]);
term.addClass('terminal');
parseStack.push(term);
displayOrder.push(term);
currentRow = Number(entry.substring(1));
parseStack.push(currentRow);
remainingInput = remainingInput.substring(1);
parseTree.layout();
} else if (entry[0] === 'r') { // reduce
var pIndex = Number(entry.substring(1));
var p = productions[pIndex];
m.highlight(pIndex);
if (p[2] === emptystring) {
var lNode = parseTree.addNode(emptystring);
lNode.addClass('terminal');
parseTree.layout();
jsav.step();
var par = parseTree.addNode(p[0]);
parseTree.addEdge(par, lNode);
var n = currentRow;
} else {
var par = parseTree.addNode(p[0]);
var childs = [];
for (var i = p[2].length - 1; i >= 0; i--) {
parseStack.pop();
childs.unshift(parseStack.pop());
}
for (var i = 0; i < childs.length; i++) {
parseTree.addEdge(par, childs[i]);
}
var n = parseStack[parseStack.length - 1];
}
parseTree.layout();
updateSLRDisplay(remainingInput,
_.map(parseStack, function(x, k) {
if (typeof x === 'number' || typeof x === 'string') {
return x;
}
return x.value();}));
jsav.step();
parseStack.push(par);
displayOrder.push(par);
currentRow = Number(parseTable[n][tv.indexOf(p[0])]);
for (var j = 0; j < parseTableDisplay._arrays.length; j++) {
parseTableDisplay.unhighlight(j);
}
parseTableDisplay.highlight(n+1, tv.indexOf(p[0]) + 1);
parseStack.push(currentRow);
parseTree.layout();
}
updateSLRDisplay(remainingInput,
_.map(parseStack, function(x, k) {
if (typeof x === 'number' || typeof x === 'string') {
return x;
}
return x.value();}));
jsav.step();
}
if (accept) {
jsav.umsg('"' + inputString + '" accepted');
} else {
jsav.umsg('"' + inputString + '" rejected');
}
jsav.recorded();
};
$('#parsebutton').click(continueParse);
};
// change editing modes
var editMode = function() {
$('.jsavmatrix').addClass("editMode");
$('.jsavmatrix').removeClass("deleteMode");
$('.jsavmatrix').removeClass("addrowMode");
$("#mode").html('Editing');
};
var deleteMode = function() {
$('#firstinput').remove();
$('.jsavmatrix').addClass("deleteMode");
$('.jsavmatrix').removeClass("addrowMode");
$('.jsavmatrix').removeClass("editMode");
jsav.umsg('Deleting');
};
var addrowMode = function(){
if (lastRow === arr.length - 1 || lastRow === arr.length) {
var l = arr.length;
for (var i = 0; i < l; i++) {
arr.push(['', arrow, '']);
}
m = init();
$('.jsavmatrix').addClass('editMode');
// if (!arr[index][2]) {
// arr[index][2] = lambda;
// m.value(index, 2, lambda);
// }
}
m._arrays[lastRow + 1].show();
lastRow++;
layoutTable(m);
jsav.umsg('Editing');
$('.jsavmatrix').addClass("editMode");
$('.jsavmatrix').removeClass("deleteMode");
$('.jsavmatrix').removeClass("addrowMode");
};
// Function to start grammar transformation
var transformGrammar = function () {
if (typeof getCombinations === "undefined") {
console.error("No generator support.");
return;
}
var productions = _.map(_.filter(arr, function(x) { return x[0];}), function(x) { return x.slice();});
if (productions.length === 0) {
alert('No grammar.');
return;
}
// apply each transformation to the original grammar to find which step to start with
var noLambda = removeLambda();
var noUnit = removeUnit();
var noUseless = removeUseless();
var fullChomsky = convertToChomsky();
var strP = _.map(productions, function(x) {return x.join('');});
// store original grammar for reloading later
backup = ""+strP;
if (!checkTransform(strP, noLambda)) {
interactableLambdaTransform(noLambda);
} else if (!checkTransform(strP, noUnit)) {
interactableUnitTransform(noUnit);
} else if (!checkTransform(strP, noUseless)) {
interactableUselessTransform(noUseless);
} else if (!checkTransform(strP, fullChomsky)) {
interactableChomsky(fullChomsky);
} else {
backup = null;
jsav.umsg('Grammar already in Chomsky Normal Form.');
return true;
}
};
//=================================
// Conversions
// interactive converting right-linear grammar to FA
var convertToFA = function () {
if(checkLHSVariables()){
alert('Your production is unrestricted on the left hand side');
return;
}
if (!checkRightLinear()) {
alert('The grammar is not right-linear!');
return;
}
var productions = _.filter(arr, function(x) { return x[0];});
startParse();
$('.jsavcontrols').hide();
$('#completeallbutton').show();
$(m.element).css("margin-left", "auto");
jsav.umsg('Complete the FA.');
// keep a map of variables to FA states
var nodeMap = {};
builtDFA = jsav.ds.FA({width: '90%', height: 440, layout: "automatic"});
builtDFA.enableDragging();
var newStates = []; // variables
for (var i = 0; i < productions.length; i++) {
newStates.push(productions[i][0]);
newStates = newStates.concat(_.filter(productions[i][2], function(x) {return variables.indexOf(x) !== -1;}));
}
newStates = _.uniq(newStates);
// create FA states
for (var i = 0; i < newStates.length; i++) {
var n = builtDFA.addNode();
nodeMap[newStates[i]] = n;
if (i === 0) {
builtDFA.makeInitial(n);
}
n.stateLabel(newStates[i]);
}
// add final state
var f = builtDFA.addNode();
// nodeMap[emptystring] = f;
f.addClass("final");
builtDFA.layout();
selectedNode = null;
// check if FA is finished; if it is, ask if the user wants to export the FA
var checkDone = function () {
var edges = builtDFA.edges();
var tCount = 0;
for (var next = edges.next(); next; next = edges.next()) {
var w = next.weight().split('<br>');
tCount = tCount + w.length;
}
console.log("tCount: " + tCount + " productions.length: " + productions.length);
if (tCount === productions.length) {
var confirmed = confirm('Finished! Export?');
if (confirmed) {
exportConvertedFA();
}
}
};
var completeConvertToFA = function() {
for (var i = 0; i < productions.length; i++) {
// if the current production is not finished yet
if (!m.isHighlight(i)){
var start = nodeMap[productions[i][0]];
var rhs = productions[i][2];
//if there is no capital letter, then go to final state
if(variables.indexOf(rhs[rhs.length-1]) === -1){
var end = f;
var w = rhs;
} else {
var end = nodeMap[rhs[rhs.length-1]];
var w = rhs.substring(0, rhs.length-1);
}
m.highlight(i);
var newEdge = builtDFA.addEdge(start, end, {weight: w});
if (newEdge) {
newEdge.layout();
checkDone();
}
}
}
}
$('#completeallbutton').click(completeConvertToFA);
// handler for the nodes of the FA
var convertDfaHandler = function (e) {
// adding transitions
this.highlight();
if (selectedNode) {
var t = prompt('Terminal to transition on?');
if (t === null) {
selectedNode.unhighlight();
selectedNode = null;
this.unhighlight();
return;
}
var lv = selectedNode.stateLabel();
var rv = this.stateLabel();
// check if valid transition
for (var i = 0; i < productions.length; i++) {
var r = productions[i][2];
var add = false;
if (rv && productions[i][0] === lv && r[r.length - 1] === rv && r.substring(0, r.length - 1) === t) {
add = true;
}
if (productions[i][0] === lv && this.hasClass('final') && (r === t || (r === emptystring && t === ""))) {
add = true;
}
if (add) {
m.highlight(i);
var newEdge = builtDFA.addEdge(selectedNode, this, {weight: t});
selectedNode.unhighlight();
selectedNode = null;
this.unhighlight();
if (newEdge) {
newEdge.layout();
checkDone();
}
return;
}
}
alert('That transition is not correct.');
selectedNode.unhighlight();
selectedNode = null;
this.unhighlight();
} else {
selectedNode = this;
}
e.stopPropagation();
};
// handler for the grammar table: clicking a production will create the appropriate transition
var convertGrammarHandler = function (index) {
this.highlight(index);
var l = this.value(index, 0);
var r = this.value(index, 2);
var nodes = builtDFA.nodes();
if (variables.indexOf(r[r.length - 1]) === -1) {
var newEdge = builtDFA.addEdge(nodeMap[l], f, {weight: r});
} else {
var newEdge = builtDFA.addEdge(nodeMap[l], nodeMap[r[r.length - 1]], {weight: r.substring(0, r.length - 1)});
}
if (newEdge) {
newEdge.layout();
checkDone();
}
};
builtDFA.click(convertDfaHandler);
m.click(convertGrammarHandler);
$('#av').append($('#convertmovebutton'));
};
// interactive converting context-free grammar to NPDA
var convertToPDA = function (event) {
if(checkLHSVariables()){
alert('Your production is unrestricted on the left hand side');
return;
}
var productions = _.filter(arr, function(x) { return x[0];});
startParse();
$('.jsavcontrols').hide();
$(m.element).css("margin-left", "auto");
jsav.umsg('Complete the NPDA.');
builtDFA = jsav.ds.FA({width: '90%', height: 440});
var gWidth = builtDFA.element.width(),
gHeight = builtDFA.element.height();
var a = builtDFA.addNode({left: 0.17 * gWidth, top: 0.87 * gHeight}),
b = builtDFA.addNode({left: 0.47 * gWidth, top: 0.87 * gHeight}),
c = builtDFA.addNode({left: 0.77 * gWidth, top: 0.87 * gHeight});
builtDFA.makeInitial(a);
c.addClass('final');
var startVar = productions[0][0];
if(event.data.param1){
convertToPDAinLL(a, b, c, productions, startVar);
}else{
convertToPDAinLR(a, b, c, productions, startVar);
}
};
//=================================
// Files
// Function to save and download the grammar
var saveFile = function () {
var downloadData = "text/xml; charset=utf-8,";
if (!multiple) {
downloadData += encodeURIComponent(serializeGrammar());
}
else {
grammars[currentExercise] = serializeGrammar();
var data = '<?xml version="1.0" encoding="UTF-8"?><structure><type>grammar</type>';
_.each(grammars, function(grammar) {
data += grammar;
});
data += "</structure>";
downloadData += encodeURIComponent(data);
}
$('#download').html('<a href="data:' + downloadData + '" target="_blank" download="grammar.jff">Download Grammar</a>');
$('#download a')[0].click();
};
// Loading:
// Function to read the loaded XML file and create the grammar
// @param condition: whether text is of the form "<grammar>...</grammar>"
// used for parsing a grammar in multiple mode
// "exer": LL, BF, SLR parsing exercises
// "multiple": multiple grammar editing
var parseFile = function (text, condition) {
var parser,
xmlDoc,
xmlElem;
if (!condition) {
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
} else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
if (xmlDoc.getElementsByTagName("type")[0].childNodes[0].nodeValue !== 'grammar') {
alert('File does not contain a grammar.');
return;
} else {
xmlElem = xmlDoc.getElementsByTagName("production");
}
}
else if (condition == "exer") {
xmlElem = text.getElementsByTagName("production");
}
else if (condition == "multiple") {
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
} else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
xmlElem = xmlDoc.getElementsByTagName("production");
}
else {
alert("unknown error");
}
arr = [];
for (var i = 0; i < xmlElem.length; i++) {
var l = xmlElem[i].getElementsByTagName("left")[0].childNodes[0].nodeValue;
var r = xmlElem[i].getElementsByTagName("right")[0].childNodes[0].nodeValue;
var row = [l, arrow, r];
arr.push(row);
}
lastRow = arr.length;
// add an empty row for editing purposes (clicking the empty row allows the user to add productions)
arr.push(["", arrow, ""]);
m = init();
$('.jsavmatrix').addClass("editMode");
// clear input
var loaded = $('#loadfile');
loaded.wrap('<form>').closest('form').get(0).reset();
loaded.unwrap();
return;
};
// Function for reading the XML file
var waitForReading = function (reader) {
reader.onloadend = function(event) {
var text = event.target.result;
parseFile(text);
}
};
// Function to load in an XML file
var loadFile = function () {
var loaded = document.getElementById('loadfile');
var file = loaded.files[0],
reader = new FileReader();
waitForReading(reader);
reader.readAsText(file);
};
/*
Function to check if FIRST / FOLLOW sets are correct (either FIRST sets or FOLLOW sets).
Returns a list of the incorrect variables.
*/
function checkTable(firsts, follows) {
var checker;
// arrayStep can be 1 or 2
if (arrayStep === 1) {
checker = firsts;
} else {
checker = follows;
}
var incorrect = [];
for (var i = 1; i < ffTable._arrays.length; i++) {
var a = ffTable._arrays[i];
var fvar = a.value(0);
var fset = a.value(arrayStep);
var check1 = checker[fvar];
var check2 = fset.split(',');
var inter = _.intersection(check1, check2);
if (inter.length !== check1.length || inter.length !== check2.length) {
incorrect.push(fvar);
}
}
return incorrect
};
// Function to check if the SLR parse table is correct and transition
function checkslrParseTable(parseTableDisplay, parseTable) {
$('#firstinput').remove();
var incorrect = false;
for (var i = 1; i < parseTableDisplay._arrays.length; i++) {
var ptr = parseTableDisplay._arrays[i];
ptr.unhighlight();
for (var j = 1; j < ptr._indices.length; j++) {
// check conflict table first to avoid mistaken the students
var wrongEntry = false;
if (conflictTable[i - 1] && conflictTable[i - 1][j - 1]) {
if (conflictTable[i-1][j-1].indexOf(parseTableDisplay.value(i, j)) == -1) {
parseTableDisplay.highlight(i, j);
incorrect = true;
wrongEntry = true;
}
}
else if (parseTable[i-1][j-1] !== parseTableDisplay.value(i, j)) {
parseTableDisplay.highlight(i, j);
incorrect = true;
wrongEntry = true;
}
if (!wrongEntry) {
parseTable[i-1][j-1] = parseTableDisplay.value(i, j);
}
}
}
// provide option to automatically complete the parse table
if (incorrect) {
var container = document.getElementById("container");
container.scrollTop = container.scrollHeight;
window.scrollTo(0,document.body.scrollHeight);
var confirmed = confirm('Highlighted cells are incorrect.\nFix automatically?');
if (confirmed) {
for (var i = 1; i < parseTableDisplay._arrays.length; i++) {
for (var j = 1; j < ptr._indices.length; j++) {
var wrong = parseTableDisplay.isHighlight(i, j);
parseTableDisplay.unhighlight(i, j);
// when current entry is wrong && there is a conflict
if (wrong && conflictTable[i-1] && conflictTable[i-1][j-1] && conflictTable[i-1][j-1].length > 1) {
// there is a conflict, either reduce-reduce or reduce-shift
parseTableDisplay.highlight(i, j);
}
parseTableDisplay.value(i, j, parseTable[i-1][j-1]);
}
}
layoutTable(parseTableDisplay);
} else {
return;
}
}
$('#parsereadybutton').hide();
$('#parsebutton').show();
$temp = $('<div>').attr({"align":"center"});
$temp.append($('#parsebutton'));
$temp.insertBefore($('.jsavcanvas .jsavmatrix:last-child'));
jsav.umsg("");
$('.jsavarray').off();
};
// check for the correctness of parse table of LL
var checkllParseTable = function (parseTableDisplay, parseTable) {
$('#firstinput').remove();
var incorrect = false;
for (var i = 1; i < parseTableDisplay._arrays.length; i++) {
var ptr = parseTableDisplay._arrays[i];
ptr.unhighlight();
for (var j = 1; j < ptr._indices.length; j++) {
if (parseTable[i-1][j-1] !== parseTableDisplay.value(i, j)) {
parseTableDisplay.highlight(i, j);
incorrect = true;
}
}
}
// provide option to automatically complete the parse table
if (incorrect) {
var container = document.getElementById("container");
container.scrollTop = container.scrollHeight;
var confirmed = confirm('Highlighted cells are incorrect.\nFix automatically?');
if (confirmed) {
for (var i = 1; i < parseTableDisplay._arrays.length; i++) {
var ptr = parseTableDisplay._arrays[i];
ptr.unhighlight();
for (var j = 1; j < ptr._indices.length; j++) {
parseTableDisplay.value(i, j, parseTable[i-1][j-1]);
}
}
layoutTable(parseTableDisplay);
} else {
return;
}
}
$('#parsereadybutton').hide();
$('#parsebutton').show();
jsav.umsg("");
$('.jsavarray').off();
};
// click handler for the SLR parse table
function slrparseTableHandler (index, index2, e) {
// ignore if first row or column
$('#firstinput').remove();
if (index === 0 || index2 === 0) { return; }
if (conflictTable[index-1] && conflictTable[index-1][index2-1] && conflictTable[index-1][index2-1].length > 1) {
$('.conflictMenu').remove();
var offsetX = e.pageX;
var offsetY = e.pageY;
var $chooseConflict = $("<div>", {class: "conflictMenu"});
_.each(conflictTable[index-1][index2-1], function(choice) {$chooseConflict.append("<input type='button' value='" + choice + "' class='choice'/><br>");});
// in order to pass indices of matrix
$chooseConflict.attr({"i": index, "j": index2});
$chooseConflict.css({"position": "absolute", top: offsetY, left: offsetX});
$chooseConflict.show();
$('#container').append($chooseConflict);
$('.choice').off('click').click(choiceClickHandler);
return;
}
var self = this;
var prev = this.value(index, index2);
if (!prev) return;
// create input box
var createInput = "<input type='text' id='firstinput' value="+prev+" onfocus='this.value = this.value;'>";
$('body').append(createInput);
var offset = this._arrays[index]._indices[index2].element.offset();
var topOffset = offset.top;
var leftOffset = offset.left;
var fi = $('#firstinput');
fi.offset({top: topOffset, left: leftOffset});
fi.outerHeight($('.jsavvalue').height());
fi.width($(this._arrays[index]._indices[index2].element).width());
fi.focus();
// finalize changes when enter key is pressed
fi.keyup(function(event){
if(event.keyCode == 13){
var firstInput = $(this).val();
firstInput = firstInput.replace(/!/g, emptystring);
self.value(index, index2, firstInput);
layoutTable(self, index2);
fi.remove();
}
});
};
// Function to transition from editing FIRST sets to editing FOLLOW sets
function continueToFollow (firsts, follows) {
$('#firstinput').remove();
var incorrect = checkTable(firsts, follows);
// provide option to complete the FIRST sets automatically
if (incorrect.length > 0) {
var confirmed = confirm('The following sets are incorrect: ' + incorrect + '.\nFix automatically?');
if (confirmed) {
for (var i = 1; i < ffTable._arrays.length; i++) {
var a = ffTable._arrays[i].value(0);
ffTable.value(i, 1, firsts[a]);
}
layoutTable(ffTable);
} else {
return false;
}
}
$(ffTable.element).off();
$('#followbutton').hide();
jsav.umsg('Define FOLLOW sets. $ is the end of string character.');
arrayStep = 2;
ffTable.click(firstFollowHandler);
return true;
};
function cykParse() {
if(!transformGrammar()){
alert("The grammar must be in CNF form to be parsed!");
return;
}
var productions = _.map(_.filter(arr, function(x) { return x[0]}), function(x) {return x.slice();});
localStorage['grammars'] = JSON.stringify(productions);
window.open("./CYKParser.html");
}
//=================================
// Buttons for editing the SLR DFA
$('#finalbutton').click(function() {
$('.jsavgraph').removeClass('builddfa');
$('.jsavgraph').addClass('addfinals');
jsav.umsg('Click a node to toggle final state.');
});
$('#gotobutton').click(function() {
$('.jsavgraph').removeClass('addfinals');
$('.jsavgraph').addClass('builddfa');
jsav.umsg('Build the DFA: Click a state.');
});
//=================================
// Button for exiting a proof (parsing or transformation)
$('#backbutton').click(function () {
if (parseTree) {
parseTree.clear();
jsav.clear();
jsav = new JSAV("av");
}
if (derivationTable) { derivationTable.clear();}
if (ffTable) { ffTable.clear();}
parseTable = [];
$('.conflictMenu').remove();
if (parseTableDisplay) { parseTableDisplay.clear();}
if (modelDFA) { modelDFA.clear();}
if (builtDFA) { builtDFA.clear();}
if (tGrammar) { tGrammar.clear();}
if (backup) {
arr = _.map(backup.split(','), function(x) {
var d = x.split(arrow);
d.splice(1, 0, arrow);
return d;
});
lastRow = arr.length;
arr.push(["", arrow, ""]);
backup = null;
}
$('.jsavcanvas').height("auto");
$('#movebutton').off();
$('#finalbutton').off();
$('#gotobutton').off();
$('#dfabuttons').hide();
$('#convertmovebutton').off();
$('#convertmovebutton').hide();
m = init();
$('#firstinput').remove();
$('#temp').remove();
jsav.umsg('');
$('button').show();
$('#transformbutton').show();
$('.jsavcontrols').hide();
$('#backbutton').hide();
$('.parsingbutton').off();
$('.parsingbutton').hide();
$('#completeallbutton').hide();
$('#files').show();
$(m.element).css("margin-left", "auto");
$('.jsavmatrix').addClass("editMode");
});
$('#helpbutton').click(displayHelp);
$('#editbutton').click(editMode);
$('#deletebutton').click(deleteMode);
$('#addrowbutton').click(addrowMode);
$('#mbfpbutton').click(mbfParse);
$('#llbutton').click(llParse);
$('#slrbutton').click(slrParse);
$('#cykbutton').click(cykParse);
$('#transformbutton').click(transformGrammar);
$('#loadfile').on('change', loadFile);
$('#savefile').click(saveFile);
$('#convertRLGbutton').click(convertToFA);
$('#convertCFGbuttonLL').click({param1: true}, convertToPDA);
$('#convertCFGbuttonLR').click({param1: false}, convertToPDA);
$('#multipleButton').click(toggleMultiple);
$('#addExerciseButton').click(addExercise);
$('#identifybutton').click(identifyGrammar);
$('#clearbutton').click(clearAll);
$('#completeallbutton').hide();
$(document).click(defocus);
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$('#firstinput').remove();
fi = null;
}
});
function buildDFA(){
var randomDFA = jsav.ds.FA($.extend({width: '750px', height: 440, layout: "automatic", directed: true}));
var a, b, c, d, e, f, g;
var nodeArray = [a, b, c, d, e, f, g];
var randomInputType = Math.floor(Math.random() * 2);
var transferArray;
if (randomInputType === 0){
transferArray = ["0", "1"];
}
else{
transferArray = ["a", "b"];
}
var nodeSize = Math.floor(Math.random() * 6) + 2;
var i;
nodeArray[0] = randomDFA.addNode();
randomDFA.makeInitial(nodeArray[0])
for (i = 1; i < nodeSize; i++){
nodeArray[i] = randomDFA.addNode();
}
nodeArray[i-1].addClass("final");
//start node
var randomWeight = Math.floor(Math.random() * 2);
var toNode3 = Math.floor(Math.random() * nodeSize) + 1;
randomDFA.addEdge(nodeArray[0], nodeArray[toNode3], {weight: transferArray[randomWeight]});
//the rest node
for (i = 0; i < nodeSize; i++){
if (i === 0){
var toNode4 = Math.floor(Math.random() * nodeSize) + 1;
randomDFA.addEdge(nodeArray[0], nodeArray[toNode4], {weight: transferArray[randomWeight ^ 1]});
}
else {
var firstTransferRandom = Math.floor(Math.random() * 2);
if (firstTransferRandom === 1) {
var toNode = Math.floor(Math.random() * nodeSize);
randomDFA.addEdge(nodeArray[i], nodeArray[toNode], {weight: transferArray[0]});
}
var secondTransferRandom = Math.floor(Math.random() * 2);
if (secondTransferRandom === 1) {
var toNode2 = Math.floor(Math.random() * nodeSize);
randomDFA.addEdge(nodeArray[i], nodeArray[toNode2], {weight: transferArray[1]});
}
if (firstTransferRandom === 0 && secondTransferRandom === 0) {
var randomWeight = Math.floor(Math.random() * 2);
var toNode3 = Math.floor(Math.random() * nodeSize);
randomDFA.addEdge(nodeArray[i], nodeArray[toNode3], {weight: transferArray[randomWeight]});
}
}
}
randomDFA.layout();
}
function buildNFA(){
var randomNFA = jsav.ds.FA($.extend({width: '750px', height: 440, layout: "automatic", directed: true}));
var a, b, c, d, e, f, g;
var nodeArray = [a, b, c, d, e, f, g];
var randomInputType = Math.floor(Math.random() * 2);
var transferArray;
if (randomInputType === 0){
transferArray = ["0", "1"];
}
else{
transferArray = ["a", "b"];
}
var nodeSize = Math.floor(Math.random() * 6) + 2;
var i;
nodeArray[0] = randomNFA.addNode();
randomNFA.makeInitial(nodeArray[0])
for (i = 1; i < nodeSize; i++){
nodeArray[i] = randomNFA.addNode();
}
nodeArray[i-1].addClass("final");
//start node
var randomWeight = Math.floor(Math.random() * 2);
var toNode3 = Math.floor(Math.random() * nodeSize) + 1;
randomNFA.addEdge(nodeArray[0], nodeArray[toNode3], {weight: transferArray[randomWeight]});
for (i = 0; i < nodeSize; i++){
if (i === 0){
var toNode4 = Math.floor(Math.random() * nodeSize) + 1;
randomNFA.addEdge(nodeArray[0], nodeArray[toNode4], {weight: transferArray[randomWeight ^ 1]});
}
else {
var transferTimes = Math.floor(Math.random() * 3) + 1;
var j;
for (j = 0; j < transferTimes; j++) {
var toNode = Math.floor(Math.random() * nodeSize);
randomNFA.addEdge(nodeArray[i], nodeArray[toNode], {weight: transferArray[0]});
if (j > 0 && randomNFA.hasEdge(nodeArray[i], nodeArray[toNode], {weight: transferArray[0]})) {
break;
}
}
var transferTimes2 = Math.floor(Math.random() * 3) + 1;
for (j = 0; j < transferTimes2; j++) {
var toNode2 = Math.floor(Math.random() * nodeSize);
randomNFA.addEdge(nodeArray[i], nodeArray[toNode2], {weight: transferArray[1]});
if (j > 0 && randomNFA.hasEdge(nodeArray[i], nodeArray[toNode2], {weight: transferArray[1]})) {
break;
}
}
}
}
randomNFA.layout();
}
function onLoadHandler() {
$('#loadFile').hide();
$('#saveFile').hide();
$('#backbutton').hide();
$('.multiple').hide();
$('#addExerciseButton').hide();
buildDFA()
buildNFA()
}
function initQuestionLinks() {
$("#exerciseLinks").html("");
//not from localStorage but from XML file
if (grammars) {
for (i = 0; i < grammars.length; i++) {
$("#exerciseLinks").append("<a href='#' id='" + i + "' class='links'>" + (i+1) + "</a>");
}
$('.links').click(toExercise);
}
}
function updateQuestionLinks() {
$(".links").removeClass("currentExercise");
$("#" + currentExercise).addClass("currentExercise");
}
function updateExercise(index) {
currentExercise = index;
if (multiple) {
parseFile(grammars[index], "multiple");
}
else {
parseFile(grammars[index], "exer");
}
updateQuestionLinks();
}
function toExercise() {
$('#firstinput').remove();
grammars[currentExercise] = serializeGrammar();
var index = $(this).attr('id');
updateExercise(index);
}
function toggleMultiple() {
multiple = !multiple;
if (multiple) {
$('#addExerciseButton').show();
$('#loadfile').hide();
$('.multiple').show();
$('#firstinput').remove();
grammars = [];
grammars.push(serializeGrammar());
initQuestionLinks();
updateQuestionLinks();
}
else {
$('.multiple').hide();
$('#addExerciseButton').hide();
$('#loadfile').show();
}
}
function addExercise() {
grammars.push("<grammar></grammar>");
initQuestionLinks();
updateQuestionLinks();
}
onLoadHandler();
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function displayHelp(){
alert(document.getElementById('helpInfo').innerHTML);
}
function isRegularGrammar(){
return (checkRightLinear() || checkLeftLinear());
}
function checkLeftLinear(){
var productions = _.filter(arr, function(x) { return x[0]});
for (var i = 0; i < productions.length; i++) {
//r is the RHS
var r = productions[i][2];
for (var j = 0; j < r.length; j++) {
if (variables.indexOf(r[j]) !== -1 && j !== 0) {
return false;
}
}
}
return true;
}
function isContextFreeGrammar(){
var productions = _.filter(arr, function(x) { return x[0]});
for (var i = 0; i < productions.length; i++) {
var lhs = productions[i][0];
if (lhs.length !== 1 || variables.indexOf(lhs) === -1) {
return false;
}
}
return true;
}
function checkLHSVariables(){
//check if there is more than one variable on the LHS
var productions = _.filter(arr, function(x) { return x[0]});
for (var i = 0; i < productions.length; i++) {
var lhs = productions[i][0];
if (lhs.length !== 1) {
return true;
} else if (variables.indexOf(lhs) === -1){
return true;
}
}
return false;
}
function clearAll(){
window.location.href="";
}
function identifyGrammar() {
//Check if there is more than one variable on the LHS, if so it is an unrestricted grammar.
if(checkLHSVariables()){
alert('This grammar is an unrestricted grammar');
return;
}
// e.g. S->a could be both
if(checkLeftLinear() && checkRightLinear()){
alert('This grammar is both left-linear and right-linear (Regular Grammar and Context-Free Grammar)');
return;
}
if(checkLeftLinear()) {
alert('This grammar is a left-linear Grammar (Regular Grammar and Context-Free Grammar)');
return;
}
if(checkRightLinear()) {
alert('This grammar is a right-linear Grammar (Regular Grammar and Context-Free Grammar)');
return;
}
if(isContextFreeGrammar()){
alert('This grammar is a Context-Free Grammar');
return;
}
}
});
|
/*
Description:
Given a text, for example:
const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?";
get an array of last names of people named Michael.
The result should be:
["Jordan", "Johnson", "Green", "Wood"]
Notes:
First name will always be Michael with upper case 'M'.
There will always be a space character between 'Michael' and last name.
Last name will always be one word, starting with an upper-case letter and continuing with lower-case letters.
There will always be at least one 'Micheal' with a valid last name in the input text.
*/
function getMichaelLastName(inputText) {
var fullNames = inputText.match(/Michael\s[A-Z][a-z]{0,}/g);
var lastNames = [];
for (var i = 0; i < fullNames.length; i++) {
var currentFullName = fullNames[i];
var lastName = currentFullName.split(/Michael\s/)[1];
lastNames.push(lastName);
}
return lastNames;
}
|
export function reduceValueAction(state, action) {
return {
...state,
[action.id]: action.value
};
}
/* eslint func-names:0 */
export function valueReducer(actionType, initialState) {
return function (state = initialState, action) {
switch (action.type) {
case actionType:
return reduceValueAction(state, action);
default:
return state;
}
};
}
export function topLevelReducer(actionType, initialState) {
return function (state = initialState, action) {
switch (action.type) {
case actionType:
return action.value;
default:
return state;
}
};
}
export function nestedReducer(actionType, initialState) {
return function (state = initialState, action) {
switch (action.type) {
case actionType:
return {
...state,
[action.idx]: reduceValueAction(state[action.idx], action)
};
default:
return state;
}
};
}
|
import Phaser from 'phaser';
import ScrollingBackground from './entityScrollingBackground';
import localScore from './localScore';
import api from './apiController';
import display from './domController';
class SceneMainMenu extends Phaser.Scene {
constructor() {
super({ key: 'SceneMainMenu' });
}
preload() {
this.load.setBaseURL('./assets/');
this.load.image('gameTitle', 'content/Title.png');
this.load.image('alien', 'content/alien_94.png');
this.load.image('sprBg0', 'content/sprBg0.png');
this.load.image('sprBg1', 'content/sprBg1.png');
this.load.image('sprBtnPlay', 'content/play_buttons.png');
this.load.image('sprBtnPlayHover', 'content/play_button_pressed.png');
this.load.image('sprBtnPlayDown', 'content/play_button_pressed.png');
this.load.image('sprBtnRestart', 'content/exit_buttons.png');
this.load.image('sprBtnRestartHover', 'content/exit_buttons_pressed.png');
this.load.image('leaderBoard1', 'content/button_leader-board.png');
this.load.image('leaderBoard2', 'content/button_leader-board2.png');
this.load.image('sprBtnRestartDown', 'content/exit_buttons_pressed.png');
this.load.audio('sndBtnOver', 'content/sndBtnOver.wav');
this.load.audio('sndBtnDown', 'content/sndBtnDown.wav');
}
create() {
// Controller instructions
display.displayControls();
// end
// get leaderBoard to localStorage
api.allScores();
// end
this.sfx = {
btnOver: this.sound.add('sndBtnOver'),
btnDown: this.sound.add('sndBtnDown'),
};
this.btnPlay = this.add.sprite(
this.game.config.width * 0.5,
this.game.config.height * 0.5,
'sprBtnPlay',
);
this.alien = this.add
.sprite(
this.game.config.width * 0.55,
this.game.config.height * 0.94,
'alien',
)
.setScale(0.8);
this.btnLeader = this.add.sprite(
this.game.config.width * 0.5,
this.game.config.height * 0.9,
'leaderBoard1',
);
this.btnLeader.setInteractive();
this.btnPlay.setInteractive();
this.btnPlay.on(
'pointerover',
// eslint-disable-next-line
function () {
this.btnPlay.setTexture('sprBtnPlayHover'); // set the button texture to sprBtnPlayHover
this.sfx.btnOver.play(); // play the button over sound
},
this,
);
this.btnLeader.on(
'pointerover',
// eslint-disable-next-line
function () {
this.btnLeader.setTexture('leaderBoard2'); // set the button texture to sprBtnPlayHover
this.sfx.btnOver.play(); // play the button over sound
},
this,
);
// eslint-disable-next-line
this.btnPlay.on("pointerout", function () {
this.setTexture('sprBtnPlay');
});
// eslint-disable-next-line
this.btnLeader.on("pointerout", function () {
this.setTexture('leaderBoard1');
});
this.btnPlay.on(
'pointerdown',
// eslint-disable-next-line
function () {
this.btnPlay.setTexture('sprBtnPlayDown');
this.sfx.btnDown.play();
},
this,
);
this.btnPlay.on(
'pointerup',
// eslint-disable-next-line
function () {
this.btnPlay.setTexture('sprBtnPlay');
// reset and save username to local storage
localStorage.clear();
// hide user input field
const user = document.getElementById('username');
user.classList.add('hidden');
// hide control settings
display.offControl();
// save input to localstorage
if (user.value === '') {
localScore.saveName('No Name');
} else {
localScore.saveName(user.value);
}
// start next Scene
this.scene.start('SceneMain');
},
this,
);
this.btnLeader.on(
'pointerdown',
// eslint-disable-next-line
function () {
this.btnLeader.setTexture('leaderBoard1');
},
this,
);
this.btnLeader.on(
'pointerup',
() => {
// start next Scene
// hide user input field
display.offControl();
const user = document.getElementById('username');
user.classList.add('hidden');
this.scene.start('SceneLeaderBoard');
},
this,
);
this.add.sprite(
this.game.config.width * 0.5,
this.game.config.height * 0.2,
'gameTitle',
);
const createScrollBg = () => {
this.backgrounds = [];
for (let i = 0; i < 5; i += 1) {
const keys = ['sprBg0', 'sprBg1'];
const key = keys[Phaser.Math.Between(0, keys.length - 1)];
const bg = new ScrollingBackground(this, key, i * 10);
this.backgrounds.push(bg);
}
};
createScrollBg();
}
update() {
// eslint-disable-next-line
const backgrounds = (() => {
for (let i = 0; i < this.backgrounds.length; i += 1) {
this.backgrounds[i].update();
}
})();
}
}
export default SceneMainMenu;
|
import React from 'react';
import { StyleSheet, TouchableHighlight, View, Text } from 'react-native';
import Icon from 'react-native-vector-icons/Entypo';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import ModalDropdown from 'react-native-modal-dropdown';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import firebase from 'react-native-firebase';
import { addLineToFavourites, removeLineFromFavourites } from '../../../Actions/UserActions';
import { TEXT_COLOR } from '../../../Configuration/colors';
const DROPDOWN_OPTIONS = {
ADD_FAVOURITE: 'ADD_FAVOURITE',
REMOVE_FAVOURITE: 'REMOVE_FAVOURITE',
REPORT_PROBLEM: 'REPORT_PROBLEM',
GIVE_REVIEW: 'GIVE_REVIEW'
};
class RightButton extends React.Component {
constructor(props) {
super(props);
this.dropdownOption = '';
this.state = {
favourites: []
};
this.onSelect = this.onSelect.bind(this);
this.onMenuPress = this.onMenuPress.bind(this);
this.renderDropdownRow = this.renderDropdownRow.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.user)
this.setState({ favourites: nextProps.user.favourites });
else this.setState({ favourites: [] });
}
onMenuPress() {
this.dropdownRef.show();
}
onSelect(selectIndex) {
const { bus } = this.props.routeState;
const index = parseInt(selectIndex, 10);
const isUserAnonymous = firebase.auth().currentUser.isAnonyoums;
switch (index){
case 0: {
if (this.dropdownOption === DROPDOWN_OPTIONS.ADD_FAVOURITE)
this.props.addToFavourites(bus.id);
else this.props.removeFromFavourites(bus.id);
break;
}
case 1: {
Actions.push('ReportProblem', { bus });
break;
}
case 2: {
if (!isUserAnonymous)
Actions.ReviewPopup({ busID: bus.id });
else Actions.MessageBox({ message: 'Нужна е регистрация за това действие' });
break;
}
default: break;
}
}
renderIcon(type) {
switch (type) {
case DROPDOWN_OPTIONS.ADD_FAVOURITE: {
return (<Icon name="star" size={25} color="yellow" />);
}
case DROPDOWN_OPTIONS.REPORT_PROBLEM: {
return (<MaterialIcons name="report-problem" size={25} color="red" />);
}
case DROPDOWN_OPTIONS.GIVE_REVIEW: {
return (<MaterialIcons name="rate-review" size={25} color="#00cec9" />);
}
case DROPDOWN_OPTIONS.REMOVE_FAVOURITE: {
return (<MaterialIcons name="star-border" size={25} color="yellow" />);
}
default: break;
}
return null;
}
renderDropdownRow(data) {
return (
<TouchableHighlight
activeOpacity={0.9}
style={styles.dropdownRow}
>
<View style={{
flex: 1,
flexDirection: 'row',
padding: 5,
justifyContent: 'flex-start',
alignItems: 'center'
}}
>
{this.renderIcon(data.action)}
<Text style={styles.dropdownText}>{data.value}</Text>
</View>
</TouchableHighlight>
);
}
renderSeparator() {
return (<View style={styles.dropdownSeparator} key="separator" />);
}
render() {
let addRemoveText;
if (this.state.favourites
&& this.state.favourites.some(x => x.id === this.props.routeState.bus.id)) {
addRemoveText = 'Премахни от Любими';
this.dropdownOption = DROPDOWN_OPTIONS.REMOVE_FAVOURITE;
} else {
addRemoveText = 'Добави в Любими';
this.dropdownOption = DROPDOWN_OPTIONS.ADD_FAVOURITE;
}
return (
<View>
<TouchableHighlight
activeOpacity={0.5}
onPress={this.onMenuPress}
style={styles.container}
>
<Icon name="menu" size={32} style={styles.iconStyle} />
</TouchableHighlight>
<ModalDropdown
label=""
showsVerticalScrollIndicator={false}
ref={dropdown => { this.dropdownRef = dropdown; }}
textStyle={{ color: 'white' }}
options={[
{
value: addRemoveText,
action: this.dropdownOption
},
{
value: 'Докладвай проблем',
action: DROPDOWN_OPTIONS.REPORT_PROBLEM
},
{
value: 'Оцени',
action: DROPDOWN_OPTIONS.GIVE_REVIEW
}]}
dropdownStyle={styles.dropdownContainer}
renderRow={this.renderDropdownRow}
renderSeparator={this.renderSeparator}
onSelect={this.onSelect}
/>
</View>
);
}
}
const styles = StyleSheet.create({
iconStyle: {
color: TEXT_COLOR
},
container: {
marginRight: 14,
marginTop: 4
},
dropdownContainer: {
elevation: 2,
backgroundColor: '#0e0614',
borderWidth: 0,
marginRight: -2,
height: 'auto'
},
dropdownRow: {
backgroundColor: '#0e0614',
height: 50
},
dropdownText: {
fontFamily: 'Roboto',
color: 'white',
fontSize: 16,
textAlign: 'center',
lineHeight: 20,
fontWeight: '800',
marginHorizontal: 4
},
dropdownSeparator: {
height: StyleSheet.hairlineWidth,
backgroundColor: '#634c75'
}
});
const mapDispatchToProps = dispatch => ({
addToFavourites: busID => dispatch(addLineToFavourites(busID)),
removeFromFavourites: busID => dispatch(removeLineFromFavourites(busID))
});
const mapStateToProps = state => ({
routeState: state.route,
user: state.user
});
export default connect(mapStateToProps, mapDispatchToProps)(RightButton);
|
'use strict'
const dao = require('../model/dao');
const validation = require('../validation');
const github = require('../model/github');
const Promise = require('promise');
exports.addParticipateConfig = function(participateConfig){
validation.repository.checkParticipateConfig(participateConfig);
return dao.participateDao.insertParticipateConf(participateConfig);
};
exports.getParticipateConfig = function(repsId){
repsId = validation.generic.checkNumber(repsId);
return dao.participateDao.getParticipateConf(repsId);
};
exports.deleteParticipateConfig = function(repsId){
repsId = validation.generic.checkNumber(repsId);
return dao.participateDao.deleteParticipateConf(repsId);
};
exports.updateParticipateConfig = function(participateConfig){
validation.repository.checkParticipateConfig(participateConfig);
return dao.participateDao.updateParticipateConf(participateConfig);
};
exports.getParticipate = function(authInfo, repsName){
return new Promise((resolve, reject) => {
github.repos.getRepositoryAll(authInfo).then((repositorys) => {
let repository = repositorys.find((repository) => {
return repository.name == repsName;
});
github.repos.getCommit(authInfo, {
user: repository.owner.login,
repo: repsName,
per_page: 100
}).then((commits) => {
resolve(commits.length);
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
});
};
/*exports.getParticipate({
userName: '',
password: ''
}, '').then((res) => {
console.log(res);
}).catch((err) => {
console.error(err);
});*/
|
var searchData=
[
['waitforclosing',['waitForClosing',['../classDCCTransfer.html#aeab6ad8d6c904dfdd559c4ae756e2dae',1,'DCCTransfer']]]
];
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import CadastrarUsuario from '../views/Usuarios/Cadastrar.vue'
import Postagens from '../views/Usuarios/Postagens.vue'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/home/:id',
name: 'Pagina Inicial',
component: Home
},
{
path: '/home/',
name: 'Pagina Inicial',
component: Login
},
{
path: '/minhas-postagens/:id',
name: 'Minhas Postagens',
component: Postagens
},
{
path: '/minhas-postagens/',
name: 'Minhas Postagens',
component: Login
},
{
path: '/cadastrar-usuario',
name: 'Cadastro de usuario',
component: CadastrarUsuario
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
|
import React, { useContext } from "react";
import { ErrorContext } from "../../context/error/ErrorContext";
import { StyledError } from "./StyledError";
const Error = () => {
const { errorMessage } = useContext(ErrorContext);
return errorMessage !== null && <StyledError>{errorMessage}</StyledError>;
};
export default Error;
|
const investorsController = require("./investors.controller");
const router = require("express").Router();
router.post("/login",investorsController.login);
router.post("/change-password",investorsController.changePassword);
router.post("/create",investorsController.create);
router.post("/get",investorsController.get);
router.post("/get/one",investorsController.getOne);
router.post("/host",investorsController.checkHost);
router.post("/update",investorsController.updateInv);
router.post("/d/update",investorsController.updateInvDistributor);
router.post("/chnage-theme",investorsController.chnageTheme);
router.post("/ucc",investorsController.ucc_registration);
router.post("/ucc/existing",investorsController.ucc_existing);
router.post("/mobile-email",investorsController.mob_email);
module.exports = router;
|
$(document).ready(function() {
"use strict";
var empty = [];
empty.length = 10;
var av = new JSAV("hashIntroCON");
// Create an array object under control of JSAV library
var arr = av.ds.array(empty, {indexed: true});
av.umsg("We will demonstrate the simplest hash function, storing records in an array of size 10.");
av.displayInit();
av.umsg("We store the record with key value i at array position i. Of course, this only works for records with keys in the range 0 to 9.");
av.step();
av.umsg("Insert a record with key value 5.");
av.step();
av.umsg("Store it in array position 5.");
arr.value(5, 5);
arr.highlight(5);
av.step();
av.umsg("Insert a record with key value 7.");
arr.unhighlight(5);
av.step();
av.umsg("Store it in array position 7.");
arr.value(7, 7);
arr.highlight(7);
av.step();
av.umsg("Insert a record with key value 2.");
arr.unhighlight(7);
av.step();
av.umsg("Store it in array position 2.");
arr.value(2, 2);
arr.highlight(2);
av.step();
av.umsg("Of course, we cannot store multiple records with the same key value either.");
arr.unhighlight();
av.step();
av.umsg("The good news is that we can immediately tell if there is a record with key value 5 in the array.");
av.recorded();
});
|
import React, { Component } from 'react';
import {View, Image, StyleSheet, Keyboard} from 'react-native';
import { Card, Text } from 'react-native-elements';
import propTypes from 'prop-types';
import constants from '../../constant';
/**
*
* @component
*
*/
class QuestHeader extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: false
}
}
componentDidMount() {
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardHidden.bind(this));
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardShown.bind(this));
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardHidden = () => {
this.setState({
isVisible: false
})
}
_keyboardShown = () => {
this.setState({
isVisible: true
})
}
render() {
const { title, iconName, iconWidth, iconHeight, vw, vh, isTablet, isLandScape } = this.props;
const {isVisible} = this.state;
const { headerIcons } = constants;
const fv = isLandScape ? vh : vw;
return(
<View style={{ width: '100%', paddingHorizontal: 2 * fv, flex: 0, height: (isLandScape && isVisible) ? 0 : null, overflow: 'hidden'}}>
<Card containerStyle={{ width: '100%', borderRadius: 10, alignItems: 'center', justifyContent: 'center', margin: 0, height: (isLandScape && isVisible) ? 0 : (isLandScape ? 10 * vh : 8 * vh)}}>
<View style={[styles.cardContainer, {height: (isLandScape && isVisible) ? 0 : null}]}>
<View style={{height: (isLandScape && isVisible) ? 0 : null}}>
<Image
style={{ width: isLandScape ? iconWidth / 1.5 : iconWidth, height: (isLandScape && isVisible) ? 0 : (isLandScape ? iconHeight / 1.5 : iconHeight)}}
source={headerIcons[iconName]} />
</View>
<View>
<Text style={[styles.titleText, {fontSize: 4 * fv, paddingLeft: 10, height: (isLandScape && isVisible) ? 0 : null }]}>{title}</Text>
</View>
</View>
</Card>
</View>
);
}
}
/* Styles */
const styles = StyleSheet.create({
cardContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
width: '100%'
},
titleText: {
color: '#414141',
}
});
/**
*
* @PropTypes
* title string 'Titre de l'alerte', iconName string 'sommeil'
*/
QuestHeader.propTypes = {
title: propTypes.string,
iconName: propTypes.string,
iconWidth: propTypes.oneOfType([
propTypes.string,
propTypes.number
]),
iconHeight: propTypes.oneOfType([
propTypes.string,
propTypes.number
]),
vw: propTypes.number,
vh: propTypes.number,
isLandScape: propTypes.bool,
isTablet: propTypes.bool
};
export default QuestHeader;
|
import homeRoutes from './Home'
export default homeRoutes |
/// <reference path="../References/_references.js" />
describe('function isNullOrWhiteSpace()', function () {
'use strict';
describe('returns \'true\' when', function () {
it('input is undefined', function () {
expect(einstein.isNullOrWhiteSpace(undefined)).toBeTruthy();
});
it('input is null', function () {
expect(einstein.isNullOrWhiteSpace(null)).toBeTruthy();
});
it('input is an empty string', function () {
expect(einstein.isNullOrWhiteSpace("")).toBeTruthy();
});
it('input is a string containing only spaces', function () {
expect(einstein.isNullOrWhiteSpace(" ")).toBeTruthy();
});
it('input is an empty array', function () {
expect(einstein.isNullOrWhiteSpace([])).toBeTruthy();
});
});
describe('returns \'false\' when', function () {
it('input is an object', function () {
expect(einstein.isNullOrWhiteSpace({})).toBeFalsy();
});
it('input is an array with a value', function () {
expect(einstein.isNullOrWhiteSpace([{}])).toBeFalsy();
});
it('input is an int', function () {
expect(einstein.isNullOrWhiteSpace(0)).toBeFalsy();
});
});
}); |
Meteor.publish('edges', function() {
return Edges.find();
});
Meteor.publish('nodes', function() {
return Nodes.find();
});
Meteor.publish('comments', function() {
return Comments.find();
});
// Meteor.publish('singleItem', function(id,type) {
// var current = "";
// if( type == "node") {
// current= Nodes.findOne({"data.id" : id});
// } else if (type== "edge"){
// current= Edges.findOne({"data.id" : id});
// }
// console.log(current);
// return current;
// });
|
const express = require("express");
const morgan = require("morgan");
const helmet = require("helmet");
const jwt = require("express-jwt");
var jwtAuthz = require('express-jwt-authz');
const jwksRsa = require("jwks-rsa");
const { join } = require("path");
const authConfig = require("./auth_config.json");
var axios = require("axios").default;
const app = express();
if (!authConfig.domain || !authConfig.audience) {
throw "Please make sure that auth_config.json is in place and populated";
}
app.use(morgan("dev"));
app.use(helmet());
app.use(express.static(join(__dirname, "public")));
const checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`
}),
audience: authConfig.audience,
issuer: `https://${authConfig.domain}/`,
algorithms: ["RS256"]
});
// using authz here to validate scope of user in jwt
const checkScope = jwtAuthz(['order:pizza']);
function getManagementAccessToken() {
return new Promise(function (resolve, reject) {
// get access token - ideally not hard coded
var options = {
method: 'POST',
url: 'https://dev-jjohntest.us.auth0.com/oauth/token',
headers: {'content-type': 'application/json'},
data: {
grant_type: 'client_credentials',
client_id: 'm7IFDVms4O3lSEoLwWxLK63hopsaWIF7',
client_secret: '2zga0dsn5Dra2IwJkLkTamZx-geTs2JvlLMivLIC9eep2iQxuZCUl899fgERKmnr',
audience: 'https://dev-jjohntest.us.auth0.com/api/v2/'
}
};
axios.request(options).then(function (response) {
console.log("successfully generated management_access_token!");
resolve(response.data.access_token);
}).catch(function (error) {
console.log("there was an error");
console.error(error);
reject(error);
});
});
}
function getUserMetadata (token, userId) {
return new Promise(function (resolve, reject) {
var options = {
method: 'GET',
url: 'https://dev-jjohntest.us.auth0.com/api/v2/users/' + userId,
headers: {authorization: 'Bearer ' + token, 'content-type': 'application/json'}
};
axios.request(options).then(function (response) {
console.log("successfully retrieved user orders!");
// console.log(response.data.user_metadata);
resolve(response.data.user_metadata);
}).catch(function (error) {
console.error(error);
reject(error);
});
});
}
function setUserMetadata (token, userId, userOrders) {
return new Promise(function (resolve, reject) {
var options = {
method: 'PATCH',
url: 'https://dev-jjohntest.us.auth0.com/api/v2/users/' + userId,
headers: {authorization: 'Bearer ' + token, 'content-type': 'application/json'},
data: {user_metadata: {orders: userOrders}}
};
axios.request(options).then(function (response) {
console.log("successfully updated user orders!");
// console.log(response.data.user_metadata);
resolve(response.data);
}).catch(function (error) {
console.error(error);
reject(error);
});
});
}
async function updateUserWithOrderId(orderId, userId) {
var token = await getManagementAccessToken();
// console.log("awaited access token: " + token);
// first fetch user metadata
var userMetadata = await getUserMetadata(token, userId);
// console.log("awaited metadata: " + Object.keys(userMetadata));
// make either empty array or array of user's old orders
var user_orders = [];
if (userMetadata && userMetadata.hasOwnProperty('orders')) {
user_orders = userMetadata.orders;
};
// console.log("awaited and updated user orders: " + user_orders);
user_orders.push(orderId);
var updateOrdersRes = await setUserMetadata(token, userId, user_orders);
return updateOrdersRes;
// console.log("made it");
// console.log(updateOrdersRes);
}
app.get("/api/external/pizza", checkJwt, checkScope, (req, res) => {
var randomId = Math.floor(Math.random() * 10000);
updateUserWithOrderId(randomId, req.user.sub).then(function (result) {
console.log("updateRes: " + result.user_metadata.orders);
res.send({
msg: "Your pizza is on the way!",
orderId: randomId,
previousOrders: result.user_metadata.orders
});
});
});
app.get("/auth_config.json", (req, res) => {
res.sendFile(join(__dirname, "auth_config.json"));
});
app.get("/*", (req, res) => {
res.sendFile(join(__dirname, "index.html"));
});
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
return res.status(401).send({ msg: "Invalid token" });
}
next(err, req, res);
});
process.on("SIGINT", function() {
process.exit();
});
module.exports = app;
|
// Entypo.ttf', 'EvilIcons.ttf', 'Feather.ttf', 'FontAwesome.ttf', 'Foundation.ttf', 'Ionicons.ttf', 'MaterialCommunityIcons.ttf',
// 'MaterialIcons.ttf', 'Octicons.ttf', 'SimpleLineIcons.ttf', 'Zocial.ttf'
/** 配置 FONT 文件,方便导出 */
import EntypoIcon from 'react-native-vector-icons/Entypo';
import EvilIconsIcon from 'react-native-vector-icons/EvilIcons';
import FeatherIcon from 'react-native-vector-icons/Feather';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import FoundationIcon from 'react-native-vector-icons/Foundation';
import IoniconsIcon from 'react-native-vector-icons/Ionicons';
import MaterialCommunityIconsIcon from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIconsIcon from 'react-native-vector-icons/MaterialIcons';
import OcticonsIcon from 'react-native-vector-icons/Octicons';
import SimpleLineIconsIcon from 'react-native-vector-icons/SimpleLineIcons';
import ZocialIcon from 'react-native-vector-icons/Zocial';
exports.EntypoIcon = EntypoIcon
exports.EvilIconsIcon = EvilIconsIcon
exports.FeatherIcon = FeatherIcon
exports.FontAwesomeIcon = FontAwesomeIcon
exports.FoundationIcon = FoundationIcon
exports.IoniconsIcon = IoniconsIcon
exports.MaterialCommunityIconsIcon = MaterialCommunityIconsIcon
exports.MaterialIconsIcon = MaterialIconsIcon
exports.OcticonsIcon = OcticonsIcon
exports.SimpleLineIconsIcon = SimpleLineIconsIcon
exports.ZocialIcon = ZocialIcon |
var express = require('express');
var bodyParser = require('body-parser');
var port = process.env.PORT || 5000;
var path = require('path');
// console.log(path.join(__dirname, 'views/index.html'));
var app = express(); // Self instantiating constructor
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var data = [
{
name: 'JD',
age: 38
},
{
name: 'Bob',
age: 99
},
{
name: 'Sarah',
age: 27
}
];
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'views/index.html'));
});
app.get('/data', function(request, response) {
response.send(data);
});
app.listen(port, function() {
console.log('Listening on port ' + port);
});
// // reference those data values
// function test(str, another_string, num) {
// console.log(another_string);
// }
// // pass actual data values
// test('some string', 50, 'another');
// var obj = {
// name: 'JD',
// age: 38,
// getAge: function() {
// }
// }
// function Person(name, age) {
// this.name = name;
// this.age = age;
// }
// var jd = new Person('JD', 38);
// console.log(test);
// var test = false;
// process.env.PORT = 55;
// // console.log(process.env.PORT); |
/**
* Created by duyle on 4/1/17.
*/
$(document).ajaxStart(function () {
$.LoadingOverlay("show");
});
$(document).ajaxComplete(function () {
$.LoadingOverlay("hide");
});
function readURL(input) {
var nimeType = input.files[0]['type'];
if (nimeType.split('/')[0] == 'image') {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
} else {
$(document).ready(function () {
$.simplyToast('File được chọn không phải hình!', 'danger');
});
}
}
;
$(document).ready(function () {
var height = $(window).height() - 190;
console.log(height);
$('#list-species').css("max-height", height);
});
function show() {
console.log($('#image').val());
if ($('#image').val() == "" || $('#image').val() == null) {
$(document).ready(function () {
$.simplyToast('Bạn chưa chọn hình!', 'danger');
});
} else {
var myForm = new FormData();
myForm.append("file", $('#image')[0].files[0]);
$.ajax({
type: "POST",
url: window.location.origin + "/searchimage",
data: myForm,
encoding: "UTF-8",
processData: false,
contentType: false,
dataType: 'json',
timeout: 100000,
success: function (data) {
console.log("SUCCESS: ", data);
if (data != null) {
var result = "";
for (var key in data) {
var obj = data[key];
result += "<div class=\"w3-container\" style=\"height: auto\">"
+ "<div class=\"w3-card-4 index-card\">";
var img = obj.image.split(",");
console.log(obj.image);
result += "<a href=\"/detailspecies/" + obj.id +
"\"><img src=\"http://localhost:8081/resources/images/" + img[0] + "\" width=\"150px\" height=\"150px\" alt=\"Avatar\"";
result += " class=\"w3-left w3-margin-right\"></a>"
+ "<div align=\"left\">"
+ "<a href=\"/detailspecies/" + obj.id + "\"><p class=\"vietnamese-name\">" + obj.vietnameseName + "</p></a>"
+ "<p class=\"science-name\">Tên khoa học: " + obj.scienceName + "</p>"
+ "<p class=\"science-name\">Họ: " + obj.vietnameseNameFamily + "</p>"
+ "<p class=\"science-name\">Chi: " + obj.vietnameseNameGenus + "</p>"
+ "</div>"
+ "</div>"
+ "</div>";
}
$("#list-species").html(result);
} else {
var result = "<h5 style='color:red' aglin='center'> Không tìm thấy dữ liệu! </h5>";
$("#list-species").html(result);
}
},
error: function (e) {
var result = "<h5 style='color:red' aglin='center'> Không tìm thấy dữ liệu! </h5>";
$("#list-species").html(result);
}
});
}
} |
angular.module('sxroApp')
.controller('UploadCtrl', ['$rootScope', '$scope', 'FileUploader', '$state', 'FilesFactory', 'users', 'utils', 'localStorageService', 'Upload',
function($rootScope, $scope, FileUploader, $state, FilesFactory, users, utils, localStorageService, Upload) {
$scope.uploader = new FileUploader();
var fileTooBig = utils.trans('fileTooBig', {
number: utils.getSetting('maxFileSize')
}),
invalidExtension = utils.trans('invalidExtension');
//already been upload or rejected during this session
//files that are currently being uploaded or have
$scope.uploadHistory = [];
//number of files that are currently being uploaded
$scope.uploadsInPrograss = 0;
$scope.whitelist = getWhitelist();
$scope.blacklist = getBlacklist();
// array of uploaded files models
$scope.uploadedFiles = [];
$scope.upload = function(files) {
//reset previous upload history in case there is any
$scope.uploadsInProgress = 0;
$scope.uploadHistory = [];
$scope.uploadedFiles = [];
//if there are no files bail
if (!files || !files.length) return;
// $rootScope.$emit('upload.started');
//make sure user is not trying to upload
//more files at the same time then allowed
files = filterSimultUploads(files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
//push the file we're currently uploading into
//upload history and get it's index in the array
var index = $scope.uploadHistory.push(file) - 1;
sendRequest(file, $scope.uploadHistory[index]);
}
};
/**
* Remove files that don't pass validation from given array.
*
* @param {array} files
* @returns {array}
*/
function filterOutInvalidFiles(files) {
if (!files || !files.length) return [];
return files.filter(function(file) {
if (file.type === 'directory') {
return false;
}
//filter out any invalid files so we don't send them
//to server, but add them to upload history as rejected
else if (fileNotValid(file)) {
file.uploaded = true;
file.rejected = true;
$scope.uploadHistory.push(file);
return false;
}
return true;
});
}
/**
* Check if file extension and size are valid.
*
* @param {object} file
* @returns {boolean}
*/
function fileNotValid(file) {
var extensionInvalid = extensionInvalid(file);
//turn max file size from mb to byes and compare to given file size
var sizeNotValid = (parseInt($scope.maxFileSize) * 1000000) <= file.size;
if (extensionInvalid) {
file.rejectReason = invalidExtension;
}
if (sizeNotValid) {
file.rejectReason = fileTooBig;
}
return extensionNotValid || sizeNotValid;
}
/**
* Check if given file upload extension is not valid.
*
* @param {object} file
* @returns {boolean}
*/
function extensionInvalid(file) {
var mimeExt = file.type.split('/')[1];
var nameExt = utils.extractExtension(file.name);
if ($scope.whitelist) {
if ($scope.whitelist.indexOf(mimeExt) === -1) return true;
if (nameExt && $scope.blacklist.indexOf(nameExt) > -1) return true;
}
if ($scope.blacklist) {
if ($scope.blacklist.indexOf(mimeExt) > -1) return true;
if (nameExt && $scope.blacklist.indexOf(nameExt) > -1) return true;
}
}
/**
* If user is trying to upload more files at the same time then limit
* we'll slice the give files array until the limit.
*
* @param {array} files
* @returns {array}
*/
function filterSimultUploads(files) {
var maxUploads = utils.getSetting('maxSimultUploads');
if (files.length > maxUploads) {
utils.showToast(utils.trans('maxSimultUploadsWarning', {
number: maxUploads
}));
files.splice(0, files.length - maxUploads);
}
return files;
}
/**
* If user is trying to upload more files at the same time then limit
* we'll slice the give files array until the limit.
*
* @param {array} files
* @returns {array}
*/
function filtersMultiUploads(files) {
var maxUploads = utils.getSetting('maxSimultUploads');
if (files.length > maxUploads) {
utils.showToast(utils.trans('maxSimultUploadsWarning', {
number: maxUploads
}));
files.splice(0, files.length - maxUploads);
}
return files;
}
/**
* If a file being uploaded by not a logged in user,
* than store this and later attached to the logged user
* @return {[type]} [description]
*/
function getUploadFields() {
if (!user.current) {
var rand = utils.randomString();
//store the random string we've generated in localStorageService so we can
//later attach these uploads to user if he registers or logs in
localStorageService.set('attachIds', rand, true);
return {
attach_id: rand
};
} else {
return {
folder: folders.selected.id
};
}
}
/**
* [sendRequest description]
* @param {[type]} file [description]
* @param {[type]} historyItem [description]
* @return {[type]} [description]
*/
function sendRequest(file, historyItem) {
Upload.upload({
url: $scope.baseUrl + 'files',
data: {
file: file
},
fields: getUploadFields()
}).then(function(evt) {
historyItem.percentageUploaded = parseInt(100.0 * evt.loaded / evt.total);
historyItem.bytesUploaded = utils.formatFileSize(evt.loaded);
}).success(function(data) {
//if we are not in dashboard just fire an event and bail
// if (!$state.includes('dashboard')) {
// $scope.uploadedFiles = $scope.uploadedFiles.concat(data.uploaded);
// $scope.selectedFile = $scope.uploadedFiles[0];
// return $rootScope.$emit('photos.uploaded', data);
// }
if (data.uploaded && data.uploaded.length) {
folders.selected.files = folders.selected.files.concat(data.uploaded);
historyItem.id = data.uploaded[0].id;
}
if (data.rejected && data.rejected.length) {
historyItem.uploaded = true;
historyItem.rejected = true;
}
}).error(function(data) {
historyItem.rejected = true;
if (angular.isString(data) && data.length < 300) {
utils.showToast(data);
}
}).finally(function() {
historyItem.uploaded = true;
$scope.uploadsInProgress -= 1;
if ($scope.uploadsInProgress === 0 && users.current) {
var files = $scope.uploadHistory.filter(function(f) {
return !f.rejected;
});
if (files && files.length) {
$rootScope.$emit('activity.happened', 'uploaded', 'files', files);
}
}
});
}
/**
* A whilte list of files which are allowed to upload
* @return list of files
*/
function getWhitelist() {
var wl = utils.getSetting('whiltelist');
if (wl && angular.isString(wl)) {
return wl.replace(/ /g, '').split(',');
}
}
/**
* A list of files which are not allowed to upload
* @return list of files
*/
function getBlacklist() {
var bl = utils.getSetting('blacklist');
if (bl && angular.isString(bl)) {
return bl.replace(/ /g, '').split(',');
}
}
}
]);
|
import { combineReducers } from 'redux'
import docsReducer from './documents/reducer';
import procedureReducer from './procorgs/reducer';
import actorsReducer from './acteurs/reducer';
import procmetsReducer from './procmets/reducer';
import vueensReducer from './vueens/reducer';
import appReducer from './application/reducer';
import diagReducer from './diagramme/reducer';
import opReducer from './operations/reducer';
export default combineReducers({
documents: docsReducer,
procorgs: procedureReducer,
acteurs: actorsReducer,
procmets: procmetsReducer,
vueensemble: vueensReducer,
application: appReducer,
diagramme: diagReducer,
operations: opReducer
})
|
(function(){
console.log('find2');
})(); |
var searchData=
[
['planarprojection',['PlanarProjection',['../classThreeDGraph__class.html#a38e1e26698241cdc5feb2337b061c997',1,'ThreeDGraph_class']]]
];
|
import React from 'react'
import Select from 'react-select';
import { useQuery } from '@apollo/client';
import { QUERY_USER } from '../../utils/queries';
export default function DropDown({ tripsTitle = [] }) {
const { data } = useQuery(QUERY_USER);
const trips = data?.user.trips || [];
console.log(data)
return (
<div>
<label for="activities">Add to a Trip:</label>
{tripsTitle &&
tripsTitle.map((tripsTitle) => (
<div key={trips._id} className="">
<Select options={ trips.tripTitle } />
</div>
))}
</div>
)
}
|
import React from "react";
import { Navbar, Nav, NavDropdown } from "react-bootstrap";
import "./Navigation.css";
class Navigation extends React.Component {
render() {
if (window.location.pathname === '/') return null;
return (
<Navbar collapseOnSelect expand="lg" fixed="top" bg="dark" variant="dark">
<Navbar.Brand href="/">Boulder Bike Tour</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/">Home</Nav.Link>
<Nav.Link href="/Media">Media</Nav.Link>
<NavDropdown title="The Race" >
<NavDropdown.Item href="/Location">Rider Location</NavDropdown.Item>
<NavDropdown.Item href="/Information">Rider Information</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="/Form">Slogan Submission</NavDropdown.Item>
</NavDropdown>
</Nav>
<Nav>
<Nav.Link href="#"><i className="fab fa-facebook-f"></i></Nav.Link>
<Nav.Link href="#"><i className="fab fa-instagram"></i></Nav.Link>
<Nav.Link href="#"><i className="fab fa-twitter"></i></Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
export default Navigation; |
function showResult(data, id) {
return {
"jsonrpc": "2.0",
"result": data || {},
"id": id || 1
};
}
function showError(errorCode, id) {
return {
"jsonrpc": "2.0",
"error": {
"code": errorCode,
"message": "error"
},
"id": id || 1
};
}
module.exports = {
result: showResult,
error: showError
}
|
import styled from 'styled-components'
export const Container = styled.div`
margin: 80px auto;
display: block;
width: 100%;
@media screen and (min-width: 60em) {
width: 941px;
}
`
export const Content = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${({padding}) => padding};
p {
padding: 0;
margin: 0;
}
`
Content.defaultProps = {
padding: '0',
}
export const H1 = styled.h1`
margin-bottom: 40px;
font-size: 1.8em;
font-weight: bold;
`
export const Line = styled.div`
width: 100%;
margin: 40px auto;
opacity: 0.5;
border: solid 1px ${({color}) => color};
@media screen and (min-width: 60em) {
width: ${({width}) => width};
}
`
Line.defaultProps = {
width: '939px',
color: '#979797'
}
export const ContainerProduct = styled.div`
padding-top: 40px;
ul {
margin: 0 0 50px;
padding: 0;
> li {
list-style: none;
}
}
`
export const Product = styled.div`
display: grid;
grid-template-columns: 60px 141px 1fr 1fr;
align-items: center;
margin-bottom: 40px;
.addCart {
width: 20px;
height: 20px;
padding: 0;
position: relative;
cursor: pointer;
&::before {
content: "";
display: inline-block;
height: 16px;
width: 16px;
border: 2px solid;
background: #fff;
position: absolute;
}
&::after {
content: none;
display: inline-block;
height: 6px;
width: 9px;
top: 4px;
left: 4px;
border-left: 2px solid #000;
border-bottom: 2px solid #000;
transform: rotate(-45deg);
position: absolute;
}
&:checked {
::after {
content: ""
}
}
}
`
export const Price = styled.p`
font-size: 1.8em;
font-weight: bold;
justify-self: end;
`
export const Total = styled.div`
margin: 0 auto 40px;
display: flex;
align-items: center;
justify-content: space-between;
p {
padding: 0;
margin: 0;
}
`
|
import styled from "styled-components";
export const StyledDiscordButton = styled.a`
background: #6271c0;
display: block;
width: 100%;
color: #fff;
padding: 8px 15px;
border-radius: 4px;
border: none;
font-size: 0.95rem;
font-family: "Roboto Slab", serif;
font-weight: 300;
text-align: center;
margin-top: 1rem;
position: relative;
:hover {
background: #809bff;
}
`;
export const StyledDiscordDiv = styled.div`
margin: 15% auto;
width: 80%;
`;
|
const axios = require('axios');
const helpers = require('../helpers');
const Image = require('../../../database/models/image');
module.exports = {
// selects the best fitting image out of an array of Spotify image results
selectImage(imageArray) {
const idealSize = 300;
let bestImage;
let bestScore;
imageArray.forEach((image) => {
if (image.height < 200 || image.width < 200) return;
const score = Math.abs(image.height - idealSize) + Math.abs(image.width - idealSize);
if (score < bestScore || bestScore === undefined) {
bestScore = score;
bestImage = image;
}
});
return bestImage;
},
// retrieves content id based on url
getId(longUrl) {
return new Promise((resolve, reject) => {
if (!longUrl) reject(new Error('No link provided.'));
const id = longUrl.match(/\w+$/g)[0];
id ? resolve(id) : reject(new Error('Id could not be extracted.'));
});
},
getType(longUrl) {
const typeRegex = {
track: /([/:])track\1/g,
album: /([/:])album\1/g,
artist: /([/:])artist\1/g,
};
for (const type in typeRegex) {
if (longUrl.match(typeRegex[type])) return type;
}
throw new Error('Could not derive type based on provided url.');
},
// retrieves content information based on id
getInfo({ type, id }) {
return axios.get(`https://api.spotify.com/v1/${type}s/${id}`)
.then((response) => {
response = response.data;
const info = {};
info.image = module.exports.selectImage(response.images || response.album.images);
info.type = response.type;
if (info.type === 'track') info.type = 'song';
info.artist = info.type === 'artist' ? response.name : response.artists[0].name;
if (info.type === 'album') {
info.album = response.name;
} else if (response.album) {
info.album = response.album.name;
}
if (info.type === 'song') info.song = response.name;
module.exports.gatherInfo(info, response);
return info;
});
},
// helper for .getInfo and .scan. Properties that need to be retrieved during any contact with the Spotify API may be retrieved with this method.
gatherInfo(info, content) {
info.spotify_artist_id = content.artists ? content.artists[0].id : content.id;
info.spotify_album_id = content.album ? content.album.id : content.id;
info.spotify_song_id = content.id;
info.spotify_artist_url = content.artists ? content.artists[0].external_urls.spotify : content.external_urls.spotify;
info.spotify_album_url = content.album ? content.album.external_urls.spotify : content.external_urls.spotify;
info.spotify_song_url = content.external_urls.spotify;
info.artist_image = content.artists ? null : module.exports.selectImage(content.images); // we'll need to ge the image some other way.
info.album_image = module.exports.selectImage(content.album ? content.album.images : content.images);
info.song_image = info.album_image;
return info;
},
// retrieves Spotify link based on search criteria
getLink({ artist, album, song, type }) {
return module.exports.search(arguments[0])
.then(response => module.exports.scan(response, arguments[0]));
},
getData(link) {
const data = { service: 'spotify' };
return module.exports.getId(link)
.then((id) => {
data.id = id;
data.spotify_id = id;
const type = module.exports.getType(link);
data.spotify_url = `https://open.spotify.com/${type === 'song' ? 'track' : type}/${id}`;
return module.exports.getInfo({ type, id });
})
.then((info) => {
Object.assign(data, info);
return helpers.findOrCreate(Image, info.image);
})
.then((image) => {
return Object.assign(data, { image_id: image.id });
});
},
// analyze a Spotify search API response object and return item with the highest score
scan(response, info, benchmark = 0.75) {
if (!response || !info) throw new Error('scan.song must take a response and info.');
const { artist, album, song, type } = info;
let link = null;
let highScore = null;
const coefficientMap = { song: 3, album: 2, artist: 1 };
const coefficient = coefficientMap[type];
const dataMap = { song: 'tracks', album: 'albums', artist: 'artists' };
const dataType = dataMap[type];
const items = response.data[dataType].items;
for (let i = 0; i < items.length; i += 1) {
let totalScore = 0;
const currentArtist = items[i].artists ? items[i].artists[0].name : items[i].name;
const artistScore = helpers.isMatch(helpers.normalize(currentArtist), helpers.normalize(artist));
totalScore += artistScore;
if (album) {
const currentAlbum = items[i].album ? items[i].album.name : items[i].name;
const albumScore = helpers.isMatch(helpers.normalize(currentAlbum), helpers.normalize(album));
totalScore += albumScore;
}
if (song) {
const songScore = helpers.isMatch(helpers.normalize(items[i].name), helpers.normalize(song));
totalScore += songScore;
}
if (totalScore > highScore) {
highScore = totalScore;
link = items[i].external_urls.spotify;
info.image = module.exports.selectImage(items[i].images || items[i].album.images);
module.exports.gatherInfo(info, items[i]);
}
}
const score = highScore / coefficient;
if (score >= benchmark) {
return link;
} throw new Error('No link was found whose score was high enough');
},
search({ song, album, artist, type }) {
const songSearches = [
[
`track:${JSON.stringify(song)} artist:${JSON.stringify(artist)} album:${JSON.stringify(album)}`,
JSON.stringify(song),
`${JSON.stringify(album)} ${JSON.stringify(artist)}`,
`track:${JSON.stringify(song)} album:${JSON.stringify(album)}`,
`track:${JSON.stringify(song)} artist:${JSON.stringify(artist)}`,
],
[`${JSON.stringify(song)} ${JSON.stringify(artist)} ${JSON.stringify(album)}`],
[
`${JSON.stringify(song)} ${JSON.stringify(artist)}`,
`${JSON.stringify(song)} ${JSON.stringify(album)}`,
],
];
const albumSearches = [
[`artist:${JSON.stringify(artist)} album:${JSON.stringify(album)}`],
[JSON.stringify(album)],
[`${JSON.stringify(artist)} ${JSON.stringify(album)}`],
[`${JSON.stringify(helpers.removeParensContent(album))}`],
[JSON.stringify(artist)],
];
const artistSearches = [
[
`artist:${JSON.stringify(artist)}`,
JSON.stringify(artist),
],
];
const spotifySearches = { song: songSearches, album: albumSearches, artist: artistSearches };
return new Promise((resolve, reject) => {
const dataMap = { song: 'tracks', album: 'albums', artist: 'artists' };
const dataType = dataMap[type];
const cases = spotifySearches[type];
const trySearch = (index = 0) => {
if (!cases[index]) reject('Could not retrieve any results from Spotify\'s search API.');
const searches = cases[index]
.map((search) => {
const params = { type, q: search, limit: 50 };
if (type === 'song') params.type = 'track';
return axios.get('https://api.spotify.com/v1/search', { params });
});
Promise.all(searches).then((results) => {
const combinedResults = { data: { [dataType]: { items: [] } } };
for (let i = 0; i < results.length; i += 1) {
combinedResults.data[dataType].items = combinedResults.data[dataType].items.concat(results[i].data[dataType].items);
}
if (!combinedResults.data[dataType].items.length) return trySearch(index + 1);
return resolve(combinedResults);
});
};
trySearch();
});
},
};
|
//Retriving the Values for Both the Input Fields
var x = document.getElementById("input1");
var input_2 = document.getElementById("input_2");
//Retrieving the Button Elements by Id
btn_2 = document.getElementById("btn_2");
btn_1 = document.getElementById("btn_1");
btn_3 = document.getElementById("btn_3");
//disbling the Start Button
document.getElementById("btn_2").disabled = true;
//onclick event for Start Button
btn_1.onclick = function(){
var str=x.value;
var sv = str.charAt(0);
var vs = str.charAt((x.length)-1);
if(document.getElementById("input1").value.length == 0 || document.getElementById("input1").value == ' '){
alert("Please Enter a Valid Input !!!");
}
//else if(sv != '"' && vs != '"'){
//alert("Please Put \" \" before Strings");
// }
else if(!isNaN(input1.value)){
alert("!!!!Only Strings are Allowed");
}
else{
document.getElementById('step').style.display = "block";
document.getElementById('btn_1').disabled = true;
document.getElementById('btn_2').disabled = false;
}
}
//Function for Repetion of the Characters
function Repetition(){
var str = x.value;
var v = input_2.value;
var array = [];
for(var k = 0; k < v;)
array[k++] = str;
var arr = array.join('');
document.getElementById("res_2").innerHTML =arr ;
}
//Global Variable to Permanently Store the Counter for the Array
var i = 0;
//onclick event for Start button
btn_2.onclick = function(){
var v = [1,2,3,4];
if(v[i] == 1){
document.getElementById("1").style.color = "red";
i++;
}
else if(v[i] == 2) {
document.getElementById("2").style.color = "red";
i++;
}
else if(v[i] == 3){
document.getElementById("3").style.color = "red";
document.getElementById("res_1").style.display = "block";
document.getElementById("res_2").style.display = "block";
Repetition();
i++;
}
else if(v[i] == 4) {
alert('Program Completed');
}
}
//onclick event for Reset button
btn_3.onclick = function(){
location.reload(true);
}
|
import React from 'react';
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper";
const testimonial_contents = {
subtitle: 'Testimonial',
title: 'Customer',
highlight_text: 'feedback',
testimonial_data: [
{
id: 1,
ratings: [1, 2, 3, 4, 5],
desc: 'Wow. What a great experience with this copywriter. Muhammad Noman is a very talented copywriter. yesterday I got his first Email that was amazing...',
img: '/assets/img/testimonial/testi-slide-1.png',
name: 'Floyd Miles',
title: 'CEO of (Amazon)',
brand_img: '/assets/img/testimonial/testi-brands.png',
},
{
id: 2,
ratings: [1, 2, 3, 4, 5],
desc: 'Wow. What a great experience with this copywriter. Muhammad Noman is a very talented copywriter. yesterday I got his first Email that was amazing...',
img: '/assets/img/testimonial/testi-slide-1.png',
name: 'Jerome Bell',
title: 'Web Developer',
brand_img: '/assets/img/testimonial/testi-brands-2.png',
},
{
id: 3,
ratings: [1, 2, 3, 4, 5],
desc: 'Wow. What a great experience with this copywriter. Muhammad Noman is a very talented copywriter. yesterday I got his first Email that was amazing...',
img: '/assets/img/testimonial/testi-slide-1.png',
name: 'Jerome Bell',
title: 'Web Developer',
brand_img: '/assets/img/testimonial/testi-brands-2.png',
},
{
id: 4,
ratings: [1, 2, 3, 4, 5],
desc: 'Wow. What a great experience with this copywriter. Muhammad Noman is a very talented copywriter. yesterday I got his first Email that was amazing...',
img: '/assets/img/testimonial/testi-slide-1.png',
name: 'Jerome Bell',
title: 'Web Developer',
brand_img: '/assets/img/testimonial/testi-brands-2.png',
},
]
}
const { highlight_text, subtitle, testimonial_data, title } = testimonial_contents;
const TestimonialArea = () => {
const [sliderLoop, setSliderLoop] = React.useState(false);
React.useEffect(() => setSliderLoop(true), [])
return (
<div className="tp-testimonial-area grey-bg pt-125 pb-120 fix">
<div className="container-fluid">
<div className="row">
<div className="col-xl-12">
<div className="tp-testimonial-title-box text-center pb-25">
<h5 className="tp-subtitle">{subtitle}</h5>
<h2 className="tp-title">{title}
<span className="tp-section-highlight">
{highlight_text}
<svg width="253" height="11" viewBox="0 0 253 11" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0 0L253 11H0V0Z" fill="#FFDC60" />
</svg>
</span>
</h2>
</div>
</div>
</div>
<div className="tp-testimonial-slider-section-four">
<Swiper
loop={sliderLoop}
slidesPerView={3}
spaceBetween={70}
modules={[Pagination]}
centeredSlides={true}
centeredSlidesBounds={true}
className="swiper-container testi-slider-active-four"
pagination={{
el: ".testimonial-slider-dots-four",
clickable: true,
}}
breakpoints={{
'1200': {
slidesPerView: 3,
},
'992': {
slidesPerView: 3,
},
'768': {
slidesPerView: 1,
},
'576': {
slidesPerView: 1,
},
'0': {
slidesPerView: 1,
},
}}
>
{testimonial_data.map((item) => {
const { brand_img, desc, id, img, name, ratings, title } = item;
return <SwiperSlide key={id} className="testi-slider-opacity">
<div className="tp-testimonial-box">
<div className="tp-testimonial-box__rating">
{ratings.map((r) => <span key={r}><i className="fas fa-star"></i></span>)}
<p>{desc}</p>
</div>
<div className="tp-testimonial-box__info d-flex justify-content-between align-items-center">
<div className="tp-testimonial-box__testi-slide-img d-flex align-items-center">
<img className="mr-25" src={img} alt="" />
<div className="tp-testimonial-box__testi-title">
<span className="testi-heading">{name}</span>
<span>{title}</span>
</div>
</div>
<div className="tp-testimonial-box__testi-brand d-none d-md-block">
<img src={brand_img} alt="" />
</div>
</div>
</div>
</SwiperSlide>
})}
</Swiper>
</div>
<div className="testimonial-slider-dots-four text-center mt-50"></div>
</div>
</div>
);
};
export default TestimonialArea; |
const contacts = require('../data/contacts');
const list = (req, res) => {
res.json(contacts);
};
const show = (req, res) => {
let contact = contacts.find(item => item._id == req.params.id);
if (contact)
res.json(contact);
else
res.status(400).send(`There is no contact with id: ${req.params.id}`);
};
const create = (req, res) => {
let newID = contacts.length + 1;
req.body._id = newID;
req.body.postID = 1;
contacts.push(req.body);
res.json(contacts);
};
module.exports = { list, show, create }; |
exports.do = function (url, path, datas, callback) {
var options = {
host: url,
port: 80,
path: '/resource?id=foo&bar=baz',
method: 'POST'
};
http.request(options, function(res) {
//console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var data = "";
res.on('data', function (chunk) {
data = data + chunk;
});
res.on('end', function (chunk) {
try {
var data_js = JSON.parse(data);
return callback(data_js);
} catch (ex) {
return callback(null);
}
});
}).end();
} |
import './Site.scss';
import 'bootstrap';
import 'prismjs/components/prism-ruby';
import Site from './modules/site';
import Lazy from 'jquery-lazy';
(function( $ ) {
console.log('Jquery version ' + $.fn.jquery);
$(document).ready(function($) {
Site.bootstrap();
});
})(jQuery); |
export function getSongAudio(id) {
return `https://music.163.com/song/media/outer/url?id=${id}.mp3`
}
/**
[00:00.000] 作词 : 许嵩
[00:01.000] 作曲 : 许嵩
[00:22.240]天空好想下雨
[00:24.380]我好想住你隔壁
*/
export function parseLyric(lyricStr) {
const reg = /\[(\d{2}):(\d{2})\.(\d{3})\]/;
const lines = lyricStr.split('\n');
const result = [];
for(let value of lines) {
if(!value) continue;
const match = reg.exec(value);
if(!match) continue;
const t1 = match[1] * 60 * 100;
const t2 = match[2] * 100;
const t3 = match[3].length === 3 ? match[3] * 1 : match[3] * 10;
const totalTime = t1 + t2 + t3;
const content = value.replace(reg,'').trim();
const lyricObj = {
totalTime,
content
};
result.push(lyricObj);
}
return result;
} |
//mode determine black list or whitelist mode
//0 is black 1 is white
var mode=0;
//urls contain urls for each tab.
var urls=new Object();
//blocking set contains url for current blocked origin
var blocking=new Object();
//white contain white list origin if in white list mode
var white=new Object();
init();
/*background process list initialization*/
function init(){
chrome.storage.sync.get('mode',function(result){
if(result.mode!=undefined)
mode=result.mode;
else
mode=0;
if(mode==0)
blackinit();
else
whiteinit();
});
}
/*whitelist initialization*/
function whiteinit(){
chrome.webRequest.onBeforeRequest.removeListener(blacklist);
chrome.webRequest.onBeforeRequest.addListener(
whitelist
,{urls: ["*://*/*"]},
["blocking"]
);
chrome.storage.sync.get('white',function(result){
if(result.white!=undefined)
white=result.white;
else
white=new Object();
//clear whitelist
blocking=new Object();
});
}
/*whitelist initialization*/
function blackinit(){
chrome.webRequest.onBeforeRequest.removeListener(whitelist);
chrome.webRequest.onBeforeRequest.addListener(
blacklist
,{urls: ["*://*/*"]},
["blocking"]
);
chrome.storage.sync.get('blacklist',function(result){
if(result.blacklist!=undefined)
blocking=result.blacklist;
else
blocking=new Object();
//clear whitelist
white=new Object();
});
}
/*listen to pop up menu and white list page requests*/
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse){
//flag=1 means get the pop menu data
//get blacklist data from storage
if(request.flag==1){
var tabid = request.tabid;
//check white list unblock status
if(mode==1){
for(var i in urls[tabid].block){
if(i in white)
delete urls[tabid].block[i];
}
}
urls[tabid].mode=mode;
var origin = JSON.stringify(urls[tabid]);
//send back response
sendResponse(origin);
}else if(request.flag==2 && mode==0){ //flag = 2 means update blacklist block orgin
blocking[request.blockurl]=1;
urls[request.tabid].block[request.blockurl]=0;
sendResponse({success:request.blockurl});
chrome.storage.sync.set({'blacklist':blocking});
}else if(request.flag==3){ //flag ==3 start whitelist mode
mode=1;
chrome.storage.sync.set({'mode':mode});
chrome.webRequest.onBeforeRequest.removeListener(blacklist);
urls=new Object();
blocking=new Object();
var list=JSON.parse(request.white);
for(var i in list)
white[list[i].url]=1;
chrome.storage.sync.set({'white':white});
chrome.webRequest.onBeforeRequest.addListener(whitelist,{urls: ["*://*/*"]},
["blocking"]);
}else if(request.flag==4 && mode==1){ //add white list
white[request.url]=1;
chrome.storage.sync.set({'white':white});
}else if(request.flag==5 && mode==1){ //delete origin from white list
delete white[request.url];
chrome.storage.sync.set({'white':white});
}else if(request.flag==6){ //start blacklist mode
mode=0;
chrome.storage.sync.set({'mode':mode});
//get black list from storage
blackinit();
}else if(request.flag==7 && mode==0){ // unblock origin in blacklist
if(request.unblockurl in blocking)
delete blocking[request.unblockurl];
if(request.unblockurl in urls[request.tabid].block)
delete urls[request.tabid].block[request.unblockurl];
sendResponse({success:request.unblockurl});
chrome.storage.sync.set({'blacklist':blocking});
}
});
/*web request listener for black list*/
function blacklist(details){
var url=details.url;
var origin = details.url.split('\/')[0] + "//" + details.url.split('\/')[2];
if(details.tabId!=-1){
chrome.tabs.get(details.tabId, function(tab){
if(tab!=undefined){
console.log("tab id:"+details.tabId+"tab url:"+tab.url+" url:"+details.url);
if(details.tabId in urls){
if(urls[details.tabId].dom!=tab.url){
urls[details.tabId].dom=tab.url;
urls[details.tabId].origin=[];
urls[details.tabId].block=new Object();
}
urls[details.tabId].origin.push(url);
}else{
urls[details.tabId]=new Object();
urls[details.tabId].dom=tab.url;
urls[details.tabId].block=new Object();
urls[details.tabId].origin=[];
urls[details.tabId].origin.push(url);
}
if(origin in blocking)
urls[details.tabId].block[origin]=1;
}
});
}
//else
// console.log("tab id:"+details.tabId+" url:"+details.url);
if(origin in blocking){
//add blocked url
console.log("blacklist block origin :"+origin);
return {cancel:true};
}
}
/*web request listener for white list*/
function whitelist(details){
var url=details.url;
var origin = details.url.split('\/')[0] + "//" + details.url.split('\/')[2];
if(details.tabId!=-1){
chrome.tabs.get(details.tabId, function(tab){
//console.log("tab id:"+details.tabId+"tab url:"+tab.url+" url:"+details.url);
if(tab!=undefined){
if(details.tabId in urls){
if(urls[details.tabId].dom!=tab.url){
urls[details.tabId].dom=tab.url;
urls[details.tabId].origin=[];
urls[details.tabId].block=new Object();
}
urls[details.tabId].origin.push(url);
}else{
urls[details.tabId]=new Object();
urls[details.tabId].dom=tab.url;
urls[details.tabId].block=new Object();
urls[details.tabId].origin=[];
urls[details.tabId].origin.push(url);
}
if( !(origin in white)){
urls[details.tabId].block[origin]=1;
console.log("block origin :"+origin);
}else {
urls[details.tabID].block[origin]=undefined;
console.log("whitelist block origin :"+origin);
}
}
});
}else
;
//console.log("tab id:"+details.tabId+" url:"+details.url);
if( !(origin in white)){
//add blocked url
return {cancel:true};
}
}
|
export { default as UserController } from "../../../modules/user/controller";
export { default as BusController } from "../../../modules/bus/controller";
export { default as PassajeiroController } from "../../../modules/passajeiros/controller";
export { default as AvatarController } from "../../../modules/avatar/controller";
export { default as ViagemController } from "../../../modules/viagem/controller";
|
import React, { Component } from 'react';
import Navigator from './src/navigator';
import newsReducer from './src/store/news';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
const reducers = combineReducers({
news: newsReducer,
});
const store = createStore(
reducers,
applyMiddleware(thunk)
);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Navigator />
</Provider>
);
}
}
|
import request from 'request'
export default function(msg){
request({
method: 'POST',
uri: 'https://notify-api.line.me/api/notify',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
'bearer': process.env.LINE_token
},
form: {
message: msg
}
}, (err, httpResponse, body) => {
if(err){
console.log(err);
} else {
console.log(httpResponse)
console.log(body)
}
});
} |
import React from 'react';
import {mount} from 'react-mounter';
// load Layout and Welcome React components
import {Layout, Welcome} from './app.jsx';
import Home from './components/Home.jsx';
import Instructions from './components/Instructions.jsx';
import CardListContainer from './containers/CardListContainer.jsx';
import CardContainer from './containers/CardContainer.jsx';
import GamePageContainer from './containers/GamePageContainer.jsx';
FlowRouter.route("/", {
action() {
mount(Layout, {
content: (<Home />)
});
}
});
FlowRouter.route("/instructions", {
action() {
mount(Layout, {
content: (<Instructions />)
});
}
});
FlowRouter.route("/game/:_id", {
action({_id}) {
mount(Layout, {
content: (<GamePageContainer _id={_id} />)
});
}
});
FlowRouter.route("/cards", {
action() {
mount(Layout, {
content: (<CardListContainer />)
});
}
});
FlowRouter.route("/cards/:_id", {
action({_id}) {
mount(Layout, {
content: (<CardContainer _id={_id} />)
});
}
}); |
angular.module('app')
.controller('ResetController', function ($scope) {
$scope.hideConfirm = true;
});
|
/**
* Created by Lee on 1/29/2016.
*/
Ext.define('AdvUtils.view.main.image.ImageController', {
extend: 'Ext.app.ViewController',
alias: 'controller.image',
requires: [
'AdvUtils.view.main.image.ImageInfoWindow'
],
/**
* Called when the view is created
*/
init: function () {
},
onImageFindClick: function (btn) {
var imageName = this.lookupReference('imagenamefield').value;
Ext.toast('Lookup ' + imageName, "Toast!", 'bl');
var grid = this.lookupReference('imagegrid');
grid.store.getProxy().url = "/rest/image/find/" + imageName;
grid.store.load()
},
onImageCategoryLinkClick: function(btn) {
var category = this.lookupReference('imagecategory').value;
var csHierarchy = this.lookupReference('cshierarchy').value;
var mediaType = this.lookupReference('mediatype').value;
var csLevel = this.lookupReference('cslevel').value;
var searchVal = this.lookupReference('searchval').value;
Ext.Ajax.request({
url: "/rest/image/productImageLinkFix",
method: 'POST',
params: {
ppAttribute:category,
csHierarchy:csHierarchy,
mediaType:mediaType,
csLevel:csLevel,
searchVal:searchVal
},
success: function(transport){
// do something
//alert("Completed");
},
failure: function(transport){
// alert("Error: " - transport.responseText);
}
});
},
onImageRowClick: function (grid, record, tr, rowIndex, e, eOpts) {
var imageWin = Ext.create("AdvUtils.view.main.image.ImageInfoWindow", {name: record.data.name});
// get image
imageWin.show();
}
//onImageInfoWindowShow: function(win) {
// alert(win.imageName);
//}
}); |
const assert = require('assert');
function Obj() {
this.foo = function (x) { return x + 1; };
}
const o = new Obj();
assert.equal(o['foo'](7), 8);
|
Charts.innerHTML=[ "<div id='chartObj_wrapper' style='background-color:white;'><div id='chartObj'></div></div>",
NSB.HeaderBar_jqm14('chartsTitle', 'Charts', '', 'arrow-l', 'left', '', 'false', 'right', ' style="" class=" "'),
].join('');
|
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
app.use(session({
secret: "swordfish",
resave: false,
saveUninitialized: true,
cookie: {maxAge: 60000}
}));
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost/login_reg_1");
var UserSchema = new mongoose.Schema({
email: {type: String, required: true, unique: true,
match: [/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i, 'Please fill a valid email address']},
first_name: {type: String, required: true},
last_name: {type: String, required: true},
password: {type: String, required: true},
birthday: {type: Date, required: true}
});
mongoose.model("User", UserSchema);
var User = mongoose.model("User");
app.get("/", function(req, res){
res.render("index");
});
app.get("/success", function(req, res){
if(req.session.user_id) {
User.findOne({_id: req.session.user_id}, function(err, user){
if(err) {
res.redirect("/");
}
else {
res.render("show", {user: user});
}
});
}
else {
res.redirect("/");
}
});
app.post("/users", function(req, res){
var user = new User();
var user_fields = ["email", "first_name", "last_name", "birthday"];
for(var i=0; i<user_fields.length; i++) {
user[user_fields[i]] = req.body[user_fields[i]];
}
bcrypt.hash(req.body.password, 10, function(err, hash){
if(err) {
res.redirect("/");
}
else {
user.password = hash;
user.save(function(err){
if(err) {
res.redirect("/");
}
else {
req.session.user_id = user._id;
res.redirect("/success");
}
});
}
});
});
app.post("/sessions", function(req, res){
User.findOne({email: req.body.email}, function(err, user){
if(err) {
res.redirect("/");
}
else {
console.log("found user with email " + user.email);
bcrypt.compare(req.body.password, user.password, function(err, result){
if(result) {
req.session.user_id = user._id;
res.redirect("/success");
}
else {
res.redirect("/");
}
});
}
});
});
app.listen(8000); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.