text
stringlengths 7
3.69M
|
|---|
import { createStore, applyMiddleware, combineReducers } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { userLoginAndRegisterReducer } from "./reducers/userReducer";
import {
getAllPostsReducer,
profilePostsReducer,
userLikePostReducer,
userPostReducer,
userReplyPostReducer,
userRetweetPostReducer,
} from "./reducers/postsReducer";
const reducer = combineReducers({
userLoginAndRegister: userLoginAndRegisterReducer,
userLikePost: userLikePostReducer,
userReplyPost: userReplyPostReducer,
userRetweetPost: userRetweetPostReducer,
userPost: userPostReducer,
getAllPosts: getAllPostsReducer,
profilePosts: profilePostsReducer,
});
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: {};
const initialState = {
user: { userInfoFromStorage },
};
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
|
var express = require("express");
var app = express();
app.get("/", function(req, res) {
res.send("Hi there!");
});
app.get("/bye", function(req, res) {
res.send("Goodbye!");
});
app.get("/dog", function(req, res) {
res.send("MEOW!");
});
app.get("/r/:subRedditName", function(req, res) {
res.send("Welcome to " + req.params['subRedditName']);
})
app.get("/r/:subRedditName/comments/:id/:commentTitle", function(req, res) {
res.send("Welcome to \"" + req.params['commentTitle'] + "\" comment section!");
})
app.get("*", function(req, res) {
res.send("Some stars!");
});
var port = 3000;
app.listen(port, function() {
console.log("Express app running on port " + port)
});
|
import React, { Component } from 'react';
import { Button, Card, Icon, Image } from 'semantic-ui-react';
import bg from "../assets/img/arena/1.jpg";
import pic2 from "../assets/img/arena/2.jpg";
import pic3 from "../assets/img/arena/3.jpg";
export class Arena extends Component {
render() {
return (
<React.Fragment>
<div class="ui card" style={{ width:"80%", display: "flex", margin:"0 auto"}}>
<div class="image"><img src={bg} /></div>
<div class="content">
<div class="header">Lapangan GOR Sumantri</div>
<div class="meta">GOR</div>
<div class="description">
Address: RW., RT.2/RW.5, Karet Kuningan, Setia Budi, South Jakarta City, Jakarta 12940
</div>
</div>
<div class="extra content">
<a>
<i aria-hidden="true" class="user icon"></i>
16 People
</a>
</div>
</div>
<div class="ui card" style={{ width:"80%", display: "flex", margin:"0 auto"}}>
<div class="image"><img src={pic2} /></div>
<div class="content">
<div class="header">GOR Bulu Tangkis</div>
<div class="meta">GOR</div>
<div class="description">
Address: Jl. Komp. Migas III No.69, RT.8/RW.1, Palmerah, Kec. Palmerah, Kota Jakarta Barat, Daerah Khusus Ibukota Jakarta 11480
</div>
</div>
<div class="extra content">
<a>
<i aria-hidden="true" class="user icon"></i>
8 Friends
</a>
</div>
</div>
<div class="ui card" style={{ width:"80%", display: "flex", margin:"0 auto"}}>
<div class="image"><img src={pic3} /></div>
<div class="content">
<div class="header">GOR Handayani Kemanggisan</div>
<div class="meta">GOR</div>
<div class="description">
Address: RT.10/RW.8, Kemanggisan, Palmerah, West Jakarta City, Jakarta 11480
</div>
</div>
<div class="extra content">
<a>
<i aria-hidden="true" class="user icon"></i>
5 People
</a>
</div>
</div>
</React.Fragment>
)
}
}
export default Arena
|
import React,{Component} from 'react'
import {TopWrap} from './Top.styled'
import time from '@a/images/vegetables/star.png'
import food from '@a/images/vegetables/shicai.png'
import menu from '@a/images/vegetables/shipu.png'
import {withRouter} from 'react-router-dom'
@withRouter
class Top extends Component{
hanleTimeClick = () => {
let {history} = this.props
history.push( '/time', { name: ' 时光'} )
}
hanleFoodClick = () => {
let {history} = this.props
history.push('/ingredients', { name: '拾材'})
}
hanleMenuClick = () => {
let {history} = this.props
history.push('/recipes')
}
render() {
return (
<TopWrap>
<div className="top">
<div className="tip" onClick={this.hanleTimeClick}>
<div className="time"><img src={time} alt="" /></div>
<span >时光</span>
</div>
<div className="tip" onClick={this.hanleFoodClick}>
<div className="food"><img src={food} alt="" /></div>
<span>拾材</span>
</div>
<div className="tip" onClick={this.hanleMenuClick}>
<div className="menu"><img src={menu} alt="" /></div>
<span>食谱</span>
</div>
</div>
</TopWrap>
)
}
}
export default Top
|
var images;
var length;
function setImageNumber(number, basesrc){
images = new Array(number);
length = number;
var count = 0;
for(count = 1; count < number + 1; count++){
images[count] = new Image();
images[count].src = basesrc + "slider" + count + ".jpg";
}
}
function preload(MySrc){
if(count < images.length){
images[count] = new Image();
images[count].src = MySrc;
count++;
}
}
function fadeslider(){
var timer = 0;
var imagenumber = 1;
var nextimagenumber = 2;
var fadeamount = 0;
var myHeader = document.getElementById("head-1");
var newfade = 0;
for(var c = 2; c <= length; c++){
var id = new String("head-" + c);
document.getElementById(id).style.opacity="0";
}
setInterval(function(){
timer++;
if(timer>900){
fadeamount+=0.003;
var id = new String("head-" + imagenumber);
newfade = 1-fadeamount;
document.getElementById(id).style.opacity=newfade;
var id = new String("head-" + nextimagenumber);
newfade = fadeamount;
document.getElementById(id).style.opacity=newfade;
if(fadeamount > 1){
fadeamount = 0;
timer = 0;
imagenumber = nextimagenumber;
nextimagenumber++;
if(nextimagenumber > length){
nextimagenumber = 1;
}
}
}
})
}
|
import Link from 'next/link'
const Featured = () => (
<React.Fragment>
<div className="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center" />
<h1 className="display-4">Introducing some of our newest friends</h1>
<p className="lead">Every week we try to feature new artists, and teachers. Listen, watch, and follow</p>
<hr className="featurette-divider" />
<div className="row featurette">
<div className="col-md-7">
<h2 className="featurette-heading">Kathy Reid Naiman. </h2>
<div className="text-muted">Award winning early childhood educator</div>
<p className="lead">
Famous early childhood educator. Watch and play together with her <a href="/fingerplays">fingerplays</a>
</p>
<button className="btn btn-primary" type="button" data-toggle="modal" data-target="#exampleModalLong">
Learn more
</button>
</div>
<div className="col-md-5">
<img className="img-fluid" src="../img/Kathy Head shot.jpg" />
</div>
</div>
<hr className="featurette-divider" />
<div className="row featurette">
<div className="col-md-7 order-md-2">
<h2 className="featurette-heading">
Become next month's <span className="text-muted">featured artist</span>
</h2>
<p className="lead">
Featured artists will be included in the monthly playlist. Additionally they will gain followers and
subscribers by being amazing, and with some marketing help behind the scenes from tickles and tunes.
</p>
</div>
<div className="col-md-5 order-md-1">
<svg
className="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto"
width="500"
height="500"
xmlns="http://www.w3.org/2000/svg"
preserveAspectRatio="xMidYMid slice"
focusable="false"
role="img"
aria-label="Placeholder: 500x500"
>
<title>Placeholder</title>
<rect fill="#eee" width="100%" height="100%" />
<text fill="#aaa" dy=".3em" x="50%" y="50%">
Your Face Here
</text>
</svg>
</div>
</div>
<hr className="featurette-divider" />
<div className="row featurette">
<div className="col-md-7">
<h2 className="featurette-heading">
Become next month's <span className="text-muted">featured artist </span>
</h2>
<p className="lead">
Featured artists will be included in the monthly playlist. Additionally they will gain followers and
subscribers by being amazing, and with some marketing help behind the scenes from tickles and tunes.
</p>
</div>
<div className="col-md-5">
<svg
className="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto"
width="500"
height="500"
xmlns="http://www.w3.org/2000/svg"
preserveAspectRatio="xMidYMid slice"
focusable="false"
role="img"
aria-label="Placeholder: 500x500"
>
<title>Placeholder</title>
<rect fill="#eee" width="100%" height="100%" />
<text fill="#aaa" dy=".3em" x="50%" y="50%">
Your Album Here
</text>
</svg>
</div>
</div>
<hr className="featurette-divider" />
<div
className="modal fade"
id="exampleModalLong"
tabIndex="-1"
role="dialog"
aria-labelledby="exampleModalLongTitle"
aria-hidden="true"
>
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLongTitle">
Kathy Reid-Naiman
</h5>
<button className="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<p className="lead">
Kathy Reid-Naiman makes children’s music so accessible that some adults secretly confess to listening to
it just for themselves.{' '}
</p>
<p>
Her songs bring the comfort of tradition and the sweetness of nostalgia – as well as the thrill of novelty
and innovation to young listeners, and their caregivers too. For 20 years, Kathy has made high quality
recordings for children with the diligence and professionalism you would expect from an adult recording.
She believes that a great recording should transition smoothly between songs, and the musical arrangements
should be varied. This simple, but disciplined approach is the reason why she has long been recognised as
one of Canada’s leading early childhood recording artists.
</p>
<p>
In her hometown of Trenton, Ontario, Kathy grew up singing in harmony with her two sisters, in the shadow
of their jazz guitar playing dad. Kathy began playing music for children in 1980 when her children were
young, and over the years, she has developed an enriching music program that she continues to teach in
libraries and schools throughout Ontario.
</p>
<p>
On her self-run record label, Merriweather Records Ltd., Kathy has recorded 15 CDs and one DVD for
children. Her contribution to early literacy has been recognised across Canada through her inclusion in
Newborn Literacy Kits in through the Ontario Early Years, BC Books for Babies, and Edmonton Public
Libraries. Music continues to be the focus of her life and she delights in introducing children to the
wonders of language and music
</p>
</div>
<div className="modal-footer">
<ul className="float-right list-inline">
<li className="list-inline-item">
<script src="https://apis.google.com/js/platform.js" />
<div
className="g-ytsubscribe"
data-channelid="UCeEBafvohiu3_gUHsYY-jwQ"
data-layout="default"
data-count="default"
/>
</li>
<li className="list-inline-item">
<a
className="twitter-follow-button"
href="https://twitter.com/kathyreidnaiman?ref_src=twsrc%5Etfw"
data-show-count="false"
>
{' '}
@KathyReidNaiman
<script async="" src="https://platform.twitter.com/widgets.js" charSet="utf-8" />
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</React.Fragment>
)
export default Featured
|
/*
* @lc app=leetcode.cn id=146 lang=javascript
*
* [146] LRU 缓存
*/
// @lc code=start
class ListNode {
constructor(key, value) {
this.key = key
this.value = value
this.next = null
this.prev = null
}
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.hash = {};
this.count = 0;
this.dummyHead = new ListNode();
this.dummyTail = new ListNode();
this.dummyHead.next = this.dummyTail;
this.dummyTail.prev = this.dummyHead;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let node = this.hash[key];
if (node == null) return -1;
this.moveToHead(node);
return node.value;
};
/**
* @description 移动节点到头部
*/
LRUCache.prototype.moveToHead = function (node) {
this.removeFromList(node); // 将节点从链表中删除
this.addToHead(node); // 将节点连接到链表头部
}
/**
* @description 将节点从链表中删除
*/
LRUCache.prototype.removeFromList = function(node) {
let temp1 = node.next;
let temp2 = node.prev;
temp2.next = temp1;
temp1.prev = temp2;
}
/**
* @description 将节点连接到链表头部
*/
LRUCache.prototype.addToHead = function(node) {
node.prev = this.dummyHead;
node.next = this.dummyHead.next;
this.dummyHead.next.prev = node;
this.dummyHead.next = node;
}
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
let node = this.hash[key];
if (node == null) { // add
if (this.count === this.capacity) {
this.removeLastUse(node);
}
let newNode = new ListNode(key, value);
this.hash[key] = newNode;
this.addToHead(newNode);
this.count++;
} else {
// 更新value
node.value = value;
this.moveToHead(node);
}
};
LRUCache.prototype.removeLastUse = function(node) {
let tail = this.popTail(); // 尾节点一定是最久未使用的
delete this.hash[tail.key];
this.count--;
}
LRUCache.prototype.popTail = function(node) {
let tail = this.dummyTail.prev;
this.removeFromList(tail);
return tail;
}
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
// @lc code=end
|
import Link from 'next/link'
import { FaGithub, FaTwitter } from 'react-icons/fa'
import 'twin.macro'
export default function Navigation({ style, className }) {
return (
<nav style={style} className={className}>
<ul className="flex items-center p-0 text-xl list-none">
<li className="font-serif font-bold">
<Link href="/">
<a className="hover:text-green-600">NaN</a>
</Link>
</li>
<li tw="ml-auto" className="mr-4">
<a
href="https://github.com/narendrasss/blog"
target="_blank"
rel="noreferrer"
className="hover:text-green-600"
>
<FaGithub />
</a>
</li>
<li>
<a
href="https://twitter.com/nansdotio"
target="_blank"
rel="noreferrer"
className="hover:text-green-600"
>
<FaTwitter />
</a>
</li>
</ul>
</nav>
)
}
|
// dom为真实的dom,vnode为虚拟节点
function diff(dom,vnode) {
var out;
// 如果只是简单文本类型
// diff text node
if ( typeof vnode === 'string' ) {
// 如果当前的DOM就是文本节点,则直接更新内容
if ( dom && dom.nodeType === 3 ) { // nodeType: https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
if ( dom.textContent !== vnode ) {
dom.textContent = vnode;
}
// 如果DOM不是文本节点,则新建一个文本节点DOM,并移除掉原来的
} else {
out = document.createTextNode( vnode );
if ( dom && dom.parentNode ) {
dom.parentNode.replaceChild( out, dom );
}
}
return out;
}
if(!dom || dom.nodeName.toLowerCase() !== vnode.type.toLowerCase()){ // 对比节点信息
out = document.createElement( vnode.type );
if ( dom ) {
[ ...dom.childNodes ].map( out.appendChild ); // 将原来的子节点移到新节点下
if ( dom.parentNode ) {
dom.parentNode.replaceChild( out, dom ); // 移除掉原来的DOM对象
}
}
}
if ( vnode.children && vnode.children.length > 0 || ( out.childNodes && out.childNodes.length > 0 ) ) {
diffChildren( out, vnode.children );
}
console.log(out,dom,vnode)
return out
}
function diffChildren( dom, vchildren ) {
const domChildren = dom.childNodes;
const children = [];
const keyed = {};
// 将有key的节点和没有key的节点分开
if ( domChildren.length > 0 ) {
for ( let i = 0; i < domChildren.length; i++ ) {
const child = domChildren[ i ];
const key = child.key;
if ( key ) {
keyed[ key ] = child;
} else {
children.push( child );
}
}
}
if ( vchildren && vchildren.length > 0 ) {
let min = 0;
let childrenLen = children.length;
for ( let i = 0; i < vchildren.length; i++ ) {
const vchild = vchildren[ i ];
const key = vchild.key;
let child;
// 如果有key,找到对应key值的节点
if ( key ) {
if ( keyed[ key ] ) {
child = keyed[ key ];
keyed[ key ] = undefined;
}
// 如果没有key,则优先找类型相同的节点
} else if ( min < childrenLen ) {
for ( let j = min; j < childrenLen; j++ ) {
let c = children[ j ];
if ( c && isSameNodeType( c, vchild ) ) {
child = c;
children[ j ] = undefined;
if ( j === childrenLen - 1 ) childrenLen--;
if ( j === min ) min++;
break;
}
}
}
// 对比
child = diff( child, vchild );
// 更新DOM
const f = domChildren[ i ];
if ( child && child !== dom && child !== f ) {
// 如果更新前的对应位置为空,说明此节点是新增的
if ( !f ) {
dom.appendChild(child);
// 如果更新后的节点和更新前对应位置的下一个节点一样,说明当前位置的节点被移除了
} else if ( child === f.nextSibling ) {
removeNode( f );
// 将更新后的节点移动到正确的位置
} else {
// 注意insertBefore的用法,第一个参数是要插入的节点,第二个参数是已存在的节点
dom.insertBefore( child, f );
}
}
}
}
}
export default diff
|
'use strict';
const express = require('express');
let router = express.Router();
const UtilityFunctions = require('../common/functions');
console.log('Send weekly income report');
router.post('/', UtilityFunctions.sendWeeklyMpesaReport);
// UtilityFunctions.sendWeeklyIncomeReport;
// UtilityFunctions.sendWeeklyMpesaReport;
module.exports = router;
|
/**
* Toolkit JavaScript
*/
'use strict';
// apply bootstrap datepicker
// ----
$('.datepicker').datepicker({
autoclose: true,
container: '.date',
orientation: 'bottom left',
});
$('.main-question input[type="checkbox"]').on('change', function(e){
console.log(e);
if($(this).is(':checked')) {
$('.child-questions').show();
} else {
$('.child-questions').hide();
}
});
|
import * as actionTypes from "./constant";
import axios from "axios";
export const actGetMovieListApi = (tenPhim) => {
return (dispatch) => {
dispatch(actGetMovieListRequest());
axios({
url: `https://movie0706.cybersoft.edu.vn/api/QuanLyPhim/LayDanhSachPhim`,
method: "GET",
params: {
maNhom: "GP09",
tenPhim,
},
})
.then((result) => {
dispatch(actGetMovieListSuccess(result.data));
})
.catch((error) => {
dispatch(actGetMovieListFailed(error));
});
};
};
const actGetMovieListRequest = () => {
return {
type: actionTypes.GET_MOVIE_LIST_REQUEST,
};
};
const actGetMovieListSuccess = (list) => {
return {
type: actionTypes.GET_MOVIE_LIST_SUCCESS,
payload: list,
};
};
const actGetMovieListFailed = (error) => {
return {
type: actionTypes.GET_MOVIE_LIST_FAILED,
payload: error,
};
};
|
import React from 'react';
import { Link, graphql } from 'gatsby';
// Components
import Layout from '../../components/layout';
const Blog = ({ data }) => {
const posts = data.allMdx.nodes;
return (
<Layout pageTitle="My Blog Posts">
{posts.map(post => (
<article key={post.id}>
<h2>
<Link to={`/blog/${post.slug}`}>
{post.frontmatter.title}
</Link>
</h2>
<p>Posted: {post.frontmatter.date}</p>
</article>
))}
</Layout>
);
};
export const query = graphql`
{
allMdx(sort: {order: DESC, fields: frontmatter___date}) {
nodes {
frontmatter {
date(formatString: "MMMM D, YYYY")
title
}
id
slug
}
}
}
`;
export default Blog;
|
import {AiFillInfoCircle} from 'react-icons/ai'
import {BsFillHouseFill} from 'react-icons/bs';
import {AiFillPhone} from 'react-icons/ai';
import {MdLocalPostOffice} from 'react-icons/md';
export function Info({infoProps}) {
const {firstName, setFirstName, lastName, setLastName, address, setAddress, phoneNum,
setPhoneNum, emailAddress, setEmailAddress} = infoProps;
return (
<section className = 'info-container'>
<h2>Info</h2>
<AiFillInfoCircle className = 'icon-logo' size = "30px"/>
<label>First name: </label>
<input type = 'text' value = {firstName} onChange = {(e) => setFirstName(e.target.value)} name = "firstName" placeholder = "Enter Your first name"/>
<label>Last name: </label>
<input type = 'text' value = {lastName} onChange = {(e) => setLastName(e.target.value)} name = "lastName" placeholder = "Enter Your last name"/>
<div className = "info-parent">
<label>address: <BsFillHouseFill className = 'icon-right'/> </label>
<input type = 'text' value = {address} onChange = {(e) => setAddress(e.target.value)} name = "address" placeholder = "Enter Your address"/>
</div>
<div className = "info-parent">
<label> phone: <AiFillPhone className = 'icon-right'/></label>
<input type = 'number' value = {phoneNum} onChange = {(e) => setPhoneNum(e.target.value)}name = "phone" placeholder = "Enter Your phone number"/>
</div>
<div className = "info-parent">
<label>email: <MdLocalPostOffice className = 'icon-right'/></label>
<input type = 'text' value = {emailAddress} onChange = {(e) => setEmailAddress(e.target.value)} name = "email" placeholder = "Enter Your email adress"/>
</div>
</section>
)
}
export default Info
|
import { expect } from "chai";
import { createFBStorageAPI } from "../createFBStorageAPI.js";
const mockFirebase = {
get: () => Promise.resolve({ val: () => ({ id: 0 }) }),
set: ( v ) => Promise.resolve( v )
};
const wait = ( time ) =>
new Promise( ( res ) => {
setTimeout( res(), time );
});
describe( "createFBStorageAPI", () => {
it( "should provide the functions for a redux-persist storage", () => {
const actual = Object.keys( createFBStorageAPI( mockFirebase ) );
const expected = [ "getItem", "setItem", "deleteItem" ];
expect( actual ).to.members( expected );
});
it( "getItem should return a promised value", async () => {
const actual = await createFBStorageAPI( mockFirebase, 0 )
.getItem()
.then( ( v ) => v.id );
const expected = 0;
expect( actual ).to.eqls( expected );
});
it( "setItem should return a promised", async () => {
const actual = await createFBStorageAPI( mockFirebase )
.setItem( 1 )
.then( ( v ) => v );
const expected = 1;
await wait( 2100 );
expect( actual ).to.eqls( expected );
});
});
// describe( "createFireBaseRealTimePersistConfig", () => {
// expect( createFireBaseRealTimePersistConfig() ).to.be.rejectedWith( Error );
// });
|
_socialQueue.push({
url: '//assets.pinterest.com/js/pinit.js',
id: '<?php echo $this->name; ?>',
preload: function(f) {
window.PinIt = window.PinIt || {
loaded:false
};
if (window.PinIt.loaded) {
return;
}
window.PinIt.loaded = true;
},
onload: function(f) {
if ('<?php echo $this->fadeIn; ?>') {
f.awaitRender({
buttons: document.getElementsByClassName('coi-social-button-<?php echo $this->name; ?>'),
duration: '<?php echo $this->fadeIn; ?>',
isRendered: function(element) {
return element.getElementsByTagName('A')[0];
}
});
}
}
});
|
export { default } from '@upfluence/ember-upf-utils/components/errors-list';
|
jQuery.sap.require("com.hcl.app.SMPController");
sap.ui.controller("ui5bp.view.PlantChangedList", {
onInit: function() {
//this.getView().setModel(new sap.ui.model.json.JSONModel("model/coffee2.json"));
this.bus = sap.ui.getCore().getEventBus();
this.bus.subscribe("read", "plantChanged", this.plantsReadDone, this);
},
doNavBack: function(event) {
this.bus.publish("nav", "back");
},
onPlantSelect: function(event) {
console.log("plant select ");
//event.getSource().getSelectedItem().getBindingContextPath()
//this.bus.publish("status", "online", {value:"This is a test"});
var oPlant = event.getSource().getSelectedItem() //evt.getParameter("listItem");
var sPath = oPlant.getBindingContext().getPath();
var oObject = this.getView().getModel().getProperty(sPath);
//this._oRouter.navTo("detail", {detailId: oObject.ID});
this.bus.publish("nav", "to", {
id: "PlantEdit",
data: oObject
});
//event.oSource.oBindingContexts
/*this.bus.publish("nav", "to", {
id: "PlantEdit",
data: {
plantId: oObject.Werks,
plantStand:"Greg"
}
});*/
//beforeShow
},
doRefresh: function(){
console.log("onRefresh");
com.hcl.app.SMPController.read(true, false);
},
plantsReadDone: function(sChannelId, sEventId, oData){
console.log("plantsReadDone changed");
this.getView().setModel(oData.value);
sap.ui.getCore().setModel(oData.value,"plantChanged");
},
onSearch: function (oEvt) {
// add filter for search
var aFilters = [];
var sQuery = oEvt.getSource().getValue();
if (sQuery && sQuery.length > 0) {
var filter = new sap.ui.model.Filter("Werks", sap.ui.model.FilterOperator.Contains, sQuery);
aFilters.push(filter);
}
// update list binding
var list = this.getView().byId("plantChangedList");
var binding = list.getBinding("items");
binding.filter(aFilters, "Werks");
}
});
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsChromeReaderMode = {
name: 'chrome_reader_mode',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/></svg>`
};
|
var Board = {
/*
getListUrl:function(form) {
var form = $(form);
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","listUrl"),
data:form.serialize(),
dataType:"json",
success:function(result) {
if (result.success == true) {
location.href = result.url;
}
},
error:function() {
iModule.alertMessage.show("Server Connect Error!");
}
});
return false;
},*/
list:{
init:function() {
var $form = $("#ModuleBoardListForm");
// secret post
$("a[href|=#secret]",$form).on("click",function(e) {
var idx = $(this).attr("href").split("-").pop();
Board.post.secret(idx);
e.preventDefault();
});
}
},
view:{
init:function(idx) {
var $view = $("#ModuleBoardViewContext-"+idx);
var $pagination = $("div[data-role=ment-pagination]",$view);
$("a[href|=#page]",$pagination).on("click",function(e) {
var parent = $pagination.attr("data-parent");
var page = $(this).attr("href").split("-").pop();
Board.ment.loadPage(parent,page);
e.preventDefault();
});
$("div[data-role=ment][data-secret-password=true]",$view).on("click",function() {
Board.ment.secret($(this).attr("data-idx"));
});
}
},
post:{
init:function(form) {
var $form = $("#"+form);
$form.formInit(Board.post.submit,Board.post.check);
$(document).triggerHandler("Board.post.init",[$form]);
},
check:function($input) {
if ($input.attr("required") == "required") {
if ($input.val().length == 0) {
$input.inputStatus("error");
} else {
$input.inputStatus("success");
}
}
},
submit:function($form) {
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","savePost"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
location.href = ENV.getUrl(null,null,"view",result.idx);
} else {
$form.formStatus("error",result.errors);
if (result.message) {
iModule.alertMessage.show("error",result.message,5);
}
}
},
error:function() {
iModule.alertMessage.show("Server Connect Error!");
}
});
},
modify:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","modifyPost"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
$form.formStatus("success");
var idx = $("input[name=idx]",$form).val();
$form.attr("action",ENV.getUrl(null,null,"write",idx));
$form.attr("method","POST");
$form.off("submit");
$form.submit();
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
$form.formStatus("error",result.errors);
}
}
});
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","modifyPost"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.modalHtml) {
iModule.modal.showHtml(result.modalHtml);
} else {
location.href = ENV.getUrl(null,null,"write",idx);
}
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
}
}
});
}
},
secret:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","secretPost"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
$form.formStatus("success");
var idx = $("input[name=idx]",$form).val();
$form.attr("action",ENV.getUrl(null,null,"view",idx));
$form.attr("method","POST");
$form.off("submit");
$form.submit();
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
$form.formStatus("error",result.errors);
}
}
});
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","secretPost"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.modalHtml) {
iModule.modal.showHtml(result.modalHtml);
} else {
location.href = ENV.getUrl(null,null,"write",idx);
}
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
}
}
});
}
},
delete:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","deletePost"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
location.href = ENV.getUrl(null,null,"list",result.page);
} else {
if (result.message) {
iModule.alertMessage.show("error",result.message,5);
}
if (result.errors) {
$form.formStatus("error",result.errors);
}
}
}
});
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","deletePost"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.modal.showHtml(result.modalHtml);
} else {
iModule.alertMessage.show("error",result.message,5);
}
}
});
}
}
},
ment:{
$activeButton:null,
init:function(form,type) {
var $form = $("#"+form);
var type = type ? type : "write";
$form.formInit(Board.ment.submit,Board.ment.check);
$("span[data-title-"+type+"]",$form).html($("span[data-title-"+type+"]",$form).attr("data-title-"+type));
$(document).triggerHandler("Board.ment.init",[$form,type]);
},
check:function($input) {
if ($input.attr("required") == "required") {
if ($input.val().length == 0) {
$input.inputStatus("error");
} else {
$input.inputStatus("success");
}
}
},
submit:function($form) {
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","saveMent"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.message) iModule.alertMessage.show("success",result.message,5);
Board.ment.loadIdx(result.idx);
$form.formStatus("default");
Board.ment.reset(result.parent);
} else {
$form.formStatus("error",result.errors);
if (result.message) {
iModule.alertMessage.show("error",result.message,5);
}
}
}
});
},
reset:function(parent) {
if (Board.ment.$activeButton != null) {
Board.ment.$activeButton.removeClass("selected");
Board.ment.$activeButton.html(Board.ment.$activeButton.data("default"));
}
Board.ment.$activeButton = null;
var $form = $("#ModuleBoardMentForm-"+parent);
var idx = $("input[name=idx]",$form).val();
var parent = $("input[name=parent]",$form).val();
var source = $("input[name=source]",$form).val();
if (idx) {
var $ment = $("div[data-role=ment][data-idx="+idx+"]");
var $context = $("*[data-role=context]",$ment).show();
}
$form.reset();
$("input[name=parent]",$form).val(parent);
if (idx || source) {
$("textarea[data-wysiwyg=true]",$form).froalaEditor("destroy");
var $moveForm = $form.clone();
$form.remove();
$("div[data-role='ment-write-form'][data-parent="+parent+"]").append($moveForm);
$("textarea[data-wysiwyg=true]",$moveForm).wysiwyg(true);
}
Board.ment.init("ModuleBoardMentForm-"+parent);
},
formMove:function(type,parent,source) {
var $ment = $("div[data-role=ment][data-idx="+source+"]");
var $form = $("#ModuleBoardMentForm-"+parent);
var $button = $("button[data-role='btn-"+type+"']",$ment);
if (Board.ment.$activeButton != null) {
Board.ment.reset(parent);
}
Board.ment.$activeButton = $button;
$form.reset();
$("textarea[data-wysiwyg=true]",$form).froalaEditor("destroy");
var $moveForm = $form.clone();
$form.remove();
$ment.append($moveForm);
$("textarea[data-wysiwyg=true]",$moveForm).wysiwyg(true);
$("input[name=parent]",$moveForm).val(parent);
$("input[name=source]",$moveForm).val(source);
$button.addClass("selected");
if ($button.attr("data-cancel") !== undefined) {
$button.data("default",$button.html());
$button.html($button.attr("data-cancel"));
}
Board.ment.init("ModuleBoardMentForm-"+parent,"reply");
$moveForm.positionScroll();
},
reply:function(idx) {
var $ment = $("div[data-role=ment][data-idx="+idx+"]");
var $button = $("button[data-role='btn-reply']",$ment);
if ($button.hasClass("selected") == true) {
Board.ment.reset($ment.attr("data-parent"));
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","getMentDepth"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
Board.ment.formMove("reply",result.parent,result.source)
} else {
iModule.alertMessage.show("error",result.message,5);
}
}
});
}
},
modify:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var idx = $("input[name=idx]",$form).val();
var $ment = $("div[data-role=ment][data-idx="+idx+"]");
var $button = $("button[data-role='btn-modify']",$ment);
var data = $form.serialize();
} else {
var $form = null;
var $ment = $("div[data-role=ment][data-idx="+idx+"]");
var $button = $("button[data-role='btn-modify']",$ment);
var data = {idx:idx};
}
if ($button.hasClass("selected") == true) {
Board.ment.reset($ment.attr("data-parent"));
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","modifyMent"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.modalHtml) {
iModule.modal.showHtml(result.modalHtml);
}
if (result.data) {
iModule.modal.close();
Board.ment.formMove("modify",result.data.parent,result.data.idx);
(function(data) {
var $form = $("#ModuleBoardMentForm-"+data.parent);
var $ment = $("div[data-role=ment][data-idx="+data.idx+"]");
var $context = $("*[data-role=context]",$ment);
$context.hide();
$("textarea[data-wysiwyg=true]",$form).each(function () {
$(this).wysiwyg(true);
Attachment.loadFile($(this).attr("id")+"-attachment",data.attachment);
$(this).froalaEditor("html.set",data[$(this).attr("name")]);
});
$("input[name=parent]",$form).val(data.parent);
$("input[name=source]",$form).val("");
$("input[name=idx]",$form).val(data.idx);
if ($("input[name=name]").length > 0) $("input[name=name]",$form).val(data.name);
if ($("input[name=email]").length > 0) $("input[name=email]",$form).val(data.email);
$("input[name=is_secret]",$form).prop("checked",data.is_secret == "TRUE");
$("input[name=is_hidename]",$form).prop("checked",data.is_hidename == "TRUE");
Board.ment.init("ModuleBoardMentForm-"+data.parent,"modify");
})(result.data);
}
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
if ($form !== null) {
$form.formStatus("error",result.errors);
}
}
}
});
}
},
reload:function(parent) {
var $view = $("#ModuleBoardViewContext-"+parent);
var $pagination = $("div[data-role=ment-pagination]",$view);
Board.ment.loadPage(parent,$pagination.attr("data-current-page"));
},
loadPage:function(parent,page) {
var $view = $("#ModuleBoardViewContext-"+parent);
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","getMents"),
data:{get:"page",parent:parent,page:page},
dataType:"json",
success:function(result) {
if (result.success == true) {
Board.ment.print(result);
if (iModule.isInScroll($("div[data-role=ments][data-parent="+result.parent+"]")) == false) {
$("html,body").animate({scrollTop:$("div[data-role=ments][data-parent="+result.parent+"]").offset().top - 100},"fast");
}
}
}
});
},
loadIdx:function(idx) {
var $view = $("#ModuleBoardViewContext-"+parent);
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","getMents"),
data:{get:"idx",idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
Board.ment.print(result);
var $ment = $("div[data-role=ment][data-idx="+idx+"]",$view);
if (iModule.isInScroll($ment) == false) {
$("html,body").animate({scrollTop:$ment.offset().top - 100},"fast");
}
}
}
});
},
print:function(result) {
var $view = $("#ModuleBoardViewContext-"+result.parent);
var $ments = $("div[data-role=ments][data-parent="+result.parent+"]",$view);
if (result.mentHtml !== undefined) {
$ments.html(result.mentHtml);
} else {
$("div[data-role=empty]",$ments).remove();
Board.ment.printRemove(result.parent,result.idxs);
for (var i=0, loop=result.ments.length;i<loop;i++) {
var $ment = $(result.ments[i].html);
$ment.find("img").on("load",function() {
if ($(this).parents(".wrapContent").innerWidth() < $(this).width()) {
$(this).width($(this).parents(".wrapContent").innerWidth());
}
});
var isPrint = false;
if ($("div[data-role=ment][data-idx="+result.ments[i].idx+"]",$ments).length == 0) {
if (i == 0) {
$ments.prepend($ment);
} else {
$ment.insertAfter($("div[data-role=ment]",$ments)[i-1]);
}
isPrint = true;
} else if ($("div[data-role=ment][data-idx="+result.ments[i].idx+"]",$ments).attr("data-modify") != result.ments[i].modify_date) {
$("div[data-role=ment][data-idx="+result.ments[i].idx+"]",$ments).replaceWith($ment);
isPrint = true;
}
if (isPrint == true && $ment.attr("data-secret-password") == "true") {
$ment.on("click",function() {
Board.ment.secret($(this).attr("data-idx"));
});
}
}
}
// $(".liveUpdateBoardPostMent"+result.parent).text(result.mentCount);
$("div[data-role=ment-pagination]",$view).replaceWith(result.pagination);
var $pagination = $("div[data-role=ment-pagination]",$view);
$("a[href|=#page]",$pagination).on("click",function(e) {
var parent = $pagination.attr("data-parent");
var page = $(this).attr("href").split("-").pop();
Board.ment.loadPage(parent,page);
e.preventDefault();
});
$(document).triggerHandler("Board.ment.print",[result]);
},
printRemove:function(parent,ments) {
var $view = $("#ModuleBoardViewContext-"+parent);
var $ments = $("div[data-role=ments][data-parent="+parent+"]",$view);
var $ment = $("div[data-role=ment]",$ments);
for (var i=0, loop=$ment.length;i<loop;i++) {
if ($.inArray(parseInt($($ment[i]).attr("data-idx")),ments) == -1) {
$($ment[i]).remove();
}
}
},
delete:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","deleteMent"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.modal.close();
if (result.position) {
Board.ment.loadIdx(result.position);
} else {
Board.ment.reload(result.parent);
}
} else {
if (result.message) {
iModule.alertMessage.show("error",result.message,5);
}
if (result.errors) {
$form.formStatus("error",result.errors);
}
}
}
});
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","deleteMent"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.modal.showHtml(result.modalHtml);
} else {
iModule.alertMessage.show("error",result.message,5);
}
}
});
}
},
secret:function(idx) {
if (typeof idx == "object" && idx.is("form") == true) {
var $form = idx;
var data = $form.serialize();
$form.formStatus("loading");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","secretMent"),
data:data,
dataType:"json",
success:function(result) {
if (result.success == true) {
var $ment = $(result.ment);
$ment.find("img").on("load",function() {
if ($(this).parents(".wrapContent").innerWidth() < $(this).width()) {
$(this).width($(this).parents(".wrapContent").innerWidth());
}
});
iModule.modal.close();
$("div[data-role=ment][data-idx="+result.idx+"]").replaceWith($ment);
if (iModule.isInScroll($ment) == false) {
$("html,body").animate({scrollTop:$ment.offset().top - 100},"fast");
}
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
$form.formStatus("error",result.errors);
}
}
});
} else {
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","secretMent"),
data:{idx:idx},
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.modalHtml) {
iModule.modal.showHtml(result.modalHtml);
} else {
var $ment = $(result.ment);
$ment.find("img").on("load",function() {
if ($(this).parents(".wrapContent").innerWidth() < $(this).width()) {
$(this).width($(this).parents(".wrapContent").innerWidth());
}
});
$("div[data-role=ment][data-idx="+result.idx+"]").replaceWith($ment);
if (iModule.isInScroll($ment) == false) {
$("html,body").animate({scrollTop:$ment.offset().top - 100},"fast");
}
}
} else {
if (result.message) iModule.alertMessage.show("error",result.message,5);
}
}
});
}
},
vote:{
good:function(idx,button) {
if (button) {
$(button).addClass("selected").attr("disabled",true);
$(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin");
}
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","vote"),
data:{type:"ment",idx:idx,vote:"good"},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.alertMessage.show("default",result.message,5);
$("."+result.liveUpdate).text(result.liveValue);
} else {
iModule.alertMessage.show("error",result.message,5);
if (result.result === undefined || result.result != "GOOD") {
$(button).removeClass("selected");
}
}
if (button) {
$(button).attr("disabled",false);
$(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class"));
}
}
});
},
bad:function(idx,button) {
if (button) {
$(button).addClass("selected").attr("disabled",true);
$(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin");
}
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","vote"),
data:{type:"ment",idx:idx,vote:"bad"},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.alertMessage.show("default",result.message,5);
$("."+result.liveUpdate).text(result.liveValue);
} else {
iModule.alertMessage.show("error",result.message,5);
if (result.result === undefined || result.result != "BAD") {
$(button).removeClass("selected");
}
}
if (button) {
$(button).attr("disabled",false);
$(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class"));
}
}
});
}
}
},
vote:{
good:function(idx,button) {
if (button) {
$(button).addClass("selected").attr("disabled",true);
$(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin");
}
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","vote"),
data:{type:"post",idx:idx,vote:"good"},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.alertMessage.show("default",result.message,5);
$("."+result.liveUpdate).text(result.liveValue);
} else {
iModule.alertMessage.show("error",result.message,5);
if (result.result === undefined || result.result != "GOOD") {
$(button).removeClass("selected");
}
}
if (button) {
$(button).attr("disabled",false);
$(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class"));
}
}
});
},
bad:function(idx,button) {
if (button) {
$(button).addClass("selected").attr("disabled",true);
$(button).find(".fa").data("class",$(button).find(".fa").attr("class")).removeClass().addClass("fa fa-spinner fa-spin");
}
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","vote"),
data:{type:"post",idx:idx,vote:"bad"},
dataType:"json",
success:function(result) {
if (result.success == true) {
iModule.alertMessage.show("default",result.message,5);
$("."+result.liveUpdate).text(result.liveValue);
} else {
iModule.alertMessage.show("error",result.message,5);
if (result.result === undefined || result.result != "BAD") {
$(button).removeClass("selected");
}
}
if (button) {
$(button).attr("disabled",false);
$(button).find(".fa").removeClass("fa-spinner fa-spin").addClass($(button).find(".fa").data("class"));
}
}
});
}
},
delete:function(form) {
var form = $(form);
iModule.buttonStatus(form,"loading");
iModule.inputStatus(form,"default");
$.ajax({
type:"POST",
url:ENV.getProcessUrl("board","delete"),
data:form.serialize(),
dataType:"json",
success:function(result) {
if (result.success == true) {
if (result.type == 'post') {
$("form[name=ModuleBoardListForm]").submit();
} else {
if (result.message) iModule.alertMessage.show("success",result.message,5);
if (result.position) {
Board.ment.loadIdx(result.position);
} else {
Board.ment.loadPage(1,result.parent);
}
iModule.modal.close();
}
} else {
var errorMsg = "";
for (field in result.errors) {
iModule.inputStatus(form.find("input[name="+field+"], textarea[name="+field+"]"),"error",result.errors[field]);
}
if (result.message) {
iModule.alertMessage.show("error",result.message,5);
}
iModule.buttonStatus(form,"reset");
}
}
});
return false;
}
};
$(document).ready(function() {
var temp = location.href.split("#");
if (temp.length == 2 && temp[1].indexOf("ment") == 0) {
var ment = temp[1].replace("ment","");
if ($("#ModuleBoatdMentItem-"+ment).length == 1) {
$("html, body").animate({scrollTop:$("#ModuleBoatdMentItem-"+ment).offset().top - 100},"fast");
} else {
Board.ment.loadIdx(ment);
}
}
$("a").on("click",function() {
var temp = $(this).attr("href").split("#");
if (temp.length == 2 && location.href.split("#").shift().search(new RegExp(temp[0]+"$")) != -1 && temp[1].indexOf("ment") == 0) {
var ment = temp[1].replace("ment","");
if ($("#ModuleBoatdMentItem-"+ment).length == 1) {
$("html, body").animate({scrollTop:$("#ModuleBoatdMentItem-"+ment).offset().top - 100},"fast");
} else {
Board.ment.loadIdx(ment);
}
}
});
});
|
const path = require('path')
const webpack = require('webpack')
let src_path = 'resources/assets/js/'
module.exports = {
node: {
fs: "empty"
},
resolve: {
alias: {
"@assets": path.resolve(__dirname, 'resources/assets'),
"@components": path.resolve(__dirname, src_path + 'components')
}
},
}
|
var clicked = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "complete"){
chrome.browserAction.setIcon({path: "icon2.png"});
clicked[tabId] = clicked[tabId] || {};
clicked[tabId].loading = false;
clicked[tabId].opened = false;
}
if(changeInfo.status == "loading"){
clicked[tabId] = clicked[tabId] || {};
clicked[tabId].loading = true;
chrome.browserAction.setIcon({path: "icon2_disabled.png"});
}
});
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({
'active': true,
'lastFocusedWindow': true
}, function(tabs) {
if( !clicked[tabs[0].id].opened && !clicked[tabs[0].id].loading){
clicked[tabs[0].id].opened = true;
chrome.browserAction.setIcon({path: "icon2_disabled.png"});
}else{
return;
}
var _nocache = new Date().getTime();
chrome.tabs.executeScript(null, {
code: "var script = document.createElement('link');" +
"script.setAttribute('rel', 'stylesheet');" +
"script.setAttribute('href', 'http://localhost:8081/main.css?" + _nocache +"');" +
"document.head.appendChild(script);"
});
});
});
|
let num = [2, 5, 0];
num.sort();
console.log(`Nosso vetor é o ${num}`);
console.log(`O primeiro valor do vetor é ${num[0]}`);
console.log(`Nosso vetor é o ${num}`);
for (let i = 0; i < num.length; i++) {
console.log(` O valor do indice ${i} é :${num[i]}`);
}
console.log("-------------------");
for(let i in num){
console.log(` O valor do indice ${i} é :${num[i]}`);
}
let pos = num.indexOf(5)
if (pos==-1){
console.log(`o valor não foi encontrado`);
}else{
console.log(` O valor do indice ${pos} é :${num[pos]}`);
}
|
import React, { useState } from 'react';
import Display from './Display';
import { GridButton, LargeButton } from './Button';
import Layout from './Layout';
const DIGIT = 'DIGIT';
const OPERATOR = 'OPERATOR';
export default function App() {
const [currentValue, setCurrentValue] = useState('0');
const [memoryValue, setMemoryValue] = useState(null);
const [lastClicked, setLastClicked] = useState(null);
const [lastOperatorUsed, setLastOperatorUsed] = useState(null);
const [history, setHistory] = useState([]);
const [isDisabled, setIsDisabled] = useState(false);
// DIGIT
const handleDigit = (digit) => {
if (isDisabled) return;
if (currentValueReachedLimit()) return;
// Prevent multiple zeros
if (digit === '00' && (currentValue === '0' || lastClicked === OPERATOR)) return;
// Append zero before decimal point
if (digit === '.' && currentValue === '0') {
setCurrentValue('0.');
}
// If clicked on decimal and there is already decimal point
if (digit === '.' && currentValue.includes('.')) return;
// Clicked on digit right after clicking on equals
if (lastOperatorUsed === '=') {
setCurrentValue(digit === '.' ? '0.' : digit);
setMemoryValue(null);
setLastOperatorUsed(null);
setHistory([]);
// When current value is zero or is empty (after clearing negative operator)
} else if (currentValue === '0' || currentValue === '') {
setCurrentValue(digit);
// When previously clicked on digit or current value is negative sign
} else if (lastClicked === DIGIT || currentValue === '-') {
// Append clicked number to the end
setCurrentValue(currentValue + digit);
// When last time clicked on operator
} else if (lastClicked === OPERATOR) {
// If clicked on decimal after clicking on operator
if (digit === '.') {
setCurrentValue('0' + digit);
} else {
setCurrentValue(digit);
}
// Store current value in memory and set current value to clicked digit
if (lastOperatorUsed !== '√') {
setMemoryValue(currentValue);
}
}
setLastClicked(DIGIT);
};
// OPERATOR
const handleOperator = (operator) => {
if (isDisabled) return;
if (currentValue.slice(-1) === '.') return;
// Clicked the same operator twice, do nothing
if (lastClicked === OPERATOR && lastOperatorUsed === operator) return;
// Clicked on square root right after clicking on equals
if (operator === '√' && lastOperatorUsed === '=') {
setHistory(['√' + currentValue]);
setCurrentValue(Math.sqrt(currentValue).toString());
setLastOperatorUsed('√');
}
// Clicked square root and nothing is in memory
else if (operator === '√' && memoryValue === null) {
// Calculate the value and append to history
setCurrentValue(Math.sqrt(currentValue).toString());
// setHistory(history.concat("√" + currentValue));
setHistory(['√' + currentValue]);
setLastClicked(OPERATOR);
setLastOperatorUsed('√');
return;
// Clicked on square root and something is in memory
} else if (operator === '√' && memoryValue) {
setCurrentValue(
(Math.sqrt(currentValue) + parseFloat(memoryValue)).toString()
);
setHistory(history.concat('√' + currentValue));
setMemoryValue(null);
setLastOperatorUsed('√');
// Last clicked was square root
} else if (lastOperatorUsed === '√') {
// Append new operator to history
setHistory(history.concat(operator));
setLastOperatorUsed(operator);
setMemoryValue(currentValue);
}
// Right after clicking on equals clicked on operator
else if (lastOperatorUsed === '=') {
setMemoryValue(currentValue);
setHistory([currentValue, operator]);
setLastOperatorUsed(operator);
// When repeatedly clicking on operators
} else if (lastClicked === OPERATOR) {
// Last time clicked on operator and then on subtract
if (operator === '-') {
// Set current to negative value
setCurrentValue('-');
} else {
// Last time changed the value to negative and clicked operator
// again, so the user wants to change the operation
if (currentValue === '-') {
// Remove negative sign from current value
setCurrentValue('');
}
// Update operator clicked
setLastOperatorUsed(operator);
// Update history
setHistory(history.slice(0, -1).concat(operator));
}
// Last time clicked on a digit
} else if (lastClicked === DIGIT) {
updateResult();
setHistory(history.concat([currentValue, operator]));
setLastOperatorUsed(operator);
}
setLastClicked(OPERATOR);
};
// EQUALS
const handleEquals = () => {
if (isDisabled) return;
// If last clicked on equals or there is nothing to calculate
if (lastOperatorUsed === '=' || lastOperatorUsed === null) return;
// User is trying to divide by zero
if (lastOperatorUsed === '/' && currentValue === '0') {
setTimeout(() => {
setCurrentValue('0');
setIsDisabled(false);
}, 1000)
setCurrentValue('You cannot divide by zero');
setMemoryValue(null);
setHistory([]);
setIsDisabled(true);
setLastClicked(null);
setLastOperatorUsed(null);
return;
};
// Last clicked on square root, already has the result
if (lastOperatorUsed === '√') {
setLastOperatorUsed(history.concat(['=', currentValue]));
// Clicked on equals right after clicking on operator
} else if (lastClicked === OPERATOR && !memoryValue) {
setHistory(history.slice(0, -1).concat(['=', currentValue]));
} else {
// Update current value and history
updateResult();
setHistory(
history.concat([
currentValue,
'=',
calculate(memoryValue, currentValue, lastOperatorUsed),
])
);
}
setLastClicked(OPERATOR);
setLastOperatorUsed('=');
};
// CLEAR
const handleClear = () => {
if (isDisabled) return;
console.log("WHY");
setCurrentValue('0');
setMemoryValue(null);
setHistory([]);
setLastClicked(null);
setLastOperatorUsed(null);
};
// DELETE
const handleDelete = () => {
if (isDisabled) return;
if (lastClicked === OPERATOR) return;
// Last clicked on equals
if (lastOperatorUsed === '=') {
setMemoryValue(null);
setHistory([]);
// Current value is just one digit
} else if (currentValue.length === 1) {
setCurrentValue('0');
} else {
// Remove last digit
setCurrentValue(currentValue.slice(0, -1));
}
};
// PLUS/MINUS
const handlePlusMinus = () => {
if (isDisabled) return;
// Append/remove minus sign
setCurrentValue(
currentValue[0] === '-' ? currentValue.slice(1) : '-' + currentValue
);
};
// Updates result
const updateResult = () => {
// There is something in memory
if (memoryValue) {
// Calculate the result and clear memory
setCurrentValue(calculate(memoryValue, currentValue, lastOperatorUsed));
setMemoryValue(null);
} else {
// There is nothing in memory so update memory
setMemoryValue(currentValue);
}
};
// Digit limit
const currentValueReachedLimit = () => {
if (currentValue.length >= 23 && lastClicked === DIGIT) {
setTimeout(() => {
setCurrentValue(currentValue);
setIsDisabled(false);
}, 1000);
setCurrentValue('LIMIT REACHED');
setIsDisabled(true);
return true;
}
};
return (
<Layout
top={<Display topValue={history.join(' ')} bottomValue={currentValue} />}
middle={
<>
<GridButton id="clear" keyCodes={[46]} value="AC" onClick={handleClear} />
<GridButton keyCodes={[8]} value="DEL" onClick={handleDelete} />
<GridButton id="plus-minus" value="+/-" onClick={handlePlusMinus} />
<GridButton
id="sqrt"
value="√"
onClick={handleOperator}
/>
<GridButton id="seven" keyCodes={[55,103]} value="7" onClick={handleDigit} />
<GridButton id="eight" keyCodes={[56,104]} value="8" onClick={handleDigit} />
<GridButton id="nine" keyCodes={[57,105]} value="9" onClick={handleDigit} />
<GridButton
id="divide"
keyCodes={[111,191]}
value="/"
onClick={handleOperator}
/>
<GridButton id="four" keyCodes={[52,100]} value="4" onClick={handleDigit} />
<GridButton id="five" keyCodes={[53,101]} value="5" onClick={handleDigit} />
<GridButton id="six" keyCodes={[54,102]} value="6" onClick={handleDigit} />
<GridButton
id="multiply"
keyCodes={[106, 56]}
value="x"
onClick={handleOperator}
/>
<GridButton id="one" keyCodes={[49,97]} value="1" onClick={handleDigit} />
<GridButton id="two" keyCodes={[50,98]} value="2" onClick={handleDigit} />
<GridButton id="three" keyCodes={[51,99]} value="3" onClick={handleDigit} />
<GridButton
id="subtract"
keyCodes={[189,109]}
value="-"
onClick={handleOperator}
/>
<GridButton id="zero" keyCodes={[48,96]} value="0" onClick={handleDigit} />
<GridButton
id="double-zero"
value="00"
onClick={handleDigit}
/>
<GridButton
id="decimal"
keyCodes={[190,110]}
value="."
onClick={handleDigit}
/>
<GridButton
id="add"
keyCodes={[107]}
value="+"
onClick={handleOperator}
/>
</>
}
bottom={
<LargeButton
id="equals"
keyCodes={[13]}
value="="
onClick={handleEquals}
/>
}
/>
);
}
function calculate(a, b, operation) {
a = parseFloat(a);
b = parseFloat(b);
let result;
switch (operation) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case 'x':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
break;
}
return result.toString();
}
|
sap.ui.define([
"sap/ui/test/Opa5",
"sap/ui/test/actions/Press",
"sap/ui/test/matchers/Properties"
],function(
Opa5,
Press,
Properties
){
"use strict";
return Opa5.extend("z.fiori.tutorial.test.integration.arrangement.Arrangement", {
iStartMyApp : function () {
//try to open our application
return this.iStartMyAppInAFrame("/fiori/index.html")
.waitFor({
controlType: "sap.m.GenericTile",
actions: new Press(),
matchers: new Properties({
header: "z_fiori_tutorial"
})
});
}
});
});
|
import React from "react";
import styled from "styled-components";
const StyledSection = styled.div`
display: flex;
margin-left: 5px;
align-items: space-around;
`;
function AssignChildren({ children, selectedChildren, onChange }) {
function handleChange(id) {
onChange(id);
}
return (
<StyledSection>
{children &&
children.map(child => (
<label key={child.id}>
{child.firstName}
<input
type="checkbox"
name={child.id}
checked={selectedChildren.includes(child.id)}
onChange={() => handleChange(child.id)}
/>
</label>
))}
</StyledSection>
);
}
export default AssignChildren;
|
import React, { Component } from 'react';
import {Button, Modal, Header} from 'semantic-ui-react'
import './About.css'
import Register from './Registerform'
class About extends Component {
render(){
return(
<div>
<h1>If you're an...</h1>
<div className="about-wrapper">
<div className = "mission-statement">
<div className="ui raised segment" id='mission-statement-box'>
<h1>Influncer</h1>
<h2>I want songs for my video content</h2>
<p>You are an influencer with tens of thousands of followers but want to improve your production
quality as well as further monetize your audience. We curate music that you and your fans like and
pay you support those artists!</p>
<div className='join-us-button'>
<Modal trigger={<Button>Join us now!</Button>}>
<Modal.Content>
<Register/>
</Modal.Content>
</Modal>
</div>
</div>
</div>
<div className = "mission-statement">
<div className="ui raised segment" id='mission-statement-box'>
<h1>Label</h1>
<h2>I want to promote my music</h2>
<p>As artists ourselves, we understand the struggle of figuring out how to show your music to the world.
So we built a platform to music to show your music to people it will mean the world to. We find what potential
fans like to watch and put your music in those videos. Your exposure is all based on what you can afford
we got you covered from 1000 impressions to 1M+.</p>
<div className='join-us-button'>
<Modal trigger={<Button>Join us now!</Button>}>
<Modal.Content>
<Register/>
</Modal.Content>
</Modal>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default About
|
export { TimeSliderTitle } from "./TimeSliderTitle";
export { TimeSliderContainer } from "./TimeSliderContainer";
export { TimeSliderList } from "./TimeSliderList";
|
// import { createStore, combineReducers, applyMiddleware } from 'redux'
import { createStore, applyMiddleware, combineReducers } from "./tyRedux";
// import thunk from "redux-thunk";
// import logger from "redux-logger";
// 定义修改规则
function countReducer(state = 0, action) {
switch (action.type) {
case "ADD":
return state + 1;
case "MINUS":
return state - 1;
case "InputADD":
return state + action.payload;
case "InputMINUS":
return state - action.payload;
default:
return state;
}
}
// const store = createStore(combineReducers({ count: countReducer }), applyMiddleware(logger, thunk));
const store = createStore(countReducer, applyMiddleware(logger, thunk));
export default store;
function thunk({ dispatch, getState }) {
return next => action => {
if (typeof action === "function") {
return action(dispatch, getState);
}
return next(action);
};
}
function logger({ getState }) {
return next => action => {
console.log("====================================");
console.log(action.type + "执⾏了!");
const prevState = getState();
console.log("prev state", prevState);
const returnValue = next(action);
const nextState = getState();
console.log("next state", nextState);
console.log("====================================");
return returnValue;
};
}
|
import React, { Component } from 'react';
import TweenOne from 'rc-tween-one';
import ticker from 'rc-tween-one/lib/ticker';
import './index.css';
export default class Avatar extends Component {
constructor(props) {
super(props);
this.state = {
image: require('../../assets/avatar.png'),
w: 300,
h: 300,
pixSize: 20,
pointSizeMin: 6,
};
this.interval = null;
this.gather = true;
this.dom = React.createRef();
this.sideBoxComp = React.createRef()
}
componentDidMount() {
setTimeout(async () => {
await this.onResize();
await this.createPointData();
this.interval = ticker.timeout(this.updateTweenData, 1000);
// window.addEventListener('resize', this.onResize, false);
}, 0)
}
componentWillUnmount() {
ticker.clear(this.interval);
this.interval = null;
// window.removeEventListener('resize', this.onResize, false);
}
onResize = () => {
return new Promise((resolve, reject) => {
const $header = document.querySelector('header')
this.setState({
w: Math.floor($header.offsetWidth * 0.7),
h: Math.floor($header.offsetWidth * 0.7),
}, () => {
resolve();
});
});
}
onMouseEnter = () => {
// !this.gather && this.updateTweenData();
if (!this.gather) {
this.updateTweenData();
}
this.componentWillUnmount();
};
onMouseLeave = () => {
// this.gather && this.updateTweenData();
if (this.gather) {
this.updateTweenData();
}
};
setDataToDom(data, w, h) {
this.pointArray = [];
const number = this.state.pixSize;
for (let i = 0; i < w; i += number) {
for (let j = 0; j < h; j += number) {
if (data[((i + j * w) * 4) + 3] > 150) {
this.pointArray.push({ x: i, y: j });
}
}
}
const children = [];
this.pointArray.forEach((item, i) => {
const r = Math.random() * this.state.pointSizeMin + this.state.pointSizeMin;
const b = Math.random() * 0.4 + 0.1;
const rgbs = [
[229, 102, 95],
[243, 173, 192],
[201, 228, 172],
[254, 210, 111],
[197, 188, 242],
[147, 201, 218],
];
const col = rgbs[Math.round(Math.random() * 5)].join(',');
children.push((
<TweenOne className="point-wrapper" key={i} style={{ left: item.x, top: item.y }}>
<TweenOne
className="point"
style={{
width: r,
height: r,
opacity: b,
backgroundColor: `rgb(${col})`,
}}
animation={{
y: (Math.random() * 2 - 1) * 10 || 5,
x: (Math.random() * 2 - 1) * 5 || 2.5,
delay: Math.random() * 1000,
repeat: -1,
duration: 3000,
yoyo: true,
ease: 'easeInOutQuad',
}}
/>
</TweenOne>
));
});
this.setState({
children,
boxAnim: { opacity: 0, type: 'from', duration: 800 },
});
}
createPointData = () => {
return new Promise((resolve, reject) => {
const { w, h } = this.state;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, w, h);
canvas.width = this.state.w;
canvas.height = h;
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, w, h);
ctx.fillStyle = 'rgba(255, 255, 255, 0)';
const data = ctx.getImageData(0, 0, w, h).data;
this.setDataToDom(data, w, h);
// this.dom.current.removeChild(canvas);
resolve();
};
img.crossOrigin = 'anonymous';
img.src = this.state.image;
});
};
gatherData = () => {
const children = this.state.children.map(item =>
React.cloneElement(item, {
animation: {
x: 0,
y: 0,
opacity: 1,
scale: 1,
delay: Math.random() * 500,
duration: 800,
ease: 'easeInOutQuint',
},
}));
this.setState({ children });
};
disperseData = () => {
const rect = this.dom.current.getBoundingClientRect();
const sideRect = this.sideBoxComp.dom.getBoundingClientRect();
const sideTop = sideRect.top - rect.top;
const sideLeft = sideRect.left - rect.left;
const children = this.state.children.map(item =>
React.cloneElement(item, {
animation: {
x: Math.random() * rect.width - sideLeft - item.props.style.left,
y: Math.random() * rect.height - sideTop - item.props.style.top,
opacity: Math.random() * 0.4 + 0.1,
scale: Math.random() * 2.4 + 0.1,
duration: Math.random() * 500 + 500,
ease: 'easeInOutQuint',
},
}));
this.setState({
children,
});
};
updateTweenData = () => {
((this.gather && this.disperseData) || this.gatherData)();
this.gather = !this.gather;
};
render() {
return (
<div ref={this.dom} className="avatar">
<TweenOne
animation={this.state.boxAnim}
className="right-side blur"
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
ref={(c) => {
this.sideBoxComp = c;
}}
>
{this.state.children}
</TweenOne>
<img alt="avatar" className="avatar-img" src={this.state.image} />
</div>
);
}
}
|
import React, {Component} from 'react';
import {NavLink} from 'react-router-dom';
class FilterLinkComponent extends Component {
render() {
return (
<NavLink
exact
to={this.props.filter === 'all' ? '/' : `/${this.props.filter}`}
activeStyle={{
textDecoration: 'none',
color: 'black'
}}
>
{this.props.children}
</NavLink>
);
}
}
export default FilterLinkComponent;
|
import { StyleSheet } from 'react-native'
import { Colors,Fonts } from 'App/Theme'
export default StyleSheet.create({
button: {
width: '100%',
height: 40,
backgroundColor: Colors.white,
borderWidth: 0.5,
borderRadius: 5,
borderColor: Colors.borderBtn,
},
text: {
color: Colors.bottonTxt,
fontSize: Fonts.fs12,
textAlign: 'center',
fontWeight: 'bold',
//textTransform: 'capitalize'
},
})
|
import { createBrowserHistory, createMemoryHistory } from "history";
import { connectRouter, routerMiddleware } from "connected-react-router";
import {createStore,compose,applyMiddleware} from 'redux'
import RootReducer from './reducer/index'
import createSagaMiddleware, { END } from "redux-saga";
const windowDefined = typeof window !== "undefined";
const sagaMiddleware = createSagaMiddleware();
export const configureStore = (url = '/') => {
const history = windowDefined ? createBrowserHistory() : createMemoryHistory( { initialEntries: [ url ] } )
const initialState = windowDefined ? ( window.REDUX_DATA || {} ) : {};
const store = createStore(
RootReducer(history),
initialState,
compose(
applyMiddleware(
routerMiddleware(history),sagaMiddleware
)
)
)
store.runSaga = sagaMiddleware.run;
store.close = () => store.dispatch( END );
return {
store,
history
}
}
|
'use strict';
const zlib = require('zlib');
const _ = require('./util');
const DEFAULT = {
header: [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
end: [0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82]
};
class Png {
constructor(options) {
this.index = 0; // 解码游标
this.dataChunks = []; // 图像数据chunk数组
this.length = 0; // 数据总长度
if (_.getType(options) === 'uint8array') {
// 传入buffer数组,做解码用
this.buffer = new Uint8Array(options);
}
if (this.buffer) this.decode(true); // 预解码
}
/**
* 读取buffer数组的指定字节数
* @param {Number} length 读取长度
* @return {Array} 读取到的数据
*/
readBytes(length) {
let buffer = _.readBytes(this.buffer, this.index, length);
this.index += length;
return buffer;
}
/**
* 解码
* @param {Boolean} onlyDecodePngInfo 是否只解析png的基本信息
* @return {Array} 像素数组
*/
decode(onlyDecodePngInfo) {
if (!this.buffer) {
throw new Error('不存在待解码数据!');
}
this.decodeHeader(); // 解析头部信息
this.decodeChunk(); // 解析IHDR数据块
if (!onlyDecodePngInfo) {
if (this.pixels) return this.getPixels();
while (this.index < this.buffer.length) {
// 继续解析其他数据块
let type = this.decodeChunk();
if (type === 'IEND') break;
}
this.decodeIDATChunks();
return this.getPixels();
}
}
/**
* 解码头部信息
* https://www.w3.org/TR/PNG/#5PNG-file-signature
* @return {Void}
*/
decodeHeader() {
if (this.header) return;
if (this.index !== 0) {
throw new Error('png的index属性指向非0!');
}
let header = this.readBytes(8);
if (!_.equal(header, DEFAULT.header)) {
throw new Error('png的签名信息不合法!')
}
this.header = header;
}
/**
* 解码关键数据块:IHDR、PLTE、IDAT、IEND
* https://www.w3.org/TR/PNG/#5Chunk-layout
* @return {String} 数据块类型
*/
decodeChunk() {
let length = _.readInt32(this.readBytes(4)); // 数据块长度
if (length < 0) {
throw new Error('不合法的数据块长度信息');
}
let type = _.bufferToString(this.readBytes(4)); // 数据块类型
let chunkData = this.readBytes(length);
let crc = this.readBytes(4); // crc冗余校验码
switch (type) {
case 'IHDR':
this.decodeIHDR(chunkData);
break;
case 'PLTE':
this.decodePLTE(chunkData);
break;
case 'IDAT':
this.decodeIDAT(chunkData);
break;
case 'IEND':
this.decodeIEND(chunkData);
break;
// 针对索引颜色,需要解析透明数据块
case 'tRNS':
this.decodetRNS(chunkData);
break;
}
return type;
}
/**
* 解码IHDR数据块
* https://www.w3.org/TR/PNG/#11IHDR
* @param {Array} chunk 数据块信息
* @return {Void}
*/
decodeIHDR(chunk) {
this.width = _.readInt32(chunk); // 宽
this.height = _.readInt32(chunk, 4); // 高
// 图像深度,即每个通道包含的位数
this.bitDepth = _.readInt8(chunk, 8);
if ([1, 2, 4, 8, 16].indexOf(this.bitDepth) === -1) {
throw new Error('不合法的图像深度!');
}
// 颜色类型
// 其中 this.colors 代表每个像素数据包含的颜色数量信息
this.colorType = _.readInt8(chunk, 9);
switch (this.colorType) {
case 0:
// 灰度图像
this.colors = 1;
break;
case 2:
// rgb真彩色图像
this.colors = 3;
break;
case 3:
// 索引颜色图像
this.colors = 1;
break;
case 4:
// 灰度图像 + alpha通道
this.colors = 2;
this.alpha = true;
break;
case 6:
// rgb真彩色图像 + alpha通道
this.colors = 4;
this.alpha = true;
break;
default:
throw new Error('不合法的颜色类型!');
}
// 压缩方法
this.compressionMethod = _.readInt8(chunk, 10);
if (this.compressionMethod !== 0) {
throw new Error('不合法的压缩方法!');
}
// 过滤器方法
this.filterMethod = _.readInt8(chunk, 11);
if (this.filterMethod !== 0) {
throw new Error('不合法的过滤器方法!');
}
// 行扫描方法
this.interlaceMethod = _.readInt8(chunk, 12);
if (this.interlaceMethod !== 0 && this.interlaceMethod !== 1) {
throw new Error('不合法的行扫描方法!');
}
}
/**
* 解码tRNS数据块
* https://www.w3.org/TR/PNG/#11tRNS
* @param {Array} chunk 数据块信息
* @return {Void}
*/
decodetRNS(chunk) {
if (this.colorType === 3) {
// 目前只处理索引色透明的情况
this.transparentPanel = chunk;
}
}
/**
* 解码PLTE数据块
* https://www.w3.org/TR/PNG/#11PLTE
* @param {Array} chunk 数据块信息
* @return {Void}
*/
decodePLTE(chunk) {
if (chunk.length % 3 !== 0) {
throw new Error('不合法的PLTE数据块长度!');
}
if (chunk.length > (Math.pow(2, this.bitDepth) * 3)) {
throw new Error('调色板颜色数量不能超过图像深度规定的颜色数');
}
this.palette = chunk;
}
/**
* 解码IDAT数据块
* https://www.w3.org/TR/PNG/#11IDAT
* @param {Array} chunk 数据块信息
* @return {Void}
*/
decodeIDAT(chunk) {
this.dataChunks.push(chunk);
this.length += chunk.length;
}
/**
* 解码IEND数据块
* https://www.w3.org/TR/PNG/#11IEND
* @param {Array} chunk 数据块信息
* @return {Void}
*/
decodeIEND(chunk) {
// ignore
}
/**
* 解码完整连续的IDAT数据块
* @return {Void}
*/
decodeIDATChunks() {
let data = Buffer.alloc(this.length, 0xFF);
let index = 0;
this.dataChunks.forEach((chunk) => {
chunk.forEach((item) => {data[index++] = item});
});
let bytesPerPixel = Math.max(1, this.colors * this.bitDepth / 8); // 每像素字节数
let bytesPerRow = bytesPerPixel * this.width; // 每行字节数
// inflate解压缩
data = this.inflateSync(data);
if (this.interlaceMethod === 0) {
this.pixelsBuffer = this.interlaceNone(data, this.width, this.height, bytesPerPixel, bytesPerRow);
} else {
this.pixelsBuffer = this.interlaceAdam7(data, this.width, this.height, bytesPerPixel, bytesPerRow);
}
}
/**
* 逐行扫描
* @param {Array} data 待扫描数据
* @param {Number} width 图像宽度
* @param {Number} height 图像高度
* @param {Number} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @return {Array} 已解析图像数据
*/
interlaceNone(data, width, height, bytesPerPixel, bytesPerRow) {
let pixelsBuffer = Buffer.alloc(bytesPerPixel * width * height, 0xFF);
let offset = 0; // 当前行的偏移位置
// 逐行扫描解析
// https://www.w3.org/TR/PNG/#4Concepts.EncodingScanlineAbs
for (let i = 0, len = data.length; i < len; i += bytesPerRow + 1) {
let scanline = data.slice(i+1, i+1+bytesPerRow); // 当前行
let args = [pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, true];
// 第一个字节代表过滤类型
let filterType = _.readInt8(data, i);
switch (filterType) {
case 0:
this.filterNone.apply(this, args);
break;
case 1:
this.filterSub.apply(this, args);
break;
case 2:
this.filterUp.apply(this, args);
break;
case 3:
this.filterAverage.apply(this, args);
break;
case 4:
this.filterPaeth.apply(this, args);
break;
default:
throw new Error('未知过滤类型!');
}
offset += bytesPerRow;
}
return pixelsBuffer;
}
/**
* Adam7扫描
* @param {Array} data 待扫描数据
* @param {Number} width 图像宽度
* @param {Number} height 图像高度
* @param {Number} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @return {Array} 已解析图像数据
*/
interlaceAdam7(data, width, height, bytesPerPixel, bytesPerRow) {
let pixelsBuffer = Buffer.alloc(bytesPerPixel * width * height, 0xFF);
let startX = [0, 0, 4, 0, 2, 0, 1];
let incX = [8, 8, 8, 4, 4, 2, 2];
let startY = [0, 4, 0, 2, 0, 1, 0];
let incY = [8, 8, 4, 4, 2, 2, 1];
let offset = 0;
// 7次扫描
for (let i = 0; i < 7; i++) {
// 子图像信息
let subWidth = Math.ceil((width - startY[i]) / incY[i], 10);
let subHeight = Math.ceil((height - startX[i]) / incX[i], 10);
let subBytesPerRow = bytesPerPixel * subWidth;
let offsetEnd = offset + (subBytesPerRow + 1) * subHeight;
let subData = data.slice(offset, offsetEnd);
let subPixelsBuffer = this.interlaceNone(subData, subWidth, subHeight, bytesPerPixel, subBytesPerRow);
let subOffset = 0;
// 拷贝到正式图像数据位置
// https://www.w3.org/TR/PNG/#figure48
for (let x = startX[i]; x < height; x += incX[i]) {
for (let y = startY[i]; y < width; y += incY[i]) {
for (let z = 0; z < bytesPerPixel; z++) {
pixelsBuffer[(x * width + y) * bytesPerPixel + z] = subPixelsBuffer[subOffset++] & 0xFF;
}
}
}
offset = offsetEnd;
}
return pixelsBuffer;
}
/**
* 无过滤器
*
* @param {Array} pixelsBuffer 已经解析的图片数据
* @param {Array} scanline 当前行带解析数据
* @param {Numver} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @param {Number} offset 偏移位置
* @param {Boolean} isReverse 是否反向解析
* @return {Void}
*/
filterNone(pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, isReverse) {
for (let i = 0; i < bytesPerRow; i++) {
pixelsBuffer[offset + i] = scanline[i] & 0xFF;
}
}
/**
* Sub过滤器
* 增量 --> Row(x - bytesPerPixel)
*
* @param {Array} pixelsBuffer 已经解析的图片数据
* @param {Array} scanline 当前行带解析数据
* @param {Numver} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @param {Number} offset 偏移位置
* @param {Boolean} isReverse 是否反向解析
* @return {Void}
*/
filterSub(pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, isReverse) {
for (let i = 0; i < bytesPerRow; i++) {
if (i < bytesPerPixel) {
// 第一个像素,不作解析
pixelsBuffer[offset + i] = scanline[i] & 0xFF;
} else {
// 其他像素
let a = pixelsBuffer[offset + i - bytesPerPixel];
let value = isReverse ? scanline[i] + a : scanline[i] - a;
pixelsBuffer[offset + i] = value & 0xFF;
}
}
}
/**
* Up过滤器
* 增量 --> Row(x - bytesPerRow)
*
* @param {Array} pixelsBuffer 已经解析的图片数据
* @param {Array} scanline 当前行带解析数据
* @param {Numver} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @param {Number} offset 偏移位置
* @param {Boolean} isReverse 是否反向解析
* @return {Void}
*/
filterUp(pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, isReverse) {
if (offset < bytesPerRow) {
// 第一行,不作解析
for (let i = 0; i < bytesPerRow; i++) {
pixelsBuffer[offset + i] = scanline[i] & 0xFF;
}
} else {
for (let i = 0; i < bytesPerRow; i++) {
let b = pixelsBuffer[offset + i - bytesPerRow];
let value = isReverse ? scanline[i] + b : scanline[i] - b;
pixelsBuffer[offset + i] = value & 0xFF;
}
}
}
/**
* Average过滤器
* 增量 --> floor((Row(x - bytesPerPixel) + Row(x - bytesPerRow)) / 2)
*
* @param {Array} pixelsBuffer 已经解析的图片数据
* @param {Array} scanline 当前行带解析数据
* @param {Numver} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @param {Number} offset 偏移位置
* @param {Boolean} isReverse 是否反向解析
* @return {Void}
*/
filterAverage(pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, isReverse) {
if (offset < bytesPerRow) {
// 第一行,只做Sub
for (let i = 0; i < bytesPerRow; i++) {
if (i < bytesPerPixel) {
// 第一个像素,不作解析
pixelsBuffer[offset + i] = scanline[i] & 0xFF;
} else {
// 其他像素
let a = pixelsBuffer[offset + i - bytesPerPixel];
let value = isReverse ? scanline[i] + (a >> 1) : scanline[i] - (a >> 1); // 需要除以2
pixelsBuffer[offset + i] = value & 0xFF;
}
}
} else {
for (let i = 0; i < bytesPerRow; i++) {
if (i < bytesPerPixel) {
// 第一个像素,只做Up
let b = pixelsBuffer[offset + i - bytesPerRow];
let value = isReverse ? scanline[i] + (b >> 1) : scanline[i] - (b >> 1); // 需要除以2
pixelsBuffer[offset + i] = value & 0xFF;
} else {
// 其他像素
let a = pixelsBuffer[offset + i - bytesPerPixel];
let b = pixelsBuffer[offset + i - bytesPerRow];
let value = isReverse ? scanline[i] + ((a + b) >> 1) : scanline[i] - ((a + b) >> 1);
pixelsBuffer[offset + i] = value & 0xFF;
}
}
}
}
/**
* Paeth过滤器
* 增量 --> Pr
*
* pr的求导方法
* p = a + b - c
* pa = abs(p - a)
* pb = abs(p - b)
* pc = abs(p - c)
* if pa <= pb and pa <= pc then Pr = a
* else if pb <= pc then Pr = b
* else Pr = c
* return Pr
*
* @param {Array} pixelsBuffer 已经解析的图片数据
* @param {Array} scanline 当前行带解析数据
* @param {Numver} bytesPerPixel 每像素字节数
* @param {Number} bytesPerRow 每行字节数
* @param {Number} offset 偏移位置
* @param {Boolean} isReverse 是否反向解析
* @return {Void}
*/
filterPaeth(pixelsBuffer, scanline, bytesPerPixel, bytesPerRow, offset, isReverse) {
if (offset < bytesPerRow) {
// 第一行,只做Sub
for (let i = 0; i < bytesPerRow; i++) {
if (i < bytesPerPixel) {
// 第一个像素,不作解析
pixelsBuffer[offset + i] = scanline[i] & 0xFF;
} else {
// 其他像素
let a = pixelsBuffer[offset + i - bytesPerPixel];
let value = isReverse ? scanline[i] + a : scanline[i] - a;
pixelsBuffer[offset + i] = value & 0xFF;
}
}
} else {
for (let i = 0; i < bytesPerRow; i++) {
if (i < bytesPerPixel) {
// 第一个像素,只做Up
let b = pixelsBuffer[offset + i - bytesPerRow];
let value = isReverse ? scanline[i] + b : scanline[i] - b;
pixelsBuffer[offset + i] = value & 0xFF;
} else {
// 其他像素
let a = pixelsBuffer[offset + i - bytesPerPixel];
let b = pixelsBuffer[offset + i - bytesPerRow];
let c = pixelsBuffer[offset + i - bytesPerRow - bytesPerPixel];
let p = a + b - c;
let pa = Math.abs(p - a);
let pb = Math.abs(p - b);
let pc = Math.abs(p - c);
let pr;
if (pa <= pb && pa <= pc) pr = a;
else if (pb <= pc) pr = b;
else pr = c;
let value = isReverse ? scanline[i] + pr : scanline[i] - pr;
pixelsBuffer[offset + i] = value & 0xFF;
}
}
}
}
/**
* inflate解压缩算法封装
* @param {Array} data 待解压数据
* @return {Array} 已解压数据
*/
inflateSync(data) {
return zlib.inflateSync(new Buffer(data));
}
/**
* deflate压缩算法封装
* @param {Array} data 待压缩数据
* @return {Array} 已压缩数据
*/
deflateSync(data) {
return zlib.deflateSync(new Buffer(data));
}
/**
* 获取像素数组
* @return {Array} 像素数组
*/
getPixels() {
if (this.pixels) return pixels;
if (!this.pixelsBuffer) {
throw new Error('像素数据还没有解析!');
}
let pixels = this.pixels = new Array(this.width);
for (let i = 0; i < this.width; i++) {
pixels[i] = new Array(this.height);
for(let j = 0; j < this.height; j++) {
pixels[i][j] = this.getPixel(i, j);
}
}
return pixels;
}
/**
* 获取像素
* @param {Number} x x坐标
* @param {Number} y y坐标
* @return {Array} rgba色值
*/
getPixel(x, y) {
if (x < 0 || x >= this.width || y < 0 || y >= this.height) {
throw new Error('x或y的值超出了图像边界!');
}
if (this.pixels && this.pixels[x][y]) return this.pixels[x][y];
let bytesPerPixel = Math.max(1, this.colors * this.bitDepth / 8); // 每像素字节数
let index = bytesPerPixel * (y * this.width + x);
let pixelsBuffer = this.pixelsBuffer;
switch (this.colorType) {
case 0:
// 灰度图像
return [pixelsBuffer[index], pixelsBuffer[index], pixelsBuffer[index], 255];
case 2:
// rgb真彩色图像
return [pixelsBuffer[index], pixelsBuffer[index + 1], pixelsBuffer[index + 2], 255];
case 3:
// 索引颜色图像
let paletteIndex = pixelsBuffer[index];
let transparent = this.transparentPanel[paletteIndex]
if (transparent === undefined) transparent = 255;
return [this.palette[paletteIndex * 3 + 0], this.palette[paletteIndex * 3 + 1], this.palette[paletteIndex * 3 + 2], transparent];
case 4:
// 灰度图像 + alpha通道
return [pixelsBuffer[index], pixelsBuffer[index], pixelsBuffer[index], pixelsBuffer[index + 1]];
case 6:
// rgb真彩色图像 + alpha通道
return [pixelsBuffer[index], pixelsBuffer[index + 1], pixelsBuffer[index + 2], pixelsBuffer[index + 3]];
}
}
}
module.exports = Png;
|
import { SAVE_ME, SIGN_OUT } from "../constants/actionType";
// import axios from "axios";
// import API from "../components/global/axios";
//example init state
const initState = {
me: {},
};
//actions
export const saveMe = (me) => (dispatch) =>
dispatch({
type: SAVE_ME,
me,
});
export const actions = {
saveMe,
// authenticate,
// unauthenticate,
};
const ACTION_HANDLERS = {
// [AUTH_CHANGE]: (state, { isLoggedIn, checked }) => ({
// ...state,
// isLoggedIn,
// checked,
// }),
[SAVE_ME]: (state, { me }) => ({
...state,
me,
}),
};
export default function reducer(state = initState, action) {
const handler = ACTION_HANDLERS[action.type];
return handler ? handler(state, action) : state;
}
|
const express = require('express');
const { login, signup, resetPass, tokenRefresh } = require('../controllers/auth.controller');
const { authenticatedOnly } = require('../middlewares/auth.middleware');
const router = express.Router();
router.post('/login', login);
router.post('/signup', signup);
router.post('/refresh', tokenRefresh)
router.post('/resetPass', authenticatedOnly, resetPass);
module.exports = router;
|
//import fetch from "node-fetch";
const hello = async () => {
alert("hi");
const x = await fetch("");
};
hello();
|
const express = require("express")
const bodyParser = require("body-parser")
const cors = require("cors")
const path = require("path")
const http = require("http")
const enforce = require("express-sslify")
const helmet = require("helmet")
const morgan = require("morgan")
const uuid = require("uuid/v4")
const crypto = require("crypto")
const db = require("./src/db.js")
const app = express()
const expiresIn = 7 * 24 * 60 * 60 * 1000 // 7 days
// Enforce traffic on ssl
// heroku reverse proxies set the x-forwarded-proto header flag
if (process.env.NODE_ENV === "production") {
app.use(enforce.HTTPS({ trustProtoHeader: true }));
} else {
// app.use(morgan('combined'));
}
app.use(helmet())
// app.use(bodyParser.json())
app.use(express.static(__dirname + '/ui/public'))
app.set('port', (process.env.PORT || 3001))
const jsonParser = bodyParser.json()
const urlencodedParser = bodyParser.urlencoded({ extended: false })
// bcrypt.hash(pw, 10, (err, hash) => {})
// APIs
var hash = ""
var token = ""
app.post('/v1/token', jsonParser, (req, res) => {
// todo: use bcrypt to generate hash
hash = crypto.createHash("md5").update(req.body.password).digest("hex")
db.any("SELECT * FROM users WHERE id=$1 and hash=$2", [req.body.username, hash])
.then(d => {
if (d.length === 0) {
res.status(401)
res.json({error: "Invalid Credentials"})
} else {
if (d.token_created && new Date(d.token_created).getTime() + expiresIn > new Date().getTime()) {
console.log(d.token_created)
res.json({token: d.token, expiry: new Date(d.token_created).getTime() + expiresIn})
}
else {
// token expired or token not present
token = uuid()
// update _modified, token_created and token for username
var q = db.one(`UPDATE users SET _modified=NOW(), token_created=NOW(), token=$1 WHERE id=$2 RETURNING *`, [token, req.body.username])
return q.then(d2 => {
console.log(d2)
res.json({token: d2.token, expiry: new Date(d2.token_created).getTime() + expiresIn})
})
}
}
})
.catch(err => {
res.status(500)
res.json({error: "Something went wrong"})
console.log("Error", err)
})
})
// token validation middleware
var checkToken = (req, res, next) => {
var token = req.headers['authorization']
if (!token) {
res.status(403)
res.json({error: "Token missing"})
} else {
db.one("SELECT * FROM users WHERE token=$1", [token.slice(7)])
.then(d => {
if (d.length === 0) {
res.status(403)
res.json({error: 'Invalid token'})
} else next()
}).catch(err => {
res.status(403)
res.json({error: 'Invalid token'})
console.log("Error",err)
})
}
}
// Loading checkToken after the registering the /token endpoint
// https://expressjs.com/en/guide/writing-middleware.html
app.use(checkToken)
app.get('/v1/leads', cors(), (req, res) => {
db.any("SELECT * FROM leads where visible=true")
.then(d => res.json(d))
.catch(err => console.log('ERROR:', err))
})
app.get('/v1/leads/:id', cors(), (req, res) => {
db.one("SELECT * FROM leads WHERE id = $1", [req.params.id])
.then(d => res.json(d))
.catch(err => console.log('ERROR:', err))
})
app.post('/v1/leads', jsonParser, cors(), (req, res) => {
db.one('INSERT INTO leads(data) VALUES($1) RETURNING *', [req.body])
.then(d => res.json(d))
.catch(err => console.log('ERROR:', err))
})
app.put('/v1/leads/:id', urlencodedParser, cors(), (req, res) => {
var updatedData = {}
updatedData[req.body.name] = req.body.value
db.tx(t => {
var q1 = t.none(`UPDATE leads SET _modified=NOW() WHERE id=$1`, [req.params.id])
var q2 = t.one(`UPDATE leads SET data = data::jsonb || '${JSON.stringify(updatedData)}' WHERE id=${req.params.id} RETURNING *`)
return t.batch([q1, q2])
}).then(d => {
res.json(d[1])
})
.catch(err => {
res.status(500)
res.json({error: "Something went wrong"})
console.log("Error", err)
})
})
app.delete('/v1/leads/:id', cors(), (req, res) => {
db.one(`UPDATE leads SET visible=false WHERE id=${req.params.id} RETURNING visible`)
.then(d => res.json(d))
.catch(err => console.log('ERROR: ', err))
})
http.createServer(app).listen(app.get('port'), function() {
console.log(`Server up: http(s)://localhost:${app.get('port')}`)
});
|
var webpack = require('webpack');
module.exports = {
entry: "./js/index.js",
output: {
path: __dirname,
filename: "./public/js/bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" },
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" },
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
mangle: false
})
]
};
|
function CScenario() {
var m, c, e, g, a, d, b, l, k, h, f, q, n, p, u, r
if (SHOW_3D_RENDER) var w = new CANNON.Demo()
this.getDemo = function() {
return w
}
this._init = function() {
m = SHOW_3D_RENDER ? w.getWorld() : new CANNON.World()
m.gravity.set(0, 0, -9.81)
m.broadphase = new CANNON.NaiveBroadphase()
m.solver.iterations = 50
m.solver.tolerance = 1e-5
c = new CANNON.Material()
e = new CANNON.Material()
g = new CANNON.Material()
var a = new CANNON.ContactMaterial(e, g, {
friction: 0.1,
restitution: 0.01,
}),
b = new CANNON.ContactMaterial(e, c, { friction: 0.2, restitution: 0.3 })
m.addContactMaterial(a)
m.addContactMaterial(b)
s_oScenario._createBallBody()
s_oScenario._createFieldBody()
s_oScenario._createGoal()
s_oScenario.createBackGoalWall()
SHOW_AREAS_GOAL
? s_oScenario.createAreasGoal()
: s_oScenario.createAreaGoal(GOAL_LINE_POS, BACK_WALL_GOAL_SIZE, COLOR_AREA_GOAL[0], null)
}
this.createAreasGoal = function() {
for (
var a = 0, b = FIRST_AREA_GOAL_POS.x, c = FIRST_AREA_GOAL_POS.z, d = 0;
d < NUM_AREA_GOAL.h;
d++
) {
for (var e = 0; e < NUM_AREA_GOAL.w; e++)
s_oScenario.createAreaGoal(
{
x: b,
y: FIRST_AREA_GOAL_POS.y,
z: c,
},
AREA_GOAL_PROPERTIES,
COLOR_AREA_GOAL[a],
AREAS_INFO[a],
),
(b += 2 * AREA_GOAL_PROPERTIES.width),
a++
b = FIRST_AREA_GOAL_POS.x
c -= 2 * AREA_GOAL_PROPERTIES.height
}
}
this._createFieldBody = function() {
l = new CANNON.Plane()
k = new CANNON.Body({ mass: 0, material: c })
k.addShape(l)
k.position.z = -9
k.addEventListener('collide', function(a) {
s_oScenario.fieldCollision()
})
m.addBody(k)
if (SHOW_3D_RENDER) {
var a = new THREE.MeshPhongMaterial({
color: 5803568,
specular: 1118481,
shininess: 10,
})
w.addVisual(k, a)
}
}
this._createGoal = function() {
h = new CANNON.Cylinder(
POLE_RIGHT_LEFT_SIZE.radius_top,
POLE_RIGHT_LEFT_SIZE.radius_bottom,
POLE_RIGHT_LEFT_SIZE.height,
POLE_RIGHT_LEFT_SIZE.segments,
)
q = new CANNON.Body({ mass: 0 })
f = new CANNON.Cylinder(
POLE_UP_SIZE.radius_top,
POLE_UP_SIZE.radius_bottom,
POLE_UP_SIZE.height,
POLE_UP_SIZE.segments,
)
var a = new CANNON.Quaternion()
a.setFromAxisAngle(new CANNON.Vec3(0, 1, 0), Math.PI / 2)
f.transformAllPoints(new CANNON.Vec3(), a)
q.addShape(h, new CANNON.Vec3(0.5 * POLE_UP_SIZE.height, 0, 0))
q.addShape(h, new CANNON.Vec3(0.5 * -POLE_UP_SIZE.height, 0, 0))
q.addShape(f, new CANNON.Vec3(0, 0, 0.5 * POLE_RIGHT_LEFT_SIZE.height))
q.position.set(
BACK_WALL_GOAL_POSITION.x,
BACK_WALL_GOAL_POSITION.y - UP_WALL_GOAL_SIZE.depth,
BACK_WALL_GOAL_POSITION.z,
)
q.addEventListener('collide', function(a) {
s_oScenario.poleCollision()
})
m.addBody(q)
SHOW_3D_RENDER &&
((a = new THREE.MeshPhongMaterial({
color: 16777215,
specular: 1118481,
shininess: 50,
})),
w.addVisual(q, a))
}
this.createBackGoalWall = function() {
n = new CANNON.Box(
new CANNON.Vec3(
BACK_WALL_GOAL_SIZE.width,
BACK_WALL_GOAL_SIZE.depth,
BACK_WALL_GOAL_SIZE.height,
),
)
p = new CANNON.Box(
new CANNON.Vec3(
LEFT_RIGHT_WALL_GOAL_SIZE.width,
LEFT_RIGHT_WALL_GOAL_SIZE.depth,
LEFT_RIGHT_WALL_GOAL_SIZE.height,
),
)
u = new CANNON.Box(
new CANNON.Vec3(UP_WALL_GOAL_SIZE.width, UP_WALL_GOAL_SIZE.depth, UP_WALL_GOAL_SIZE.height),
)
r = new CANNON.Body({ mass: 0, material: g })
r.addShape(n)
r.addShape(p, new CANNON.Vec3(BACK_WALL_GOAL_SIZE.width, 0, 0))
r.addShape(p, new CANNON.Vec3(-BACK_WALL_GOAL_SIZE.width, 0, 0))
r.addShape(u, new CANNON.Vec3(0, 0, BACK_WALL_GOAL_SIZE.height))
r.position.set(BACK_WALL_GOAL_POSITION.x, BACK_WALL_GOAL_POSITION.y, BACK_WALL_GOAL_POSITION.z)
m.addBody(r)
SHOW_3D_RENDER && w.addVisual(r)
}
this.createAreaGoal = function(a, b, c, d) {
b = new CANNON.Box(new CANNON.Vec3(b.width, b.depth, b.height))
d = new CANNON.Body({ mass: 0, userData: d })
d.addShape(b)
d.position.set(a.x, a.y, a.z)
d.collisionResponse = 0
d.addEventListener('collide', function(a) {
s_oScenario.lineGoalCollision(a)
})
m.addBody(d)
SHOW_3D_RENDER &&
((a = new THREE.MeshPhongMaterial({
color: c,
specular: 1118481,
shininess: 70,
})),
w.addVisual(d, a))
return d
}
this._createBallBody = function() {
a = new CANNON.Sphere(BALL_RADIUS)
d = new CANNON.Body({
mass: BALL_MASS,
material: e,
linearDamping: BALL_LINEAR_DAMPING,
angularDamping: 2 * BALL_LINEAR_DAMPING,
})
var c = new CANNON.Vec3(POSITION_BALL.x, POSITION_BALL.y, POSITION_BALL.z)
d.position.copy(c)
d.addShape(a)
m.add(d)
SHOW_3D_RENDER &&
((c = new THREE.MeshPhongMaterial({
color: 16777215,
specular: 1118481,
shininess: 70,
})),
(b = w.addVisual(d, c)))
}
this.addImpulse = function(a, b) {
var c = new CANNON.Vec3(0, 0, BALL_RADIUS),
d = new CANNON.Vec3(b.x, b.y, b.z)
a.applyImpulse(d, c)
}
this.addForce = function(a, b) {
var c = new CANNON.Vec3(0, 0, 0),
d = new CANNON.Vec3(b.x, b.y, b.z)
a.applyForce(d, c)
}
this.getBodyVelocity = function(a) {
return a.velocity
}
this.ballBody = function() {
return d
}
this.ballMesh = function() {
return b
}
this.getCamera = function() {
return w.camera()
}
this.fieldCollision = function() {
s_oGame.fieldCollision()
s_oGame.ballFadeForReset()
}
this.setElementAngularVelocity = function(a, b) {
a.angularVelocity.set(b.x, b.y, b.z)
}
this.setElementVelocity = function(a, b) {
var c = new CANNON.Vec3(b.x, b.y, b.z)
a.velocity = c
}
this.setElementLinearDamping = function(a, b) {
a.linearDamping = b
}
this.getFieldBody = function() {
return k
}
this.lineGoalCollision = function(a) {
s_oGame.areaGoal(a.contact.bj.userData)
}
this.update = function() {
m.step(PHYSICS_STEP)
}
this.getGoalBody = function() {
return q
}
this.poleCollision = function() {
s_oGame.poleCollide()
}
this.destroyWorld = function() {
for (var a = m.bodies, b = 0; b < a.length; b++) m.remove(a[b])
m = null
}
s_oScenario = this
SHOW_3D_RENDER ? (w.addScene('Test', this._init), w.start()) : this._init()
}
|
function RestaMayor(num1,num2)
{
let resta=0;
if (num1>num2) {
resta=num1-num2;
} else {
resta=num2-num1;
}
return resta;
}
console.log(`La diferencia de los dos numeros es ${RestaMayor(7,20)}`);
|
import React from "react";
import { Redirect } from "react-router";
import { useSelector } from "react-redux";
import Header from "./Header/Header";
import Sidebar from "./Sidebar/Sidebar";
import Profile from "./Profile/Profile";
import "./Main.scss";
const Main = props => {
const user = useSelector(state => state.auth.user);
if(!user) return <Redirect to="/login" />
return(
<section className="mainWrap">
<Header />
<Sidebar />
<Profile />
</section>
)
}
export default Main;
|
function toMeters(pixels) { // перевод из пикселей в метры
return pixels / SCALE;
}
function addBox_expanded(x, y, width, height, density, restitution, is_static) { // больше параметров
var fixDef = new b2FixtureDef;
if (is_static === undefined) { // параметр по умолчанию
is_static = false; // тела считаем динамическими
}
fixDef.density = density; // плотность
fixDef.friction = 0.5; // коэфициент трения
fixDef.restitution = restitution; // коэффицент упругости
var bodyDef = new b2BodyDef; // определение тела
bodyDef.type = b2Body.b2_staticBody; // статический тип тела - не двигается
bodyDef.position.x = toMeters(x); // координаты позиции тела
bodyDef.position.y = toMeters(y);
bodyDef.type = is_static ? b2Body.b2_staticBody : b2Body.b2_dynamicBody; // уст. тип тела
fixDef.shape = new b2PolygonShape; // фигура - многоугольник
fixDef.shape.SetAsBox(toMeters(width / 2), toMeters(height / 2)); // прямоугольник
//bodyDef.linearVelocity=new b2Vec2(-15,-10); // скорость
var body = world.CreateBody(bodyDef); // создаем тело
body.CreateFixture(fixDef); // прикрепляем к телу фигуру
//body.SetAngle(0.1);
return body;
}
function addBox(x, y, width, height, is_static) { // добавить тело - прямоугольник (параметры в пикселях)
return addBox_expanded(x, y, width, height, 0.5, 0.3, is_static);
}
function addPoly(x, y, v, angle, is_static) { // многоугольник v - массив вершин
var fixDef = new b2FixtureDef;
if (is_static === undefined) { // параметр по умолчанию
is_static = false; // тела считаем динамическими
}
fixDef.density = 0.5; // плотность
fixDef.friction = 0.5; // коэфициент трения
fixDef.restitution = 0.3; // коэффицент упругости
var bodyDef = new b2BodyDef; // определение тела
bodyDef.type = b2Body.b2_staticBody; // статический тип тела - не двигается
bodyDef.position.x = toMeters(x); // координаты позиции тела
bodyDef.position.y = toMeters(y);
bodyDef.type = is_static ? b2Body.b2_staticBody : b2Body.b2_dynamicBody; // уст. тип тела
fixDef.shape = new b2PolygonShape; // фигура - многоугольник
vecs = [];
for (i = 0; i < v.length; i++) {
cc = new b2Vec2(v[i][0], v[i][1]);
vecs[i] = cc;
}
fixDef.shape.SetAsArray(vecs, vecs.length); // устанавливаем форму многоугольника (массив вершин)
var body = world.CreateBody(bodyDef); // создаем тело
body.CreateFixture(fixDef); // прикрепляем к телу фигуру
body.SetAngle(angle); // угол фигуры
return body;
}
function addBall_expanded(x, y, radius, density, restitution, is_static) { // круг больше параметров
var fixDef = new b2FixtureDef;
if (is_static === undefined) { // параметр по умолчанию
is_static = false; // тела считаем динамическими
}
fixDef.density = density; // плотность
fixDef.friction = 0.5; // коэфициент трения
fixDef.restitution = restitution; // коэффицент упругости
var bodyDef = new b2BodyDef; // определение тела
bodyDef.type = b2Body.b2_staticBody; // статический тип тела - не двигается
bodyDef.position.x = toMeters(x); // координаты позиции тела
bodyDef.position.y = toMeters(y);
bodyDef.type = is_static ? b2Body.b2_staticBody : b2Body.b2_dynamicBody; // уст. тип тела
fixDef.shape = new b2CircleShape(toMeters(radius));
var body = world.CreateBody(bodyDef); // создаем тело
body.CreateFixture(fixDef); // прикрепляем к телу фигуру
return body;
}
function addBall(x, y, radius, is_static) { // добавить тело - круг (параметры в пикселях)
return addBall_expanded(x, y, radius, 0.5, 0.3, is_static);
}
function addHuman_expanded(x, y, k, density, restitution) { // фигура человека k - коэф. размера (1-норм)
var body1;
var body2;
var jointDef;
body1 = addBall_expanded(x, y - k * 61, k * 20, density, restitution); // голова
body2 = addBox_expanded(x, y, k * 30, k * 80, density, restitution); // тело
jointDef = new Box2D.Dynamics.Joints.b2DistanceJointDef();
jointDef.Initialize(body1,
body2,
body1.GetWorldCenter(),
new b2Vec2(body2.GetWorldCenter().x, body2.GetWorldCenter().y - k * toMeters(40)));
jointDef.collideConnected = true;
world.CreateJoint(jointDef);
body1 = addBox_expanded(x - k * 30, y, k * 14, k * 60, density, restitution); // левая рука
jointDef = new Box2D.Dynamics.Joints.b2DistanceJointDef();
jointDef.Initialize(body1,
body2,
new b2Vec2(body1.GetWorldCenter().x, body1.GetWorldCenter().y - k * toMeters(25)),
new b2Vec2(body2.GetWorldCenter().x - k * toMeters(15), body2.GetWorldCenter().y - k * toMeters(30)));
jointDef.collideConnected = true;
world.CreateJoint(jointDef);
body1 = addBox_expanded(x + k * 30, y, k * 14, k * 60, density, restitution); // правая рука
jointDef = new Box2D.Dynamics.Joints.b2DistanceJointDef();
jointDef.Initialize(body1,
body2,
new b2Vec2(body1.GetWorldCenter().x, body1.GetWorldCenter().y - k * toMeters(25)),
new b2Vec2(body2.GetWorldCenter().x + k * toMeters(15), body2.GetWorldCenter().y - k * toMeters(30)));
jointDef.collideConnected = true;
world.CreateJoint(jointDef);
body1 = addBox_expanded(x - k * 10, y + k * 71, k * 14, k * 60, density, restitution); // левая нога
jointDef.Initialize(body1,
body2,
new b2Vec2(body1.GetWorldCenter().x, body1.GetWorldCenter().y - k * toMeters(25)),
new b2Vec2(body2.GetWorldCenter().x - k * toMeters(5), body2.GetWorldCenter().y + k * toMeters(30)));
jointDef.collideConnected = true;
world.CreateJoint(jointDef);
body1 = addBox_expanded(x + k * 10, y + k * 71, k * 14, k * 60, density, restitution); // правая нога
jointDef.Initialize(body1,
body2,
new b2Vec2(body1.GetWorldCenter().x, body1.GetWorldCenter().y - k * toMeters(25)),
new b2Vec2(body2.GetWorldCenter().x + k * toMeters(5), body2.GetWorldCenter().y + k * toMeters(30)));
jointDef.collideConnected = true;
world.CreateJoint(jointDef);
}
function addHuman(x, y, k) { // фигура человека k - коэф. размера (1-норм)
addHuman_expanded(x, y, k, 0.5, 0.3);
}
function addWater(x, y, width, height) {
var fixDef = new b2FixtureDef;
//fixDef.density = 1.0; // плотность устанавливается в setupBuoyancyController()
fixDef.friction = 0.5; // коэфициент трения
fixDef.restitution = 0.3; // коэффицент упругости
fixDef.isSensor = true; // сенсор
var bodyDef = new b2BodyDef; // определение тела
bodyDef.type = b2Body.b2_staticBody; // статический тип тела - не двигается
bodyDef.position.x = toMeters(x); // координаты позиции тела
bodyDef.position.y = toMeters(y);
fixDef.shape = new b2PolygonShape; // фигура - многоугольник
fixDef.shape.SetAsBox(toMeters(width / 2), toMeters(height / 2)); // прямоугольник
var body = world.CreateBody(bodyDef); // создаем тело
body.CreateFixture(fixDef); // прикрепляем к телу фигуру
return body;
}
function createPool(x, y, width, height) { // создаем бассейн
addWater(x, y, width, height); // создаем воду
addBox(x, y + height / 2 + 5, width, 10, true); // дно
addBox(x, y + height / 2 + 5, width, 10, true);
addBox(x - width / 2 - 5, y - 5, 10, height + 30, true); // бортик
addBox(x - width / 2 - 5, y - 5, 10, height + 30, true);
addBox(x + width / 2 + 5, y - 5, 10, height + 30, true); // бортик
addBox(x + width / 2 + 5, y - 5, 10, height + 30, true);
}
|
/**
* Created by heath on 12/03/16.
*/
function setDimensions(){
var windowsHeight = $(window).height();
$('.tronsSlider').css('height', windowsHeight -50);
$('.carousel-inner').css('height', windowsHeight -50);
$('.tron-item').css('height', windowsHeight - 50);
}
setDimensions();
//when resizing the site, we adjust the heights of the sections
$(window).resize(function() {
setDimensions();
});
// Function to pre load images after everything else has been done
$(window).load(function() {
// + any other carousel related stuff that has to wait for the images to complete loading
$('.carousel').carousel()
})
|
import React, {useState} from "react";
import './style.css';
const App=()=>{
let [score, setScore] = useState(0)
return(
<div>
<h1 className="title">Helo People ..</h1>
<h1 className="heading">Its my counter app !</h1>
<h3 className="value">The value of score is {score}</h3>
<button className="btn" onClick={()=>{(score<=24) ? setScore(score+1): setScore(score)}}>Increment</button>
<button className="btn" onClick={()=>{(score > 0) ? setScore(score-1): setScore(0)}}>Decrement</button>
<button className="btn" onClick={()=>{setScore(0)}}>Reset</button>
</div>
)
}
export default App
|
// import something here
import {
AddressbarColor
} from 'quasar'
import Vue from 'vue'
import VueParticles from 'vue-particles'
Vue.use(VueParticles)
// "async" is optional
export default async ({
Vue
}) => {
// something to do
AddressbarColor.set('#7861a9')
}
|
import Drawer from './Drawer'
import Overlay from './Overlay'
import Sidebar from './Sidebar'
import Chat from './Chat'
export default function init () {
Drawer.initDrawer({})
Overlay.initOverlay({})
Sidebar.initSidebar({})
Chat.initChat({})
}
|
const path = require(`path`);
const query = folder => `
{
allMarkdownRemark(filter: { fileAbsolutePath: {regex: "/(${folder})/.*/"}}) {
edges { node { frontmatter { slug } } }
}
}
`;
const WORKSHOPS = {
query: query('workshops'),
template: 'src/templates/workshop.js',
};
const render = createPage => templatePath => result => {
if (result.errors) {
Promise.reject(result.errors);
}
const component = path.resolve(templatePath);
const { edges } = result.data.allMarkdownRemark;
return edges.map(({ node: { frontmatter: { slug } } }) =>
createPage({
component,
path: slug,
context: { slug },
})
);
};
module.exports = ({ boundActionCreators: { createPage }, graphql }) => {
const renderFn = render(createPage);
return Promise.all([
graphql(WORKSHOPS.query).then(renderFn(WORKSHOPS.template)),
]);
};
|
// Copyright (c) 2015 N.T.WORKS All Rights Reserved.
// [ngeditor/version.js]
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
/** ngeditor/version.js
* @fileoverview NGEditor: version info
* @author nagisc007@yahoo.co.jp (N.T.WORKS)
* update (13/12/2015)
*/
goog.provide('ngeditor.version');
/**
* Descriptions:
*
*/
goog.scope(function() {
/** @const */
var g = ngeditor;
/** @const */
g.MAJOR_VERSION = 0;
/** @const */
g.MINOR_VERSION = 1;
/** @const */
g.MICRO_VERSION = 0;
}); // goog.scope
/** Note:
* ---
*/
|
var resu = new Array(12);
function vaciar(){
document.getElementById("n1").value= " ";
}
function desglose(){
mont=document.getElementById('n1').value;
var pri= mont*0.30;
pri=Math.floor(pri);
resu[0]= "Alimentos= "+pri+"<br>";
var seg= mont*0.15;
seg=Math.floor(seg);
resu[1]= "Gastos escolares= "+seg+"<br>";
var ter= mont*0.10;
ter=Math.floor(ter);
resu[2]= "Prendas de vestir= "+ter+"<br>";
var cua= mont*0.05;
cua=Math.floor(cua);
resu[3]= "Ahorro= "+cua+"<br>";
var quin= mont*0.03;
quin=Math.floor(quin);
resu[4]= "Entretenimiento= "+quin+"<br>";
var sext= mont*0.17;
sext=Math.floor(sext);
resu[5]= "Pago de recibos= "+sext+"<br>";
var sep= mont*0.10;
sep=Math.floor(sep);
resu[6]= "Meriendas= "+sep+"<br>";
var dec= mont*0.10;
dec=Math.floor(dec);
resu[7]= "Salud= "+dec+"<br>";
document.getElementById("res").innerHTML = resu;
}
|
document.writeln("<div class=\'ui-footer border-top-3 margin-top-30\'>");
document.writeln(" <div class=\'wrap\'>");
document.writeln(" <span>厦门市豪鑫行环保科技有限公司 All rights reserved. 闽ICP备17001482号</span>");
document.writeln(" <span class=\'right\'><em></em>0592-2960829</span>");
document.writeln(" <div class=\'clear\'></div>");
document.writeln(" </div>");
document.writeln(" </div>");
document.writeln(" ");
document.writeln(" <!--jquery-->");
document.writeln(" <script type=\'text/javascript\' src=\'../js/jquery-3.1.1.min.js\'></script>");
document.writeln(" <!-- jQuery (necessary for Bootstrap\'s JavaScript plugins) -->");
/*document.writeln(" <script src=\'http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js\'></script>");*/
document.writeln(" <!-- Include all compiled plugins (below), or include individual files as needed -->");
document.writeln(" <script src=\'../js/bootstrap.min.js\'></script>");
document.writeln(" <script src=\'../js/common.js\'></script>");
document.writeln(" <!--photoView 照片查看-->");
document.writeln(" <script type=\'text/javascript\' src=\'../plug-in/photoView/js/fresco/fresco.js\'></script>");
document.writeln(" <!--浮动层-->");
document.writeln(" <div class=\' float-box\'>");
document.writeln(" <ul>");
document.writeln(" <li class=\'weixin\'>");
document.writeln(" <div class=\'weixin-logo\'></div>");
document.writeln(" </li>");
document.writeln(" <a href=\'http://hxhtech.vicp.io/\' target=\'_blank\'><li class=\'app\'>");
document.writeln(" <div class=\'app-logo\'></div>");
document.writeln(" </li></a>");
document.writeln(" </ul>");
document.writeln(" </div>");
|
module.exports = {
isAuthenticated : (req,res,next) => {
if(req.isAuthenticated()){
next();
}else {
res.redirect('/login');
}
},
isAdmin : (req,res,next) => {
if(req.user.isAdmin === true){
next();
}else {
res.redirect("/admin");
}
},
isLoggedIn : (req,res,next) => {
if(req.user){
res.redirect("/");
}else {
next();
}
}
}
|
import * as _ from 'lodash';
import moment from 'moment-timezone';
import { AsyncStorage } from 'react-native';
import config from './config';
import AxiosRequest from './axiosRequest';
const API_ROOT = config.ROOT_URL;
const loadMessages = async function(params) {
try {
const apiUrlString = await AsyncStorage.getItem('apiUrl')
const apiUrl = JSON.parse(apiUrlString)
const beforeDate = moment(new Date()).utc(false)
.tz('Europe/Paris').format("YYYY-MM-DD hh:mm:ss a");
return AxiosRequest.getAPI(
`${apiUrl.url}/messages?order[date]=desc&date[before]=${beforeDate}&page=${params.page}&pageSize=20`,
null, null)
.then(response => {
const { data } = response;
let i = 0;
let messages = [];
while(i < data.length) {
let user = {
_id: data[i].author.id,
name: data[i].author.firstname + ' ' + data[i].author.lastname,
avatar: data[i].author.avatar && data[i].author.avatar.id ?
data[i].author.avatar.id : 1,
};
let message = {
_id: data[i].id,
text: data[i].content,
createdAt: new Date(data[i].date),
user: user,
patient: data[i].patient,
readBy: data[i].readBy,
readDate: new Date(data[i].readDate),
};
messages.push(message);
i = i + 1;
}
return messages;
});
} catch (error) {
throw error;
}
}
const getMessage = async function(params) {
const apiUrlString = await AsyncStorage.getItem('apiUrl')
const apiUrl = JSON.parse(apiUrlString)
const { id } = params;
return AxiosRequest.getAPI(`${apiUrl.url}/messages/${id}`, null, null)
.then(response => {
const message = response.data;
return Promise.all(message);
})
}
const createMessage = async (params) => {
try {
const apiUrlString = await AsyncStorage.getItem('apiUrl')
const apiUrl = JSON.parse(apiUrlString)
const { message } = params;
return AxiosRequest.postAPI(`${apiUrl.url}/messages`, null, JSON.stringify(message))
.then(response => {
const { data } = response;
let user = {
_id: data.author.id,
name: data.author.firstname + ' ' + data.author.lastname,
avatar: data.author.avatar && data.author.avatar.id ?
data.author.avatar.id : 1,
};
let newMessage = {
_id: data.id,
text: data.content,
createdAt: new Date(data.date),
user: user,
patient: data.patient,
readBy: data.readBy,
readDate: new Date(data.readDate),
};
return newMessage;
});
} catch (error) {
throw error;
}
}
export default {
loadMessages,
getMessage,
createMessage,
};
|
// library
import React, { Component } from 'react';
import { BrowserRouter, Route, history } from "react-router-dom";
import { connect } from "react-redux";
// components
import Header from "./Header";
// routes
import Dashboard from "./Dashboard";
import Landing from "./Landing";
import Signup from "./Signup";
import Login from "./Login";
// local
import '../sass/css-loader.scss';
import * as actions from "../actions/index";
class App extends Component {
// componentDidMount() {
// this.props.fetchUser();
// }
render() {
return (
<div>
<BrowserRouter >
<div>
<Header />
<Route path="/" component={ Landing } exact />
<Route path="/users" component={ Signup } exact />
<Route path="/users/login" component={ Login } exact />
<Route path="/dashboard" component={ Dashboard } exact />
</div>
</BrowserRouter>
</div>
);
}
};
// function mapStateToProps(state) {
// return { auth: state.auth.authenticated }
// }
export default connect(null, actions)(App);
|
module.exports = require('./kebiao');
|
'use strict';
var NodeCache = require("node-cache");
module.exports = function ldapContext(options) {
var context = {};
context.client = require('./client')(context);
context.options = require('./options')();
context.users = require('./repositories/users')(context);
context.units = require('./repositories/units')(context);
context.viewModelsMappers = require('./viewModels/mappers')();
if (options == undefined || options.memoryCache == undefined ) {
context.memoryCache = new NodeCache({ stdTTL: 14400 }); // 4 hour of cache
} else {
context.memoryCache = new NodeCache(options.memoryCache);
}
return context;
};
|
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import { configRouter } from './route-config.js'
import { directive } from './directive.js'
var VueValidator = require('vue-validator')
Vue.use(VueValidator)
Vue.use(VueRouter);//通过全局方法use使用vue-router插件
Vue.validator('url', function (val) {
return /^(http\:\/\/|https\:\/\/)(.{4,})$/.test(val)
})
Vue.filter('date', function (value,format) {
return moment(new Date(value)).format(format)
})
directive(Vue)
var router = new VueRouter()
configRouter(router)
router.start(App, '#app')
|
export { default } from '@smile-io/ember-smile-polaris/components/polaris-form-layout/item';
|
'use strict';
/*
* ADAPTER: Web
*/
const extender = require(`object-extender`);
const RequestNinja = require(`request-ninja`);
const AdapterBase = require(`./adapterBase`);
module.exports = class AdapterWeb extends AdapterBase {
/*
* Instantiates the handler.
*/
constructor (_options) {
// Configure the handler.
super(`adapter`, `web`);
// Default config for this handler.
this.options = extender.defaults({
accessToken: null,
endpoint: null,
paths: {
threadSettings: null,
typingStatus: null,
readReceipts: null,
sendMessage: null,
userProfile: null,
},
supports: {
whitelistedDomains: false,
getStartedButton: false,
greetingText: false,
menu: false,
typing: false,
readReceipts: false,
userProfiles: false,
},
}, _options);
// Ensure paths begin with "/".
Object.keys(this.options.paths).forEach(key => {
const path = this.options.paths[key];
return (!path || path[0] === `/` ? path : `/${path}`);
});
this.endpoint = this.options.endpoint;
}
/*
* Initialise this adapter.
*/
async init (hippocampOptions) {
this.sendMessageDelay = hippocampOptions.sendMessageDelay;
// Nothing to do if we don't have a thread settings path to POST to.
if (!this.options.paths.threadSettings) { return; }
const postData = {};
if (this.options.supports.whitelistedDomains) {
postData.whitelistedDomains = [ hippocampOptions.baseUrl ];
}
if (hippocampOptions.getStartedButton) {
postData.getStartedButton = hippocampOptions.getStartedButton;
}
if (hippocampOptions.greetingText && this.options.supports.greetingText) {
postData.greetingText = hippocampOptions.greetingText;
}
if (hippocampOptions.menu) {
postData.menu = hippocampOptions.menu;
}
// Nothing to do.
if (!Object.keys(postData).length) { return; }
// Update the thread settings.
await this.__makeRequest(this.options.paths.threadSettings, postData);
}
/*
* Handles an incoming request.
*/
async handleRequest (req, res) {
switch (req.method.toLowerCase()) {
case `post`: return await this.__receiveIncomingData(req, res);
default: throw new Error(`Method "${req.method}" not supported.`);
}
}
/*
* Collate and convert all incoming messages in the webhook into Hippocamp's internal message representation.
*/
async __processIncomingMessages (bodyData) {
const MessageObject = this.__dep(`MessageObject`);
const channelName = this.getHandlerId();
const userBotsToDisable = {};
const messagePromises = bodyData.messages.map(async _properties => {
const defaultProperties = { direction: `incoming` };
const readOnlyProperties = {};
// Only allow channelName to be overridden if the message is marked as from an admin.
if (bodyData.fromAdmin) {
defaultProperties.channelName = channelName;
readOnlyProperties.humanToHuman = true;
}
else {
readOnlyProperties.channelName = channelName;
readOnlyProperties.direction = `incoming`;
}
// Prepare message properties.
const properties = extender.merge(defaultProperties, _properties, readOnlyProperties);
const message = new MessageObject(properties);
// Ensure we have the both the Hippocamp user ID and the channel user ID on the message.
const messageUserRecord = await this.populateOppositeUserId(message);
// Store the user record on the message for later use.
if (bodyData.fromAdmin) { userBotsToDisable[message.userId] = messageUserRecord; }
message.recUser = messageUserRecord;
return message;
});
const messages = await Promise.all(messagePromises);
return {
messages,
userBotsToDisable,
};
}
/*
* Handles incoming data from a webhook.
*/
async __receiveIncomingData (req, res) {
const sharedLogger = this.__dep(`sharedLogger`);
let messages;
let userBotsToDisable;
// Ensure incoming messages are sane.
try {
const result = await this.__processIncomingMessages(req.body);
messages = result.messages;
userBotsToDisable = result.userBotsToDisable;
}
catch (err) {
res.status(500).respond({ success: false, error: `Incoming message in the Web API is not sane.` });
return;
}
// Tell the Web API we received the webhook successfully.
res.status(200).respond({ success: true });
// Mark the thread as read (but don't wait for it to succeed).
if (messages && messages.length) {
this.markAsRead(messages[0].channelUserId);
}
// Disable any users that were sent a message by an admin.
const userBotsToDisablePromises = Object.values(userBotsToDisable).map(recUser =>
this.setBotDisabledForUser(recUser, true)
);
await Promise.all(userBotsToDisablePromises);
// Process each message in turn.
const adapter = {
sendMessage: this.sendMessage.bind(this),
getUserProfile: this.getUserProfile.bind(this),
};
const chainStartsWith = Promise.resolve();
const promiseChain = messages.reduce(
(chain, message) => {
if (message.direction === `outgoing`) {
return chain.then(() => this.sendMessage(message.recUser, message)); // eslint-disable-line promise/prefer-await-to-then
}
else {
if (message.recUser) { delete message.recUser; }
return chain.then(() => this.__executeHandler(`incoming-message`, message, adapter)); // eslint-disable-line promise/prefer-await-to-then
}
},
chainStartsWith
);
// Wait for all the messages to be processed.
try {
await promiseChain;
}
catch (err) {
sharedLogger.error(err);
}
}
/*
* Mark the bot as typing for the given user.
*/
async markAsTypingOn (recUser) {
// Nothing to do if we don't have an endpoint for typing status.
if (!this.options.supports.typing || !this.options.paths.typingStatus) { return; }
await this.__makeRequest(this.options.paths.typingStatus, {
channelUserId: recUser.channel.userId,
typingStatus: true,
});
}
/*
* Mark the bot as not typing for the given user.
*/
async markAsTypingOff (recUser) {
// Nothing to do if we don't have an endpoint for typing status.
if (!this.options.supports.typing || !this.options.paths.typingStatus) { return; }
await this.__makeRequest(this.options.paths.typingStatus, {
channelUserId: recUser.channel.userId,
typingStatus: false,
});
}
/*
* Mark the bot as read the incoming messages for the given user.
*/
async markAsRead (channelUserId) {
// Nothing to do if we don't have an endpoint for typing status.
if (!this.options.supports.readReceipts || !this.options.paths.readReceipts) { return; }
await this.__makeRequest(this.options.paths.readReceipts, {
channelUserId: channelUserId,
});
}
/*
* Sends a single message to the given user ID.
*/
async sendMessage (recUser, message) {
const sharedLogger = this.__dep(`sharedLogger`);
// Do NOT include the user record on the message when we send it out!
if (message.recUser) { delete message.recUser; }
// Do we need to send the message via another adapter?
if (message.channelName !== this.getHandlerId()) {
return await this.sendMessageViaAnotherAdapter(recUser, message);
}
// Run outgoing middleware and start typing.
await this.__executeHandler(`outgoing-message`, message, null);
// Wait for the message to complete sending.
try {
await this.__makeRequest(this.options.paths.sendMessage, message);
}
catch (err) {
sharedLogger.error(`Failed to send messages via the Web API because of "${err}".`);
sharedLogger.error(err);
}
// Consistent return.
return null;
}
/*
* Makes a request to the Web API.
*/
async __makeRequest (path, postData) {
const sharedLogger = this.__dep(`sharedLogger`);
sharedLogger.silly({
text: `Making a request to the Web API.`,
postData,
});
const req = new RequestNinja(`${this.endpoint}${path}?accessToken=${this.options.accessToken}`, {
timeout: (1000 * 30),
returnResponseObject: true,
});
let res;
// We need to POST some data.
if (postData) {
res = await req.postJson(postData);
}
else {
res = await req.get();
}
const data = res.body;
if (data.error) {
throw new Error(`Message rejected by Web API with error: "${data.error.message}".`);
}
else if (res.statusCode !== 200) {
throw new Error(`Encountered a non-200 HTTP status code: "${res.statusCode}".`);
}
return data;
}
/*
* Returns the user's profile as a JSON object.
*/
async getUserProfile (channelUserId) {
if (this.options.paths.profileLoaded) {
await this.__makeRequest(this.options.paths.profileLoaded, {
profileLoaded: true,
channelUserId: channelUserId,
});
}
// The Web API does not support user profiles.
if (!this.options.supports.userProfiles) {
return null;
}
const webProfile = await this.__makeRequest(`${this.options.paths.userProfile}/${channelUserId}`);
// Don't return empty profile fields if there is no profile!
if (!webProfile) {
return null;
}
// Map the Web profile to the internal profile.
return {
firstName: webProfile.firstName || null,
lastName: webProfile.lastName || null,
gender: webProfile.gender || null,
email: webProfile.email || null,
tel: webProfile.tel || null,
profilePicUrl: webProfile.profilePicUrl || null,
timezoneUtcOffset: webProfile.timezoneUtcOffset || null,
age: null,
};
}
};
|
import { env } from '../helper';
const config = {
ethereal: {
host: 'smtp.ethereal.email',
port: 587,
auth: {
user: 'trevor96@ethereal.email',
pass: 'bYctqz65JRMe3cD22y',
},
tls: {
rejectUnauthorized: false,
},
},
gmail: {
service: 'gmail',
auth: {
user: 'peterrueca@gmail.com',
pass: 'googlekeyw0rd',
},
tls: {
rejectUnauthorized: false,
},
},
};
export default config[env('SMTP', 'ethereal')];
|
//DevelopmentReviewInProgress.js
export const PERFORMANCE = "PERFORMANCE";
export const STRENGTH = "STRENGTH";
export const DEVELOPMENT = "DEVELOPMENT";
const START = "KRO/REVIEWINPROGRESS/START";
const STOP = "KRO/REVIEWINPROGRESS/STOP";
const initialState = {
reviewInProgress: false,
reviewType: "",
reviewId: 0,
managerId: 0,
managerToken: "",
other: {}
};
export default (state = initialState, action) => {
switch (action.type) {
case START:
return Object.assign(
{},
state,
action.payload,
{ reviewInProgress: true }
);
case STOP:
return initialState;
default:
return state;
}
};
export const startReview = reviewInfo => ({
type: START,
payload: reviewInfo
});
export const stopReview = () => ({ type: STOP });
|
const handleKeywords = (keyword, cb) => {
const keywordArr = keyword?.split(",");
if (keywordArr && keywordArr.length) {
cb(keywordArr.map((s) => s.trim()));
}
};
module.exports = handleKeywords;
|
import { getOwner } from '@ember/application';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
export default class SmartLinkToComponent extends Component {
@service router;
@tracked tagName = '';
@tracked cssClass = null;
@tracked target = null;
get isRoute() {
return getOwner(this).hasRegistration(`route:${this.args.link}`);
}
constructor(owner, args) {
super(owner, args);
if (this.args.link === 'application') {
this.cssClass += ' active';
}
}
}
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import CardContent from "./components/Cards/CardContent"
function Data() {
// Pull in the date and then break it into parts to be passed into
// the card and then rendered into the App
const [data, setData] = useState([]);
useEffect(() => {
axios.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2019-07-15")
.then(e => {
setData(e.data);
})
.catch(err => { return 'nothing' })
}, []);
return (
<div>
{data ?
<CardContent
title={data.title}
url={data.url}
copyright={data.copyright}
explanation={data.explanation}
date={data.date} />
:
<div>Loading...</div>
}
</div>
)
}
export default Data;
|
const express = require('express');
const firebase = require('../db');
const firestore = firebase.firestore();
const lib = require("../globals/global.js");
const {
updateStudent,
deleteClassRoom,
addClassroom,
getAllUsers,
getAllClassRooms,
getAllClassRooms1,
getBookingHistory,
getClassRoom,
addSport,
getAllSports,
addLab,
getAllLabs,
deleteSports,
deleteLabs,
updateClassroom,
editThisClassroom,
updateLab,
editThisLab,
updateSport,
editThisSport,
deleteCollection,
addslot,
getAllDateBookings
} = require('../controllers/controller');
const router = express.Router();
router.get('/',(req,res) => {
if(lib.login=='true')
res.render("../views/home.ejs");
else
res.render("../views/login.ejs");
})
router.get('/login',(req,res) => {
if(lib.login=='true')
res.redirect('/');
else
res.render("../views/login.ejs")
})
router.post('/getlogin',function(req,res,next){
var username = req.body.exampleInputEmail1;
var password = req.body.exampleInputPassword1;
console.log('start');
console.log(username);
console.log(password);
if(username == "admin@gmail.com" && password == "Admin123")
{
lib.login = 'true';
console.log('worked');
}
else
{
console.log('not');
}
res.redirect('/');
})
router.get('/classrooms',(req,res) => {
if(lib.login=='false')
res.redirect('/login');
res.render("../views/classrooms.ejs")
})
router.get('/sports',(req,res) => {
if(lib.login=='false')
res.redirect('/login');
res.render("../views/sports.ejs")
})
router.get('/labs',(req,res) => {
if(lib.login=='false')
res.redirect('/login');
res.render("../views/labs.ejs")
})
router.get('/addslot',(req,res) => {
if(lib.login=='false')
res.redirect('/login');
res.render("../views/selectdate.ejs")
})
router.get('/logout',(req,res)=>{
lib.login = 'false';
res.redirect('/');
})
router.get('/delete',deleteCollection)
router.get('/addslotfor7',addslot)
//router.get('/deleteupcoming',deleteupcomingslots)
router.get('/users',getAllUsers)
router.post('/classrooms',addClassroom)
router.get('/classrooms/edit',getAllClassRooms)
router.post('/sports',addSport)
router.get('/sports/editsports',getAllSports)
router.post('/labs',addLab)
router.get('/labs/editlabs',getAllLabs)
router.post('/classrooms/edit/:id',deleteClassRoom)
router.post('/sports/editsports/:id',deleteSports)
router.post('/labs/editlabs/:id',deleteLabs)
router.post('/bookings',getAllDateBookings)
router.get('/users/:id',getBookingHistory)
router.get('/classrooms/edit/:id/editthis',updateClassroom)
router.post('/classrooms/edit/:id/editthis',editThisClassroom)
router.get('/sports/editsports/:id/editthis',updateSport)
router.post('/sports/editsports/:id/editthis',editThisSport)
router.get('/labs/editlabs/:id/editthis',updateLab)
router.post('/labs/editlabs/:id/editthis',editThisLab)
//ADD slot section------------
router.get('/addslot/:DATE',getAllClassRooms1);
router.post('/addslot/submit',function(req,res,next){
var DATE = req.body.date;
res.redirect('/addslot/'+DATE);
})
router.get('/addslot/:DATE/:CLASSNAME/:TYPE',function(req,res,next)
{
const DATE = req.params.DATE;
const CLASSNAME = req.params.CLASSNAME;
const TYPE = req.params.TYPE;
res.render("../views/additem.ejs",{DATE,CLASSNAME,TYPE});
})
router.post('/addslot/:DATE/:CLASSNAME/:TYPE',async function(req,res,next){
var date = req.params.DATE;
const docname = req.params.CLASSNAME;
const type = req.params.TYPE;
const data = {};
if(req.body.btncheck1)
data['09to10'] = 'acadSlots';
if(req.body.btncheck2)
data['13to14'] = 'acadSlots';
if(req.body.btncheck3)
data['16to17'] = 'acadSlots';
if(req.body.btncheck4)
data['09to10'] = 'available';
if(req.body.btncheck5)
data['13to14'] = 'available';
if(req.body.btncheck6)
data['16to17'] = 'available';
data['type'] = type;
date = date.toString();
var newdate = '';
newdate = date[8] + date[9] + date[5] + date[6] + date[0] + date[1] + date[2] + date[3];
await firestore.collection(newdate).doc(docname).set(data);
res.redirect('/addslot/'+date);
})
module.exports = {
routes: router
}
|
const socket = io('/');
socket.on('update-list', () => {
putLocal();
});
const submitName = (sub = 0) => {
const name = document.getElementById('name').value;
const alias = document.getElementById('alias').value;
const url = document.getElementById('url').value;
if (sub) {
if (!name || !alias) {
document.getElementById("error").innerHTML = "<span style='color: yellow;'>Please enter all required fields</span>";
return;
}
const hero = { "name": name, "alias": alias, "image": url };
}
const hero = { "name": name, "alias": alias, "image": url };
var existingEntries = new Array();
fetch('/prove/10/fetch')
.then(res => res.json())
.then(existingEntries => {
if (matchingName(existingEntries.avengers, name)) {
document.getElementById("error").innerHTML = "<span style='color: yellow;'>Name already exists in system</span>";
return;
}
if (sub == 1) {
var i = existingEntries.avengers.length;
if (name) {
existingEntries.avengers[i] = hero;
}
postData();
// Broadcast a change to the database
buildEntry(hero);
socket.emit('hero');
}
putLocal();
document.getElementById('name').value = '';
document.getElementById('alias').value = '';
document.getElementById('url').value = '';
})
.catch(err => {
console.error("error: ", err);
});
}
submitName();
const postData = () => {
const name = document.getElementById('name').value;
const alias = document.getElementById('alias').value;
const url = document.getElementById('url').value;
const hero = { "name": name, "alias": alias, "image": url };
fetch('/prove/10', {
method: 'POST', // Send a POST request
headers: {
// Set the Content-Type, since our server expects JSON
'Content-Type': 'application/json',
},
body: JSON.stringify(hero),
})
.then((res) => {
// Clear the input
document.getElementById('name').value = '';
document.getElementById('alias').value = '';
document.getElementById('url').value = '';
// Repopulate the list with our new name added
})
.catch((err) => {
// Clear the input
document.getElementById('name').value = '';
document.getElementById('alias').value = '';
document.getElementById('url').value = '';
console.error(err);
});
}
const putLocal = () => {
fetch('/prove/10/fetch')
.then(res => res.json())
.then(data => {
const nameList = document.getElementById('nameList')
var data = JSON.parse(data);
while (nameList.firstChild) nameList.firstChild.remove()
for (const avenger of data.avengers) {
if (avenger.name != NULL) {
buildEntry(avenger);
}
}
})
.catch(err => {
console.error("error: ", err);
});
}
const matchingName = (JSON, nameValue) => {
var hasMatch = false;
for (var index = 0; index < JSON.length; ++index) {
var hero = JSON[index];
if (hero.name == nameValue) {
hasMatch = true;
break;
}
}
return hasMatch;
}
const buildEntry = (avenger) => {
const nameList = document.getElementById('nameList')
const article = document.createElement('article');
article.setAttribute("class", "card");
const div_img = document.createElement('div');
div_img.setAttribute("class", "card__image_prev");
const img = document.createElement('img');
if (avenger.image) {
img.setAttribute("src", avenger.image);
} else {
img.setAttribute("src", "/images/heroes/none.jpg");
}
img.setAttribute("alt", avenger.name);
div_img.appendChild(img);
article.appendChild(div_img);
const div_card = document.createElement('div');
div_card.setAttribute("class", "card__header");
const h2 = document.createElement('h2');
h2.appendChild(document.createTextNode(avenger.name))
const h3 = document.createElement('h3');
if (avenger.alias) {
h3.appendChild(document.createTextNode("AKA " + avenger.alias))
}
div_card.appendChild(h2);
div_card.appendChild(h3);
article.appendChild(div_card);
nameList.appendChild(article)
}
/*
<article class="card">
<div class="card__image_prev">
<img src="<%= domain %><%= object.image %>" alt="<%= object.name %>">
</div>
<div class="card__header">
<h2>
<%= object.name %>
</h2>
<h3>
AKA <%= object.alias %>
</h3>
</div>
</article>
*/
|
module.exports = {
stripPrefix: 'build/',
staticFileGlobs: [
'build/*.html',
'build/manifest.json',
'build/sw-import.js',
'build/static/**/!(*map*)'
],
dontCacheBustUrlsMatching: /\.\w{8}\./,
swFilePath: 'build/service-worker.js',
importScripts: ['sw-import.js'],
runtimeCaching: [{
urlPattern: '/(.*)',
handler: 'networkFirst',
options: {
cache: {
name: 'amazonaws',
maxEntries: 10,
maxAgeSeconds: 86400
},
origin: /\.amazonaws\.com/
}
}, {
urlPattern: '/(.*)',
handler: 'cacheFirst',
options: {
cache: {
name: 'googleapis',
maxEntries: 10,
maxAgeSeconds: 86400
},
origin: /\.googleapis\.com/
}
}, {
urlPattern: '/(.*)',
handler: 'cacheFirst',
options: {
cache: {
name: 'gstatic',
maxEntries: 10,
maxAgeSeconds: 86400
},
origin: /\.gstatic\.com/
}
}]
};
|
import React from "react"
function Footer() {
return (
<section id="follow" class="section section-follow black darken-2 white-text scrollspy">
<footer class="black page-footer">
<div class="container">
<div class="row">
<div class="col s12 center">
<h4 class="white-text">FOLLOW</h4>
<a href="https://www.instagram.com/glzcoding/" class="white-text">
<i class="fab fa-instagram fa-4x"></i>
</a>
<a href="https://twitter.com/Guliz66443828" class="white-text">
<i class="fab fa-twitter fa-4x"></i>
</a>
</div>
</div>
</div>
</footer>
</section>
);
}
export default Footer
|
// move buttons
const menu_results_button = document.querySelector('.menu-button-results');
const results_menu_button = document.querySelector('.results-back-button');
const menu_play_button = document.querySelector('.menu-button-play');
const game_score_button = document.querySelector('.game-button-score');
const score_menu_button = document.querySelector('.score-back-button');
// areas
const menu_area = document.querySelector('.menu');
const game_area = document.querySelector('.game');
const results_area = document.querySelector('.results');
const match_score_area = document.querySelector('.match-score');
// move buttons (without "Dalej" button)
const results_and_menu_buttons = () => {
menu_area.classList.toggle('disabled');
results_area.classList.toggle('disabled');
}
const game_and_menu_button = () => {
menu_area.classList.toggle('disabled');
game_area.classList.toggle('disabled');
document.querySelector('#user-name').value = '';
}
const game_and_score_button = () => {
game_area.classList.toggle('disabled');
match_score_area.classList.toggle('disabled');
}
const score_and_menu_button = () => {
menu_area.classList.toggle('disabled');
match_score_area.classList.toggle('disabled');
}
menu_results_button.addEventListener('click', results_and_menu_buttons);
results_menu_button.addEventListener('click', results_and_menu_buttons);
menu_play_button.addEventListener('click', game_and_menu_button);
game_score_button.addEventListener('click', game_and_score_button);
score_menu_button.addEventListener('click', score_and_menu_button);
|
/*
CoolBot Discord bot created by [YT] iCodeZz#5784
This bot was entirely rewritten on Friday the 6th of April, 2018 (yeet)
You can skid off some commands, but you cant fork the project.
*/
const Discord = require("discord.js")
const prefix = "]"
const owner = "[YT] iCodeZz#5784"
const ytdl = require("ytdl-core")
const Fortnite = require("fortnite")
const stats = new Fortnite(process.env.TRN)
const encode = require("strict-uri-encode")
const superagent = require("superagent")
//const token = "token here" (if you wanna local host the bot)
var ball = [
"Yes.",
"No.",
"I don't know.",
"You're asking a bot this.",
"What?",
]
var sixsided = [
"1",
"2",
"3",
"4",
"5",
"6",
]
var eightsided = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
]
var tensided = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
]
var gayrate = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59",
"60",
"61",
"62",
"63",
"64",
"65",
"66",
"67",
"68",
"69",
"70",
"71",
"72",
"73",
"74",
"75",
"76",
"77",
"78",
"79",
"80",
"81",
"82",
"83",
"84",
"85",
"86",
"87",
"88",
"89",
"90",
"91",
"92",
"93",
"94",
"95",
"96",
"97",
"98",
"99",
"100",
]
var rps = [
"Rock",
"Paper",
"Scissors",
]
var rpswinlose = [
"You won!",
"I won!",
]
var bot = new Discord.Client;
bot.on('ready', () => {
console.log("CoolBot is up and running!")
bot.user.setActivity("online")
bot.user.setActivity('for ]help', { type: 'WATCHING' })
});
bot.on('message', async function(message) {
if (message.author.equals(bot.user)) return;
if (!message.content.startsWith(prefix)) return;
if (message.channel.type === "dm") return message.channel.send("Please execute this command in a server!")
var args = message.content.substring(prefix.length).split(" ")
switch (args[0].toLowerCase()) {
case "help":
message.channel.send(`Commands are in your DM's, ${message.author}!`)
var embed = new Discord.RichEmbed()
.setAuthor("Available Commands")
.addField("Normal Commands", "]help, ]ping, ]pong, ]cookie, ]say <whatever here>, ]noticeme")
.addField("Info Commands", "]userinfo <optional user>, ]serverinfo, ]getavatar <optional user>")
.addField("8ball Commands", "]8ball <question here>")
.addField("Rolling Dice", "]6sided, ]8sided, ]10sided")
.addField("Rating Commands", "]gayrate <optional user>, ]lesbianrate <optional user>, ]straightrate <optional user>, ]bisexualrate <optional user>, ]dankrate <optional user>, ]waifurate <optional user>")
.addField("Fun Commands", "]punch <user>, ]stab <user>, ]shoot <user>, ]roast <user>, ]bomb <user>, ]annihilate <user>, ]rps <whatever here>, ]dog")
.addField("Fun Music Commands", "]nootnoot, ]imgay")
.addField("Search Commands", "]search <search query here>, ]fortnite <pc/xb1/ps4> <player name>")
.addField("Moderation Commands", "]kick <user> <reason>, ]ban <user> <reason>, ]purge <number between 1 and 100>, ]mute <user>, ]unmute <user>")
.addField("Bot Commands", "]botinfo, ]invite, ]credits")
.addBlankField()
.addField("Please join our Discord server! It really helps us grow!", "https://discord.gg/9JTSAvH")
.addField("Please consider upvoting our bot at Discord Bots, it well and truly helps us grow!", "https://discordbots.org/bot/416496004699783190?")
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.author.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send messages/embeds to you! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "ping":
message.channel.send(`:ping_pong: Pong! It took ${bot.ping}ms to deliver this message!`)
break;
case "pong":
message.channel.send("Ping?")
break;
case "cookie":
message.channel.send(":cookie:")
break;
case "say":
if (!args[1]) return message.channel.send("You need to specify a string of words after the command that you want me to say!")
message.delete()
message.channel.send(args.join(" ").slice(3))
break;
case "noticeme":
message.channel.send(`${message.author} ${message.author} ${message.author} ${message.author} ${message.author} ${message.author} ${message.author} ${message.author} ${message.author} ${message.author}\nThere you just got noticed.`)
break;
case "userinfo":
var userCreated = message.author.createdAt.toString().split(" ");
var userinfotoget = message.mentions.users.first()
if (!userinfotoget) {
var embed = new Discord.RichEmbed()
.setAuthor(`User info for you`)
.addField("Discord name", `${message.author.username}`)
.addField("Discord ID", `${message.author.id}`)
.addField("Date of creation", "**" + userCreated[0] + '**, **' + userCreated[1] + ' ' + userCreated[2] + ' ' + userCreated[3] + '**, at **' + userCreated[4] + "**")
.addField("Highest role", message.member.highestRole.name)
.setThumbnail(message.author.avatarURL)
.setFooter(`Credits: made by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
nessage.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
});
return
}
var userinfoembed = new Discord.RichEmbed()
.setAuthor(`User info for ${userinfotoget.username}`)
.addField("Discord name", `${userinfotoget.username}`)
.addField("Discord ID", `${userinfotoget.id}`)
.setThumbnail(userinfotoget.avatarURL)
.setFooter(`Credits: made by ${owner}`)
.setColor("RANDOM")
message.channel.send(userinfoembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
});
break;
case "serverinfo":
var serverCreated = message.guild.createdAt.toString().split(" ");
var embed = new Discord.RichEmbed()
.setAuthor("Info about this Discord Server:")
.addField("Server name", `${message.guild}`)
.addField("Creation date", serverCreated[0] + ', ' + serverCreated[1] + ' ' + serverCreated[2] + ' ' + serverCreated[3] + ' at ' + serverCreated[4])
.addField("Server ID", `${message.guild.id}`)
.addField("Members", message.guild.memberCount)
.setColor("RANDOM")
.setFooter(`Credits: made by ${owner}`)
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
});
break;
case "getavatar":
var avatartoget = message.mentions.users.first()
if (!avatartoget) return message.channel.send(`${message.author}, your avatar is here: ${message.author.displayAvatarURL}`)
message.channel.send(`${message.author}, here is the avatar of ${avatartoget}: ${avatartoget.displayAvatarURL}`)
break;
case "8ball":
if (args[1]) {
message.channel.send(ball[Math.floor(Math.random() * ball.length)]);
return;
} else {
message.channel.send("There is no question for me to answer!");
return;
}
case "6sided":
message.channel.send("You rolled a **" + sixsided[Math.floor(Math.random() * sixsided.length)] + "**!");
break;
case "8sided":
message.channel.send("You rolled a **" + eightsided[Math.floor(Math.random() * eightsided.length)] + "**!");
break;
case "10sided":
message.channel.send("You rolled a **" + tensided[Math.floor(Math.random() * tensided.length)] + "**!");
break;
case "gayrate":
var gaymember = message.mentions.users.first()
if (!gaymember) {
var embed = new Discord.RichEmbed()
.setAuthor("Gay Rater")
.addField(`Gay rate below :gay_pride_flag:`, `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}% gay.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return
}
var gayembed = new Discord.RichEmbed()
.setAuthor("Gay Rater")
.addField(`Gay rate below :gay_pride_flag:`, `${gaymember.username} is ${gayrate[Math.floor(Math.random() * gayrate.length)]}% gay.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(gayembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "lesbianrate":
var lesbianmember = message.mentions.users.first()
if (!lesbianmember) {
var embed = new Discord.RichEmbed()
.setAuthor("Lesbian Rater")
.addField("Lesbian rate below :gay_pride_flag:", `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}% lesbian.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return
}
var lesbianembed = new Discord.RichEmbed()
.setAuthor("Lesbian Rater")
.addField("Lesbian rate below :gay_pride_flag:", `${lesbianmember.username} is ${gayrate[Math.floor(Math.random() * gayrate.length)]}% lesbian.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(lesbianembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "straightrate":
var straightmember = message.mentions.users.first()
if (!straightmember) {
var embed = new Discord.RichEmbed()
.setAuthor("Straight Rater")
.addField("Straight rate below :gay_pride_flag:", `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}% straight.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return
}
var straightembed = new Discord.RichEmbed()
.setAuthor("Straight Rate")
.addField("Straight rate below :gay_pride_flag:", `${straightmember.username} is ${gayrate[Math.floor(Math.random() * gayrate.length)]}% straight.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(straightembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "bisexualrate":
var bisexualmember = message.mentions.users.first()
if (!bisexualmember) {
var embed = new Discord.RichEmbed()
.setAuthor("Bisexual Rate")
.addField("Bixesual rate below :gay_pride_flag:", `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}% bisexual.`)
.setFooter("Created by srsklrboii#5784")
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return;
}
var bisexualembed = new Discord.RichEmbed()
.setAuthor("Bisexual Rate")
.addField("Bisexual rate below :gay_pride_flag:", `${bisexualmember.username} is ${gayrate[Math.floor(Math.random() * gayrate.length)]}% bisexual.`)
.setFooter("Created by srsklrboii#5784")
.setColor("RANDOM")
message.channel.send(bisexualembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "dankrate":
var dankmember = message.mentions.users.first()
if (!dankmember) {
var embed = new Discord.RichEmbed()
.setAuthor("Dank Rate")
.addField("Dank rate below", `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}% dank.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return
}
var dankembed = new Discord.RichEmbed()
.setAuthor("Dank Rate")
.addField("Dank rate below", `${dankmember.username} is ${gayrate[Math.floor(Math.random() * gayrate.length)]}% dank.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(dankembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "waifurate":
var waifumember = message.mentions.users.first()
if (!waifumember) {
var embed = new Discord.RichEmbed()
.setAuthor("Waifu Rate")
.addField("Waifu rate below :shrug:", `You are ${gayrate[Math.floor(Math.random() * gayrate.length)]}/100 waifu.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
return
}
var waifuembed = new Discord.RichEmbed()
.setAuthor("Waifu Rate")
.addField("Waifu rate below :shrug:", `${gayrate[Math.floor(Math.random() * gayrate.length)]}/100 waifu.`)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(waifuembed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "punch":
var punchmember = message.mentions.users.first()
if (!punchmember) return message.channel.send("You need to mention a person you want to punch!")
message.channel.send(`${message.author}, you just punched **${punchmember.username}**! :punch: :scream:`)
break;
case "stab":
var stabmember = message.mentions.users.first()
if (!stabmember) return message.channel.send("You need to mention a person you want to stab!")
message.channel.send(`${message.author}, you just stabbed **${stabmember.username}**! :knife: :dagger: :scream:`)
break;
case "shoot":
var shootmember = message.mentions.users.first()
if (!shootmember) return message.channel.send("You need to mention a person you want to shoot!")
message.channel.send(`${message.author}, you just shot **${shootmember.username}**! :gun: :scream:`)
break;
case "bomb":
var bombmember = message.mentions.users.first()
if (!bombmember) return message.channel.send("You need to mention a person you want to bomb!")
message.channel.send(`${message.author}, you just bombed **${bombmember.username}**! :bomb: :scream:`)
break;
case "annihilate":
var annihilatemember = message.mentions.users.first()
if (!annihilatemember) return message.channel.send("You need to mention someone you want to annihilate!")
message.channel.send(`${message.author}, you just annihilated **${annihilatemember.username}**! :gun: :knife: :dagger: :punch: :bomb: :scream:`)
break;
case "rps":
if (!args[1]) return message.channel.send("You need to specify something to battle me with!")
message.channel.send(`You chose **${args[1]}** while I chose **${rps[Math.floor(Math.random() * rps.length)]}**!`)
message.channel.send(rpswinlose[Math.floor(Math.random() * rpswinlose.length)])
break;
case "nootnoot":
var voiceChannel = message.member.voiceChannel
if (!voiceChannel) return message.channel.send("You are not in a voice channel!")
if (!voiceChannel.joinable) return message.channel.send("I cannot join that voice channel!")
try {
var connection = await voiceChannel.join()
} catch (error) {
message.channel.send("I could not play in the voice channel for an undefined reason!")
}
var dispatcher = connection.playStream(ytdl("https://www.youtube.com/watch?v=Fs3BHRIyF2E"))
.on('end', () => {
voiceChannel.leave()
})
dispatcher.setVolumeLogarithmic(5 / 5)
break;
case "imgay":
var voiceChannel = message.member.voiceChannel
if (!voiceChannel) return message.channel.send("You are not in a voice channel!")
if (!voiceChannel.joinable) return message.channel.send("I cannot join that voice channel!")
try {
var connection = await voiceChannel.join()
} catch (error) {
message.channel.send("I could not play in the voice channel for an undefined reason!")
}
var dispatcher = connection.playStream(ytdl("https://www.youtube.com/watch?v=_AZDaW3GLQw"))
.on('end', () => {
voiceChannel.leave()
})
dispatcher.setVolumeLogarithmic(5 / 5)
break;
case "search":
let question = encode(args.join(" ").slice(7))
let link = `https://www.lmgtfy.com/&q=${question}`
message.channel.send(link).catch(e => {
message.channel.send("Woops! Looks like I can't send links in here!")
})
break;
case "fortnite":
let platform
let username
if (!['pc','xb1','ps4'].includes(args[1])) return message.channel.send("You need to specify a platform for Fortnite.")
if (!args[2]) return message.channel.send("You have to specify a valid username of a Fortnite player.")
platform = args[1]
username = args[2]
stats.getInfo(username, platform).then(data => {
var embed = new Discord.RichEmbed()
.setAuthor(`Stats for ${data.username}`)
.addField("Top Placement", `Top 3's: ${data.lifetimeStats[0].value}\nTop 5's: ${data.lifetimeStats[1].value}\nTop 6's: ${data.lifetimeStats[3].value}\nTop 12's: ${data.lifetimeStats[4].value}\nTop 25's: ${data.lifetimeStats[5].value}`, true)
.addField("Total Score", data.lifetimeStats[6].value, true)
.addField("Matches Played", data.lifetimeStats[7].value, true)
.addField("Wins", data.lifetimeStats[8].value, true)
.addField("Win Percentage", data.lifetimeStats[9].value, true)
.addField("Kills", data.lifetimeStats[10].value, true)
.addField("K/D Ratio", data.lifetimeStats[11].value, true)
.addField("Kills Per Minute", data.lifetimeStats[12].value, true)
.addField("Time Played", data.lifetimeStats[13].value, true)
.addField("Average Survival Time", data.lifetimeStats[14].value, true)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
}).catch(e => {
message.channel.send("The player wasn't found!")
})
break;
case "dog":
let {body} = await superagent
.get(`http://random.dog/woof.json`);
var embed = new Discord.RichEmbed()
.setAuthor("Here's a dog for you!")
.setImage(body.url)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "kick":
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You do not have the permission to do this!");
var kickedmember = message.mentions.members.first()
if (!kickedmember) return message.reply("Please mention a valid member of this server!")
if (kickedmember.hasPermission("KICK_MEMBERS")) return message.reply("I cannot kick this member because he/she is a mod/admin!")
var kickreasondelete = 10 + kickedmember.user.id.length
var kickreason = message.content.substring(kickreasondelete).split(" ");
var kickreason = kickreason.join(" ");
if (!kickreason) return message.reply("Please indicate a reason for the kick!")
kickedmember.send(`You have been kicked from ${message.guild} for the following reason: ${kickreason}.`)
kickedmember.kick(kickreason)
.catch(error => message.reply(`Sorry @${message.author} I couldn't kick because of : ${error}`));
message.reply(`${kickedmember.user.username} has been kicked by ${message.author.username} because: ${kickreason}`);
break;
case "ban":
if (!message.member.hasPermission("BAN_MEMBERS")) return message.reply("You do not have the permission to do this!");
var banmember = message.mentions.members.first()
if (!banmember) return message.reply("Please mention a valid member of this server!")
if (banmember.hasPermission("BAN_MEMBERS")) return message.reply("I cannot ban this member because he/she is a mod/admin!")
var banreasondelete = 10 + banmember.user.id.length
var banreason = message.content.substring(banreasondelete).split(" ");
var banreason = banreason.join(" ");
if (!banreason) return message.reply("Please indicate a reason for the ban!")
banmember.send(`You have been banned from ${message.guild} for the following reason: ${kickreason}.`)
banmember.ban(banreason).catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
message.reply(`${kickedmember} has been kicked by ${message.author.username} because: ${kickreason}`);
break;
case "purge":
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You do not have the permission to do this!")
if (!args[1]) return message.channel.send("Please specify a number!")
if (args[1] >= 100) return message.channel.send("Please specify a number between 1 and 100!")
if (args[1] <= 1) return message.channel.send("Please specify a number between 1 and 100!")
if (isNaN(args[1])) return message.channel.send("Please specify a vaild number!")
message.delete();
message.channel.bulkDelete(args[1]).catch(e => {
console.error(e)
})
message.channel.send(`Purged **${args[1]}** messages!`)
break;
case "mute":
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have the permission to do this!")
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("Please specify a valid user!");
if(tomute.hasPermission("MUTE_MEMBERS")) return message.reply("I cannot mute this member since he/she is a mod/admin!");
let muterole = message.guild.roles.find(`name`, "Muted");
if(!muterole){
try{
muterole = await message.guild.createRole({
name: "Muted",
color: "#000000",
permissions:[]
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch(e){
console.log(e.stack);
}
}
await(tomute.addRole(muterole.id));
message.channel.send(`${tomute} has been successfully muted!`)
break;
case "unmute":
var unmuterole = message.guild.roles.find("name", "muted")
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have the permission to do this!")
var tounmute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]))
if (!tounmute) return message.channel.send("Please specify a valid user!")
await(tounmute.removeRole(unmuterole.id))
message.channel.send(`${tounmute} has been successfully unmuted!`)
break;
case "botinfo":
var embed = new Discord.RichEmbed()
.setAuthor("Info for me!")
.addField("Name", bot.user.username)
.addField("Discriminator", bot.user.discriminator)
.addField("ID", bot.user.id)
.setThumbnail(bot.user.avatarURL)
.setFooter(`Credits: created by ${owner}`)
.setColor("RANDOM")
message.channel.send(embed).catch(e => {
message.channel.send("Woops! Looks like I can't send embeds to the chat! Join our Discord if this issue is persisting: https://discord.gg/9JTSAvH")
})
break;
case "invite":
message.channel.send("Thank you for taking the time to invite me to your Discord server! The link is below:\nhttps://discordapp.com/api/oauth2/authorize?client_id=416496004699783190&permissions=8&scope=bot")
break;
case "credits":
message.channel.send(`I was created by ${owner}!`)
break;
}
})
bot.login(process.env.TOKEN)
//bot.login(token) (if u wanna local host the bot)
|
// First line after a line break
|
let loginBtn = document.getElementById('loginBtn');
let inputs = document.querySelectorAll('input');
loginBtn.addEventListener('click', (event) => {
inputs.forEach((input)=>{
if(input.value == ""){
input.className = 'invalid';
event.preventDefault();
}
});
});
|
export default class elementControler {
constructor(languageItems, createdItems, languageTypeItem, ) {
this.languageItems = languageItems
this.createdItems = createdItems
this.languageTypeItem = languageTypeItem
}
createElements() {
for (let index = 0; index < this.languageItems.length; index++) {
const createdDiv = document.createElement('div')
const createdParagraph = document.createElement('p')
createdDiv.className = "box " + this.languageTypeItem
createdParagraph.className = "boxText"
createdParagraph.innerHTML = this.languageItems[index]
createdDiv.appendChild(createdParagraph)
this.createdItems.push(createdDiv)
}
}
appendElements() {
this.createdItems.slice().forEach(element => {
wrapper.appendChild(element)
})
}
}
|
var calcDataTableHeight = function() {
return $(window).height() * 56/100;
};
var setTableHeight = function() {
var flag = document.getElementById('myForm:hidden1').value;
if (flag == 1) {
document.getElementById('myForm:hidden2').value = calcDataTableHeight();
document.getElementById('myForm:hidden1').value = '0';
document.getElementById('myForm:triggerresize').click();
}
};
$(window).load(function() {
setTableHeight();
});
window.onresize = function(event) {
document.getElementById('myForm:hidden1').value = '1';
document.getElementById('myForm:triggerresize').click();
setTableHeight();
}
function collapseAll() {
var i = $('.ui-row-toggler.ui-icon-circle-triangle-s').length;
if (i == 1) {
return;
}
$('.ui-row-toggler.ui-icon-circle-triangle-s').trigger('click');
}
var dirtyFlag = false;
var confirmLeaveMsg = "";
$(window).bind('beforeunload', function () {
if (dirtyFlag) {
if (confirm(confirmLeaveMsg)) {
history.go();
}
else {
window.setTimeout(function () {
window.stop();
},
1);
}
}
});
function setConfirmLeaveMsg(string) {
confirmLeaveMsg = string;
}
function setDirty() {
dirtyFlag = true;
}
function clearDirty() {
dirtyFlag = false;
}
|
import { renderString } from '../../src/index';
describe(`truncates a given string to a specified length`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{{ truncate("string to truncate at a certain length", 19, false, '...') }}`);
expect(html).toBe(`string to truncate...`);
});
});
|
var communityId=window.parent.document.getElementById("community_id_index").value;
$(document).ready(function() {
head_select();
});
/*
* function head_select(){ $(".operation-nav").find("ul li
* a").removeClass("select"); $(".operation-nav").find("ul li
* a[mark=statistics]").addClass("select"); $(".left-body").find("ul li
* a").removeClass("select"); $(".left-body").find("ul li
* a[mark=shop]").addClass("select"); }
*/
function head_select() {
$(".operation-nav").find("ul li a").removeClass("select");
$(".operation-nav").find("ul li a[mark=statistics]").addClass("select");
$(".left-body").find("ul li a").removeClass("select");
$(".left-body").find("ul li a[mark=lifecircle]").addClass("select");
}
function getClickAmountTop( startTime, endTime,type) {
timeQuantum(startTime, endTime);
timeDisplay(type);
}
function quickShopData() {
schedule();
var myDate = new Date();
var month = myDate.getMonth() + 1;
var da = myDate.getDate() ;
var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00";
var endTime = myDate.getFullYear() + "-" + month + "-" +(da+1)
+ " 00:00:00";
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime, '日');
onSchedule();
}
function maintainMonth() {
var myDate = new Date();
var month = myDate.getMonth();
var firstDate = new Date();
firstDate.setDate(1); // 第一天
var endDate = new Date(firstDate);
endDate.setMonth(firstDate.getMonth());
endDate.setDate(0);
var startTime = myDate.getFullYear() + "-" + month + "-" + 1 + " 00:00:00";
var endTime = myDate.getFullYear() + "-" + month + "-" + endDate.getDate()
+ " 00:00:00";
// getQuickShopList(1, startTime, endTime);
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime, '月');
}
function alterMonth(num) {
var startTime = document.getElementById("master_repir_startTime").value;
var type = document.getElementById("date_type_get").value;
var d = alterDate(num, type, startTime);
var startTime = d.start;
var endTime = d.end;
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime, type);
}
function weekMonth() {
var d = getPreviousWeekStartEnd();
var startTime = d.start;
var endTime = d.end;
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime, '周');
}
function turnover() {
document.getElementById("statistics_id").style.display = "none";
document.getElementById("turnover_id").style.display = "";
}
function statistics() {
document.getElementById("statistics_id").style.display = "";
document.getElementById("turnover_id").style.display = "none";
}
function selectStatistics() {
var startTime = document.getElementById("txtBeginDate").value + " 00:00:00";
var endTime = document.getElementById("txtEndDate").value + " 00:00:00";
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime);
}
function turnoverTurnover() {
var startTime = document.getElementById("turnoverBeginDate").value
+ " 00:00:00";
var endTime = document.getElementById("turnoverEndDate").value
+ " 00:00:00";
getClickAmountList("time", startTime, endTime);
getClickAmountTop(startTime, endTime);
}
function timeClick(clickId) {
if (clickId == "data_clik") {
document.getElementById("data_clik").className = "select";
quickShopData();
} else {
document.getElementById("data_clik").className = "";
}
if (clickId == "week_clik") {
document.getElementById("week_clik").className = "select";
weekMonth();
} else {
document.getElementById("week_clik").className = "";
}
if (clickId == "month_clik") {
document.getElementById("month_clik").className = "select";
maintainMonth();
} else {
document.getElementById("month_clik").className = "";
}
}
function getClickAmountList( type, startTime, endTime) {
getUseAmountList( type, startTime, endTime);
}
function getUseAmountList(type, startTime, endTime) {
// document.getElementById("shop_sort_id").value;
var path = "/api/v1/communities/"+communityId+"/lifeCircle/selectLifeCircleList?startTime=" + startTime + "&endTime=" + endTime+"&type="+type;
$.ajax({
url : path,
type : "GET",
dataType : 'json',
success : function(data) {
data = data.info;
var repair_overman = $("#statistics_list_id");
repair_overman.empty();
repair_overman
.append("<tr class=\"odd\"><td>话题</td><td>用户地址</td><td>图片</td><td>点赞量</td><td>评论量</td></tr>");
for ( var i = 0; i < data.length; i++) {
var liList="" ;
liList+="<tr class=\"odd\"><td><div title=\""+data[i].lifeContent+"\">"+data[i].lifeContent+"</div></td>";
liList+="<td>"+data[i].nickname+data[i].userUnit+data[i].userFloor+"</td>";
liList+="<td>";
var listPono=data[i].list;
for ( var j = 0; j < listPono.length; j++) {
var array_element = listPono[j];
//alert(array_element.photoUrl);
liList+= "<span class=\"images\"><a href=\"javascript:void(0);\" ><img src=\""+array_element.photoUrl+"\"/></a></span>";
}
liList+=" </td>";
liList+="<td>"+data[i].praiseSum+"</td>";
liList+="<td>"+data[i].contentSum+"</td>";
liList+="</tr>";
repair_overman.append(liList);
}
document.getElementById("master_repir_startTime").value = startTime;
document.getElementById("master_repir_endTime").value = endTime;
document.getElementById("is_list_detail").value="";
// document.getElementById("shop_sort_id").value=sort;
},
error : function(er) {
}
});
}
function selectData(tim) {
document.getElementById("is_list_detail").value="detail";
document.getElementById("time_day").value=tim;
var da = tim * 1000;
var myDate = new Date(da);
var month = myDate.getMonth() + 1;
var da = myDate.getDate() + 1;
var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate()
+ " 00:00:00";
var endTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00";
// alert(startTime+"=="+endTime);
getQuickShopList("time", startTime, endTime);
}
function sortRank(type) {
var startTime =document.getElementById("master_repir_startTime").value;
var endTime=document.getElementById("master_repir_endTime").value;
if(type=="time"){
document.getElementById("time_id").className="select";
}else{
document.getElementById("time_id").className="";
}
if(type=="praise"){
document.getElementById("praise_id").className="select";
}else{
document.getElementById("praise_id").className="";
}
if(type=="content"){
document.getElementById("content_id").className="select";
}else{
document.getElementById("content_id").className="";
}
getClickAmountList(type, startTime, endTime);
}
|
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context(
// 其组件目录的相对路径
'./',
// 是否查询其子目录
true,
// 匹配基础组件文件名的正则表达式
/[A-Za-z]\w+\.vue$/
)
const components = {}
requireComponent.keys().forEach(fileName => {
// 获取组件配置
const componentConfig = requireComponent(fileName)
fileName = (fileName.split('/'))[fileName.split('/').length - 1]
// 获取组件的 PascalCase 命名
const componentName = upperFirst(
camelCase(
// 排出子目录
// 结尾的扩展名
fileName.replace('.vue', '')
)
)
// 如果这个组件选项是通过 `export default` 导出的,
// 那么就会优先使用 `.default`,
// 否则回退到使用模块的根。
components[componentName] = componentConfig.default || componentConfig
})
// 注册node组件
Object.keys(components).forEach(key => {
Vue.component(key, components[key])
})
|
import React from 'react';
import {
View,
Text,
TouchableOpacity,
Switch,
FlatList,
ScrollView,
} from 'react-native';
import {styles} from './Filter.styles';
import {FilterLogic} from './Filter.logic';
import {Header, Card, TextField, Modal} from '../../components';
import {LANDSCAPE} from 'react-native-orientation-locker';
const _FilterScreen = props => {
const {
_onPressBackButton,
selectCategoryList,
onlineStatus,
_switchOnline,
_onChangeName,
name,
_closeModalStatusOnline,
showModalStatusOnline,
_onShowModalStatusOnline,
showModalCategory,
_closeModalCategory,
_onShowModalCategory,
dataCategory,
_chooseCategory,
displayCategoryListText,
onSave,
onReset,
orientation,
} = FilterLogic(props);
const _renderItemCategory = ({item}) => {
const selected = selectCategoryList.some(
cate => cate.sys.id == item.sys.id,
);
return (
<TouchableOpacity
onPress={_chooseCategory(item)}
style={[styles.itemCategory, selected && styles.backgroundSelected]}>
<Text>{item.displayName}</Text>
</TouchableOpacity>
);
};
return (
<View style={styles.container}>
<Header title={'Filter'} onPressBackButton={_onPressBackButton} />
<Card style={styles.cardDefault}>
<TextField
containerStyle={styles.input}
inputProps={{
placeholder: 'Name',
onChangeText: _onChangeName,
value: name,
}}
/>
<TouchableOpacity
onPress={_onShowModalCategory}
style={styles.btnSelectCategory}>
<Text
numberOfLines={2}
style={[
styles.txtCategory,
!selectCategoryList.length && styles.txtCategoryPlaceholder,
]}>
{!!selectCategoryList.length
? displayCategoryListText
: 'Choose category'}
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={_onShowModalStatusOnline}
style={styles.btnSelectOnlineOffline}>
<Text style={styles.txtOnlineOffline}>
{onlineStatus != undefined
? onlineStatus
? 'Online'
: 'Offline'
: 'Online and Offline'}
</Text>
</TouchableOpacity>
</Card>
<View style={styles.groupBtn}>
<TouchableOpacity onPress={onReset} style={styles.btnReset}>
<Text>RESET</Text>
</TouchableOpacity>
<TouchableOpacity onPress={onSave} style={styles.btnSave}>
<Text style={styles.txtSaveBtn}>SAVE</Text>
</TouchableOpacity>
</View>
{/* Modal Online Status */}
<Modal
isOpen={showModalStatusOnline}
style={[
styles.modalStyleStatus,
orientation == LANDSCAPE && {height: '40%'},
]}
onPressClose={_closeModalStatusOnline}
onClosed={_closeModalStatusOnline}
title={'Select Online Status'}>
<ScrollView>
<TouchableOpacity
onPress={_switchOnline(undefined)}
style={[
styles.btnItemOnlineOffline,
onlineStatus === undefined && styles.backgroundSelected,
]}>
<Text>Online and Offline</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={_switchOnline(true)}
style={[
styles.btnItemOnlineOffline,
onlineStatus === true && styles.backgroundSelected,
]}>
<Text>Online</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={_switchOnline(false)}
style={[
styles.btnItemOnlineOffline,
onlineStatus === false && styles.backgroundSelected,
]}>
<Text>Offline</Text>
</TouchableOpacity>
</ScrollView>
</Modal>
{/* Modal Category */}
<Modal
isOpen={showModalCategory}
title={'Select category'}
style={[
styles.modalStyleCategory,
orientation == LANDSCAPE && {height: '55%'},
]}
onPressClose={_closeModalCategory}
onClosed={_closeModalCategory}>
<FlatList data={dataCategory} renderItem={_renderItemCategory} />
</Modal>
</View>
);
};
export const FilterScreen = React.memo(_FilterScreen);
|
self.addEventListener('message', function(e) {
var file=e.data;
var reader = new FileReaderSync();
var url = reader.readAsDataURL(file);
// if (false){
// var options = Settings.imageSettings;
//
// destUrl = imageProcessor.processImage(url, options, function(destUrl){
// destFile = imageProcessor.dataURLtoFile(destUrl);
// var msg = {url : destUrl, file: destFile};
// postMessage(msg);
// });
//
// }
// or don not use resize:
// else{
destUrl = url;
destFile = file;
var msg = {url : destUrl, file: destFile};
postMessage(msg);
// }
});
|
import React from "react";
import "./toDoList.css";
const ToDOList = (props) =>
props.toDoList.map((list) => (
<li className="to-do-list" key={list.key}>
{list.text}{" "}
<span onClick={props.removeList} id={list.key} className="remove-link">
Remove
</span>
</li>
));
export default ToDOList;
|
const createTicket = require("../../utils/ticket");
const guildModel = require("../../models/config");
module.exports = {
name: "new",
description: "makes a ticket channel!",
cooldown: 3,
category: "tickets",
run: async (client, message, args) => {
const guildDoc = await guildModel.findOne({ GuildID: message.guild.id });
const e = message.member;
const user = await message.guild.members.cache.get(e.id);
await createTicket(message, user, guildDoc);
},
};
|
class HCSR04 {
constructor( core, component ){
this.core = core; // worker
this.component = component; // main
this.echo.connect = this.echo.connect.bind(this);
this.trigger.connect = this.trigger.connect.bind(this);
this.state = 0;
this.tick = 0;
this.port = 0;
this.portBit = 0;
core && core.updateList.push((tick, ie)=>{
switch( this.state ){
case 0: return;
case 1: // got trigger, wait 10cs
if( tick < this.tick ) break;
this.state = 2;
core.pins[ this.port ] |= 1<<this.portBit;
this.tick = tick + 1000000;
break;
case 2:
if( tick < this.tick ) break;
this.state = 0;
core.pins[ this.port ] &= ~(1<<this.portBit);
break;
}
});
}
echo = {
connect( target ){
console.log("Sonar.echo connecting to ", target.in);
this.port = target.in.port;
this.portBit = target.in.bit;
}
}
trigger = {
connect( target, core ){
console.log("Sonar.trigger connecting to ", target.out);
core.pins.onHighToLow( target.out.port, target.out.bit, (tick)=>{
this.tick = tick + 500;
this.state = 1;
});
}
}
};
module.exports = HCSR04;
|
// start enchant.js
enchant();
// Document on load
window.onload = function() {
// Starting point
var gameWidth = parseInt(window.innerWidth);
var gameHeight = parseInt(window.innerHeight);
var game = new Game(gameWidth, gameHeight);
//var game = new Game(320, 440);
//Preload resources
game.preload('assets/background-320.png',
'assets/background-410.png',
'assets/background-768.png',
'assets/snow.jpg',
'assets/pocoyo-sheet.png',
'assets/candy.png',
'assets/candy2.png',
'assets/rabbit.png',
'assets/gingerbread.png',
'assets/chocolate.png',
'assets/cupcake.png',
'assets/pause.png',
'assets/play.png',
'assets/mute.png',
'assets/speaker.png',
'assets/bt-jugar-de-nuevo.png',
'assets/bt-twitter.png',
'assets/bt-facebook.png',
'assets/caramelo.mp3',
'assets/bg-music.mp3')
// Game settings
game.fps = 30;
game.scale = 1;
game.onload = function() {
var scene = new SceneGame();
game.pushScene(scene);
}
// start:
game.start();
window.scrollTo(0, 0); //para ios
// clase SceneGame hereda de la clase Scene
var SceneGame = Class.create(Scene, {
// constructor (initialize):
initialize: function() {
var game, label, fLabel, bg, character, candyGroup, sensorBottom, pauseBt, resumeBt;
// llamamos al constructor de la superclase Scene:
Scene.apply(this);
// Access to the game singleton instance:
game = Game.instance;
// creamos los child nodes:
//label = new Label('Hola, Océano');
label = new Label('SCORE: 0');
label.x = 5;
label.y = 15;
label.color = 'white';
label.font = '19px sans-serif';
//label.textAlign = 'center';
label._style.textShadow ="-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black";
this.scoreLabel = label;
fLabel = new Label('FALLOS: 0');
fLabel.x = 5;
fLabel.y = 40;
fLabel.color = '#f00';
fLabel.font = '19px Arial';
//fLabel.textAlign = 'center';
fLabel._style.textShadow ="-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black";
this.failLabel = fLabel;
// background:
//bg = new Sprite(320,440);
bg = new Sprite(gameWidth, gameHeight);
if(gameWidth <= 320) {
bg.image = game.assets['assets/background-320.png'];
} else if(gameWidth <= 410) {
bg.image = game.assets['assets/background-410.png'];
} else if(gameWidth <= 768) {
bg.image = game.assets['assets/background-768.png'];
} else {
bg.image = game.assets['assets/background-768.png'];
}
// barra detectar fondo
//sensorBottom = new Sprite(320,440);
sensorBottom = new Sprite(gameWidth, gameHeight);
//sensorBottom.image = game.assets['assets/pocoyo-sheet.png'];
sensorBottom.x = 0;
sensorBottom.y = gameHeight;
this.sensorBottom = sensorBottom;
// pausa
pauseBt = new Sprite(30,30);
pauseBt.image = game.assets['assets/pause.png'];
pauseBt.x = gameWidth-40;
pauseBt.y = 10;
this.pauseBt = pauseBt;
// pausa
resumeBt = new Sprite(30,30);
resumeBt.image = game.assets['assets/play.png'];
resumeBt.x = -500; // fuera del lienzo
resumeBt.y = 10;
this.resumeBt = resumeBt;
// boton mute:
muteBt = new Sprite(30,30);
muteBt.image = game.assets['assets/speaker.png'];
muteBt.x = gameWidth-85;
muteBt.y = 10;
this.muteBt = muteBt;
// boton speaker poner musica de nuevo:
speakerBt = new Sprite(30,30);
speakerBt.image = game.assets['assets/mute.png'];
speakerBt.x = -500;
speakerBt.y = 10;
this.speakerBt = speakerBt;
// character
character = new Character();
character.x = game.width/2 - character.width/2;
//character.y = 350;
character.y = gameHeight-150;
this.character = character;
// caramelos candy Group
candyGroup = new Group();
this.candyGroup = candyGroup;
// añadir child nodes (El orden de invocación Importa! mira explicación de candyGroup):
this.addChild(bg);
this.addChild(candyGroup); //By adding the candyGroup after the background but before the character, you make sure that the character will always be above the candy
this.addChild(character);
this.addChild(pauseBt);
this.addChild(resumeBt);
this.addChild(muteBt);
this.addChild(speakerBt);
this.addChild(label);
this.addChild(fLabel);
this.addChild(sensorBottom);
// Touch Detection
/*
TOUCH_START: fires when the mouse button is clicked or a finger touches the screen.
TOUCH_MOVE: keeps firing as long as the player drags a mouse while pressing the button, or moves a finger that’s continually touching the screen.
TOUCH_END: fires once the player releases the mouse button, or lifts the finger off the screen.
*/
this.addEventListener(Event.TOUCH_START, this.handleTouchControl);
// Update
this.addEventListener(Event.ENTER_FRAME, this.update);
// Instance variables
this.generateCandyTimer = 0;
this.scoreTimer = 0;
this.score = 0;
this.countFails = 10;
// Background music
this.bgm = game.assets['assets/bg-music.mp3'];
// Start BGM
this.bgm.play();
this.bgm.src.loop = true;
// pausa:
pauseBt.addEventListener(Event.TOUCH_END, this.pause);
// continua:
resumeBt.addEventListener(Event.TOUCH_END, this.resume);
// mute:
muteBt.addEventListener(Event.TOUCH_END, this.mute);
// quitar mute y volver a poner musiquita:
speakerBt.addEventListener(Event.TOUCH_END, this.musicOn);
},
mute: function() {
// quitar musica:
game.currentScene.bgm.pause();
// oculto botón de mute y muestro el de altavoces:
game.currentScene.muteBt.x = -500;
game.currentScene.speakerBt.x = gameWidth-85;
},
musicOn: function() {
// volver a poner musica:
game.currentScene.bgm.play();
// oculto botón de mute y muestro el de altavoces:
game.currentScene.muteBt.x = gameWidth-85;
game.currentScene.speakerBt.x = -500;
},
pause: function() {
// paro juego y musica:
game.pause();
game.currentScene.bgm.pause();
// oculto botón de pausa y muestro el de play:
game.currentScene.pauseBt.x = -500;
game.currentScene.resumeBt.x = gameWidth-40;
},
resume: function() {
// restauro juego y musica:
game.resume();
game.currentScene.bgm.play();
// oculto botón de play y muestro el de pausa:
game.currentScene.pauseBt.x = gameWidth-40;
game.currentScene.resumeBt.x = -500;
},
handleTouchControl: function(evt) {
var laneWidth, lane;
//laneWidth = 320/3;
laneWidth = gameWidth/3;
lane = Math.floor(evt.x/laneWidth);
lane = Math.max(Math.min(2, lane), 0);
this.character.switchToLaneNumber(lane);
},
update: function(evt) {
// generar bloques de hielo
this.generateCandyTimer += evt.elapsed * 0.001;
if(this.generateCandyTimer >= 0.5) {
var candy;
this.generateCandyTimer -= 0.5;
candy = new Candy(Math.floor(Math.random()*3));
this.candyGroup.addChild(candy);
}
var game = Game.instance;
// Check collision
for(var i = this.candyGroup.childNodes.length -1; i>=0; i--) {
var candy;
candy = this.candyGroup.childNodes[i];
// intersect method that you can use to check if two sprites are intersecting
if(candy.intersect(this.character)) {
// incrementa el score:
this.setScore(this.score+1);
// musiquita:
game.assets['assets/caramelo.mp3'].play();
// eliminar bloque de hielo:
this.candyGroup.removeChild(candy);
// se mueve Pocoyó cdo coger un caramelo y se vuelve como estaba:
cha = this.character;
cha.frame++;
setTimeout(function(){
cha.frame++;
},500);
break;
}
// gameover:
if( candy.intersect(this.sensorBottom) ) {
this.setFails(this.countFails-1);
this.candyGroup.removeChild(candy);
if(this.countFails < 1){
this.bgm.stop();
game.replaceScene(new SceneGameOver(this.score))
}
break;
}
}
},
setScore: function(value) {
this.score = value;
this.scoreLabel.text = 'SCORE<br />' + this.score;
},
setFails: function(countFails) {
this.countFails = countFails;
this.failLabel.text = 'Fails<br />' + this.countFails;
}
});
// Animacion del Personaje:
var Character = Class.create(Sprite, {
// constructor:
initialize: function(){
// llamamso al constructor de la superclase
Sprite.apply(this, [150,150]);
this.image = Game.instance.assets['assets/pocoyo-sheet.png'];
// animación:
this.animationDuration = 0;
// animación automática, la he desactivado para q se active al coger un carmelo solo:
//this.addEventListener(Event.ENTER_FRAME, this.updateAnimation);
},
updateAnimation: function(evt){
this.animationDuration += evt.elapsed * 0.001;
if(this.animationDuration >= 0.25) {
this.frame = (this.frame + 1) % 2;
this.animationDuration -= 0.25;
}
},
switchToLaneNumber: function(lane){
//var targetX = 160 - this.width/2 + (lane-1)*90;
distance = parseInt(gameWidth/3);
var targetX = (gameWidth/2) - this.width/2 + (lane-1)*distance;
this.x = targetX;
}
});
// clase para los bloques de caramelos:
var Candy = Class.create(Sprite, {
// constructor:
initialize: function(lane){
// llamada a la superclase Sprite
Sprite.apply(this, [50,50]);
var aCandies = [
'assets/candy.png',
'assets/candy2.png',
'assets/rabbit.png',
'assets/gingerbread.png',
'assets/chocolate.png',
'assets/cupcake.png'
];
var randomCandy = aCandies[ Math.floor(Math.random() * aCandies.length) ];
this.image = Game.instance.assets[ randomCandy ];
this.rotationSpeed = 0;
this.setLane(lane);
this.addEventListener(Event.ENTER_FRAME, this.update);
},
setLane: function(lane){
var game, distance;
game = Game.instance;
//distance = 90;
distance = parseInt(gameWidth/3);
this.rotationSpeed = Math.random() * 100 - 50;
this.x = game.width/2 - this.width/2 + (lane-1) * distance;
this.y = -this.height;
this.rotation = Math.floor(Math.random()*360);
},
update: function(evt){
var ySpeed, game;
game = Game.instance;
ySpeed = 150; // velocidad de caida de los caramelos del juego
this.y += ySpeed * evt.elapsed * 0.001;
this.rotation += this.rotationSpeed * evt.elapsed * 0.001;
if(this.y > game.height){
this.parentNode.removeChild(this);
}
}
});
// Game Over
var SceneGameOver = Class.create(Scene, {
initialize: function(score) {
var gameOverlabel, scoreLabel;
Scene.apply(this);
this.backgroundColor = '#000000'; // or 'black' or 'rgb(0,0,0)'
this.score = score;
// Score label
scoreLabel = new Label('SCORE: ' + score);
scoreLabel.x = (gameWidth/2)-75;
scoreLabel.y = 32;
scoreLabel.color = 'white';
scoreLabel.font = '19px sans-serif';
scoreLabel.textAlign = 'center';
scoreLabel.width = '150';
// Game Over label
/*
gameOverLabel = new Label("GAME OVER<br />Toca para jugar de nuevo.");
gameOverLabel.x = gameWidth/2;
gameOverLabel.y = 200;
gameOverLabel.color = 'white';
gameOverLabel.font = '21px sans-serif';
gameOverLabel.textAlign = 'center';
gameOverLabel.lineHeight = '150%';
this.gameOverLabel = gameOverLabel;
*/
btGameOver = new Sprite(300,112);
btGameOver.image = game.assets['assets/bt-jugar-de-nuevo.png'];
btGameOver.x = (gameWidth/2)-150;
btGameOver.y = 200;
this.btGameOver = btGameOver;
// boton compartir Twitter:
btShareTwitter = new Sprite(150,35);
btShareTwitter.image = game.assets['assets/bt-twitter.png'];
btShareTwitter.x = (gameWidth/2)-150;
btShareTwitter.y = 400;
this.btShareTwitter = btShareTwitter;
// boton compartir Facebook:
btShareFb = new Sprite(150,35);
btShareFb.image = game.assets['assets/bt-facebook.png'];
btShareFb.x = (gameWidth/2)+10;
btShareFb.y = 400;
this.btShareFb = btShareFb;
// Add labels
//this.addChild(gameOverLabel);
this.addChild(btGameOver);
this.addChild(scoreLabel);
this.addChild(btShareTwitter);
this.addChild(btShareFb);
// Event listener paar el botónde compartir Twitter y Facebook
this.btShareTwitter.addEventListener(Event.TOUCH_START, this.shareTwitter);
this.btShareFb.addEventListener(Event.TOUCH_START, this.shareFacebook);
// Listen for taps
// esta es si tocas toda la pantalla:
//this.addEventListener(Event.TOUCH_START, this.touchToRestart);
// la sustituimso por un label para volver a jugar
this.btGameOver.addEventListener(Event.TOUCH_START, this.touchToRestart);
},
touchToRestart: function(evt) {
var game = Game.instance;
game.replaceScene(new SceneGame());
},
shareTwitter: function(evt) {
var shareTwitterUrl = "http://twitter.com/share?text=He conseguido "+evt.target.scene.score+" puntos en el juego de Pocoyo coger los caramelos&url=http://www.pocoyo.com&hashtags=pocoyo,juegos";
window.open(shareTwitterUrl);
},
shareFacebook: function(evt) {
var shareFbUrl = "http://www.facebook.com/sharer.php?u=url_http://www.pocoyo.com&p[title]=El juego de las golosinas de Pocoyo&p[summary]=He conseguido "+evt.target.scene.score+" puntos en el juego de Pocoyo coger los caramelos";
window.open(shareFbUrl);
}
});
};
|
//manager class also has office number
//getRole returns manager
const Employee = require("./Employee");
class Manager extends Employee {
constructor(name, id, email, officeNumber) {
super(name, id, email);
this.officeNumber = officeNumber;
}
//be able to:
getOfficeNumber() {
return this.officeNumber;
}
//get role (returns employee)
getRole() {
return "Manager";
}
}
module.exports = Manager;
|
const sidebarMap = [
{title: 'Blog', dirname: 'blog'},
{title: 'JS 中的算法', dirname: 'algorithm'}
]
module.exports = sidebarMap
|
import('./common');
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you import will output into a single css file (app.css in this case)
import '../scss/app.scss';
// Need jQuery? Install it with "yarn add jquery", then uncomment to import it.
// import $ from 'jquery';
//Requete ajax
let scoreForm = document.getElementById('score-form');
if (null != scoreForm) { // Test si le formulaire existe bien
let clickedSubmit = null;
// Event onclick sur chaque boutons pour stocker le bouton qui a été cliqué
let submitButtons = scoreForm.querySelectorAll('button');
submitButtons.forEach((value) => {
value.onclick = function () {
clickedSubmit = this;
};
});
scoreForm.onsubmit = () => {
let request = new XMLHttpRequest();
request.open('post', scoreForm.getAttribute('action'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = () => {
let json = JSON.parse(request.responseText);
let result = document.createElement('div');
result.innerHTML = json.message;
scoreForm.parentNode.replaceChild(result, scoreForm);
};
// Récupére la valeur du bouton cliqué
let formData = new FormData(scoreForm);
formData.set('score', clickedSubmit.value);
request.send(formData);
return false; // empéche l'envois du formulaire
}
}
|
import { CreateAccountScreen, SelectAccountScreen, WelcomeScreen } from './Aozora';
import { ImportLibrary, ImportDetail } from './Kitsu';
import { RateScreen, OnboardingHeader, FavoritesScreen, ManageLibrary, RatingSystemScreen } from './common';
export {
CreateAccountScreen,
SelectAccountScreen,
WelcomeScreen,
RateScreen,
ImportLibrary,
ImportDetail,
OnboardingHeader,
FavoritesScreen,
ManageLibrary,
RatingSystemScreen,
};
|
import {elements} from '../views/base';
//add audio to the game
export const backgroundMusic = () => {
// Playlist array
var files = [
"music/texasradiofish_-_Amiable_Sky.mp3",
"music/texasradiofish_-_HAPPY_6.mp3",
"music/airtone_-_forgottenland.mp3",
"music/speck_-_Salsa_Lenta.mp3",
];
// Current index of the files array
var i = 0;
// Get the audio element
var music_player = document.querySelector("#music_list");
// function for moving to next audio file
function next() {
// Check for last audio file in the playlist
if (i === files.length - 1) {
i = 0;
} else {
i++;
}
// Change the audio element source
music_player.src = files[i];
if(musicOn) elements.audio.play();
}
// Check if the player is selected
if (music_player === null) {
throw "Playlist Player does not exists ...";
} else {
// Start the player
music_player.src = files[i];
// Listen for the music ended event, to play the next audio file
music_player.addEventListener('ended', next, false);
}
}
export var musicOn = false;
export const musicActive = () => {
for (const button of elements.audioBtns) button.volume = 0.2;
elements.audio.volume = 0.2;
elements.audioBtnPlus.play();
elements.audio.play();
elements.musicIcon.classList.remove('fa-volume-up');
elements.musicIcon.classList.add('fa-volume-mute');
musicOn = true;
}
export const musicDisactive = () => {
elements.audio.pause();
elements.musicIcon.classList.remove('fa-volume-mute');
elements.musicIcon.classList.add('fa-volume-up');
musicOn = false;
}
elements.musicBtn.addEventListener('click', ev => {
if (elements.audio.paused) {
musicActive();
} else {
musicDisactive();
}
});
|
const fs = require('fs')
const { execFileSync } = require('child_process')
const entry = process.argv[2]
console.log(entry, 'is being watched')
function compileandrun(filename) {
console.log('compiling', filename)
const compiletask = execFileSync("g++", [
"-g",
filename
], { stdio: 'inherit' })
console.log('running', filename)
const runtask = execFileSync("./a.out", { stdio: 'inherit' })
}
const reload = debounce(() => {
console.log('')
compileandrun(entry)
console.log('')
}, 500)
fs.watch('.', {}, (ev, filename) => {
console.log(filename, ev)
if (ev === 'change' && filename.includes('.cpp')) {
reload()
}
})
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func = () => { }, wait = 500, immediate = false) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
|
import { call, put } from 'redux-saga/effects';
import { CADCLI_VINCULO_DESVINCULO_FALHA, CADCLI_VINCULO_DESVINCULO_INICIA, CADCLI_VINCULO_DESVINCULO_SUCESSO } from '../../actions/clinicas/CadastroClinicasAction';
import { CADMED_ESPECIALIDADE_FALHA, CADMED_ESPECIALIDADE_INICIA, CADMED_ESPECIALIDADE_SUCESSO, CADMED_INICIANDO, CADMED_SALVO_FALHA, CADMED_SALVO_SUCESSO } from '../../actions/medicos/CadastroMedicosAction';
import { MEUMED_DESVINCULAR_FALHA, MEUMED_DESVINCULAR_SUCESSO, MEUMED_EDITAR_MEDICO_FALHA, MEUMED_EDITAR_MEDICO_INICIA, MEUMED_EDITAR_MEDICO_SUCESSO, MEUMED_INICIANDO, MEUMED_RETORNO_FALHA, MEUMED_RETORNO_SUCESSO } from "../../actions/medicos/MeusMedicosAction";
import { MensagemInformativa } from "../../components/mensagens/Mensagens";
import { RETORNO_SUCESSO, RETORNO_SERVER_INDISPONIVEL } from "../../constants/ConstantesInternas";
import ClinicaServico from '../../servicos/ClinicaServico';
import MedicosServico from "../../servicos/MedicosServico";
export function* recuperarMedicos(action){
yield put({type: MEUMED_INICIANDO});
try {
const retorno = yield call(MedicosServico.recuperarMedicos);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: MEUMED_RETORNO_SUCESSO, listaMedicos: retorno.data.retorno});
} else {
yield put({type: MEUMED_RETORNO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
console.log('falha na busca dos médicos')
}
} catch(error){
yield put({type: MEUMED_RETORNO_FALHA, mensagemFalha: error});
}
}
export function* desvincularMedico(action){
yield put({type: MEUMED_INICIANDO});
try {
const retorno = yield call(MedicosServico.desvincularMedico, action.medico);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: MEUMED_DESVINCULAR_SUCESSO, idMedico: action.medico.idMedico});
MensagemInformativa('Médico desvinculado da sua lista com sucesso!');
} else {
yield put({type: MEUMED_DESVINCULAR_FALHA, mensagemFalha: retorno.mensagemErro, idMedico: null});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: MEUMED_DESVINCULAR_FALHA, mensagemFalha: error});
MensagemInformativa(error);
}
}
export function* salvarMedico(action){
yield put({type: CADMED_INICIANDO});
try {
const {medico} = action;
if (medico.idMedico != null){
retorno = yield call(MedicosServico.alterarMedico, medico);
} else {
retorno = yield call(MedicosServico.salvarMedico, medico);
}
if (retorno.status === RETORNO_SUCESSO){
let idMedico = medico.idMedico == null ? retorno.data.retorno : medico.idMedico;
yield put({type: CADMED_SALVO_SUCESSO, idMedico});
MensagemInformativa('Médico salvo com sucesso! Vincule clínicas na aba "Clínicas do médico" ');
} else {
yield put({type: CADMED_SALVO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: CADMED_SALVO_FALHA, mensagemFalha: error});
}
}
export function* buscarEspecialidades(action){
yield put({type: CADMED_ESPECIALIDADE_INICIA});
try {
const retorno = yield call(MedicosServico.obterEspecialidades);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: CADMED_ESPECIALIDADE_SUCESSO, listaEspecialidades: retorno.data.retorno});
} else {
yield put({type: CADMED_ESPECIALIDADE_FALHA, mensagemFalha: retorno.menagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: CADMED_ESPECIALIDADE_FALHA, mensagemFalha: error});
}
}
export function* buscarMedicoEdicao(action){
yield put({type: MEUMED_EDITAR_MEDICO_INICIA});
try {
const retorno = yield call(MedicosServico.buscarMedico, action.codMedico);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: MEUMED_EDITAR_MEDICO_SUCESSO, medico: retorno.data.retorno});
} else {
yield put({type: MEUMED_EDITAR_MEDICO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: MEUMED_EDITAR_MEDICO_FALHA, mensagemFalha: error});
}
}
export function* desvincularClinica(action){
yield put({type: CADCLI_VINCULO_DESVINCULO_INICIA});
try {
const retorno = yield call(ClinicaServico.desvincularClinicaMedico, action.codClinica, action.codMedico);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: CADCLI_VINCULO_DESVINCULO_SUCESSO, codClinicaDesvinculada: action.codClinica});
MensagemInformativa('Clínica desvinculada com sucesso');
} else {
yield put({type: CADCLI_VINCULO_DESVINCULO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
console.log('Erro retorno')
}
} catch(error){
yield put({type: CADCLI_VINCULO_DESVINCULO_FALHA, mensagemFalha: error});
}
}
|
var script = document.createElement("script")
script.src = "https://cdn.rawgit.com/chrisveness/crypto/4e93a4d/sha256.js"
document.head.appendChild(script)
var elements = [
{
tagName: "div",
insertIn: "body",
attrs: {
id: "wrapper",
style: `
margin: 0 auto;
max-width: 300px;
height: 550px;
border: 2px solid cyan;
border-radius: 10px;
padding: 10px;
background-color: #20B2AA;
`
}
},
{
tagName: "p",
insertIn: "#wrapper",
attrs: {
innerText: "Форма входа / регистрации пользователя",
style: `
font-size: 20px;
margin: 15px 10px;
text-align: center;
`
}
},
{
tagName: "form",
insertIn: "#wrapper",
attrs: {
id: "formRegistration",
}
},
{
tagName: "p",
insertIn: "#formRegistration",
attrs: {
innerText: ` Если Вы еще не загеристрированный пользователь, введите свои данный и нажмите 'Зарегистрироваться'.
Если Вы уже регистрировались, введите почту и пароль и нажмите 'Войти'`,
style: `
font-size: 16px;
margin: 5px 10px 15px 10px;
text-align: justify;
`
}
},
{
tagName: "lable",
insertIn: "#formRegistration",
attrs: {
innerText: "Введите Имя: ",
id: "lable-name",
placeholder: "User Name",
style: `
font-size: 18px;
margin: 10px 10px;
font-style: italic;
`
}
},
{
tagName: "input",
insertIn: "#lable-name",
attrs: {
type: "text",
id: "inpt-name",
style: `
width: 95%;
font-size: 18px;
margin: 10px 10px;
`
}
},
{
tagName: "lable",
insertIn: "#formRegistration",
attrs: {
innerText: "Введите E-mail:* ",
id: "lable-log",
placeholder: "login",
style: `
font-size: 18px;
margin: 10px 10px;
font-style: italic;
`
}
},
{
tagName: "input",
insertIn: "#lable-log",
attrs: {
type: "text",
id: "inpt-mail",
style: `
width: 95%;
font-size: 18px;
margin: 10px 10px;
`
}
},
{
tagName: "lable",
insertIn: "#formRegistration",
attrs: {
innerText: "Введите пароль:* ",
id: "lable-pass",
placeholder: "password",
style: `
font-size: 18px;
margin: 10px 10px;
font-style: italic;
`
}
},
{
tagName: "input",
insertIn: "#lable-pass",
attrs: {
type: "password",
id: "inpt-pass",
style: `
width: 95%;
font-size: 18px;
margin: 10px 10px;
`
}
},
{
tagName: "p",
insertIn: "#formRegistration",
attrs: {
innerText: "",
style: `
font-size: 16px;
margin: 5px 10px;
text-align: center;
`
}
},
{
tagName: "button",
insertIn: "#formRegistration",
attrs: {
innerText: "Зарегистрироваться",
id: "regist",
style: `
font-size: 18px;
margin: 10px 10px;
padding: 10px 25px;
border-radius: 20px;
`
}
},
{
tagName: "button",
insertIn: "#formRegistration",
attrs: {
innerText: "Войти",
id: "enter",
style: `
font-size: 18px;
margin: 10px 10px;
padding: 10px 25px;
border-radius: 20px;
`
}
},
]
elements.forEach ( elemObj => {
var elem = document.querySelector( [ elemObj.insertIn ] ).appendChild (
document.createElement ( elemObj.tagName )
)
for ( var attr in elemObj.attrs ) {
elem [ attr ] = elemObj.attrs [ attr ]
}
})
var users = []
var message = document.createElement("p")
message.style = "font-size: 22px; color: red "
message.id="message"
document.body.appendChild(message)
function init () {
var userName = document.querySelector("#inpt-name")
var userEmail = document.querySelector("#inpt-mail")
var userPass = document.querySelector("#inpt-pass")
if (!userName.value || !userEmail.value || !userPass.value) return
var hash = Sha256.hash(userPass.value + userEmail.value)
users.push({
"key": `${hash}`,
"name": `${userName.value}`,
"email": `${userEmail.value}`
})
return users
}
function cleaner () {
document.querySelector("#inpt-name").value = ""
document.querySelector("#inpt-mail").value = ""
document.querySelector("#inpt-pass").value = ""
}
function clickHandlerRegistration (event) {
event.preventDefault()
var userArr = init()
if (!userArr) {
document.querySelector("#message").innerText = "*Заполните все поля ввода"
return
}
var name
for (var ind in userArr) {
if (userArr[ind]["name"] === document.querySelector("#inpt-name").value)
name = userArr[ind]["name"]
}
document.querySelector("#message").style = "color: black; font-size: 20px"
document.querySelector("#message").innerText = name + ", успешно загеристрировался"
cleaner()
}
function createNewWindow(usName) {
var newWin = window.open('about:blank')
newWin.console.log("Hello")
var body = newWin.document.body
body.style = `margin: 20px auto;
max-width: 500px;
height: 350px;
border: 2px solid cyan;
border-radius: 10px;
padding: 10px;
background-color: #20B2AA;
`
var div = newWin.document.createElement("div")
body.appendChild(div)
var avatar = newWin.document.createElement("img")
avatar.src = "https://intellihr.com.au/wp-content/uploads/2017/06/avatar_placeholder_temporary.png"
avatar.style = `
display: block;
width: 150px;
height: 150px;
border: 1px solid cyan;
border-radius: 50%;
margin: 15px auto;
`
div.appendChild(avatar)
var text = newWin.document.createElement("p")
text.style = "font-size: 30px; color: black; text-align: center; margin: 30px 0"
text.innerHTML = "Добро пожаловать, " + usName + "!"
div.appendChild(text)
}
function clickHandlerEnter (event) {
event.preventDefault()
if (users.length === 0) {
document.querySelector("#message").style = "font-size: 22px; color: red "
document.querySelector("#message").innerText = "Сначало зарегистрируйтеся"
} else {
var userEmail = document.querySelector("#inpt-mail")
var userPass = document.querySelector("#inpt-pass")
if (!userEmail.value || !userPass.value) return
var hash = Sha256.hash(userPass.value + userEmail.value)
for (var ind in users) {
if (document.querySelector("#inpt-mail").value === users[ind]["email"] && hash === users[ind]["key"]) {
document.querySelector("#message").style = "color: black; font-size: 20px"
document.querySelector("#message").innerText = "Hello " + users[ind]["name"]
createNewWindow(users[ind]["name"])
}
else {
document.querySelector("#message").style = "font-size: 22px; color: red "
document.querySelector("#message").innerText = "*Неверное введены данные"
}
}
cleaner()
}
}
var btnRegistration = document.querySelector("#regist")
btnRegistration.addEventListener ( 'click', clickHandlerRegistration )
var btnEnter = document.querySelector("#enter")
btnEnter.addEventListener ( 'click', clickHandlerEnter )
|
function ControladorDifuso(){
}
ControladorDifuso.prototype.seleccionarPromociones = function(entradas){
var difusor = new Difusor();
var entradasFusificadas = difusor.fusificar(entradas);
var sistemaExperto = new SistemaExperto();
var salidas = sistemaExperto.ejecutar(entradas.lugares, entradasFusificadas);
console.log(salidas);
var defusificador = new Defusificador();
var lugarElegido = defusificador.defusificar(salidas);
var lugarFinal;
//repositorioLugares.getLugarPorNombre(lugarElegido);
entradas.lugares.forEach(function(lugar){
var cochinada = sistemaClasificador.standarizarNombreVariable(lugar.nombre);
if(cochinada == lugarElegido){
lugarFinal = lugar;
}
})
return lugarFinal;
}
|
(function(app) {
'use strict';
function verifyRec(params) {
if (!params.incomeType) {
return 'Income type must not be empty.';
}
if (!params.account) {
return 'Account must not be empty.';
}
if (!params.amount) {
return 'Ammount must not be empty.';
}
if (!params.date) {
return 'Date must not be empty.';
}
return null;
}
function buildRec(params, rec, callback) {
rec = rec || {};
rec.incomeType = params.incomeType;
rec.account = params.account;
rec.amount = params.amount;
rec.date = params.date;
rec.comments = params.comments;
callback(null, rec);
}
app.db.createActualIncome = function(params, callback) {
var activePeriod = app.getActiveBudgetPeriod();
var data = activePeriod.actualIncomes;
var err = verifyRec(params);
if (err) {
callback(err, null);
} else {
buildRec(params, null, function(err, rec) {
if (err) {
callback(err, null);
} else {
data.push(rec);
app.db.persist(function() {
callback(null, data.length - 1);
});
}
});
}
};
app.db.updateActualIncome = function(params, callback) {
var activePeriod = app.getActiveBudgetPeriod();
var data = activePeriod.actualIncomes;
var err = verifyRec(params);
if (err) {
callback(err, null);
} else {
buildRec(params, data[params.id], function(err, rec) {
if (err) {
callback(err, null);
} else {
app.db.persist(function() {
callback(null, params.id);
});
}
});
}
};
app.db.deleteActualIncome = function(params, callback) {
var activePeriod = app.getActiveBudgetPeriod();
var data = activePeriod.actualIncomes;
data.splice(params.id, 1);
app.db.persist(function() {
callback(null);
});
};
app.db.getActualIncomes = function() {
var activePeriod = app.getActiveBudgetPeriod();
if (activePeriod && activePeriod.actualIncomes) {
return activePeriod.actualIncomes.sort(function(a, b) {
return a.date - b.date;
});
} else {
return [];
}
};
app.db.getActualIncome = function(id) {
var activePeriod = app.getActiveBudgetPeriod();
return activePeriod.actualIncomes[id];
}
app.db.calcTotalActualIncome = function(callback) {
var actualIncomes = app.db.getActualIncomes();
var totalActualIncome = actualIncomes.reduce(function(total, income) {
return total + income.amount;
}, 0);
callback(null, totalActualIncome);
}
})(frugalisApp);
|
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt
function _3DEntity(_3dmodel)
{
this.model = _3dmodel ;
this.scale = 1 ;
this.position = Vector4.Create() ;
this.rotation = Vector4.Create() ;
this.transMatrix = Matrix44.Create() ;
this.className = _3DEntity.className ;
this.Init() ;
}
_3DEntity.className = "_3DEntity"
_3DEntity.Create = function(_3dmodel)
{
return new _3DEntity(_3dmodel) ;
} ;
_3DEntity.prototype =
{
_3DEntity: constructor,
Init: function()
{
this.BuildTransformationMatrix() ;
},
Clone: function()
{
var ent = new _3DEntity(this.model)
ent.SetPosition(Vector4.Create(this.GetPosition())) ;
ent.SetRotation(Vector4.Create(this.GetPosition())) ;
return ent ;
},
SetModel: function(model)
{
this.model = model ;
},
GetPosition: function()
{
return this.position ;
},
GetRotation: function()
{
return this.rotation ;
},
SetPosition: function(position)
{
this.position.SetXyzw(position.X(),position.Y(),position.Z(),0) ;
this.BuildTransformationMatrix() ;
return this ;
},
SetRotation: function(rotation)
{
this.rotation.SetXyzw(rotation.X(),rotation.Y(),rotation.Z(),0) ;
this.BuildTransformationMatrix() ;
return this ;
},
BuildTransformationMatrix: function()
{
var rotation = this.rotation ;
var position = this.position ;
var matrix = Matrix44.Create()
this.transMatrix = matrix ;
var rx = rotation.X(), ry = rotation.Y(), rz = rotation.Z() ;
var px = position.X(), py = position.Y(), pz = position.Z() ;
matrix.SetRotationXyz(rx,ry,rz,MATRIX_REPLACE) ;
matrix.SetTranslation(pz,py,px,MATRIX_POSTMULTIPLY) ;
},
toString: function()
{
return "_3DEntity.toString" ;
},
Render: function(renderHelper,camera)
{
this.model.Render(renderHelper,camera,this.transMatrix,this.position,this.rotation) ;
},
RenderDebug: function(renderHelper,x,y)
{
var r1 = this.transMatrix.GetRow(1) ;
var r2 = this.transMatrix.GetRow(2) ;
var r3 = this.transMatrix.GetRow(3) ;
var r4 = this.transMatrix.GetRow(4) ;
renderHelper.drawText("r1 "+r1,x,y) ;
renderHelper.drawText("r2 "+r2,x,y+20) ;
renderHelper.drawText("r3 "+r3,x,y+40) ;
renderHelper.drawText("r4 "+r4,x,y+60) ;
}
}
|
import Vue from 'vue'
import Vuex from 'vuex'
import authLocalService from '@/datasources/local/authentication'
import authHttpService from '@/datasources/http/authentication'
import productHttpService from '@/datasources/http/product'
import productVariantHttpService from '@/datasources/http/product-variant'
import productCategoryHttpService from '@/datasources/http/product-category'
Vue.use(Vuex)
function handleUnauthorizedSession (store) {
return (error) => {
if (error.response &&
error.response.status === 401 &&
error.response.data.code === 401) {
store.commit('FLUSH_AUTH_SESSION')
}
}
}
const initialState = {
token: '',
isAuthInitialized: false
}
export default new Vuex.Store({
state: {
...initialState
},
mutations: {
'INITIALIZE_STORED_AUTH_SESSION' (state) {
const oldToken = authLocalService.getToken()
if (oldToken) {
Vue.set(state, 'token', oldToken)
}
Vue.set(state, 'isAuthInitialized', true)
},
'START_AUTH_SESSION' (state, payload) {
authLocalService.persistToken(payload)
Vue.set(state, 'token', payload)
},
'FLUSH_AUTH_SESSION' (state) {
authLocalService.flushToken()
Vue.set(state, 'token', initialState.token)
}
},
actions: {
authenticate ({ commit }, payload) {
return authHttpService.authenticate(payload)
.then((response) => {
if (response.status === 200 && response.data.code === 200) {
commit('START_AUTH_SESSION', response.data.token)
return true
}
return false
})
},
loadProducts (store, params = {}) {
const { getters } = store
return productHttpService.index(getters.getToken())
.then((response) => {
if (response.status === 200 && response.data.code === 200) {
return response.data.products.map((product, index) => {
return {
_rid: index,
_id: product.productId,
imageURL: product.productImage,
code: product.productCode,
name: product.productName,
variants: product.variants,
outlets: {},
categoryId: product.categoryId,
category: product.Category,
price: product.productPrice,
cost: product.productCost
}
})
}
return []
})
.catch(handleUnauthorizedSession(store))
},
duplicateProducts (store, products) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < products.length; i++) {
promisedRequests.push(
fetch(products[i].imageURL)
.then((res) => res.blob())
.then((blob) => {
const productImage = new File(
[blob],
`PROD-${products[i].code}-DUP.jpg`,
{
type: 'image/jpeg'
}
)
let variants = ''
for (let j = 0; j < products[i].variants.length; j++) {
variants = variants + products[i].variants[i]
.productVariant
.variantId
if (j < (products[i].variants.length - 1)) {
variants = variants + ','
}
}
var productFormData = new FormData()
productFormData.append('name', products[i].name)
productFormData.append('code', products[i].code)
productFormData.append('cost', products[i].cost)
productFormData.append('price', products[i].price)
productFormData.append('category', products[i].categoryId)
productFormData.append('variants', `[${variants}]`)
productFormData.append('image', productImage)
return productHttpService.create(
getters.getToken(),
productFormData
)
})
)
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
},
removeProducts (store, products) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < products.length; i++) {
promisedRequests.push(productHttpService.remove(
getters.getToken(),
products[i]._id)
)
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
},
loadProductVariants (store, params = {}) {
const { getters } = store
return productVariantHttpService.index(getters.getToken())
.then((response) => {
if (response.status === 200 && response.data.code === 200) {
return response.data.variants.map((variant, index) => {
return {
_rid: index,
_id: variant.variantId,
name: variant.variantName,
type: variant.variantType,
products: [],
options: variant.variantOption
}
})
}
return []
})
.catch(handleUnauthorizedSession(store))
},
duplicateProductVariants (store, variants) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < variants.length; i++) {
promisedRequests.push(
productVariantHttpService.create(getters.getToken(), {
name: variants[i].name,
type: variants[i].type,
options: variants[i].options
})
)
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
},
removeProductVariants (store, variants) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < variants.length; i++) {
promisedRequests.push(productVariantHttpService.remove(
getters.getToken(),
variants[i]._id))
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
},
loadProductCategories (store, params = {}) {
const { getters } = store
return productCategoryHttpService.index(getters.getToken())
.then((response) => {
if (response.status === 200 && response.data.code === 200) {
return response.data.categories.map((category, index) => {
return {
_rid: index,
_id: category.id,
name: category.categoryName
}
})
}
return []
})
.catch(handleUnauthorizedSession(store))
},
duplicateProductCategories (store, categories) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < categories.length; i++) {
promisedRequests.push(
productCategoryHttpService.create(getters.getToken(), {
name: categories[i].name
})
)
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
},
removeProductCategories (store, categories) {
const { getters } = store
var promisedRequests = []
for (let i = 0; i < categories.length; i++) {
promisedRequests.push(productCategoryHttpService.remove(
getters.getToken(),
categories[i]._id)
)
}
return Promise.all(promisedRequests)
.catch(handleUnauthorizedSession(store))
}
},
getters: {
isAuthenticated (state) {
return !(state.token.length < 1)
},
isAuthSessionInitialized (state) {
return state.isAuthInitialized
},
getToken (state) {
return () => {
return state.token
}
}
},
modules: {
}
})
|
import React from 'react';
import './WelcomeBar.css';
const WelcomeBar = () => {
return (
<div className="welcomebar-container">
<h1 className="welcome-name">Bienvenid@</h1>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="502px" height="67px" viewBox="38 23.5 502 67">
<line fill="none" stroke="#FFBD3A" x1="85.1" y1="48.3" x2="193.1" y2="48.3"/>
<line fill="none" stroke="#8CAFAE" x1="195.1" y1="48.3" x2="303.1" y2="48.3"/>
<line fill="none" stroke="#8CAFAE" x1="302.6" y1="48.3" x2="410.6" y2="48.3"/>
<line fill="none" stroke="#8CAFAE" x1="410.2" y1="48.3" x2="518.2" y2="48.3"/>
<circle fill="#FFBD3A" cx="83.3" cy="48.4" r="6.4"/>
<circle fill="#8CAFAE" cx="195.1" cy="48.4" r="4.3"/>
<circle fill="#8CAFAE" cx="302.6" cy="48.4" r="4.3"/>
<circle fill="#8CAFAE" cx="410.2" cy="48.4" r="4.3"/>
<circle fill="#8CAFAE" cx="518.8" cy="48.4" r="4.3"/>
<circle fill="none" stroke="#FFBD3A" stroke-width="2" cx="83.3" cy="48.4" r="9.6"/>
<circle fill="none" stroke="#8CAFAE" stroke-width="2" cx="195.1" cy="48.4" r="6.5"/>
<circle fill="none" stroke="#8CAFAE" stroke-width="2" cx="302.6" cy="48.4" r="6.5"/>
<circle fill="none" stroke="#8CAFAE" stroke-width="2" cx="410.2" cy="48.4" r="6.5"/>
<circle fill="none" stroke="#8CAFAE" stroke-width="2" cx="518.8" cy="48.4" r="6.5"/>
<text transform="matrix(1 0 0 1 45.2866 71.7002)" fill="#5E807F" font-family="'Mada-Bold'" font-size="10">Datos Personales</text>
<text transform="matrix(1 0 0 1 154.8047 71.7002)" fill="#8CAFAE" font-family="'Mada-Bold'" font-size="10">Datos de Contacto</text>
<text transform="matrix(1 0 0 1 279.8823 71.7002)" fill="#8CAFAE" font-family="'Mada-Bold'" font-size="10">Educación</text>
<text transform="matrix(1 0 0 1 366.3457 71.7002)" fill="#8CAFAE" font-family="'Mada-Bold'" font-size="10">Experiencia Laboral</text>
<text transform="matrix(1 0 0 1 504.543 71.7002)" fill="#8CAFAE" font-family="'Mada-Bold'" font-size="10">¡Listo!</text>
</svg>
</div>
);
};
export default WelcomeBar;
|
require("dotenv").config();
const lens = require("../models/Lens");
const mongoose = require("mongoose");
const lenses = [{
img:"https://res.cloudinary.com/des8h9eva/image/upload/v1601560674/lens/vblwvw9oqzqxbx7yjsiu.jpg",
brand:"Acuvue",
reference:"#1233434",
description:"They give you a very acute view"
},
{
img:"https://res.cloudinary.com/des8h9eva/image/upload/v1601560848/lens/v9gy4f2yi50n61ii6ubl.jpg",
brand:"Dailies",
reference:"#MV2344",
description:"Give us this day our daily lens"
},
{
img:"https://res.cloudinary.com/des8h9eva/image/upload/v1601560938/lens/g2jzr4at1t1yfnlzc7ak.jpg",
brand:"Air",
reference:"#44544",
description:"So light."
}
];
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
lens.create(lenses)
.then((dbResult) => {
console.log(dbResult);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
console.log(error);
});
|
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
// 推送订单信息
exports.main = async (event, context) => {
console.log(event)
try {
const { OPENID } = cloud.getWXContext();
const result = await db.collection('orders').add({
data:{
touser: OPENID,
page: 'page/component/order/order', // 订阅消息卡片点击后会打开小程序的哪个页面
data: event.data,
totalMoney: event.totalMoney,
time: event.time,
templateId: 'iClEtI_1cJOdp6E-W8j_4gMJsDTahSmHQZlMZWcatO4',
done: false, // 消息发送状态设置为 false
}
})
console.log(result)
return result
} catch (err) {
console.log(err)
return err
}
}
|
/**
MODULOS EXPRESS
**/
require('dotenv').config(); //carregando variavieis .env
let express = require('express'); //modulo servidor
let http = require('http'); //servidor http
let path = require('path'); //path para urls estaticas
let favicon = require('serve-favicon'); //icone servidor
let logger = require(process.cwd() + '/utils/logger.js'); //gerador de logs
let bodyParser = require('body-parser'); //conversor json
let cors = require('cors'); //controle de acesso de origem
let consign = require('consign'); //autoload de componentes
let morgan = require("morgan");
let requestUpdate = require('request-promise');
let sudoExec = require('sudo-js');
sudoExec.setPassword('123!@#321#@!');
/**
START EXPRESS
**/
logger.info('INICIANDO CONFIGURAÇÕES DO SERVIDOR');
let app = express();
app.use(bodyParser.urlencoded({limit: '50mb', extended: false, parameterLimit: 1000000 }));
app.use(bodyParser.json({limit: '50mb'}));
/**
CORS
**/
logger.info('CARREGANDO CONFIGURAÇÕES DO CORS');
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "HEAD,OPTIONS,GET,POST,PUT,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType, Content-Type, Accept, Authorization");
next();
});
app.use(cors());
/**
ARQUIVOS ESTATICOS
**/
app.use('/api/contents', express.static(path.join(process.cwd(), 'public')));
app.use(favicon(path.join(process.cwd(), 'public', 'favicon.ico')));
process.setMaxListeners(0);
/**
LOGS
**/
logger.info('CARREGANDO SERVIÇO DE LOGS...');
app.use(require("morgan")(function (tokens, req, res) {
return [
//date, '-',
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms'
].join(' ');
}, { "stream": logger.stream }));
/**
IMPORTANDO MODULOS, ROTAS, CONTROLADORES E FUNCOES
**/
logger.info('IMPORTANDO MODULOS, ROTAS, CONTROLADORES E FUNCOES!');
consign({
cwd: process.cwd(),
locale: 'pt-br',
logger: console,
verbose: true,
extensions: ['.js', '.json', '.node'],
loggingType: 'info'
})
.then('utils')
.then('routes')
.into(app);
/**
ROTA INICIAL
**/
logger.info('CARREGANDO ROTA INICIAL');
app.get('/', function (req, res, next) {
res.status(200);
res.sendFile(path.join(process.cwd() + '/public/200.html'));
});
/**
VERSAO ATUAL
**/
logger.info('CARREGANDO VERSAO ATUAL');
app.get('/api/versao', function (req, res, next) {
let versaoCheff = {
APPGARCOM: '2.0.0',
};
res.status(200).send(versaoCheff);
});
/**
TRATAMENTO DE ERRO 404
**/
logger.info('CARREGANDO ROTA 404');
app.use(function (req, res, next) {
res.status(404);
res.sendFile(path.join(process.cwd() + '/public/404.html'));
});
/**
INICIANDO SERVIDOR
**/
let server = app.listen(process.env.PORT || 13579, function () {
let port = server.address().port;
logger.info(`SERVIDOR INICIALIZADO NA PORTA: ${port}`);
});
server.on('error', erroServer);
/**
TRATAMENTO ERRO SERVIDOR
**/
function erroServer(error) {
switch (error.code) {
case 'EACCES':
logger.error(`SEM PERMISSÃO DE ACESSO!`);
process.exit(1);
break;
case 'EADDRINUSE':
logger.error(`A PORTAL ESTÁ EM USO!`);
process.exit(1);
break;
default:
throw error;
}
}
|
import React, { Component } from 'react';
import { Link, Router } from '../../routes';
import Layout from '../../components/Layout';
import SearchAdress from '../../components/SearchAdress';
import Navbar from '../../components/Navbar';
import './styles.scss';
class index extends Component {
render() {
return (
<main className={'fullHeight'}>
<Navbar />
<div className="indexContainer">
<div className="overlay" />
<div className="centerDiv searchAdress">
<SearchAdress />
<Link route="restaurants">Lista de Restaurantes</Link>
</div>
</div>
</main>
);
}
}
export default index;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.