text
stringlengths 7
3.69M
|
|---|
const lottoList = require('./lottoList.json')
var lottoSpecs = function (name) {
var specs = {}
for (var i in lottoList){
if (lottoList[i].name == name){
specs = lottoList[i]
}
}
return specs
}
module.exports = lottoSpecs;
|
<section class="result">
<header>
<img src="/images/icon-star.png" class="control_right">
<a class="event_link" data-bind="attr: { href: url, rel: $index }">
<img class="header_icon" src="/images/tmp_icon.png">
<h2 data-bind="text: name"></h2>
</a>
</header>
<ul>
<li>
<span class="date"><span data-bind="text: date"></span>
<span class="separator" data-bind="visible: time"> / </span>
<span data-bind="text: time"></span>
</li>
<li>
<span class="loc">
<span data-bind="text: venue"></span>
<span data-bind="text: neighborhood"></span>
<span class="separator" data-bind="visible: city"> / </span>
<span data-bind="text: city"></span><span data-bind="visible: state">,</span> <span data-bind="text: state"></span>
<span class="separator" data-bind="visible: distance"> / </span>
<span data-bind="text: distance"></span>
</li>
</ul>
</section>
|
var React = require('react');
var startSingalR = require('../js/signalR/StartSignalR.js');
var ClientSideViewModelUpdates = require('../js/view-model-updates/ClientSide.js');
var _ = require('underscore');
var Router = require('../js/router/Router.js');
var Home = require('./home/Home.jsx');
var ErrorFeed = require('./generic-ui/errors/Errors.jsx');
var LogIn = require("./generic-ui/login/LogIn.jsx");
var Four0Four = require('./generic-ui/four0four/Four0Four.jsx');
var Loader = require('./generic-ui/loader/Loader.jsx');
Router.initialize([
{
pattern: "Home",
page: "Home",
getView: function(state) {
return <Home HelloMessageViewModel={state.HelloMessageViewModel}></Home>;
}
},{
pattern: ".*",
page: "404",
disableUrlUpdates: true,
getView: function() {
return <Four0Four></Four0Four>;
}
}
], "Home");
module.exports = React.createClass({
getInitialState: function () {
return Router.getViewModelFromUrl();
},
componentDidMount: function () {
ClientSideViewModelUpdates.initialize(_.bind(this.setState, this), _.bind(this.replaceState, this));
startSingalR(_.bind(this.setState, this), _.bind(this.replaceState, this));
},
componentDidUpdate: function() {
Router.updateUrlHash(this.state);
},
render: function () {
var view;
if (this.state.UserAuthenticationFinished) {
view = this.state.User ? Router.getView(this.state) : <LogIn />;
} else {
view = <Loader text="Authenticating..."></Loader>;
}
return (
<div>
<div>
{view}
</div>
<ErrorFeed newErrorMessage={this.state.Error}></ErrorFeed>
</div>
);
}
})
|
import api from '../services/api';
import { useMutation } from 'react-query';
export default function useAddComment() {
return useMutation((data) => api.post(`posts`, data));
}
|
import React from 'react';
import { shallow } from 'enzyme';
import ContactForm from '../../components/ContactForm';
import contacts from '../fixtures/contacts';
let getFormData;
beforeEach(() => {
getFormData = jest.fn();
});
test('should render correctly on AddContactPage', () => {
const wrapper = shallow(<ContactForm page="addContact" getFormData={getFormData} />);
expect(wrapper).toMatchSnapshot();
});
test('should render correctly on EditContactPage', () => {
const wrapper = shallow(<ContactForm page="editContact" getFormData={getFormData} contact={contacts[0]} />);
expect(wrapper).toMatchSnapshot();
});
|
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import GA from '../utils/GoogleAnalytics';
import LandingPage from '../pages/landingPage.js';
// import Signup from '../pages/onboarding/signup';
// import Signup1 from '../pages/onboarding/signup1';
// import Signup2 from '../pages/onboarding/signup2';
// import Signup3 from '../pages/onboarding/signup3';
// import Signup4 from '../pages/onboarding/signup4';
// import Signup5 from '../pages/onboarding/signup5';
// import Signup52 from '../pages/onboarding/signup52';
// import Welcome from '../pages/onboarding/welcome';
// import Profile from '../pages/profile';
// import Tasks from '../pages/tasks';
import PressPage from '../pages/pressPage.js';
import About from '../pages/about.js';
import Story from '../pages/story.js';
import Platform from '../pages/platform.js';
import Partners from '../pages/partners.js';
// import GridPage from '../pages/gridPage.js';
// import News from '../pages/news.js';
// import NewsArticle from '../pages/newsArticle.js';
const AppRouter = () => (
<BrowserRouter>
<div>
{ GA.init() && <GA.RouteTracker /> }
<Switch>
<Route path="/" component={LandingPage} exact={true} />
{/*
<Route path="/signup" component={Signup} exact={true} />
<Route path="/signup/1" component={Signup1} exact={true} />
<Route path="/signup/2" component={Signup2} exact={true} />
<Route path="/signup/3" component={Signup3} exact={true} />
<Route path="/signup/4" component={Signup4} exact={true} />
<Route path="/signup/5" component={Signup5} exact={true} />
<Route path="/signup/52" component={Signup52} exact={true} />
<Route path="/welcome" component={Welcome} exact={true} />
<Route path="/tasks" component={Tasks} exact={true} />
<Route path="/profile" component={Profile} exact={true} />
*/}
{/* <Route path="/news" component={News} exact={true} /> */}
<Route path="/press" component={PressPage} exact={true} />
<Route path="/roadmap" component={About} exact={true} />
<Route path="/story" component={Story} exact={true} />
<Route path="/platform" component={Platform} exact={true} />
<Route path="/partners" component={Partners} exact={true} />
{/* <Route path="/news/:slug" component={NewsArticle} exact={true} /> */}
{/* <Route path="/grid" component={GridPage} exact={true} /> */}
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
|
// @flow strict
import * as React from 'react';
import { View } from 'react-native';
import { StyleSheet } from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import AppleWalletScene from '../scenes/appleWallet/AppleWalletScene';
import WalletContext from '../context/WalletContext';
type PropsWithContext = {|
+setSelectedSegment: (segmentId: string | null) => void,
|};
class AppleWalletScreen extends React.Component<PropsWithContext> {
componentWillUnmount() {
this.props.setSelectedSegment(null);
}
render() {
return (
<View style={styles.container}>
<AppleWalletScene />
</View>
);
}
}
export default function AppleWalletScreenWithContext() {
return (
<WalletContext.Consumer>
{({ actions: { setSelectedSegment } }) => (
<AppleWalletScreen setSelectedSegment={setSelectedSegment} />
)}
</WalletContext.Consumer>
);
}
AppleWalletScreenWithContext.navigationOptions = () => ({
headerStyle: {
backgroundColor: 'transparent',
},
headerTransparent: true,
headerTintColor: defaultTokens.paletteWhite,
});
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
|
import { StyleSheet } from 'react-native'
export default StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
inputTitle: {
fontSize: 15,
fontWeight: '500',
marginLeft: 20
},
input: {
height: 40,
marginLeft: 20,
marginRight: 20,
borderWidth: 1,
borderRadius: 8,
marginTop: 5,
paddingLeft: 5,
},
button: {
marginLeft: 20,
marginRight: 20,
marginTop: 20,
backgroundColor: '#ff0000',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 8,
height: 40
},
buttonTitle: {
fontSize: 15,
color: 'white'
}
})
|
/*
var c = 1
while (c <= 6) {
console.log(`Passo ${c}`)
c++
}
*/
/*
var c = 1
do {
console.log(`Passo ${c}`)
c++
}
while (c <= 6)
*/
console.log('Vai comecar...')
for (var c = 1; c <= 5; c++) {
console.log(`Passo ${c}`)
}
console.log(`Fim!`)
|
import React, { Component } from 'react';
import {
BrowserRouter as Router, // we can declare aliases for our imports
Route,
Link,
hashHistory } from 'react-router-dom'; // importing all our react-router business
// import Nav from '../components/Nav';
// import Header from '../components/Header';
// import Footer from '../components/Footer';
import Archives from './Archives';
import Featured from './Featured';
import Layout from './Layout';
import Settings from './Settings';
export default class App extends Component {
constructor(){
super();
this.state = {
title: "Welcome",
username: "placeholderForUser",
history: null,
// location: ''
}
this.changeGreeting = this.changeGreeting.bind(this);
}
changeGreeting(username){
this.setState({ username })
}
render(){
// const { history } = this.props;
// console.log(history.isActive("/archives"));
const { username, title, history, location } = this.state;
return(
<Router history={ hashHistory }>
<div>
<Layout changeGreeting={this.changeGreeting} title={title} username={username} location={location}> </Layout>
{/* Router uses these to know what components to render */}
<Route exact path="/" component={Featured} />
{/* if we want to pass props to our routes, we need an anonymous function that returns our Component as jsx */}
<Route path="/archives/:article" component={Archives} />
<Route path="/settings" component={Settings} />
</div>
</Router>
);
}
}
// return(
// <Router history={ history }>
// <div>
// <Header changeGreeting={this.changeGreeting} title={title} username={username} />
// <h2>Layout is here!</h2>
// <Nav />
// {/* Router uses these to know what components to render */}
// <Route exact path="/" component={Featured} />
// {/* if we want to pass props to our routes, we need an anonymous function that returns our Component as jsx */}
// <Route path="/archives/:article" component={Archives} />
// <Route path="/settings" component={Settings} />
// <Footer />
// </div>
// </Router>
|
//Import packages
const express = require('express')
const path = require('path')
const cors = require('cors')
const bodyParser = require('body-parser')
//Initialize app
const app = express()
//Import script
const poll = require('./routes/poll')
//Set public folder
app.use(express.static(path.join(__dirname, 'public')))
//Body parsing
app.use(express.json())
//Cross-domain enabling
app.use(cors())
//Routing
app.use('/poll', poll )
//Port
const port = 3000
const server = app.listen(port, ()=> console.log(`Server started on port ${port}`))
//Handle unhandled promise rejections
// process.on("unhandledRejection", (err, promise) => {
// console.log(`Error: ${err.message}`.red);
// //close server and exit process
// server.close(() => process.exit(1));
// });
|
import React from "react";
import { useHistory } from "react-router-dom";
import Template from "../components/templates/MainPageTemplate";
import useCoops from "../hooks/useCoops";
import axios from "axios";
const MainPage = () => {
const { push } = useHistory();
const coopsData = useCoops();
const handleGoNewToCoop = () => push("/coop-add");
//console.log(coopsData);
return (
<Template
coopsData={coopsData}
onClickNewCoop={handleGoNewToCoop}
/>
);
};
export default MainPage;
|
'use strict';
chrome.runtime.onInstalled.addListener(() => {
console.log('onInstalled...');
// create alarm after extension is installed / upgraded
chrome.alarms.create('refresh', { periodInMinutes: 1 });
});
//This will be ran every minute checking if the video has changed
chrome.alarms.onAlarm.addListener((alarm) => {
console.log(alarm.name); // Prints alarm's name aka refresh
getYoutubeTab();
console.log('done');
});
//Gets every single tab of my browswer
function getTabs(){
const queryOptions = {
currentWindow: true
}
return new Promise((resolve, reject) => {
try {
chrome.tabs.query(queryOptions, function(tabs){
resolve(tabs);
})
} catch(error) {
reject(`Error is ${error}`)
}
})
}
function saveTab(key, obj){
chrome.storage.sync.set({key: obj});
}
function getTab(key){
return new Promise((resolve, reject) =>{
try {
chrome.storage.sync.get(key, function(data){
resolve(data[key]);
})
} catch(error){
reject(`Error is ${error}`)
}
})
}
//Gets all my tabs then sorts through all of them and finds the youtube ones
async function getYoutubeTab(){
const urls = await getTabs();
var youtubeTabs = []
for(var i =0;i<urls.length; i++){
//If the tab is active and includes youtube in the url
if(urls[i]['url'].includes('youtube') && urls[i]['active'] == true){
youtubeTabs.push(urls[i]);
//if the url has youtube and is playing in the background
} else if (urls[i]['url'].includes('youtube') && urls[i]['active'] == false && urls[i]['audible'] == true){
youtubeTabs.push(urls[i]);
}
}
console.log(youtubeTabs);
const oneTab = youtubeTabs[0];
console.log(oneTab);
var tabDetails = {
"Title": oneTab['title'].slice(0, -10),
'url': oneTab['url'],
'timeSpentWatching': new Date()
}
console.log(oneTab['title'].slice(0, -10));
chrome.storage.sync.set({'title': oneTab['title'].slice(0, -10)});
var dataTitle = await getTab('title');
console.log(dataTitle);
chrome.runtime.sendMessage({
msg: "Data Transfer",
data: {
subject: "Data",
content: dataTitle
}
});
}
|
/*
import request from '../utils/request';
export function login({username, password}){
return request("/service/siwangyin/login", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({username:username, password:password})
});
}
*/
const users = [
{username:1, password:1},
{username:2, password:2},
{username:3, password:3},
];
export function login({username, password}){
//表单获得的值为string类型,这里是'=='而不是'===',filter方法返回为数组,验证数据时要注意。
return users.filter((user) => (user.username == username && user.password == password));
}
|
function validateForm() {
var x = document.forms["login_form"]["email"].value;
var y = document.forms["login_form"]["password"].value;
if (x == "" || x == null || y == "" || y == null) {
alert("Login form must be filled out");
return false;
}
}
function validateFormB(){
var a = document.forms["register_form"]["name"].value;
var x = document.forms["register_form"]["email"].value;
var y = document.forms["register_form"]["password"].value;
var b = document.forms["register_form"]["address"].value;
if (x == "" || x == null || y == "" || y == null || a== "" || a == null || b == "" || b == null) {
alert("Register form must be filled out");
return false;
}
}
|
import React from 'react'
import { shallow } from 'enzyme'
import ListControls from './ListControls'
describe('ListControls Component', () => {
it('should render', () => {
const component = shallow(<ListControls />)
expect(component.find('.c-list-controls').exists()).toBe(true)
})
it('should be able to toggle the controls open and closed', () => {
const analyticsMock = {
event: () => {},
}
const component = shallow(<ListControls analytics={analyticsMock} />)
const button = component.find('.o-button')
expect(component.find('.c-list-controls--is-open').exists()).toBe(false)
button.simulate('click')
component.update()
expect(component.find('.c-list-controls--is-open').exists()).toBe(true)
})
})
|
const styles = theme => ({
mainDiv: {
backgroundColor: '#171824',
minHeight: '100vh',
backgroundImage: "linear-gradient(to right top, #2f3038, #272930, #202228, #191b20, #121419, #0f1217, #0b0f15, #070c13, #0a0f17, #0e121a, #10151d, #121720)", width: '100%',
padding: 10
},
box: {
color:'grey',
margin: 'auto',
maxWidth: '450px',
},
buttonConfirm: {
textTransform: 'none',
backgroundColor: '#2a292f',
margin: 10,
width: 250,
heigth: 36.5,
color: 'white',
'&:hover': {
backgroundColor: '#43414d',
},
},
bootstrapFormLabel: {
fontSize: 18,
color:'white',
'&:focus': {},
},
bootstrapRoot: {
'label + &': {
marginTop: theme.spacing.unit * 2.5,
},
},
bootstrapInput: {
borderRadius: 8,
backgroundColor: '#5b605838',
color: 'white',
border: '1px solid #ced4da',
fontSize: 10,
height: '1.6875em',
width: '250px',
padding: '5px 6px',
transition: theme.transitions.create(['border-color', 'box-shadow']),
},
boxError: {
backgroundColor: '#f1d0cc',
maxWidth: 250,
padding: 15,
borderRadius: 8
},
boxSecondary: {
backgroundColor: '#ccccff',
maxWidth: 250,
padding: 15,
borderRadius: 8
},
logo:{
margin: 10
}
})
export default styles
|
var searchData=
[
['pressure_5foversample',['pressure_oversample',['../group__group__board__libs.html#ad35ab3377cb6752d200e4452e47d1f54',1,'xensiv_dps3xx_config_t']]],
['pressure_5frate',['pressure_rate',['../group__group__board__libs.html#a564c597b64e379d64f87e40a29e3cedc',1,'xensiv_dps3xx_config_t']]],
['prs_5fosr_5fscale_5fcoeff',['prs_osr_scale_coeff',['../group__group__board__libs.html#a6540ec2f68b4837d54cd1cbce39bd71b',1,'xensiv_dps3xx_t']]]
];
|
export const GET_HOME_LIST = 'GET_MOVIE_LIST'
export const SET_LOGIN_INFOR = 'SET_LOGIN_INFOR'
export const GET_MOVIEMAIN_INFOR = 'GET_MOVIEMAIN_INFOR'
|
var express = require('express');
var router = express.Router();
var msgResponse = require('../modules/public/msgResponse.js');
var session = require('express-session');
/* GET home page. */
router.get('/', function(req, res) {
msgResponse.doError(0,res);
//session.Session
});
module.exports = router;
|
var pw = {
version: '0.2.4'
};
(function() {
|
import { POST } from '../../constants/postContants';
export const selectPost = (post) => ({
type: POST.SELECT,
payload: post
});
export const updatePostTitle = (title) => ({
type: POST.UPDATE,
payload: { title }
});
export const updatePostContent = (content) => ({
type: POST.UPDATE,
payload: { content }
});
export const updatePostAuthor = (author) => ({
type: POST.UPDATE,
payload: { author }
});
export const updatePostCategories = (categories) => ({
type: POST.UPDATE,
payload: { categories }
});
|
import React, { Component } from 'react';
import './Footer.css';
class Footer extends Component {
render() {
return (
<footer>
<div className="container">
<div className="row">
<div className="col-sm-4 hidden-xs">
<div className="delivery">
<h2>Пицца на дом</h2>
<p>Моментальная доставка свежей, горячей пиццы прямо к вам домой или в офис</p>
</div>
</div>
<div className="col-sm-4 hidden-xs">
<div className="address">
<p><i className="fa fa-envelope-o" aria-hidden="true"></i> pizzanadom@yandex.ru</p>
<p><i className="fa fa-phone" aria-hidden="true"></i> +7(999)999-99-99</p>
<p><i className="fa fa-map-marker" aria-hidden="true"></i> Москва, Коломенское ш., дом 46а, оф. 345</p>
</div>
</div>
<div className="col-sm-4 col-xs-12">
<div className="socialbtn">
<h2> Мы в соц.сетях</h2>
<a href="#"><i className="fa fa-facebook" aria-hidden="true"></i> <span>Facebook</span></a>
<a href="#"><i className="fa fa-twitter" aria-hidden="true"></i><span>Twitter</span></a>
<a href="#"><i className="fa fa-vk" aria-hidden="true"></i><span>Вконтакте</span></a>
</div>
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;
|
'use strict';
const gulp = require('gulp');
const concat = require('gulp-concat');
/**
* task that concatenates all the scripts
*/
gulp.task('scripts', () => {
return gulp.src(['./assets/scripts/src/jquery-3.2.1.slim.js', './assets/scripts/src/popper.js', './assets/scripts/src/bootstrap.js', './assets/scripts/src/prism.js'])
.pipe(concat('main.js'))
.pipe(gulp.dest('./assets/scripts/'));
});
const minify = require('gulp-minify');
/**
* task that minifies all the scripts
*/
gulp.task('minify', () => {
gulp.src('./assets/scripts/main.js')
.pipe(minify({
ext:{
//src:'-debug.js',
min:'.min.js'
},
//exclude: ['tasks'],
//ignoreFiles: ['.combo.js', '-min.js']
}))
.pipe(gulp.dest('./assets/scripts/dist'))
});
const sass = require('gulp-sass');
/**
* task that compiles all sass to css
*/
gulp.task('sass', () => {
return gulp.src('./assets/stylesheets/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./assets/stylesheets/'));
});
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
const cleanCSS = require('gulp-clean-css');
/**
* task that minifies the compiled css
*/
gulp.task('minify-css', () => {
return gulp.src('./assets/stylesheets/main.css')
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest('./assets/stylesheets/dist'));
});
|
/**
* 1:任何数和自身异或都是0
* 2:任何数和0异或 是任何数本身
* 3:异或操作满足交换律和结合律
*/
function singleNumber(arr = [2, 2, 1]) {
let result = 0;
for (let i = 0; i < arr.length; i++) {
result ^= arr[i]
}
return result
}
console.log(singleNumber()) // output: 1
|
'use strict';
let name = prompt("What is your name?");
alert("Welcome to my website" + " " + name)
alert("This is my gussing game")
let score = 0;
question1();
question2();
question3();
question4();
question5();
question6();
question7();
function question1(){
let painting = prompt("Do you think I can draw? yes,no").toLowerCase();
switch (painting) {
case 'yes':
case 'y':
console.log('correct');
alert("correct");
score+=1;
break;
case 'no':
case 'n':
alert("incorrect answer");
break;
default:
alert("please answer yes or no ");
}
}
function question2(){
let styling = prompt("Do you think I like styling using CSS?yes,no").toLowerCase();
switch (styling) {
case 'yes':
case 'y':
console.log('correct');
alert("correct");
score+=1;
break;
case 'no':
case 'n':
alert("incorrect answer");
break;
default:
alert("None");
}
}
function question3(){
let colors = prompt("Do you think that My favorite color is blue? yes,no").toLowerCase();
switch (colors) {
case 'yes':
case 'y':
console.log('correct');
alert("correct");
score+=1;
break;
case 'no':
case 'n':
alert("incorrect answer");
break;
default:
alert("None");
}
}
function question4(){
let tarvel = prompt("Do I like traviling? yes,no").toLowerCase();
switch (tarvel) {
case 'yes':
case 'y':
console.log('correct');
alert("correct");
score+=1;
break;
case 'no':
case 'n':
alert("incorrect answer");
break;
default:
alert("None");
}
}
function question5(){
let personality = prompt("Do you think that I'm a logical person? yes,no").toLowerCase();
switch (personality) {
case 'yes':
case 'y':
console.log('correct');
alert("correct");
score+=1;
break;
case 'no':
case 'n':
alert("incorrect answer");
break;
default:
alert("None");
}
}
function question6(){
let num
for (let i = 1; i <= 4; i++) {
num = Number(prompt("guess my age?"))
if (num === 23) {
alert("That's correct");
console.log("correct answer " + num);
score+=1;
break;
}
else if (num > 23) {
alert("too high")
}
else if (num < 23) {
alert("too low")
}
}
if (num != 23)
alert("My age is 23")
}
function question7(){
let places
let favplaces = ['France', 'Tokyo', 'Colombia', 'Italy', 'Singapore', 'Maldives', 'New Zeland', 'Bali', 'Cyprus', 'United Kingdom'];
for (let x = 1; x <= 6; x++) {
places = (prompt("What is my favorite places I want to visit? you can choose from: Tokyo, France, Eygpt, Dubai, Bali"))
console.log(places + " user answer");
let j;
for ( j = 0; j < favplaces.length; j++) {
console.log(favplaces[j] + "correct answer");
if (places == favplaces[j]) {
alert("That's corresct");
console.log("correct answer" + places);
score+=1;
break;
}
}
if(places == favplaces[j]){
break;
}
else{
alert("incorrect answer");
}
}
}
alert("You finished your attempet and this is the correct answer: France, Tokyo, Colombia, Italy, Singapore, Maldives, New Zeland, Bali, Cyprus, United Kingdom");
alert("you score is " + score +" out of 7");
alert("Thank you for visiting my Website " + name);
|
import BookUpdateContainer from './BookUpdateContainer'
export default BookUpdateContainer
|
angular
.module('uponnyc')
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home/home.html',
controller: 'HomeController as vm'
})
.state('causes', {
url: '/causes',
templateUrl: 'causes/index.html',
controller: 'CausesController as vm',
resolve: {
causes: ['CausesService', function(CausesService) {
return CausesService.getCauses();
}
]}
})
.state('causes.show', {
url: '/:id/events',
templateUrl: 'causes/show.html',
controller: 'CauseController as vm',
resolve: {
cause: ['$stateParams', 'CausesService', function($stateParams, CausesService) {
return CausesService.getCause($stateParams);
}
]}
})
.state('causes.new', {
url: '/:id/events/new',
templateUrl: 'events/new.html'
})
.state('causes.event', {
url: '/:causeId/events/:eventId',
templateUrl: 'events/show.html',
controller: 'EventsController as vm',
resolve: {
event: ['$stateParams', 'EventsService', function($stateParams, EventsService) {
return EventsService.getEvent($stateParams);
}
]}
})
$urlRouterProvider.otherwise('/')
}])
|
'use strict';
import Base from './base';
import Constants from './constants';
import Immutable from 'immutable';
export default class Chord extends Base {
constructor(fns) {
super();
this.__fns = Array.prototype.slice.call(fns);
this.__doneFns = new Immutable.Set();
this.__currentFn = -1;
this.__changeEvent = 'chord-change';
}
__doStep(step) {
this.__emit(Constants.StepStatus.STARTED, null, step);
let stepNum = this.__currentFn;
if (step instanceof Base) {
step.on(Constants.States.FINISHED, () => {
this.finishStep(step, stepNum);
});
step.on(Constants.States.FAILED, () => {
let error = step.getState('error');
if (error == null) {
error = step.getState('errors', `step ${step.name} failed`);
}
this.finishStep(step, stepNum, error);
});
// Going to the next step is safer than calling start
// because the Flow could have already started.
step.gotoNextStep();
}
else {
try {
step(
this,
() => this.finishStep(step, stepNum),
(e) => this.finishStep(step, stepNum, e)
);
}
catch (e) {
this.finishStep(step, stepNum, e);
}
}
this.gotoNextStep();
}
__handleError(step, error) {
let errors = this.getState('errors', new Immutable.List());
errors = errors.push(error);
this.setState({errors});
this.failStep(step);
}
__gotoNextStep() {
if (this.hasNextStep()) {
this.__currentFn = this.__currentFn + 1;
}
}
addStep(step) {
this.__fns.push(step);
}
failStep(step) {
this.__emit(Constants.StepStatus.FAILED, null, step);
if (this.isFinished() && this.getState('errors').size === this.__fns.length) {
this.__readyState = this.__readyState.add(
Constants.States.FAILED
);
this.__emit(Constants.States.FAILED, Constants.States.FAILED, step);
}
}
finishStep(step, stepNum, opt_error) {
if (this.__fns[stepNum] !== step) {
throw `Got incorrect step num '${stepNum}' for step`;
}
this.__doneFns = this.__doneFns.add(stepNum);
if (opt_error != null) {
this.__handleError(step, opt_error);
}
else {
this.__emit(Constants.StepStatus.FINISHED, null, step);
}
let isFinished = this.__fns.every((_, i) => {
return this.__doneFns.has(i);
});
if (isFinished) {
this.finish();
}
}
getCurrentFn() {
if (this.__currentFn > -1 && this.__currentFn < this.__fns.length) {
return this.__fns[this.__currentFn];
}
return null;
}
gotoNextStep() {
if (!this.isStarted()) {
this.start();
return;
}
if(this.hasNextStep()) {
this.__gotoNextStep();
// The naming here really sucks.
// With a Chord there is no concept of a "current function" because
// functions could be async. This needs a better name.
let step = this.getCurrentFn();
this.__doStep(step);
}
}
hasNextStep() {
return (!this.isFinished() &&
!this.isLastStep() &&
this.__currentFn < this.__fns.length);
}
isFinished() {
let isFinished = this.__fns.every((_, i) => {
return this.__doneFns.has(i);
});
return isFinished;
}
isLastStep() {
return this.__currentFn === this.__fns.length -1;
}
}
|
import React from 'react';
import {Route, NavLink} from 'react-router-dom';
import routes from './routes';
const routesList = routes.map(route => {
return (
<Route
key={route.name}
path={route.path}
component={route.component}
exact={route.exact}
/>
)
});
const navList = routes.map(route => {
if (route.menu) {
return (
<NavLink
key={route.name}
to={route.path}
activeClassName="disabled"
className="btn btn-dark"
exact
>
{route.placeholder}
</NavLink>
)
}
});
let routesMap = {};
routes.map(route => {
routesMap[route.name] = route.path;
});
export {routesList, navList, routesMap};
|
import React from 'react/addons'
import assign from 'react/lib/Object.assign'
import Cloudinary from 'Cloudinary'
import cx from "classnames"
import EditGroupLocation from './components/EditGroupLocation'
import EditGroupName from './components/EditGroupName'
import EditHeader from './components/EditHeader'
import EditLogo from './components/EditLogo'
import Emojify from 'Emojify'
import GroupActions from 'GroupActions'
import GroupDistance from 'GroupDistance'
import GroupStore from 'GroupStore'
import Icon from 'Icon'
import Loading from 'Loading'
import Redirect from 'Redirect'
import RemoveGroup from './components/RemoveGroup'
import ShoutFeed from 'ShoutFeed'
import { Button } from 'forms/material/Material'
import { Card, CardContent, CardTitle } from 'Card'
import { Grid, Cell } from 'Grid'
import { Tab, TabPanel } from 'Tab'
let GroupPage = React.createClass({
statics: {
willTransitionTo(transition, params, query) {
GroupActions.fetchGroupInformation(params.groupId)
}
},
getInitialState() {
return assign(GroupStore.getState(), {
editHeaderFormOpen: false,
editLogoFormOpen: false,
headerWidth: 800,
logoHover: false
})
},
componentDidMount() {
GroupStore.listen(this._onChange)
window.addEventListener('resize', this.calcHeaderWidth)
this.calcHeaderWidth()
},
componentWillUnmount() {
GroupStore.unlisten(this._onChange)
window.removeEventListener('resize', this.calcHeaderWidth)
},
_onChange(state) {
this.setState(state)
},
calcHeaderWidth(force) {
if ( ! this.refs.header) {
setTimeout(() => {
this.calcHeaderWidth(true)
}, 200)
return
}
let width = React.findDOMNode(this.refs.header).offsetWidth
if (Math.abs(width - this.state.headerWidth) > 30) {
this.setState({ headerWidth: width })
}
if(force) {
this.setState({ headerWidth: width })
}
},
changeTab(tabId) {
Redirect.replaceWith('group', {
tabId,
groupId: this.props.params.groupId
})
},
leaveGroup() {
GroupActions.leaveGroup(this.state.group.id)
},
joinGroup() {
GroupActions.joinGroup(this.state.group.id)
},
editLogo() {
this.setState({ editLogoFormOpen: true })
},
editHeader() {
this.setState({ editHeaderFormOpen: true })
},
updateGroup(data) {
let { group } = this.state
group = assign({}, group, data)
this.setState({ group })
},
hoverLogo() {
this.setState({ logoHover: ! this.state.logoHover })
},
onLogoEdited() {
this.setState({ editLogoFormOpen: false })
},
onHeaderEdited() {
this.setState({ editHeaderFormOpen: false })
},
removeGroup() {
Redirect.to('home')
},
render() {
let { loading } = this.state
return (
<div className="container">
{loading ? (
<Loading />
) : this.renderGroup()}
</div>
)
},
renderGroup() {
let { group, leavingOrJoiningGroupLoading, editLogoFormOpen, editHeaderFormOpen, logoHover, headerWidth } = this.state
let { params } = this.props
let memberCount = group.meta.member_count
let inGroup = group.meta.in_group
let isAdmin = group.meta.my_type == "admin"
let logoClass = cx({
"group__logo": true,
"group__logo--change": isAdmin && logoHover
})
return (
<div className="group">
{isAdmin && editLogoFormOpen && (
<EditLogo
groupId={group.id}
image={group.header_data.secure_url}
isOpen={editLogoFormOpen}
onDone={this.onLogoEdited}
/>
)}
{isAdmin && editHeaderFormOpen && (
<EditHeader
groupId={group.id}
image={group.header_data.secure_url}
isOpen={editHeaderFormOpen}
onDone={this.onHeaderEdited}
/>
)}
<Grid>
<Cell center>
<div className="group__header" ref="header">
<Cloudinary
fallbackHeight={Math.round(headerWidth / (21/9))}
image={group.header_data}
options={{width: headerWidth}}
style={{position:'relative'}}
defaultElement={<h1 className="center-both" style={{
color: 'rgba(0, 0, 0, 0.4)',
margin: 0
}}><Emojify>{group.name}</Emojify></h1>}
/>
<div className="group__header__buttons">
{isAdmin && (
<Button onClick={this.editHeader}>
Wijzig Afbeelding
</Button>
)}
<Button
disabled={(inGroup && memberCount == 1) || isAdmin}
onClick={() => {inGroup ? this.leaveGroup() : this.joinGroup()}}
>
{leavingOrJoiningGroupLoading && (
<Icon className="right" icon="loop" spinning/>
)}
{group.meta.in_group ? (
<span>Groep Verlaten</span>
) : (
<span>Lid Worden</span>
)}
</Button>
</div>
</div>
</Cell>
<Cell>
<Card style={{marginTop: 0, marginBottom: 0}} className="no-shadow group__information">
<CardContent>
<Grid style={{marginBottom: 0}}>
<Cell width={6/12}>
<div className={logoClass} onClick={this.editLogo} onMouseLeave={this.hoverLogo} onMouseEnter={this.hoverLogo}>
<Cloudinary
image={group.logo_data}
options={{ width: 100, height: 100, crop: 'fill' }}
defaultElement={<h1 className="center-both" style={{
color: 'rgba(0, 0, 0, 0.4)',
fontWeight: 'bold',
margin: 0
}}>{group.name.substr(0, 1).toUpperCase()}</h1>}
/>
</div>
<h4 className="left" style={{marginLeft: 20}}>
<Emojify>{group.name}</Emojify>
</h4>
</Cell>
<Cell width={6/12}>
<div className="right">
<GroupDistance group={group} badge/>
<span className="group-badge">
{memberCount} {memberCount == 1 ? 'lid' : 'leden'}
</span>
</div>
</Cell>
</Grid>
</CardContent>
</Card>
</Cell>
<Cell>
<Tab className="white" marginTop={0} activeTab={params.tabId} onTabChange={this.changeTab}>
<TabPanel title="Shouts" tabId="shouts">
<Grid>
<Cell width={9/12}>
<ShoutFeed
canShout={inGroup}
groupId={group.id}
url={`shouts/group/${group.id}`}
/>
</Cell>
</Grid>
</TabPanel>
{isAdmin && (
<TabPanel title="Beheer" tabId="manage">
<Grid>
<Cell width={6/12}>
<EditGroupName
group={group}
onChange={this.updateGroup}
/>
<RemoveGroup
group={group}
onDelete={this.removeGroup}
/>
</Cell>
<Cell width={6/12}>
<EditGroupLocation
group={group}
onChange={this.updateGroup}
/>
</Cell>
</Grid>
</TabPanel>
)}
</Tab>
</Cell>
</Grid>
</div>
)
}
})
export default GroupPage
|
if (typeof Global === "undefined") {
Global = {};
}
if (!Global.organizationLoader) {
Global.organizationLoader = new Disco.Ext.MemoryTreeLoader({
iconCls: 'disco-tree-node-icon',
varName: "Global.DEPARTMENT_NODES",
url: "organization.java?cmd=getTree&page Size=-1&treeData=true&all=false",
listeners: {
'beforeload': function(treeLoader, node) {
treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : "");
if (typeof node.attributes.checked !== "undefined") {
treeLoader.baseParams.checked = false;
}
}
}
});
}
if (!Global.platformMenuLoader) {
Global.platformMenuLoader = new Disco.Ext.MemoryTreeLoader({
iconCls: 'disco-tree-node-icon',
varName: "Global.PLATFORM_MENU_NODES",
url: "systemMenu.java?cmd=getTree&pageSize=-1&treeData=true&all=true",
listeners: {
'beforeload': function(treeLoader, node) {
treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : "");
if (typeof node.attributes.checked !== "undefined") {
treeLoader.baseParams.checked = false;
}
}
}
});
}
if (typeof RoleList === "undefined") {
RoleList = Ext.extend(BaseGridList, {
url: "role.java?cmd=list",
loadData: true,
storeMapping: ["id", "name", "title", "description"],
initComponent: function() {
var chkM = new Ext.grid.CheckboxSelectionModel();
this.gridConfig = {
sm: chkM
}, this.cm = new Ext.grid.ColumnModel([chkM, {
header: "编码",
sortable: true,
width: 60,
dataIndex: "name"
}, {
header: "名称",
sortable: true,
width: 120,
dataIndex: "title"
}, {
header: "简介",
sortable: true,
width: 100,
dataIndex: "description"
}])
RoleList.superclass.initComponent.call(this);
}
});
}
if (typeof PermissionList === "undefined") {
PermissionList = Ext.extend(BaseGridList, {
pageSize: 20,
loadData: true,
url: "permission.java?cmd=list",
storeMapping: ["id", "name", "description"],
quickSearch: function() {
this.grid.store.removeAll();
this.grid.store.reload({
params: {
searchKey: this.btn_search.getValue(),
start: 0
}
});
},
initComponent: function() {
var chkM = new Ext.grid.CheckboxSelectionModel();
this.gridConfig = {
sm: chkM
}, this.cm = new Ext.grid.ColumnModel([chkM, {
header: "权限名",
sortable: true,
width: 60,
dataIndex: "name"
}, {
header: "简介",
sortable: true,
width: 100,
dataIndex: "description"
}]);
this.btn_search = new Ext.form.TextField({
width: 100
});
this.tbar = ["关键字:", this.btn_search, {
text: "查询",
handler: this.quickSearch,
scope: this,
cls: "x-btn-text-icon",
icon: "img/icon-png/search.png"
}];
PermissionList.superclass.initComponent.call(this);
}
});
}
if (typeof DeptList === "undefined") {
DeptList = Ext.extend(BaseGridList, {
url: "department.java?cmd=listAll",
loadData: true,
storeMapping: ["id", "title", "sn", "admin", "parent"],
initComponent: function() {
var chkM = new Ext.grid.CheckboxSelectionModel();
this.gridConfig = {
sm: chkM
}, this.cm = new Ext.grid.ColumnModel([chkM, {
header: "名称",
sortable: true,
width: 60,
dataIndex: "title"
}, {
header: "编号",
sortable: true,
width: 120,
dataIndex: "sn"
}, {
header: "所属机构",
sortable: true,
width: 60,
dataIndex: "parent",
renderer: Disco.Ext.Util.objectRender("title")
}, {
header: "管理员",
sortable: true,
width: 100,
dataIndex: "admin",
renderer: Disco.Ext.Util.objectRender("trueName")
}])
DeptList.superclass.initComponent.call(this);
}
});
}
/**
* 员工信息管理
*
* @class EmployeePanel
* @extends Disco.Ext.CrudPanel
*/
EmployeePanel = Ext.extend(Disco.Ext.CrudPanel, {
pageSize: 20,
importData: true,
exportData: true,
importExplain: '用户数据导入规则<br />1、id 不为空时更新数据 否则插入数据<br />2、用户名不能为空,用户名存在更新该用户数据。<br />3、密码不能为空,如果长度为32位则不加密否则系统自动加密。密码建议长度小于16位。<br />4、用户所在机构如果必须为数字类型,如果为空则用户导入后不属于任何机构。<br />6、员工类型录入数字 1、撰稿人 2、部门支行管理员4、部门支行审核人 5、分行管理员 6、其它类型',
baseUrl: "employee.java",
gridSelModel: 'checkbox',
initQueryParameter: {
status: 1
},
//用户类别数据,主要用来控制数据权限
employeeTypes: [["撰稿人", 1], ["部门支行管理员", 2], ["部门支行审核人", 4], ["分行管理员", 5], ["其它类型", 6]],
searchWin: {
width: 550,
height: 225,
title: "高级查询"
},
viewWin: {
width: 800,
height: 465,
title: "员工信息"
},
choiceSelectGridData: function(grid, winName, gridList, winTitle) {
return function() {
var theGrid = this[grid];
if (!this[winName]) {
var glist = eval("new " + gridList);
this[winName] = new Disco.Ext.GridSelectWin({
border: false,
hideBorders: true,
title: winTitle,
width: 650,
grid: glist
});
this[winName].on("select", function(datas) {
var ds = [];
for (var i = 0; i < datas.length; i++) {//过滤掉重复的内容
if (theGrid.store.find("id", datas[i].id) < 0)
ds[ds.length] = datas[i];
}
theGrid.store.loadData(ds, true);
}, this);
}
this[winName].show();
}
},
selectOtherDepts: function() {
var record = this.grid.getSelectionModel().getSelected();
if (!this.otherDepts) {
var treeLoader = new Disco.Ext.MemoryTreeLoader({
preloadChildren: true,
baseAttrs: {
checked: false
},
iconCls: 'disco-tree-node-icon',
varName: "Global.DEPARTMENT_NODES2",
url: "organization.java?cmd=getTree&treeData=true&all=true&checked=true",
listeners: {
'beforeload': function(treeLoader, node) {
treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : "");
if (typeof node.attributes.checked !== "undefined") {
treeLoader.baseParams.checked = false;
}
}
}
});
var deptGrid = this.deptGrid;
treeLoader.remoteObject.on("load", function(cd, datas) {
if (datas) {
deptGrid.getStore().each(function(record) {
datas.getNodeById(record.get('id')).checked = true;
});
}
});
this.otherDepts = new Ext.tree.TreePanel({
rootVisible: false,
autoScroll: true,
listeners: {
scope: this,
checkchange: function(node, checked) {
var fn = function(n) {
if (n.getUI() && n.getUI().checkbox) {
n.getUI().checkbox.checked = checked;
n.attributes.checked = checked;
}
};
node.cascade(fn);
}
},
loader: treeLoader,
root: new Ext.tree.AsyncTreeNode({
id: 'root',
text: '根节点',
expanded: true
})
});
} else {
this.otherDepts.getRootNode().cascade(function(node) {
var ui = node.getUI();
if (ui && ui.checkbox) {
var checked = false;
ui.checkbox.defaultChecked = checked;
ui.checkbox.checked = checked;
ui.node.attributes.checked = checked;
}
}, this);
}
Disco.Ext.Window.show({
width: 400,
height: 400,
title: '组织机构树',
border: false,
items: this.otherDepts,
single: false,
scope: this,
buttons: ['yes', 'no'],
handler: function(btn, win, tree) {
var t = tree;
if (btn == 'yes') {
var arr = t.getChecked('id');
var nodes = [];
Ext.each(arr, function(key) {
var node = this.otherDepts.getNodeById(key);
var attr = node.attributes;
nodes.push({
id: attr.id,
title: attr.text
});
}, this);
this.deptGrid.store.loadData(nodes);
}
win.hide();
}
});
this.otherDepts.expandAll();
this.deptGrid.getStore().each(function(record) {
var id = record.get('id');
var node = this.otherDepts.getNodeById(id);
if (node) {
var checked = true;
var ui = node.getUI();
ui.checkbox.defaultChecked = checked;
ui.checkbox.checked = checked;
ui.node.attributes.checked = checked;
}
}, this);
},
createPermissionPanel: function(loader, checkBox, gridListeners, treeBaseConfig, gridName, treeName) {
var cm = [new Ext.grid.RowNumberer({
header: "序号",
width: 40
}), {
header: "ID",
dataIndex: "id",
hideable: true,
hidden: true
}, {
header: "权限名称",
dataIndex: "name",
width: 100
}];
if (checkBox)
cm.unshift(checkBox);
var gridpanel = new Ext.grid.GridPanel(Ext.apply({
region: 'center',
viewConfig: {
forceFit: true
},
sm: checkBox || new Ext.grid.RowSelectionModel(),
border: false,
cm: new Ext.grid.ColumnModel(cm),
store: new Ext.data.JsonStore({
id: 'id',
root: "result",
totalProperty: "rowCount",
url: 'systemMenu.java?cmd=loadPermissions',
fields: ['id', 'name', 'description']
})
}, gridListeners || {}));
if (gridName)
this[gridName] = gridpanel;
var tree = new Ext.tree.TreePanel(Ext.apply({
region: "west",
autoScroll: true,
border: false,
width: 200,
margins: '0 2 0 0',
tools: [{
id: "refresh",
handler: function() {
this[treeName].root.reload();
},
scope: this
}],
root: new Ext.tree.AsyncTreeNode({
id: "root",
text: "所有菜单",
expanded: true,
iconCls: 'treeroot-icon',
loader: loader || Global.platformMenuLoader
})
}, treeBaseConfig || {}));
if (treeName)
this[treeName] = tree;
var panel = new Ext.Panel({
layout: 'border',
region: 'center',
border: false,
hideBorders: true,
items: [gridpanel, tree]
});
panel.grid = gridpanel;
panel.tree = tree;
return panel;
},
createRolePanel: function() {
var sm = new Ext.grid.CheckboxSelectionModel();
this.roleGrid = new Ext.grid.GridPanel({
sm: sm,
region: "west",
width: 350,
bodyStyle: 'border:none;border-right:2px;',
viewConfig: {
forceFit: true
},
cm: new Ext.grid.ColumnModel([sm, new Ext.grid.RowNumberer({
header: "序号",
width: 40
}), {
header: "ID",
dataIndex: "id",
hideable: true,
hidden: true
}, {
header: "角色编码",
sortable: true,
width: 70,
dataIndex: "name"
}, {
header: "名称",
sortable: true,
width: 100,
dataIndex: "title"
}, {
header: "简介",
sortable: true,
width: 80,
dataIndex: "desciption",
hidden: true
}]),
store: new Ext.data.JsonStore({
fields: ["id", "name", "title", "description"]
})
});
this.roleGrid.on('rowclick', function(g, r) {
var record = g.getStore().getAt(r);
var grid = this.rolePanel.getComponent(1).getComponent(0);
var tree = this.rolePanel.getComponent(1).getComponent(1);
tree.getSelectionModel().select(tree.getRootNode());
grid.getStore().removeAll();
Ext.Ajax.request({
url: 'role.java?cmd=loadPermission&other=loadSystemMenuTree',
params: {
id: record.get('id')
},
success: function(res) {
var data = Ext.decode(res.responseText);
if (data) {
grid.getStore().loadData(data);
tree.getRootNode().reload();
}
},
scope: this
});
}, this);
var treeBaseConfig = {
listeners: {
click: function(node) {
var grid = this['rolePermissionGrid'];
if (node.attributes.id == 'root') {
grid.getStore().clearFilter();
return;
}
Ext.Ajax.request({
url: 'systemMenu.java?cmd=loadPermissions',
params: {
systemMenuId: node.attributes.id
},
success: function(res) {
var data = Ext.decode(res.responseText);
if (data) {
var datas = data.result;
grid.getStore().filterBy(function(r) {
var isexist = false;
Ext.each(datas, function(o) {
if (r.get('id') == o.id) {
isexist = true;
return false;
}
})
if (isexist) {
return r;
}
});
} else {
grid.getStore().filterBy(function() {
}, this);
}
},
scope: this
})
},
scope: this
}
};
var loader = new Ext.tree.TreeLoader({
iconCls: 'disco-tree-node-icon',
url: 'role.java?cmd=getSystemMenuTree',
listeners: {
beforeload: function(treeLoader, node) {
treeLoader.baseParams = {};
var o = this.roleGrid.selModel.getSelected();
if (o) {
treeLoader.baseParams.roleId = o.get('id');
} else {
return false;
}
if (node.attributes.id != 'root') {
treeLoader.baseParams.id = node.attributes.id;
}
},
scope: this
}
});
this.rolePanel = new Ext.Panel({
layout: 'border',
title: "用户角色",
border: false,
bbar: [{
text: "添加角色",
cls: "x-btn-text-icon",
icon: "img/icons/application_form_add.png",
handler: this.choiceSelectGridData("roleGrid", "selectRoleWin", "RoleList", "选择角色"),
scope: this
}, {
text: "删除角色",
cls: "x-btn-text-icon",
icon: "img/icons/application_form_delete.png",
handler: function() {
Disco.Ext.Util.removeGridRows(this.roleGrid);
},
scope: this
}],
items: [this.roleGrid, this.createPermissionPanel(loader, null, null, treeBaseConfig, "rolePermissionGrid", 'systemMenu')]
});
return this.rolePanel;
},
createunEditPanel: function() {
var treeBaseConfig = {
listeners: {
click: function(node) {
var grid = this['disablePermissionsGrid'];
if (node.attributes.id == 'root') {
grid.getStore().removeAll();
grid.getStore().loadData({
rowCount: this['disablePermissionsGrid'].tempCheck.getCount(),
result: this['disablePermissionsGrid'].tempCheck.items
});
} else {
grid.getStore().removeAll();
grid.getStore().baseParams = {
systemMenuId: node.attributes.id
}
grid.getStore().load();
}
},
scope: this
}
}
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
selectionchange: function(sm) {
var grid = this['disablePermissionsGrid'];
grid.store.each(function(r) {
if (sm.isSelected(r)) {
this['disablePermissionsGrid'].tempCheck.add(r.data);
} else {
this['disablePermissionsGrid'].tempCheck.removeKey(r.get('id'));
}
}, this);
},
scope: this
}
});
this.disablePanel = new Ext.Panel({
layout: 'border',
title: "禁用权限",
border: false,
items: [this.createPermissionPanel(Global.platformMenuLoader, sm, null, treeBaseConfig, "disablePermissionsGrid", "disableSystemMenu")]
});
this['disablePermissionsGrid'].tempCheck = new Ext.util.MixedCollection();
this['disablePermissionsGrid'].store.on('datachanged', function() {
var arr = [];
var grid = this['disablePermissionsGrid'];
this['disablePermissionsGrid'].tempCheck.each(function(o) {
if (grid.getStore().getById(o.id)) {
arr.push(grid.getStore().getById(o.id));
}
}, this);
(function() {
grid.getSelectionModel().selectRecords(arr, true);
}).defer(1, this)
}, this);
return this.disablePanel;
},
createEditPanel: function() {
var treeBaseConfig = {
listeners: {
click: function(node) {
var grid = this.editPanel.getComponent(0).grid;
if (node.attributes.id == 'root') {
grid.getStore().removeAll();
grid.getStore().loadData({
rowCount: this['extraPermissionGrid'].tempCheck.getCount(),
result: this['extraPermissionGrid'].tempCheck.items
});
} else {
grid.getStore().removeAll();
grid.getStore().baseParams = {
systemMenuId: node.attributes.id
}
grid.getStore().load();
}
},
scope: this
}
}
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
selectionchange: function(sm) {
var grid = this.editPanel.getComponent(0).grid;
grid.store.each(function(r) {
if (sm.isSelected(r)) {
this['extraPermissionGrid'].tempCheck.add(r.data);
} else {
this['extraPermissionGrid'].tempCheck.removeKey(r.get('id'));
}
}, this);
},
scope: this
}
});
this.editPanel = new Ext.Panel({
layout: 'border',
title: "额外权限",
border: false,
items: [this.createPermissionPanel(Global.platformMenuLoader, sm, null, treeBaseConfig, 'extraPermissionGrid', 'extraSystemMenu')]
});
this['extraPermissionGrid'].tempCheck = new Ext.util.MixedCollection();
this['extraPermissionGrid'].store.on('datachanged', function() {
var arr = [];
var grid = this['extraPermissionGrid'];
this['extraPermissionGrid'].tempCheck.each(function(o) {
if (grid.getStore().getById(o.id)) {
arr.push(grid.getStore().getById(o.id));
}
}, this);
(function() {
grid.getSelectionModel().selectRecords(arr, true);
}).defer(1, this)
}, this);
return this.editPanel;
},
createForm: function() {
var sm = new Ext.grid.CheckboxSelectionModel();
this.deptGrid = new Ext.grid.GridPanel({
title: '额外机构',
sm: sm,
region: "west",
width: 250,
viewConfig: {
forceFit: true
},
cm: new Ext.grid.ColumnModel([sm, new Ext.grid.RowNumberer({
header: "序号",
width: 40
}), {
header: "ID",
dataIndex: "id",
hideable: true,
hidden: true
}, {
header: "机构名称",
sortable: true,
width: 70,
dataIndex: "title"
}, {
header: "所属机构",
sortable: true,
width: 70,
dataIndex: "parent",
renderer: this.objectRender("title")
}, {
header: "机构管理员",
sortable: true,
width: 100,
dataIndex: "admin",
renderer: this.objectRender("trueName")
}]),
store: new Ext.data.JsonStore({
fields: ["id", "sn", "title", "admin", "path"]
}),
bbar: [{
text: "添加机构",
cls: "x-btn-text-icon",
icon: "img/icons/application_form_add.png",
handler: this.selectOtherDepts,
scope: this
}, {
text: "删除机构",
cls: "x-btn-text-icon",
icon: "img/icons/application_form_delete.png",
handler: function() {
Disco.Ext.Util.removeGridRows(this.deptGrid);
},
scope: this
}]
});
var formPanel = new Ext.form.FormPanel({
labelWidth: 80,
labelAlign: 'right',
border: false,
items: [{
xtype: "hidden",
name: "id"
}, {
height: 327,
labelWidth: 80,
frame: true,
border: false,
items: Disco.Ext.Util.buildColumnForm({
fieldLabel: "用户名称",
name: "name",
allowBlank: false,
listeners: {
scope: this,
"blur": function(c) {
var me = this;
var v = c.getValue();
var id = me.fp.form.findField('id').getValue();
//鼠标离开时如果没有输入值或表单ID有值(编辑状态)都不验证用户名是否重复
if (v || id) {
return;
}
var successCallback = function(data) {
var r = Ext.decode(data);
if (r && !r.success) {
Ext.Msg.alert('提醒', '用户名重复,请重新录入一个新的用户名');
c.setValue(null);
c.focus();
me.fp.form.findField('email').setValue(null);
me.fp.form.findField('password').setValue(null);
} else {
me.fp.form.findField('password').setValue(v);
me.fp.form.findField('email').setValue(v + '@ibocomm.sh');
}
};
this.executeQuietlyUrl(this.baseUrl, {
name: v,
cmd: 'checkName'
}, successCallback)();
}
}
}, {
fieldLabel: "密 码",
name: "password",
inputType: "password",
allowBlank: false
}, {
fieldLabel: "真实姓名",
name: "trueName"
}, ConfigConst.BASE.sex, {
fieldLabel: "姓名拼音",
name: "namePy"
}, {
fieldLabel: "员工职务",
name: "duty"
}, {
fieldLabel: "移动电话",
name: "mobileTel"
}, {
fieldLabel: "住宅电话",
name: "homeTel"
}, {
fieldLabel: "电话分机",
name: "telExt"
}, {
fieldLabel: "办公电话",
name: "officeTel"
}, {
fieldLabel: "学历文凭",
name: "diploma"
}, {
fieldLabel: "岗位",
name: "station"
}, {
fieldLabel: "职称",
name: "professional"
}, {
fieldLabel: "专业",
name: "specialty"
}, {
fieldLabel: "住址",
name: "address"
}, {
fieldLabel: "员工生日",
name: "birthday"
}, {
name: "email",
fieldLabel: "员工电邮",
allowBlank: false
}, {
fieldLabel: "处级信息",
name: "rankInfo"
}, {
fieldLabel: "私人信息",
name: "privateInfo"
}, {
fieldLabel: "备注",
name: "description"
}, Disco.Ext.Util.buildCombox("types", "员工类型", this.employeeTypes, 6), {
xtype: "treecombo",
fieldLabel: "组织机构",
displayField: "title",
name: "org",
allowBlank: false,
hiddenName: "orgId",
tree: new Ext.tree.TreePanel({
border: false,
rootVisible: true,
root: new Ext.tree.AsyncTreeNode({
id: "root",
expanded: true,
text: "根节点",
iconCls: 'treeroot-icon',
loader: Global.organizationLoader
})
})
}, {
fieldLabel: "最大信件量",
name: "maxMail"
}, {
fieldLabel: "最大附件量",
name: "maxAttachment"
} /*Disco.Ext.Util.buildCombox("workerOnly", "系统用户", [["是", false], ["否", true]], false)*/)
}, {
xtype: "panel",
//title : "权限资源",
anchor: "100%",
height: 236,
border: false,
layout: "fit",
cls: 'x-plain',
items: {
xtype: "tabpanel",
deferredRender: false,
hideBorders: true,
activeTab: 0,
border: false,
items: [this.createRolePanel(), this.deptGrid, this.createEditPanel(), this.createunEditPanel()]
}
}]
});
return formPanel;
},
searchFormPanel: function() {
var formPanel = new Ext.form.FormPanel({
frame: true,
labelWidth: 80,
labelAlign: "right",
items: [{
xtype: "fieldset",
title: "查询条件",
height: 140,
layout: 'column',
items: [{
columnWidth: .50,
layout: 'form',
defaultType: 'textfield',
defaults: {
anchor: '-20'
},
items: [{
fieldLabel: "用户名称",
name: "name"
}, {
fieldLabel: "真实姓名",
name: "trueName"
}, {
fieldLabel: "联系电话",
name: "tel"
}, {
fieldLabel: "输入日期(始)",
name: "inputStartTime",
xtype: 'datefield',
format: 'Y-m-d'
}]
}, {
columnWidth: .50,
layout: 'form',
defaultType: 'textfield',
defaults: {
width: 130
},
items: [{
fieldLabel: "电子邮件",
name: "email",
anchor: '90%'
}, {
fieldLabel: "合同编码",
name: "contractNo",
anchor: '90%'
}, {
xtype: "treecombo",
fieldLabel: "部 门",
displayField: "title",
name: "orgId",
hiddenName: "orgId",
anchor: '90%',
tree: new Ext.tree.TreePanel({
root: new Ext.tree.AsyncTreeNode({
id: "root",
text: "选择机构",
expanded: true,
loader: Global.organizationLoader
})
})
}, {
fieldLabel: "输入日期(末)",
name: "inputEndTime",
anchor: '90%',
xtype: 'datefield',
format: 'Y-m-d'
}]
}]
}]
});
return formPanel;
},
gridStoreRemoveAll: function() {
var gs = Array.prototype.slice.call(arguments, 0);
Ext.each(gs, function(g) {
if (Ext.type('string') && this[g])
this[g].store.removeAll();
else if (Ext.type('object')) {
g.store.removeAll();
}
}, this)
},
onCreate: function() {
this.fp.findByType('tabpanel')[0].setActiveTab(0);
this['extraPermissionGrid'].tempCheck.clear();
this['disablePermissionsGrid'].tempCheck.clear();
this.gridStoreRemoveAll('extraPermissionGrid', 'disablePermissionsGrid', 'rolePermissionGrid', this.roleGrid, this.deptGrid);
this.fp.form.findField("password").el.dom.readOnly = false;
},
onEdit: function(ret) {
this.fp.findByType('tabpanel')[0].setActiveTab(0);
this['extraPermissionGrid'].tempCheck.clear();
this['disablePermissionsGrid'].tempCheck.clear();
var record = this.grid.getSelectionModel().getSelected();
if (ret) {
this.gridStoreRemoveAll('extraPermissionGrid', 'disablePermissionsGrid', 'rolePermissionGrid', this.roleGrid, this.deptGrid);
if (record && record.get('permissions')) {
this['extraPermissionGrid'].tempCheck.addAll(record.get('permissions'));
this['extraPermissionGrid'].store.loadData({
rowCount: record.get('permissions').length,
result: record.get('permissions')
});
}
if (record && record.get('disablePermissions')) {
this['disablePermissionsGrid'].tempCheck.addAll(record.get('disablePermissions'));
this['disablePermissionsGrid'].store.loadData({
rowCount: record.get('disablePermissions').length,
result: record.get('disablePermissions')
});
}
this.roleGrid.store.loadData(this.grid.getSelectionModel().getSelected().get("roles") || {});
this.deptGrid.store.loadData(this.grid.getSelectionModel().getSelected().get("otherDepts") || {});
this.fp.form.findField("password").el.dom.readOnly = true;
}
return ret;
},
getGridValue: function(grid) {
var s = "";
for (var i = 0; i < grid.store.getCount(); i++) {
var r = grid.store.getAt(i);
s += r.get("id") + ",";
}
return s;
},
uploadEmployeeInfo: function() {
if (!this.uploadEmployeeInfoWin) {
this.uploadEmployeeInfoWin = new Ext.Window({
title: "从Excel中导入员工数据到系统中",
width: 500,
height: 230,
modal: true,
layout: "fit",
border: false,
closeAction: "hide",
items: {
xtype: "form",
fileUpload: true,
items: [{
xtype: "fieldset",
title: "选择excel文件",
autoHeight: true,
items: {
xtype: "textfield",
hideLabel: true,
inputType: "file",
name: "file",
anchor: "100%"
}
}, {
xtype: "fieldset",
title: "导入说明",
html: "运行导入office 2003 2007 2010版本生成的Excel文件,并且请严格对照Excel中的列一定要与字段对应",
autoHeight: true
}]
},
buttons: [{
text: "确定",
handler: function() {
alert(this.baseUrl)
this.uploadEmployeeInfoWin.getComponent(0).form.submit({
url: this.baseUrl,
params: {
cmd: "import"
},
waitMsg: "请稍候,正在导入数据",
success: function() {
Ext.Msg.alert("提示", "数据导入成功!", function() {
this.store.reload();
}, this)
},
failure: function() {
Ext.Msg.alert("提示", "数据导入出错,请检测所选择的文件格式是否正确?");
},
scope: this
})
},
scope: this
}, {
text: "取消",
handler: function() {
this.uploadEmployeeInfoWin.hide();
},
scope: this
}]
});
}
this.uploadEmployeeInfoWin.show();
},
save: function() {
var arr = [];
this.deptGrid.getStore().each(function(record) {
arr = arr.concat(record.get('path'));
}, this);
this.fp.form.baseParams = {
permissions: this['extraPermissionGrid'].tempCheck.keys.join(','),
disablePermissions: this['disablePermissionsGrid'].tempCheck.keys.join(','),
roles: this.getGridValue(this.roleGrid),
otherDepts: this.getGridValue(this.deptGrid),
otherDeptPath: arr.distinct(true).join(',')
};
EmployeePanel.superclass.save.call(this);
},
createWin: function(callback, autoClose) {
return this.initWin(800, 630, "员工信息", callback, autoClose);
},
deptRender: function(v) {
return v ? v.title : "上海分行";
},
employeeTypesRender: function(v) {
if (v == 1) {
return "撰稿人";
} else if (v == 2) {
return "部门支行管理员";
} else if (v == 3) {
return "分行管理员";
} else if (v == 4) {
return "部门支行审核人";
} else if (v == 5) {
return "分行管理员";
} else if (v == 6) {
return "其它类型";
}
},
statusRender: function(v) {
if (v == -1)
return "<font color='red'>禁用</font>";
else
return "正常";
},
doLoadAll: function() {
this.store.load({});
},
filterData: function(item, e) {
var name = item.parentMenu.name;
var fv = item.filterValue;
this.store.baseParams = {};
this.store.baseParams[name] = fv;
this.refresh(false);
},
storeMapping: ["id", "name", "trueName", "otherDepts", "email", "contractNo", "duty", "password", "tel", "registerTime", "sn", "org", "status", "sex", "workerOnly", "roles", "permissions", "disablePermissions", "namePy", "remark", "mobileTel", "homeTel", "telExt", "officeTel", "diploma", "station", "professional", "specialty", "address", "birthday", "maxMail", "maxAttachment", "rankInfo", "privateInfo", "description", "types"],
initComponent: function() {
this.cm = new Ext.grid.ColumnModel([{
header: "用户名",
sortable: true,
width: 80,
align: 'center',
dataIndex: "name"
}, {
header: "员工姓名",
sortable: true,
width: 100,
align: 'center',
dataIndex: "trueName"
}, {
header: "所在机构",
sortable: true,
align: 'center',
width: 100,
dataIndex: "org",
renderer: this.deptRender
}, {
header: "编码(系统生成)",
sortable: true,
align: 'center',
hidden: true,
width: 100,
dataIndex: "sn"
}, {
width: 80,
sortable: true,
header: "员工类别",
dataIndex: "types",
align: 'center',
renderer: this.employeeTypesRender
}, {
header: "注册时间",
sortable: true,
align: 'center',
width: 100,
dataIndex: "registerTime",
renderer: this.dateRender()
}, {
header: "状态",
sortable: true,
width: 50,
align: 'center',
dataIndex: "status",
align: 'center',
renderer: this.statusRender
}]);
var filterGroup = Ext.id(null, 'filterGroup');
/*this.gridButtons = ["-", {
text: "禁用/启用",
cls: "x-btn-text-icon",
icon: "img/core/up.gif",
handler: this.executeCmd("changeStatus"),
scope: this
}, {
text: "数据过滤",
cls: "x-btn-text-icon",
icon: "img/core/21.gif",
//已启用,显示全部。 默认显示已启用
menu: {
name: 'status',
listeners: {
scope: this,
itemclick: this.filterData
},
toggleGroup: true,
items: [{
text: '已启用',
filterValue: 1,
checked: true,
group: filterGroup
}, {
text: '显示全部',
filterValue: null,
checked: false,
group: filterGroup
}]
},
scope: this
}, {
text: "重置密码",
cls: "x-btn-text-icon",
icon: "img/core/23.gif",
handler: this.executeCmd("initializePassword"),
scope: this
}];*/
EmployeePanel.superclass.initComponent.call(this);
}
});
EmployeeManagePanel = Ext.extend(Ext.Panel, {
layout: 'border',
border: false,
hideBorders: true,
clickDeptNode: function(node) {
var id = node.attributes.id == 'root' ? '' : node.attributes.id;
var grid = this.crudListPanel.grid;
grid.getStore().baseParams = {
orgId: id
};
this.crudListPanel.refresh(false);
},
createDeptTree: function() {
return new Ext.tree.TreePanel({
title: '组织机构树',
region: 'west',
border: false,
width: 200,
rootVisible: true,
autoScroll: true,
tools: [{
id: "refresh",
handler: function() {
Global.organizationLoader.remoteObject.clearData();
this.deptTree.root.reload();
},
scope: this
}],
root: new Ext.tree.AsyncTreeNode({
id: "root",
text: "上海分行",
iconCls: 'treeroot-icon',
expanded: true,
loader: Global.organizationLoader
}),
listeners: {
scope: this,
click: this.clickDeptNode
}
});
},
initComponent: function() {
this.deptTree = this.createDeptTree();
this.crudListPanel = new EmployeePanel({
margins: '0 0 0 5',
region: 'center'
});
this.items = [this.deptTree, this.crudListPanel];
EmployeeManagePanel.superclass.initComponent.call(this);
}
});
|
var names = ['Abhi', 'Aniket', 'Aarushi'];
// names.forEach(function (name) {
// console.log('forEach', name);
// });
//
// names.forEach((name) => {
// console.log('arrowFunc', name);
// });
//
// names.forEach((name) => console.log(name));
// var returnMe = (name) => name + '!';
// console.log(returnMe('Abhi'));
var person = {
name: 'Abhi',
greet: function () {
names.forEach((name) => {
console.log(this.name + ' > ' + name);
});
}
}
person.greet();
|
$("#server_bajo").change(function(){
if ($(this).is(":checked")) {
$("#serverbasico").slideDown();
$("#server_medio , #server_premium").attr('checked', false);
$("#servermedio , #serverpremium").hide();
} else {
$("#serverbasico , #servermedio , #serverpremium").hide();
};
});
$("#server_medio").change(function(){
if ($(this).is(":checked")) {
$("#servermedio").slideDown();
$("#server_bajo , #server_premium").attr('checked', false);
$("#serverbasico , #serverpremium").hide();
} else {
$("#serverbasico , #servermedio , #serverpremium").hide();
};
});
$("#server_premium").change(function(){
if ($(this).is(":checked")) {
$("#serverpremium").slideDown();
$("#server_bajo , #server_medio").attr('checked', false);
$("#serverbasico , #servermedio").hide();
} else {
$("#serverbasico , #servermedio , #serverpremium").hide();
};
});
|
import fc from "./../../utils/managingFocus";
import boolean from "./../../type/boolean";
import elements from "./../../utils/elements";
import Roletype from "./Roletype";
import Option from "./../Option.js";
import mix from "@vestergaard-company/js-mixin";
import selector from "./../../utils/selector";
import owns from "./../../utils/owns";
/**
* ### Keyboard Support
*
* #### Default
* | Key | Function |
* | --- | -------- |
* | Down Arrow | Moves focus to the next option <br/> If not multiselectable, it selects the focused option.
* | Up Arrow | Moves focus to the previous option <br/> If not multiselectable, it selects the focused option.
* | Home | Moves focus to the first option <br/> If not multiselectable, it selects the focused option.
* | End | Moves focus to the last option <br/> If not multiselectable, it selects the focused option.
*
* #### Multiple selection
* | Key | Function |
* | --- | -------- |
* | Space | Changes the selection state of the focused option.
* | Shift + Down Arrow | Moves focus to and selects the next option.
* | Shift + Up Arrow | Moves focus to and selects the previous option.
* | Control + Shift + Home | Selects from the focused option to the beginning of the list.
* | Control + Shift + End | Selects from the focused option to the end of the list.
* | Control + A | Selects all options in the list. If all options are selected, unselects all options.
*
* ### Attributes
* * `aria-selected`
* * `true`
* * is the current focussed element
* * equals the value of `aria-activedescendant`
* * `tabindex`
* * allows usage of the element by keys when in focus
* * `aria-activedescendant` equals ID of current focussed element
*
* #### Multiple selection
* * `aria-selected`
* * `true`
* * can be applied to multiple element
* * not automatically applied to the focused element
* * `false`
* * `tabindex`
* * allows usage of the element by keys when in focus
*
* @summary A form widget that allows the user to make selections from a set of choices.
* @extends Roletype
*/
class Select extends Roletype {
constructor(...args) {
super(...args);
// used for determining if logic should be executed
this.target = false;
// when in focus, allow the element be controlled by the keys
if(typeof this.tabIndex !== "undefined") {
this._node.addEventListener("focus", hasTarget.bind(this));
this._node.addEventListener("blur", lostTarget.bind(this));
}
this.addEventListener("key", this.moveToStart.bind(this), {key: "home", target: this._node.ownerDocument});
this.addEventListener("key", this.moveToPrev.bind(this), {key: "up", target: this._node.ownerDocument});
this.addEventListener("key", this.moveToNext.bind(this), {key: "down", target: this._node.ownerDocument});
this.addEventListener("key", this.moveToEnd.bind(this), {key: "end", target: this._node.ownerDocument});
// this.addEventListener.call({ element: this._node.ownerDocument }, "home", this.moveToStart.bind(this));
// this.addEventListener.call({ element: this._node.ownerDocument }, "up", this.moveToPrev.bind(this));
// // this.addEventListener.call({ element: this._node.ownerDocument }, "shift + up", this.moveToNext.bind(this));
// this.addEventListener.call({ element: this._node.ownerDocument }, "down", this.moveToNext.bind(this));
// // this.addEventListener.call({ element: this._node.ownerDocument }, "shift + down", selectDown.bind(this));
// this.addEventListener.call({ element: this._node.ownerDocument }, "end", this.moveToEnd.bind(this));
this.options = owns.getAllAllowedChildren(this);
this.options.forEach(ay => {
this.addEventListener("click", this.activeChanged.bind(this), {target: ay._node});
if (ay.selected) {
fc.add(ay);
}
});
}
moveToPrev(ev) { move(this, ev, fc.prev, this.moved.bind(this)); }
moveToNext(ev) { move(this, ev, fc.next, this.moved.bind(this)); }
moveToStart(ev) { move(this, ev, fc.start, this.moved.bind(this)); }
moveToEnd(ev) { move(this, ev, fc.end, this.moved.bind(this)); }
moved(from, to) {}
activeChanged(ev) {
let option = elements.get(ev.target);
let prevFocus = fc.get(this.options);
fc.remove(prevFocus);
fc.add(option);
if (this.activeDescendant) this.activeDescendant = option;
// update selected on keyevent when only one item can be selected
if (!this.multiselectable) {
fc.setSelected(prevFocus, undefined);
}
fc.setSelected(option, boolean.toggle(option.selected));
}
}
function move(ay, ev, func, callback) {
if (!ay.target) return;
if (ev) ev.preventDefault();
let prevFocus = fc.get(ay.options);
fc.remove(prevFocus);
// update selected on keyevent when only one item can be selected
let currentFocus = func(ay.options, prevFocus);
if (ay.activeDescendant) ay.activeDescendant = currentFocus;
callback(prevFocus, currentFocus);
}
function hasTarget() { this.target = true; }
function lostTarget() { this.target = false; }
export default Select;
|
window.initializeRohBot();
|
import Vue from 'vue'
import Router from 'vue-router'
// Containers
const DefaultContainer = () => import('@/containers/DefaultContainer')
// Views
const Dashboard = () => import('@/views/Dashboard')
const Product = () => import('@/views/Product')
const ProductO = () => import('@/views/ProductO')
const SiteO = () => import('@/views/SitesO')
const Sites = () => import('@/views/Sites')
const CreateSite = () => import('@/views/CreateSite')
const CreateProduct = () => import('@/views/CreateProduct')
const MyUsers = () => import('@/views/myUsers')
const CreateUser = () => import('@/views/CreateUser')
const MyUsersO = ()=> import('@/views/myUsersO')
const Inventories = ()=> import('@/views/Inventories')
const CreateInventory = () => import('@/views/CreateInventories')
const InventoriesO = () => import('@/views/InventoriesO')
//Chat Groups
const ChatGroups = ()=> import('@/views/ChatGroups')
const CreateChatGroups = ()=> import('@/views/CreateChatGroups')
const ChatGroupsO = ()=> import('@/views/ChatGroupsO')
//Join groups
const JoinGroups = ()=> import('@/views/joinGroups')
const JoinGroupsO = ()=> import('@/views/joinGroupsO')
const Colors = () => import('@/views/theme/Colors')
const Typography = () => import('@/views/theme/Typography')
const Charts = () => import('@/views/Charts')
const Widgets = () => import('@/views/Widgets')
// Views - Components
const Cards = () => import('@/views/base/Cards')
const Forms = () => import('@/views/base/Forms')
const Switches = () => import('@/views/base/Switches')
const Tables = () => import('@/views/base/Tables')
const Tabs = () => import('@/views/base/Tabs')
const Breadcrumbs = () => import('@/views/base/Breadcrumbs')
const Carousels = () => import('@/views/base/Carousels')
const Collapses = () => import('@/views/base/Collapses')
const Jumbotrons = () => import('@/views/base/Jumbotrons')
const ListGroups = () => import('@/views/base/ListGroups')
const Navs = () => import('@/views/base/Navs')
const Navbars = () => import('@/views/base/Navbars')
const Paginations = () => import('@/views/base/Paginations')
const Popovers = () => import('@/views/base/Popovers')
const ProgressBars = () => import('@/views/base/ProgressBars')
const Tooltips = () => import('@/views/base/Tooltips')
// Views - Buttons
const StandardButtons = () => import('@/views/buttons/StandardButtons')
const ButtonGroups = () => import('@/views/buttons/ButtonGroups')
const Dropdowns = () => import('@/views/buttons/Dropdowns')
const BrandButtons = () => import('@/views/buttons/BrandButtons')
// Views - Icons
const Flags = () => import('@/views/icons/Flags')
const FontAwesome = () => import('@/views/icons/FontAwesome')
const SimpleLineIcons = () => import('@/views/icons/SimpleLineIcons')
const CoreUIIcons = () => import('@/views/icons/CoreUIIcons')
// Views - Notifications
const Alerts = () => import('@/views/notifications/Alerts')
const Badges = () => import('@/views/notifications/Badges')
const Modals = () => import('@/views/notifications/Modals')
// Views - Pages
const Page404 = () => import('@/views/pages/Page404')
const Page500 = () => import('@/views/pages/Page500')
const Login = () => import('@/views/pages/Login')
const Register = () => import('@/views/pages/Register')
// Users
const Users = () => import('@/views/users/Users')
const User = () => import('@/views/users/User')
Vue.use(Router)
export default new Router({
mode: 'history', // https://router.vuejs.org/api/#mode
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
redirect: '/dashboard',
name: 'Home',
component: DefaultContainer,
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: {
render (c) { return c('router-view') }
},
children:[
{
path:'',
component: Dashboard
},
{
path:'/product',
meta: { label: 'Products'},
component: {
render (c) { return c('router-view') }
},
children:[
{
path:'',
component: Product,
},
{
path: '/product/:prodId',
meta: { label: 'Product Details'},
name: 'Product',
component: ProductO
},
{
path:'/createproduct',
name: 'Create Product',
component: CreateProduct
},
]
},
{
path: '/sites',
meta: { label: 'Sites'},
component: {
render (c) { return c('router-view') }
},
children:[
{
path: '',
component: Sites
},
{
path: '/sites/:siteId',
meta: { label: 'Site Details'},
name: 'Sites',
component: SiteO
},
{
path:'/createsite',
meta: { label: 'Create Site'},
name: 'Create Site',
component: CreateSite
},
]
},
{
path: '/inventories',
meta: { label: 'Inventories'},
component: {
render (c) { return c('router-view') }
},
children:[
{
path: '',
component: Inventories
},
{
path: '/inventories/:inventoryId',
meta: { label: 'Inventory Details'},
name: 'Inventories',
component: InventoriesO
},
{
path:'/createinventories',
meta: { label: 'Create Inventory'},
name: 'Create Inventory',
component: CreateInventory
},
]
},
{
path: '/chatgroups',
meta: { label: 'Chat Groups'},
component: {
render (c) { return c('router-view') }
},
children:[
{
path: '',
component: ChatGroups
},
{
path: '/chatgroups/:chatgroupId',
meta: { label: 'Chat Group Details'},
name: 'Chat Groups',
component: ChatGroupsO
},
{
path:'/createchatgroups',
meta: { label: 'Create Chat Groups'},
name: 'Create Chat Groups',
component: CreateChatGroups
},
]
},
{
path: '/join',
meta: { label: 'Join Requests'},
component: {
render (c) { return c('router-view') }
},
children:[
{
path: '',
component: JoinGroups,
},
{
path: '/join/:joinId',
meta: { label: 'Join Request Details'},
name: 'Join Requests',
component: JoinGroupsO,
},
]
},
]
},
{
path: 'theme',
redirect: '/theme/colors',
name: 'Theme',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'colors',
name: 'Colors',
component: Colors
},
{
path: 'typography',
name: 'Typography',
component: Typography
}
]
},
{
path: 'charts',
name: 'Charts',
component: Charts
},
{
path: 'widgets',
name: 'Widgets',
component: Widgets
},
{
path: 'users',
meta: { label: 'Users'},
component: {
render (c) { return c('router-view') }
},
children: [
{
path: '',
component: MyUsers,
},
{
path:'/users/:userid',
meta: { label: 'User Details'},
component: MyUsersO
},
{
path: '/createuser',
meta: { label: 'Create User'},
name: 'Create User',
component: CreateUser,
},
]
},
{
path: 'base',
redirect: '/base/cards',
name: 'Base',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'cards',
name: 'Cards',
component: Cards
},
{
path: 'forms',
name: 'Forms',
component: Forms
},
{
path: 'switches',
name: 'Switches',
component: Switches
},
{
path: 'tables',
name: 'Tables',
component: Tables
},
{
path: 'tabs',
name: 'Tabs',
component: Tabs
},
{
path: 'breadcrumbs',
name: 'Breadcrumbs',
component: Breadcrumbs
},
{
path: 'carousels',
name: 'Carousels',
component: Carousels
},
{
path: 'collapses',
name: 'Collapses',
component: Collapses
},
{
path: 'jumbotrons',
name: 'Jumbotrons',
component: Jumbotrons
},
{
path: 'list-groups',
name: 'List Groups',
component: ListGroups
},
{
path: 'navs',
name: 'Navs',
component: Navs
},
{
path: 'navbars',
name: 'Navbars',
component: Navbars
},
{
path: 'paginations',
name: 'Paginations',
component: Paginations
},
{
path: 'popovers',
name: 'Popovers',
component: Popovers
},
{
path: 'progress-bars',
name: 'Progress Bars',
component: ProgressBars
},
{
path: 'tooltips',
name: 'Tooltips',
component: Tooltips
}
]
},
{
path: 'buttons',
redirect: '/buttons/standard-buttons',
name: 'Buttons',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'standard-buttons',
name: 'Standard Buttons',
component: StandardButtons
},
{
path: 'button-groups',
name: 'Button Groups',
component: ButtonGroups
},
{
path: 'dropdowns',
name: 'Dropdowns',
component: Dropdowns
},
{
path: 'brand-buttons',
name: 'Brand Buttons',
component: BrandButtons
}
]
},
{
path: 'icons',
redirect: '/icons/font-awesome',
name: 'Icons',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'coreui-icons',
name: 'CoreUI Icons',
component: CoreUIIcons
},
{
path: 'flags',
name: 'Flags',
component: Flags
},
{
path: 'font-awesome',
name: 'Font Awesome',
component: FontAwesome
},
{
path: 'simple-line-icons',
name: 'Simple Line Icons',
component: SimpleLineIcons
}
]
},
{
path: 'notifications',
redirect: '/notifications/alerts',
name: 'Notifications',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: 'alerts',
name: 'Alerts',
component: Alerts
},
{
path: 'badges',
name: 'Badges',
component: Badges
},
{
path: 'modals',
name: 'Modals',
component: Modals
}
]
}
]
},
{
path: '/pages',
redirect: '/pages/404',
name: 'Pages',
component: {
render (c) { return c('router-view') }
},
children: [
{
path: '404',
name: 'Page404',
component: Page404
},
{
path: '500',
name: 'Page500',
component: Page500
},
{
path: 'login',
name: 'Login',
component: Login
},
{
path: 'register',
name: 'Register',
component: Register
}
]
}
]
})
|
function randomString() {
let chars = '0123456789abcdefghiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ';
let str = '';
for (let i = 0; i < 10; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
function pad0(value) {
let result = value.toString();
if (result.length < 2) {
result = '0' + result;
}
return result;
};
class Stopwatch extends React.Component {
constructor() {
super();
this.state = {
running: false,
timeList: [],
times: {
miliseconds: 0,
seconds: 0,
minutes: 0,
},
}
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
this.reset = this.reset.bind(this);
this.addClick = this.addClick.bind(this);
this.clear = this.clear.bind(this);
}
step() {
if (!this.state.running) return;
this.calculate();
}
calculate() {
this.setState(state => {
const times = state.times;
times.miliseconds += 1;
if (times.miliseconds >= 100) {
times.seconds += 1;
times.miliseconds = 0;
}
if (times.seconds >= 60) {
times.minutes += 1;
times.seconds = 0;
}
return times;
})
}
start() {
if (!this.state.running) {
this.interval = setInterval(() => { this.step() }, 10)
this.setState({ running: true })
}
}
stop() {
this.setState({ running: false })
}
reset() {
this.setState(state => {
const times = state.times;
times.minutes = 0;
times.seconds = 0;
times.miliseconds = 0;
return times;
})
}
format(times) {
return `${pad0(times.minutes)}:${pad0(times.seconds)}:${pad0(times.miliseconds)}`;
}
add(val) {
const timeData = {
times: val,
id: randomString(),
}
const timeList = [...this.state.timeList, timeData];
this.setState({ timeList })
}
addClick() {
const time = Object.assign({},this.state.times);
this.add(time);
}
clear() {
const remainder = this.state.timeList.filter(id => id == '');
this.setState({ timeList: remainder });
}
render() {
const timeList = this.state.timeList.map(data => {
return <li>{this.format(data.times)}</li>;
})
return (
<div>
<nav className="controls">
<button className="button" id='start' onClick={this.start}>Start</button>
<button className="button" id='stop' onClick={this.stop}>Stop</button>
<button className="button" id='reset' onClick={this.reset}>Reset</button>
<button className="button" id='add' onClick={this.addClick}>Add</button>
<button className="button" id='clear' onClick={this.clear}>Clear list</button>
</nav>
<div className="stopwatch">
<h1>{this.format(this.state.times)}</h1>
</div>
<ul class="results">{timeList}</ul>
</div>
)
}
}
ReactDOM.render(
<Stopwatch />,
document.getElementById('root')
);
|
const mapper = require('plucky-mapper').jsonMapper;
const pluckyLoader = require('./plucky-loader');
const {
getObjectValue,
} = require('./utils');
const path = require('path');
require('./json-require');
require('./yaml-require');
require('./plucky-require');
class ConfigLoader{
constructor(configFile, mergeWith, {basePath}){
this.configFile = configFile;
this.mergeWith = mergeWith;
this.basePath = basePath;
this.loadBaseConfig();
this.config = mapper(this.baseConfig, mergeWith);
}
loadBaseConfig(){
const configFile = this.configFile;
const basePath = this.basePath;
const filePath = basePath?path.resolve(basePath, configFile):configFile;
if(filePath.match(/(^|\/)\.plucky$/i)){
const mod = {
exports: {}
};
pluckyLoader(mod, filePath);
return this.baseConfig = mod.exports;
}
return this.baseConfig = require(filePath);
}
get(path, defaultValue){
return getObjectValue(path, this.config, defaultValue);
}
}
module.exports = {
ConfigLoader,
};
|
const { CosmosClient } = require("@azure/cosmos");
const { dbURI, dbKey, dbName, container } = require("config");
// Private Methods
let buildClient = () => {
return new CosmosClient({
endpoint: dbURI,
auth: { masterKey: dbKey }
});
}
/**
* @module deleteItemCommand.
* @description Module that enables you to delete
* items from a Cosmos DB collection.
* @author Allan A. Chua
* @version 1.0
* @since August 11, 2018
*/
module.exports = {
/**
* @async
* @function execute
* @description Method used for deleting an item
* from a Cosmos DB collection.
*
* @param {Object} item - The item to remove from the collection.
* @param {number} item.id - The id of the product.
*
* @return Promise<void>
*/
async execute(item) {
try {
await buildClient()
.database(dbName)
.container(container)
.item(item.id)
.delete(item);
} catch (error) {
console.log(
`Item deletion from collection failed: ${error.message}`
);
}
}
}
|
import {StyledSynonymBuilder} from "./SynonymBuilder.style";
import {Table, TableCell, TableBody, TableRow} from "@material-ui/core";
import IconButton from "~/components/atoms/iconButton/IconButton";
import TextField from "~/components/atoms/textfield/Textfield";
import DialogContent from "~/components/atoms/dialog/DialogContent";
import useForm from "~/util/form";
import {useEffect, useState} from "react";
import MessageboxStoreManager from "~/components/molecules/Messagebox/MessageboxFactory";
import {messageboxState} from "~/components/molecules/Messagebox/MessageboxAtom";
import {useRecoilState} from "recoil";
const SynonymBuilder = function ({data, ...props}) {
const messageboxStateAtom = useRecoilState(messageboxState);
const [formData, setForm, resetForm] = useForm({synonym: ""});
const [synonyms, setSynonyms] = useState([]);
useEffect(() => {
let regex = new RegExp("(\\[((.*?)\\]))", "gi");
var match = regex.exec(props.selection);
if (match != null) {
if (match[0] != props.selection) {
invalidPropInputSelection();
} else {
setSynonyms(match[3].split("|"));
}
} else if (props.selection.trim() != "") {
var forbiddentags = [["\\{", "\\}"]];
forbiddentags.forEach((forbiddenTag) => {
regex = new RegExp("(" + forbiddenTag[0] + "((.*?)" + forbiddenTag[1] + "))", "gi");
match = regex.exec(props.selection);
if (match != null && match[0] != null) {
invalidPropInputSelection();
props.onClose();
}
});
setSynonyms([props.selection]);
}
}, [props.selection]);
const invalidPropInputSelection = () => {
MessageboxStoreManager.AddMessage(messageboxStateAtom, {
title: "Oops",
content: "Je selectie bevat een synonymgroep met daarnaast extra tekst of andere speciale code.\nSelecteer alleen een synonymgroep, tekst of niets.",
buttons: [
{
label: "OK",
onClick: () => {
props.insertSynonyms(props.selection);
},
},
],
});
props.onClose();
};
const handleAddSynonym = (e) => {
e.preventDefault();
const synonym = formData.synonym;
if (synonym == "") return;
if (synonyms.includes(synonym)) {
const duplicateElement = document.querySelector(".table-row[data-synonym='" + synonym + "']");
duplicateElement.classList.add("highlight");
setTimeout(() => {
duplicateElement.classList.remove("highlight");
}, 3000);
} else {
setSynonyms([...synonyms, synonym]);
}
resetForm();
};
const handleDeleteSynonym = (synonym) => {
let newSynonyms = [...synonyms];
newSynonyms.splice(newSynonyms.indexOf(synonym), 1);
setSynonyms(newSynonyms);
};
const handleUpdateSynonyms = () => {
if (synonyms.length == 0) {
props.insertSynonyms("");
} else if (synonyms.length == 1) {
props.insertSynonyms(synonyms.join(""));
} else {
const newSynonyms = [...synonyms].sort((a, b) => b.length - a.length);
props.insertSynonyms("[" + newSynonyms.join("|") + "]");
}
props.onClose();
};
return (
<StyledSynonymBuilder id="synonymDialog" title="Synonymen" onClose={handleUpdateSynonyms} open={true} disableBackdropClick={true}>
<DialogContent bottomMargin>
<div className="tableWrapper">
<Table>
<TableBody id="table-body">
{synonyms.map((synonym, key) => {
return (
<TableRow key={key} data-synonym={synonym} className="table-row">
<TableCell className="table-cell" size="small">
<div className="content">{synonym}</div>
<IconButton onClick={() => handleDeleteSynonym(synonym)} className="deleteButton" small icon={["fal", "trash-alt"]} />
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<form id="synonym-form" onSubmit={handleAddSynonym}>
<TextField label="Synonym toevoegen" value={formData.synonym} onChange={setForm} name="synonym" />
<IconButton type="submit" small square icon={["fal", "arrow-square-right"]} />
</form>
</DialogContent>
</StyledSynonymBuilder>
);
};
export default SynonymBuilder;
|
import React from 'react';
import { withRouter } from "react-router";
import FavStore from '../function/favoriteStoreComponent';
import '../CSS/favoriteList.css';
class FavoriteList extends React.Component{
render(){
return(
<div className='favList'>
<h1>お気に入り店舗</h1>
<div className='list-container'>
<FavStore />
</div>
</div>
);
}
}
export default withRouter(FavoriteList);
|
import _ from "lodash" ;
import {
POST_MESSAGE_FAIL,
POST_MESSAGE_SUCCESS,
GET_POSTS_SUCCESS,
GET_POSTS_FAIL,
SET_MESSAGE,
LIKE_COMMENT_SUCCESS,
LIKE_COMMENT_FAIL,
COMMENT_POST_SUCCESS,
COMMENT_POST_FAIL,
DELETE_COMMENT_SUCCESS,
DELETE_COMMENT_FAIL,
DELETE_POST_SUCCESS,
DELETE_POST_FAIL,
REPORT_POST_SUCCESS,
REPORT_POST_FAIL,
GET_REPORTED_POSTS_SUCCESS,
GET_REPORTED_POSTS_FAIL,
} from "./types";
import PostService from "../services/post.service";
export const publishPost = (content,filename) => (dispatch) => {
return PostService.postMessage(content,filename).then(
(response) => {
dispatch({
type: POST_MESSAGE_SUCCESS,
payload:{post:response.data.post}
});
dispatch({
type: SET_MESSAGE,
payload: response.data.message,
});
return Promise.resolve();
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: POST_MESSAGE_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
);
};
export const getAllPosts = () => (dispatch)=>{
return PostService.gettAllPosts().then(
(response)=>{
dispatch({
type: GET_POSTS_SUCCESS,
payload:{posts:response.data.posts}
});
return Promise.resolve();
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: GET_POSTS_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const getAllPostsByUser = (userId)=>(dispatch)=>{
return PostService.getPostsByUserId(userId).then(
(response)=>{
return Promise.resolve(response.data);
},
(error)=>{
return Promise.reject(error);
}
)
}
export const getAllReportedPosts = () => (dispatch)=>{
return PostService.gettAllReportedPosts().then(
(response)=>{
dispatch({
type: GET_REPORTED_POSTS_SUCCESS,
payload:{posts:response.data.posts}
});
return Promise.resolve();
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: GET_REPORTED_POSTS_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const likeOrUnLikePost = (postId,option) =>(dispatch)=>{
return PostService.likePost(postId,option).then(
(response)=>{
const {postId,userId} = response.data
dispatch({
type: LIKE_COMMENT_SUCCESS,
payload: {postId,userId,option}
});
return Promise.resolve();
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: LIKE_COMMENT_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const commentPost =(postId,content)=>(dispatch)=>{
return PostService.commentPost(postId,content).then(
(response)=>{
// refresh the post getpostbyid
const {comment,message} = response.data
dispatch({
type: COMMENT_POST_SUCCESS,
payload: {comment,postId}
});
return Promise.resolve(response.data);
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: COMMENT_POST_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const deleteCurrentPost =(postId)=>(dispatch)=>{
return PostService.deletePost(postId).then(
(response)=>{
const {message} = response.data
dispatch({
type: DELETE_POST_SUCCESS,
payload: {postId}
});
return Promise.resolve(response.data);
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: DELETE_POST_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const reportCurrentPost =(postId)=>(dispatch)=>{
return PostService.reportPost(postId).then(
(response)=>{
dispatch({
type: REPORT_POST_SUCCESS
});
return Promise.resolve();
},
(error) => {
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: REPORT_POST_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
export const deleteComment=(commentId,postId)=>(dispatch)=>{
return PostService.deleteComment(commentId).then(
(response)=>{
const {comment} = response.data
dispatch({
type: DELETE_COMMENT_SUCCESS,
payload: {comment,postId,commentId}
});
return Promise.resolve(response.data);
},
(error)=>{
let {message,errors} = error.response.data ;
// console.log(errors)
if(!_.isEmpty(errors)){
message=Object.keys(errors).map(function (key, index) {
return errors[key]
}).join(', ')
}
dispatch({
type: DELETE_COMMENT_FAIL,
});
dispatch({
type: SET_MESSAGE,
payload: message,
});
return Promise.reject();
}
)
}
|
/**
* 数据过滤,export 用来暴露函数
* @param {*} str
* @returns
*/
export function stripscript(str) {
var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;:”“'。,、?]");
var rs = "";
for (var i = 0; i < str.length; i++) {
rs = rs + str.substr(i, 1).replace(pattern, '');
}
return rs;
}
/**
* 用户名校验
* @param {*} str
* @returns
*/
export function checkUname(str) {
let regExp = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
return !regExp.test(str);
}
/**
* 密码校验
* @param {*} str
* @returns
*/
export function checkPwd(str) {
let regExp = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/;
return !regExp.test(str);
}
/**
* 验证码校验
* @param {*} str
* @returns
*/
export function checkCod(str) {
let regExp = /^[a-zA-Z0-9]{6}$/;
return !regExp.test(str);
}
/**
* 仅使用 export 时,可以多次使用,当使用 import 引入时必须加花括号
*/
|
(function ($) {
var initMobileMenu = function () {
$('.js-menu-link').on('click', function (event) {
event.preventDefault();
$('.js-nav-primary').slideToggle(300);
});
};
$(window).on('load', initMobileMenu);
})(window.jQuery);
|
$(function(){
//.info mousedown点击切换事件变量
var choose = true;
//保存送货信息
$('.saveinfo').click(function(){
var infoData = $('#deliveinfo input').map(function(){
return ($(this).attr('name')+'='+$(this).val())
}).get().join('&');
$.ajax({
type: 'post',
url:'/deliveinfo',
data: infoData
}).done(function(results) {
if(results.success === 1) {
var ul = $("<ul>").addClass("info-"+results.deliveinfo._id ).addClass("info").css({
"width":"200px",
"height":"100px",
"backgroundColor": "#F0F0F0",
"display":"inline-block"
}).appendTo($('.infolist'));
$("<li/>").css({"color":"green"}).html('姓名:'+results.deliveinfo.name).appendTo(ul);
$("<li/>").css({"color":"green"}).html('联系方式:'+results.deliveinfo.phone).appendTo(ul);
$("<li/>").css({"color":"green"}).html('地址:'+results.deliveinfo.address).appendTo(ul);
$("<input/>").attr({
type:'button',
value: '删除',
class: 'remInfo',
'data-id': results.deliveinfo._id
}).appendTo(ul)
}
})
})
//删除信息
$('.infolist').on('click','.remInfo',function(e){
var target = $(e.target);
var id = target.data('id');
var info = $('.info-'+id);
$.ajax({
type: 'delete',
url:'/deliveinfo/del?id='+id
}).done(function(results) {
if (results.success === 1) {
info.remove();
}
})
})
//选择信息
$('.infolist').on('click','.info',function(){
if(choose) {
$(this).css({
"backgroundColor":"red"
})
choose = false;
}else {
$(this).css({
"backgroundColor":"#F0F0F0"
})
choose = true;
}
})
//开发票
$('.offerbill').click(function(){
if($(this).is(':checked')){
$('.bill').css("display","block")
}else{
$('.bill').css("display","none")
}
})
})
|
module.exports = {
"sidebar.app": "אפליקציה",
"sidebar.horizontal": "אופקי",
"sidebar.horizontalMenu": "תפריט אופקי",
"sidebar.general": "כללי",
"sidebar.component": "רְכִיב",
"sidebar.features": "מאפיינים",
"sidebar.applications": "יישומים",
"sidebar.dashboard": "לוּחַ מַחווָנִים",
"sidebar.dashboard1": "לוח מחוונים 1",
"sidebar.dashboard2": "לוח המחוונים 2",
"sidebar.dashboard3": "לוח מחוונים 3",
"sidebar.modules": "מודולים",
"sidebar.agency": "סוֹכְנוּת",
"sidebar.pages": "דפים",
"sidebar.gallery": "גלריה",
"sidebar.pricing": "תמחור",
"sidebar.terms&Conditions": "תנאי תנאים",
"sidebar.feedback": "מָשׁוֹב",
"sidebar.report": "להגיש תלונה",
"sidebar.faq(s)": "שאלות נפוצות ",
"sidebar.advancedComponent": "רכיב מתקדם",
"sidebar.blank": "רֵיק",
"sidebar.session": "מוֹשָׁב",
"sidebar.login": "התחברות",
"sidebar.register": "הירשם",
"sidebar.lockScreen": "מסך נעילה",
"sidebar.forgotPassword": "שכחת את הסיסמא",
"sidebar.404": "404",
"sidebar.500": "500",
"sidebar.uiComponents": "רכיבי ממשק משתמש",
"sidebar.alerts": "התראות",
"sidebar.appBar": "בר יישומים",
"sidebar.avatars": "אווטרים",
"sidebar.buttons": "כפתורים",
"sidebar.bottomNavigations": "ניווט למטה",
"sidebar.badges": "תגים",
"sidebar.cards": "כרטיסים",
"sidebar.cardsMasonry": "כרטיסים מודפסים",
"sidebar.chip": "שְׁבָב",
"sidebar.dialog": "דיאלוג",
"sidebar.dividers": "מְחוּגָה",
"sidebar.drawers": "תַחתוֹנִים",
"sidebar.popover": "פופובר",
"sidebar.expansionPanel": "לוח הרחבה",
"sidebar.gridList": "רשימת רשת",
"sidebar.list": "רשימה",
"sidebar.menu": "תַפרִיט",
"sidebar.popoverAndToolTip": "פופ מעל והסבר קצר",
"sidebar.progress": "התקדמות",
"sidebar.snackbar": "סנקבר",
"sidebar.selectionControls": "פקדי בחירה",
"sidebar.advanceUiComponents": "מתקדם רכיבי ממשק משתמש",
"sidebar.dateAndTimePicker": "תאריך & תאריך בורר",
"sidebar.tabs": "כרטיסיות",
"sidebar.stepper": "צעד",
"sidebar.notification": "הוֹדָעָה",
"sidebar.sweetAlert": "התראה מתוקה",
"sidebar.autoComplete": "השלמה אוטומטית",
"sidebar.aboutUs": "עלינו",
"sidebar.widgets": "ווידג'טים",
"sidebar.forms": "טפסים",
"sidebar.formElements": "אלמנטים טופס",
"sidebar.textField": "שדה טקסט",
"sidebar.selectList": "בחר רשימה",
"sidebar.charts": "תרשימים",
"sidebar.reCharts": "תרשימים חוזרים",
"sidebar.reactChartjs2": "לְהָגִיב תרשים 2",
"sidebar.icons": "סמלים",
"sidebar.themifyIcons": "לסנכרן סמלים",
"sidebar.simpleLineIcons": "אייקונים פשוטים",
"sidebar.materialIcons": "סמלים חומר",
"sidebar.fontAwesome": "גופן מדהים",
"sidebar.tables": "טבלאות",
"sidebar.basic": "בסיסי",
"sidebar.dataTable": "טבלת נתונים",
"sidebar.responsive": "תגובה",
"sidebar.reactTable": "טבלת תגובה",
"sidebar.maps": "מפות",
"sidebar.googleMaps": "גוגל מפות",
"sidebar.leafletMaps": "מפות עלים",
"sidebar.inbox": "תיבת הדואר הנכנס",
"sidebar.users": "משתמשים",
"sidebar.userProfile1": "פרופיל משתמש 1",
"sidebar.userProfile2": "פרופיל משתמש 2",
"sidebar.userManagement": "ניהול משתמשים",
"sidebar.userProfile": "פרופיל משתמש",
"sidebar.userList": "רשימת משתמש",
"sidebar.calendar": "לוּחַ שָׁנָה",
"sidebar.cultures": "תרבויות",
"sidebar.dnd": "Dnd",
"sidebar.selectable": "ניתן לבחירה",
"sidebar.customRendering": "עיבוד מותאם אישית",
"sidebar.chat": "לְשׂוֹחֵחַ",
"sidebar.toDo": "לעשות",
"sidebar.editor": "עוֹרֵך",
"sidebar.wysiwygEditor": "עורך WYSIWYG",
"sidebar.quillEditor": "עורך",
"sidebar.reactAce": "תגובת אייס",
"sidebar.dragAndDrop": "גרור ושחרר",
"sidebar.reactDragula": "תגובתי",
"sidebar.reactDnd": "לְהָגִיב דנד",
"sidebar.blogManagement": "בלוג ניהול",
"sidebar.ecommerce": "מסחר אלקטרוני",
"sidebar.shopList": "רשימת החנות",
"sidebar.shopGrid": "חנות רשת",
"sidebar.invoice": "חשבונית",
"sidebar.multilevel": "רב",
"sidebar.sublevel": "תת-קרקעי",
"widgets.totalEarns": "סך כל הרווחים",
"widgets.emailsStatistics": "הודעות דוא ל לסטטיסטיקה",
"widgets.totalRevenue": "סך הרווחים",
"widgets.onlineVistors": "באינטרנט מבקרים",
"widgets.trafficSources": "מקורות תנועה",
"widgets.RecentOrders": "הזמנות אחרונות",
"widgets.topSellings": "Tמכירת אופ",
"widgets.productReports": "דוחות מוצרים",
"widgets.productStats": "נתונים סטטיסטיים של מוצרים",
"widgets.ComposeEmail": "כתוב מייל אלקטרוני",
"widgets.employeePayroll": "שכר שכר",
"widgets.visitors": "מבקרים",
"widgets.orders": "הזמנות",
"widgets.totalSales": 'סה"כ מכירות',
"widgets.orderStatus": "מצב הזמנה",
"widgets.netProfit": "נֶטוֹ רווח",
"widgets.overallTrafficStatus": "מצב התנועה הכולל",
"widgets.ratings": "דירוגים",
"widgets.tax": "מַס",
"widgets.expenses": "הוצאות",
"widgets.currentTime": "זמן נוכחי",
"widgets.currentDate": "דייט נוכחי",
"widgets.todayOrders": "הזמנות היום",
"widgets.toDoList": "לעשות רשימות",
"widgets.discoverPeople": "גלה אנשים",
"widgets.commments": "הערות",
"widgets.newCustomers": "לקוחות חדשים",
"widgets.recentNotifications": "הודעות אחרונות",
"widgets.appNotifications": "התראות יישום",
"widgets.siteVisitors": "",
"widgets.recentActivities": "פעילויות אחרונות",
"widgets.recentOrders": "הזמנות אחרונות",
"widgets.gallery": "גלריה",
"widgets.pricing": "תמחור",
"widgets.enterpriseEdition": "גרסה לארגונים",
"widgets.socialCompanines": "חברות חברתיות",
"widgets.personalEdition": "מהדורה אישית",
"widgets.teamEdition": "מהדורת צוות",
"widgets.standard": "תֶקֶן",
"widgets.advanced": "מִתקַדֵם",
"widgets.master": "לִשְׁלוֹט",
"widgets.Mega": "מגה",
"widgets.logIn": "התחברn",
"widgets.signUp": "הירשם",
"widgets.lockScreen": "מסך נעילה",
"widgets.alertsWithLink": "התראות עם קישור",
"widgets.additionalContent": "תוכן נוסף",
"widgets.alertDismiss": "התראה דחה",
"widgets.uncontrolledDisableAlerts": "בלתי מבוקרת השבת התראות",
"widgets.contexualAlerts": "התראות דו - צדדיות",
"widgets.alertsWithIcons": "התראות עם סמלים",
"widgets.Simple App Bars": "פשוט ברים אפליקציה",
"widgets.appBarsWithButtons": "ברים אפליקציה עם לחצנים",
"widgets.imageAvatars": "תמונה אווטרים",
"widgets.lettersAvatars": "מכתבים אווטרים",
"widgets.iconsAvatars": "סמלים אווטרים",
"widgets.flatButtons": "לחצנים שטוחים",
"widgets.raisedButton": "לחצן גויס",
"widgets.buttonWithIconAndLabel": "לחצן עם סמל ותווית",
"widgets.floatingActionButtons": "לחצני פעולה צפים",
"widgets.iconButton": "לחצן סמל",
"widgets.socialMediaButton": "לחצן מדיה חברתית",
"widgets.reactButton": "לחצן לְהָגִיב",
"widgets.buttonOutline": "מתאר",
"widgets.buttonSize": "גודל כפתור",
"widgets.buttonState": "מצב לחצן",
"widgets.buttonNavigationWithNoLabel": "כפתור ניווט ללא תווית",
"widgets.buttonNavigation": "ניווט באמצעות לחצן",
"widgets.iconNavigation": "ניווט בסמל",
"widgets.badgeWithHeadings": "תג עם כותרות",
"widgets.contexualVariations": "וריאציות מידיות",
"widgets.badgeLinks": "קישורים 'קישורים'",
"widgets.materialBadge": "תג חומר",
"widgets.simpleCards": "כרטיסים פשוטים",
"widgets.backgroundVarient": "רקע וריאנט",
"widgets.cardOutline": "מתווה כרטיס",
"widgets.overlayCard": "כרטיס כיסוי",
"widgets.cardGroup": "קבוצת כרטיס",
"widgets.cardTitle": "כותרת כרטיס",
"widgets.speacialTitleTreatment": "טיפול כותרת כותרת",
"widgets.chipWithClickEvent": "צ'יפ עם אירוע לחץ",
"widgets.chipArray": "מערך שבבים",
"widgets.dialogs": "דיאלוגים",
"widgets.listDividers": "רשימת מחיצות",
"widgets.insetDividers": "מחלקים",
"widgets.temporaryDrawers": "מגירות זמניות",
"widgets.permanentDrawers": "מגירות קבועות",
"widgets.simpleExpansionPanel": "לוח הרחבה פשוט",
"widgets.controlledAccordion": "אקורדיון מבוקר",
"widgets.secondaryHeadingAndColumns": "כותרת משנית ועמודות",
"widgets.imageOnlyGridLists": "תמונה בלבד רשימות רשת",
"widgets.advancedGridLists": "רשימות רשת מתקדמות",
"widgets.singleLineGridLists": "רשימות רשת",
"widgets.simpleLists": "רשימות פשוטות",
"widgets.folderLists": "רשימות תיקיות",
"widgets.listItemWithImage": "פריט רשימה עם תמונה",
"widgets.switchLists": "החלף רשימות",
"widgets.insetLists": "רשימות הבלעה",
"widgets.nestedLists": "רשימות מקוננות",
"widgets.checkboxListControl": "בקרת רשימת תיבות",
"widgets.pinedSubHeader": "כותרת משנה",
"widgets.InteractiveLists": "",
"widgets.simpleMenus": "תפריטים פשוטים",
"widgets.selectedMenu": "תפריט נבחר",
"widgets.maxHeightMenu": "תפריט גובה מקסימלי",
"widgets.changeTransition": "שינוי מעבר",
"widgets.paper": "עיתון",
"widgets.anchorPlayGround": "עוגן",
"widgets.tooltip": "הסבר קצר",
"widgets.positionedToolTips": "מיקום סנקבר",
"widgets.circularProgressBottomStart": "התקדמות מעגלית",
"widgets.interactiveIntegration": "אינטגרציה אינטראקטיבית",
"widgets.determinate": "קבעו",
"widgets.linearProgressLineBar": "שורת התקדמות קו לינארי",
"widgets.indeterminate": "לֹא קָבוּעַ",
"widgets.buffer": "בַּלָם",
"widgets.query": "שאילתא",
"widgets.transitionControlDirection": "כיוון בקרת מעבר",
"widgets.simpleSnackbar": "פשוט חטיף",
"widgets.positionedSnackbar": "מיקום סנקבר",
"widgets.contexualColoredSnackbars": "צבעוני חטיפים צבעוניים",
"widgets.simpleCheckbox": "תיבת סימון פשוטה",
"widgets.interminateSelection": "בחירה סופית",
"widgets.disabledCheckbox": "תיבת סימון מושבתת",
"widgets.customColorCheckbox": "תיבת צבע מותאמת אישית",
"widgets.VerticalStyleCheckbox": "תיבת סימון בסגנון אנכי",
"widgets.horizontalStyleCheckbox": "סגנון אופקי תיבת סימון",
"widgets.radioButtons": "כפתורי רדיו",
"widgets.disabledRadio": "רדיו מושבת",
"widgets.withError": "עם שגיאה",
"widgets.switches": "Swiches",
"widgets.dateAndTimePicker": "תאריך ושעה פיקר",
"widgets.defaultPicker": "בורר ברירת המחדל",
"widgets.timePicker": "בורר זמן",
"widgets.weekPicker": "בורר השבוע",
"widgets.defaultDatePicker": "בְּרִירַת מֶחדָל תַאֲרִיך קוֹטֵף",
"widgets.customPicker": "בוחר מותאם אישית",
"widgets.tabs": "כרטיסיות",
"widgets.fixedTabs": "כרטיסיות קבועות",
"widgets.basicTab": "הכרטיסייה הבסיסית",
"widgets.wrappedLabels": "תוויות עטופות",
"widgets.centeredLabels": "תוויות מרוכזות",
"widgets.forcedScrolledButtons": "לחצן גלילה כפויs",
"widgets.iconsTabs": "כרטיסיות סמלים",
"widgets.withDisableTabs": "עם השבת כרטיסיות",
"widgets.iconWithLabel": "סמל עם תווית",
"widgets.stepper": "צעד",
"widgets.horizontalLinear": "אופקי ליניארי",
"widgets.horizontalNonLinear": "אופקי לא ליניארי",
"widgets.horizontalLinerAlternativeLabel": "אופקי ליינר אלטרנטיבי תווית",
"widgets.horizontalNonLinerAlternativeLabel": "אופקי לא ליינר תווית אלטרנטיבית",
"widgets.verticalStepper": "סטפר אנכי",
"widgets.descriptionAlert": "תיאור התראה",
"widgets.customIconAlert": "התראה סמל מותאם אישית",
"widgets.withHtmlAlert": "עם התראת HTML",
"widgets.promptAlert": "התראה מוקדמת",
"widgets.passwordPromptAlert": "התראת בקשה לסיסמה",
"widgets.customStyleAlert": "התראה בסגנון מותאם אישית",
"widgets.autoComplete": "השלמה אוטומטית",
"widgets.reactSelect": "לְהָגִיב בחר",
"widgets.downshiftAutoComplete": "השלם אוטומטי",
"widgets.reactAutoSuggests": "לְהָגִיב אוטומטי מציע",
"widgets.aboutUs": "עלינו",
"widgets.ourVission": "שלנו אשר",
"widgets.ourMissions": "המשימות שלנו",
"widgets.ourMotivation": "המוטיבציה שלנו",
"widgets.defualtReactForm": "טופס תגובה ברירת המחדל",
"widgets.url": "כתובת אתר",
"widgets.textArea": "אזור טקסט",
"widgets.file": "קוֹבֶץ",
"widgets.formGrid": "טופס טבלה",
"widgets.inlineForm": "טופס מוטבע",
"widgets.inputSizing": "גודל קלט",
"widgets.inputGridSizing": "קלט שינוי גודל הרשת",
"widgets.hiddenLabels": "תוויות נסתרות",
"widgets.formValidation": "אימות טופס",
"widgets.number": "מספר",
"widgets.date": "תַאֲרִיך",
"widgets.time": "זְמַן",
"widgets.color": "צֶבַע",
"widgets.search": "לחפש",
"widgets.selectMultiple": "בחר מרובים",
"widgets.inputWithSuccess": "קלט עם הצלחה",
"widgets.inputWithDanger": "כניסה עם סכנה",
"widgets.simpleTextField": "שדה טקסט פשוט",
"widgets.componet": "רכיבים",
"widgets.layouts": "פריסות",
"widgets.inputAdorements": "הקלט",
"widgets.formattedInputs": "תשומות מעוצבות",
"widgets.simpleSelect": "בחר פשוט",
"widgets.nativeSelect": "בחירת שפת אם",
"widgets.MutltiSelectList": "רַב בחר רשימה",
"widgets.lineChart": "תרשים שורה",
"widgets.barChart": "טבלת עמודות",
"widgets.stackedBarChart": "תרשים עמודות מוערמות",
"widgets.lineBarAreaChart": "תרשים הקו של הקו בר",
"widgets.areaChart": "תרשים שטח",
"widgets.stackedAreaChart": "תרשים שטח מוערם",
"widgets.verticalChart": "תרשים אנכי",
"widgets.radarChart": "תרשים מכ ם",
"widgets.doughnut": "סופגניה",
"widgets.polarChart": "תרשים פולאר",
"widgets.pieChart": "תרשים עוגה",
"widgets.bubbleChart": "תרשים הבועה",
"widgets.horizontalBar": "בר אופק",
"widgets.basicTable": "טבלה בסיסית",
"widgets.contexualColoredTable": "טבלה צבעונית",
"widgets.dataTable": "טבלת נתונים",
"widgets.employeeList": "רשימת עובדים",
"widgets.responsiveTable": "טבלאות תגובה",
"widgets.responsiveFlipTable": "טבלת תגובה לְהַעִיף",
"widgets.reactGridControlledStateMode": "לְהָגִיב במצב מצב מבוקר",
"widgets.googleMaps": "גוגל מפות",
"widgets.productsReports": "דוחות מוצרים",
"widgets.taskList": "רשימת מטלות",
"widgets.basicCalender": "בסיסי קלנדר",
"widgets.culturesCalender": "תרבויות",
"widgets.dragAndDropCalender": "גרור ושחרר קלנדר",
"widgets.selectableCalender": "לבחירה קלנדר",
"widgets.customRendering": "עיבוד מותאם אישית",
"widgets.customCalender": "לוח שנה מותאם אישית",
"widgets.searchMailList": "חפש רשימת דואר",
"components.buyNow": "קנה עכשיו",
"compenets.choose": "בחר",
"compenets.username": "שם משתמש",
"compenets.passwords": "סיסמאות",
"widgets.forgetPassword": "שכחתי את הסיסמה",
"compenets.signIn": "היכנס",
"compenets.dontHaveAccountSignUp": "אין כניסה לחשבון",
"compenets.enterUserName": "הכנס שם משתמש",
"compenets.enterEmailAddress": "הזן כתובת דואל",
"compenets.confirmPasswords": "אשר סיסמאות",
"components.alreadyHavingAccountSignIn": "כבר יש לך חשבון כניסה",
"components.enterYourPassword": "הכנס את הסיסמה שלך",
"components.unlock": "לבטל נעילה",
"components.enterPasswords": "הזן סיסמאות",
"components.resetPassword": "Resest סיסמה",
"components.pageNotfound": "דף לא",
"components.sorryServerGoesWrong": "שרת מצטער טועה",
"components.persistentDrawer": "מגירה מתמשכת",
"components.back": "חזור",
"components.next": "הַבָּא",
"components.completeStep": "שלב שלם",
"components.success": "הַצלָחָה",
"components.passwordPrompt": "בקשה לסיסמה",
"components.warning": "אַזהָרָה",
"components.customIcon": "סמל מותאם אישית",
"components.customStyle": "סגנון מותאם אישית",
"components.basic": "בסיסי",
"components.submit": "שלח",
"components.compose": "לְהַלחִין",
"components.sendMessage": "לשלוח הודעה",
"components.addNewTasks": "הוסף משימות חדשות",
"components.addToCart": "הוסף לעגלה",
"components.payNow": "שלם עכשיו",
"components.print": "הדפס",
"components.cart": "עֲגָלָה",
"components.viewCart": "צפה בסל",
"components.checkout": "לבדוק",
"widgets.QuickLinks": "קישורים מהירים",
"widgets.upgrade": "לשדרג",
"widgets.app": "App",
"widgets.addNew": "הוסף חדש",
"widgets.orderDate": "תאריך הזמנה",
"widgets.status": "סטָטוּס",
"widgets.trackingNumber": "Tמספר מרתיעה",
"widgets.action": "פעולה",
"widgets.designation": "יִעוּד",
"widgets.subject": "נושא",
"widgets.send": "לִשְׁלוֹחַ",
"widgets.saveAsDrafts": "שמירה כטיוטות",
"widgets.onlineSources": "מקורות מקוונים",
"widgets.lastMonth": "חודש שעבר",
"widgets.widgets": "ווידג'טים",
"widgets.listing": "מודעה",
"widgets.paid": "בתשלום",
"widgets.refunded": "החזר כספי",
"widgets.done": "בוצע",
"widgets.pending": "ממתין ל",
"widgets.cancelled": "מבוטל",
"widgets.approve": "לְאַשֵׁר",
"widgets.following": "הבא",
"widgets.follow": "לעקוב אחר",
"widgets.graphs&Charts": "גרפים ותרשימים",
"widgets.open": "לִפְתוֹחַ",
"widgets.bounced": "ניתק",
"widgets.spam": "ספאם",
"widgets.unset": "לא הוגדר",
"widgets.bandwidthUse": "שימוש ברוחב פס",
"widgets.dataUse": "שימוש בנתונים",
"widgets.unsubscribe": "בטל רישום",
"widgets.profile": "פּרוֹפִיל",
"widgets.messages": "הודעות",
"widgets.support": "תמיכה",
"widgets.faq(s)": "פאק (ים)",
"widgets.upgradePlains": "שדרג שפלים",
"widgets.logOut": "להתנתק",
"widgets.mail": "דוֹאַר",
"widgets.adminTheme": "נושאים של מנהל מערכת",
"widgets.wordpressTheme": "נושאים",
"widgets.addToCart": "הוסף לעגלה",
"widgets.plan": "לְתַכְנֵן",
"widgets.basic": "בסיסי",
"widgets.pro": "מִקצוֹעָן",
"widgets.startToBasic": "התחל בסיסיים",
"widgets.upgradeToPro": "שדרוג לפרו",
"widgets.upgradeToAdvance": "שדרג מראש",
"widgets.comparePlans": "השווה תוכניות",
"widgets.free": "חופשי",
"widgets.frequentlyAskedQuestions": "שאלות נפוצות",
"widgets.newEmails": 'הודעות דוא"ל חדשות',
"widgets.searchIdeas": "חיפוש רעיונות",
"widgets.startDate": "תאריך התחלה",
"widgets.endDate": "תאריך סיום",
"widgets.category": "קטגוריה",
"widgets.apply": "להגיש מועמדות",
"widgets.downloadPdfReport": "הורד דוח PDF",
"widgets.yesterday": "אתמול",
"widgets.totalOrders": "סהכ הזמנות",
"widgets.totalVisitors": "סהכ מבקרים",
"widgets.typeYourQuestions": "הקלד את השאלות שלך",
"widgets.username": "שם משתמש",
"widgets.password": "סיסמה",
"widgets.signIn": "היכנס",
"widgets.enterYourPassword": "הכנס את הסיסמה שלך",
"widgets.alreadyHavingAccountLogin": "כבר יש לך כניסה לחשבון",
"widgets.composeMail": "כתוב דואר",
"widgets.issue": "נושא",
"widgets.recentChat": "צ'אט אחרונים",
"widgets.previousChat": "צ'אט הקודם",
"widgets.all": "את כל",
"widgets.filters": "מסננים",
"widgets.deleted": "נמחק",
"widgets.starred": "כיכב",
"widgets.frontend": "חזיתי",
"widgets.backend": "Backend",
"widgets.api": "Api",
"widgets.simpleAppBar": "פשוט אפליקציה בר",
"widgets.recents": "דוכנים",
"widgets.cardLink": "קישור כרטיס",
"widgets.anotherLink": "קישור נוסף",
"widgets.cardSubtitle": "כרטיס",
"widgets.confirmationDialogs": "דיאלוגים לאישור",
"widgets.deletableChip": "שבב נמחק",
"widgets.customDeleteIconChip": "מחיקת סמל",
"widgets.openAlertDialog": "פתח את תיבת הדו-שיח התראה",
"widgets.openResponsiveDialog": "פתח את תיבת הדו-שיח 'תגובה'",
"widgets.openSimpleDialog": "פתח דיאלוג פשוט",
"widgets.openFormDialog": "פתח את תיבת הדו-שיח 'טופס'",
"widgets.follower": "חָסִיד",
"widgets.important": "חָשׁוּב",
"widgets.private": "פְּרָטִי",
"widgets.openLeft": "פתח שמאלה",
"widgets.openRight": "פתח את 'ימין'",
"widgets.openTop": "פתח את הדף",
"widgets.openBottom": "פתח את תחתית",
"widgets.selectTripDestination": "בחר יעד נסיעה",
"widgets.pinnedSubheaderList": "רשימת כותרות משנה מוצמדות",
"widgets.singleLineItem": "פריט יחיד",
"widgets.acceptTerms": "קבל תנאים",
"widgets.optionA": "אפשרות א",
"widgets.optionB": "אפשרות ב '",
"widgets.optionC": "אפשרות ג",
"widgets.optionM": "אפשרות M",
"widgets.optionN": "אפשרות N",
"widgets.optionO": "אפשרות O",
"widgets.customColor": "צבע מותאם אישית",
"widgets.centeredTabs": "כרטיסיות מרוכזות",
"widgets.multipleTabs": "כרטיסיות מרובות",
"widgets.preventScrolledButtons": "מנע לחצני גלילה",
"widgets.browse": "לְדַפדֵף",
"widgets.formValidate": "טופס אימות",
"widgets.code": "קוד",
"widgets.company": "חֶברָה",
"widgets.price": "מחיר",
"widgets.change": "שינוי",
"widgets.high": "גָבוֹהַ",
"widgets.low": "נָמוּך",
"widgets.volume": "כרך",
"widgets.personalDetails": "פרטים אישיים",
"widgets.occupation": "כיבוש",
"widgets.companyName": "שם החברה",
"widgets.phoneNo": "בטלפון",
"widgets.city": "עִיר",
"widgets.zipCode": "מיקוד",
"widgets.updateProfile": "עדכן פרופיל",
"widgets.reject": "לִדחוֹת",
"widgets.exportToExcel": "יצוא ל - לְהִצטַיֵן",
"widgets.addNewUser": "הוסף משתמש חדש",
"widgets.workWeek": "שבוע עבודה",
"widgets.agenda": "סֵדֶר הַיוֹם",
"widgets.conference": "וְעִידָה",
"widgets.multilevel": "רב",
"widgets.dailySales": "מכירות יומיות",
"widgets.today": "היום",
"widgets.campaignPerformance": "ביצועי מסע פרסום",
"widgets.supportRequest": "בקשת תמיכה",
"widgets.usersList": "רשימת משתמשים",
"widgets.lastWeek": "שבוע שעבר",
"themeOptions.sidebarOverlay": "כיסוי שכבה צדדית",
"themeOptions.sidebarBackgroundImages": "תמונות רקע בסרגל הצד",
"themeOptions.sidebarImage": "תמונה של סרגל צדדי",
"themeOptions.miniSidebar": "מיני הסרגל הצידי",
"themeOptions.boxLayout": "פריסת תיבה",
"themeOptions.rtlLayout": "פריסת Rtl",
"themeOptions.darkMode": "מצב כהה",
"themeOptions.appSettings": "הגדרות אפליקציה",
"themeOptions.sidebarLight": "אוֹר",
"themeOptions.sidebarDark": "אפל",
"button.cancel": "לְבַטֵל",
"button.add": "לְהוֹסִיף",
"button.update": "עדכון",
"button.reply": "תשובה",
"button.delete": "לִמְחוֹק",
"button.yes": "כן",
"button.viewAll": "צפה בהכל",
"button.like": "כמו",
"button.assignNow": "הקצה עכשיו",
"button.seeInsights": "ראה תובנות",
"sidebar.dateTimePicker": "תאריך & תאריך בורר",
"components.summary": "סיכום",
"hint.whatAreYouLookingFor": "מה אתה מחפש",
"components.yesterday": "אתמול",
"components.last7Days": "שבעת הימים האחרונים",
"components.last1Month": "1 חודש אחרון",
"components.last6Month": "האחרון 6 חודש",
"components.spaceUsed": "שטח המשמש",
"components.followers": "עוקב",
"components.trending": "מגמות",
"components.paid": "שילם",
"components.refunded": "החזר כספי",
"components.done": "בוצע",
"components.pending": "בהמתנה",
"components.cancelled": "בוטל",
"components.approve": "אשר",
"components.week": "שבוע",
"components.month": "חודש",
"components.year": "שנה",
"components.today": "היום",
"components.popularity": "פופולריות",
"components.email": "אֶלֶקטרוֹנִי",
"components.drafts": "",
"components.sent": "נשלח",
"components.trash": "אשפה",
"components.all": "את כל",
"components.do": "עשה",
"components.title": "כותרת",
"components.projectName": "שם הפרויקט",
"names.companyName": "שם החברה",
"components.openAlert": "פתח התראה",
"components.slideInAlertDialog": "שקופית בדיאלוג התראה",
"components.openFullScreenDialog": "פתיחת תיבות דו-שיח מסך מלא",
"components.basicChip": "שבב בסיסי",
"components.clickableChip": "צ'יפ ללחיצה",
"components.left": "שמאל",
"components.right": "נכון",
"components.expansionPanel1": "לוח הרחבה 1",
"components.expansionPanel2": "לוח הרחבה 2",
"settings.generalSetting": "הגדרה כללית",
"components.advancedSettings": "הגדרות מתקדמות",
"names.firstName": "שם פרטי",
"names.lastName": "שם משפחה",
"components.occupation": "עיסוק",
"phones.phoneNo": "טלפון לא",
"components.address": "כתובת",
"components.city": "עיר",
"components.state": "מדינה",
"code.zip קוד": "מיקוד",
"components.social Connection": "חיבור חברתי",
"widgets.buyMore": "קנה עוד",
"widgets.trafficChannel": "ערוץ תעבורה",
"widgets.stockExchange": "הבורסה",
"widgets.tweets": "Tweets",
"widgets.ourLocations": "המיקומים שלנו",
"widgets.sales": "מכירה",
"widgets.to": "To",
"widgets.shipTo": "משלוח אל",
"widgets.description": "תיאור",
"widgets.unitPrice": "מחיר היחידה",
"widgets.total": 'סה"כ',
"widgets.note": "הערה",
"widgets.chipWithAvatar": "צ'יפ עם אווטר",
"widgets.chipWithTextAvatar": "צ'יפ עם אווטר טקסט",
"widgets.chipWithIconAvatar": "צ'יפ עם סמל גלגול",
"widgets.customClickableChip": "צ'יפ הניתן ללחיצה אישית",
"widgets.outlineChip": "צ'יפ מתאר",
"widgets.disableChip": "השבת צ'יפ",
"widgets.alertDialog": "התראת דיאלוג",
"widgets.animatedSlideDialogs": "דיאלוגים שקופיות מונפשים",
"widgets.fullScreenDialogs": "תיבות דו-שיח למסך מלא",
"widgets.formDialogs": "טופס דיאלוגים",
"widgets.simpleDialogs": "דיאלוגים פשוטים",
"widgets.responsiveFullScreen": "מסך מלא תגובה",
"widgets.primary": "ראשי",
"widgets.social": "חברתי",
"widgets.user": "משתמש",
"widgets.admin": "מנהל מערכת",
"widgets.permanentdrawer": "מגירה קבועה",
"widgets.persistentdrawer": "מגירה מתמדת",
"widgets.swiches": "Swiches",
"widgets.horizontalLinearAlternativeLabel": "תווית אלטרנטיבית ליניארית אופקית",
"widgets.horizontalNonLinearAlternativeLabel": "אופקי לא ליניארי תווית אלטרנטיבית",
"widgets.notifications": "הודעות",
"widgets.basicAlert": "התראה בסיסית",
"widgets.successAlert": "התראה הצלחה",
"widgets.warningAlert": "התראת אזהרה",
"widgets.reactAutoSuggest": "תגובה אוטומטית",
"widgets.components": "רכיבים",
"widgets.inputAdornments": "הקלט",
"widgets.multiSelectList": "רשימת רב",
"widgets.contextualColoredTable": "טבלת צבעים צבעוניים",
"widgets.updateYourEmailAddress": "עדכן את כתובת הדואר האלקטרוני שלך",
"widgets.selectADefaultAddress": "בחר כתובת ברירת מחדל",
"widgets.activity": "פעילות",
"widgets.basicCalendar": "לוח שנה בסיסי",
"widgets.culturesCalendar": "תרבויות לוח שנה",
"widgets.dragAndDropCalendar": "גרור ושחרר את לוח השנה",
"widgets.quillEditor": "עורך קוויל",
"widgets.reactDND": "תגובה dnd",
"widgets.dragula": "דראגולה",
"button.acceptTerms": "קבל תנאים",
"button.reject": "לִדחוֹת",
"button.addNew": "הוסף חדש",
"button.goToCampaign": "עבור אל מסע פרסום",
"button.viewProfile": "צפה בפרופיל",
"button.sendMessage": "לשלוח הודעה",
"button.saveNow": "שמור עכשיו",
"button.pen": "עֵט",
"button.search": "לחפש",
"button.downloadPdfReport": "הורד דוח PDF",
"button.primary": "יְסוֹדִי",
"button.secondary": "מִשׁנִי",
"button.danger": "סַכָּנָה",
"button.info": "מידע",
"button.success": "הַצלָחָה",
"button.warning": "אַזהָרָה",
"button.link": "קישור",
"button.smallButton": "כפתור קטן",
"button.largeButton": "כפתור גדול",
"button.blockLevelButton": "לחצן רמת בלוק",
"button.primaryButton": "לחצן ראשי",
"button.button": "לַחְצָן",
"button.save": "להציל",
"button.openMenu": "פתח תפריט",
"button.openWithFadeTransition": "פתח עם מעבר לדעוך",
"button.openPopover": "פתח את פופובר",
"button.accept": "לְקַבֵּל",
"button.click": "נְקִישָׁה",
"button.complete": "לְהַשְׁלִים",
"button.back": "חזור",
"button.next": "הַבָּא",
"button.completeStep": "שלב שלם",
"button.error": "שְׁגִיאָה",
"button.writeNewMessage": "כתוב הודעה חדשה",
"button.saveChanges": "שמור שינויים",
"button.addNewUser": "הוסף משתמש חדש",
"button.more": "יותר",
"hint.searchMailList": "חפש רשימת דואר",
"widgets.AcceptorrRejectWithin": "קבל או דחה בתוך",
"widgets.quoteOfTheDay": "ציטוט היום",
"widgets.updated10Minago": "עודכן לפני 10 דקות",
"widgets.personalSchedule": "לוח זמנים אישי",
"widgets.activeUsers": "משתמשים פעילים",
"widgets.totalRequest": 'סה"כ בקשה',
"widgets.new": "חָדָשׁ",
"widgets.ShareWithFriends": "לשתף עם חברים!",
"widgets.helpToShareText": "עזור לנו להפיץ את העולם על ידי שיתוף האתר שלנו עם חברים וחברים שלך על מדיה חברתית!",
"widgets.thisWeek": "השבוע",
"widgets.howWouldYouRateUs": "איך היית מדרג אותנו?",
"widgets.booking": "הזמנה",
"widgets.confirmed": "מְאוּשָׁר",
"widgets.monthly": "חודשי",
"widgets.weekly": "שבועי",
"widgets.target": "יעד",
"widgets.totalActiveUsers": 'סה"כ משתמשים פעילים',
"sidebar.user": "משתמש",
"sidebar.miscellaneous": "שונות",
"sidebar.promo": "פרומו",
"themeOptions.themeColor": "צבע ערכת נושא",
"module.inbox": "תיבת הדואר הנכנס",
"module.drafts": "",
"module.sent": "נשלח",
"module.trash": "אשפה",
"module.spam": "ספאם",
"module.frontend": "חזיתי",
"module.backend": "Backend",
"module.api": "Api",
"module.issue": "נושא",
"components.emailPrefrences": 'העדפות דוא"ל',
"components.myProfile": "הפרופיל שלי",
"sidebar.gettingStarted": "מתחילים",
"widgets.deadline": "מועד אחרון",
"widgets.team": "קְבוּצָה",
"widgets.projectManagement": "ניהול פרוייקט",
"widgets.latestPost": "הפרסום האחרון",
"widgets.projectTaskManagement": "ניהול משימות פרוייקט",
"widgets.selectProject": "בחר פרויקט",
"widgets.activityBoard": "לוח פעילות",
"widgets.checklist": "צ'ק ליסט",
"sidebar.shop": "לִקְנוֹת",
"sidebar.cart": "עֲגָלָה",
"sidebar.checkout": "לבדוק",
"components.product": "מוצר",
"components.quantity": "כַּמוּת",
"components.totalPrice": "מחיר סופי",
"components.removeProduct": "הסר מוצר",
"components.mobileNumber": "מספר טלפון נייד",
"components.address2Optional": "כתובת 2 (אופציונלי)",
"components.country": "מדינה",
"components.zip": "רוכסן",
"components.saveContinue": "שמור המשך",
"components.placeOrder": "בצע הזמנה",
"components.payment": "תַשְׁלוּם",
"components.billingAddress": "כתובת לחיוב",
"components.ShippingAddressText": "כתובת המשלוח זהה לכתובת לחיוב.",
"components.CartEmptyText": "עגלת הקניות שלך ריקה!",
"components.NoItemFound": "לא נמצא פריט",
"components.goToShop": "לך לחנות",
"components.cardNumber": "מספר כרטיס",
"components.expiryDate": "תאריך תפוגה",
"components.cvv": "CVV",
"components.nameOnCard": "שם על כרטיס",
"components.confirmPayment": "אשר תשלום",
"sidebar.saas": "ס.א.ס.",
"sidebar.multiLevel": "מדורג",
"sidebar.level1": "שלב 1",
"sidebar.level2": "שלב 2",
"sidebar.boxed": "מאורגן",
"sidebar.news": "חֲדָשׁוֹת",
"sidebar.extensions": "תוספים",
"sidebar.imageCropper": "תמונה קרופר",
"sidebar.videoPlayer": "נגן וידאו",
"sidebar.dropzone": "איזור נפילה",
"widgets.baseConfig": "תצורת Base",
"widgets.customControlBar": "סרגל בקרה מותאם אישית",
"widgets.withDownloadButton": "עם לחצן הורדה",
"widgets.httpLiveStreaming": "HTTP הזרמת חי",
"widgets.keyboardShortcuts": "קיצורי דרך במקלדת",
"button.useDefaultImage": "השתמש בתמונת ברירת מחדל",
"button.cropImage": "חתוך תמונה",
"widgets.preview": "תצוגה מקדימה",
"widgets.croppedImage": "תמונה חתוכה"
}
|
import React, { useState } from "react";
import styles from "./TaskCreator.module.scss";
export const TaskCreator = (props) => {
const [newTaskName, setNewTaskName] = useState("");
const updateNewTaskValue = (e) => setNewTaskName(e.target.value);
const createNewTask = () => {
props.callback(newTaskName);
setNewTaskName("");
};
/* ---- Añadir la nueva tarea pulsando "Enter" */
const pressEnter = (e) => {
if (e.key === "Enter") {
props.callback(newTaskName);
setNewTaskName("");
}
};
return (
<div className="my-1">
<input
type="text"
className={styles.newTask}
value={newTaskName}
onChange={updateNewTaskValue}
onKeyPress={
pressEnter
} /* ---- Añadir la nueva tarea pulsando "Enter" */
/>
{/* botón para agregar una nueva tarea */}
<button className={styles.bottonNewTask} onClick={createNewTask}>
Add
</button>
</div>
);
};
|
import PropTypes from 'prop-types';
import React from 'react';
import { css } from 'styled-components';
import injectStyles from '@/utils/injectStyles';
import { COLORS } from '@/utils/styleConstants';
const CenterLabel = ({ label, value, units, ...rest }) => (
<div {...rest}>
<p>{label}</p>
<p>{value}</p>
<p>{units}</p>
</div>
);
CenterLabel.propTypes = {
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
units: PropTypes.string.isRequired
};
CenterLabel.defaultProps = {};
CenterLabel.displayName = 'SunburstChartCenterLabelElement';
const styles = css`
position: absolute;
top: 80px;
width: 100%;
text-align: center;
& > p {
margin: 0;
color: ${COLORS.TEXT.PRIMARY};
font: 700 18px/21px var(--dff);
&:nth-child(2) {
font-size: 28px;
line-height: 34px;
}
}
`;
export default injectStyles(CenterLabel, styles);
|
import React from 'react';
import { NavLink } from 'react-router-dom'
import "../Stylesheets/navbar.scss";
const Navbar = () => {
const handleClick = (event) => {
localStorage.clear()
}
return (
<div className="nav">
<NavLink className="nav-link" exact to='/bodega'>HOME</NavLink>
<NavLink className="nav-link" exact to='/bodega/profile'>PROFILE</NavLink>
<NavLink className="nav-link" exact to='/bodega/cart'>CART</NavLink>
<NavLink className="nav-link" onClick={handleClick} exact to='/'>LOGOUT</NavLink>
</div>
)
}
export default Navbar
|
/*
The explanation on variable lifecycle is a little confusing. Let me explain more to help you better understand that concept.
First, remember this, the lifecycle of a variable declared with let is in the block scope(meaning you can't access it outside the code block where it was born) and one declared with var is in a function scope(same meaning with the function).
Here is the code with comment I added.
Copy the code into your editor to get better formatting and reading experience.
*/
function makeArray() { // If you declared the i with var, you can get it here bucause of hoisting and the var function scope lifecycle, but it will be undefined.
const arr = []
for (var i = 0; i < 5; i++) { //Beginning of the code block that i exists in.This is where i was born. You can use it from here.
//If you were to log out var or let here, there will be no differences. They will both iterate as expected.
arr.push(function () {
console.log(i)
})
//var and let will also log out the same iteration here as expected.
} //End of the code block with i. Since the lifecycle of a variable with let is the block scope, i with let dies right here. You can't get any i with let here.
//But var still lives here cuz the lifecycle of a variable wtih var is the function scope and the function has not ended yet. So here you can log out the i with a value of 5 with var. It's not about the iteration of i.
return arr /*This returns console.log(i). With let, it will use every i value in every iteration as expected cuz no i value outside the code block and therefore no value-shadowing. But with var, console.log(i) will directly use the i value outside the iteration code block because they are on the same level. Once the function finds an i, there is no need for it to dig into the code block to use the i there.*/
} //Function ends, i with var dies
const functionArr = makeArray()
functionArr[0]()
|
ko.components.register('activity-details', {
viewModel: function (params) {
var self = this;
self.SelectedActivity = params.SelectedActivity || ko.observable(new Activity({}));
self.DisplayActivityDetails = ko.observable(false);
self.SelectedActivity.subscribe(function (newSelectedActivity) {
self.fnShowActivityDetails();
})
self.fnShowActivityDetails = function () {
self.DisplayActivityDetails(true);
}
//The function removes an activity
self.fnRemoveActivity = function () {
$.ajax({
url: "/api/activities/" + self.SelectedActivity().id,
method: "Delete",
async: false,
}).done(function (result) {
})
}
},
template: { fromFileType: 'html' }
});
|
/*!
* SimpleTestJS JavaScript Library v{{version}}
* https://github.com/zoweb/SimpleTestJS
*
* Copyright zoweb and other contributors
* Released under the MIT license
* https://raw.githubusercontent.com/Zoweb/SimpleTestJS/master/LICENSE
*
* Compiled {{date}}
*/
(function(global, factory) {
"use strict";
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory(global, true);
} else {
factory(global);
}
})(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
var version = "{{version}}",
test = {};
var priv = {
extend: function(obj1, obj2) {
return Object.assign(obj1, obj2);
},
val: function(obj2) {
return Object.assign(priv, obj2);
},
each: function(obj, fn, deep) {
function loop(obj) {
for (var inner in obj) {
if (obj.hasOwnProperty(inner)) {
var innerObj = obj[inner];
if (typeof innerObj === "object" && deep) {
loop(innerObj);
} else {
fn.call(innerObj, Object.keys(obj).indexOf(inner), innerObj);
}
}
}
}
}
};
{{content}}
if (noGlobal) {
return test;
} else {
window.test = test;
}
});
|
const table = require('table');
const generateMap = (height, width) => {
const arr = new Array(height);
for (let i = 0; i < height; i++) {
arr[i] = new Array(width);
};
return arr;
};
const map = generateMap(30, 45);
const bullets = []; // x, y
const numbers = []; // x, y, num
const player = { name: '', x: map.length - 1, y: Math.floor(map[0].length / 2), score: 0, life: 3 };
let actualExercise;
let exercises = ['Lődd ki a páros számokat!', 'Lődd ki a páratlan számokat!'];
let rand = Math.floor(Math.random() * exercises.length);
const isGood = (n) => {
switch (rand) {
case 0:
if (n % 2 === 0) {
return true;
}
else return false;
break;
case 1:
if (n % 2 !== 0) {
return true;
}
else return false;
break;
}
}
const task = () => {
actualExercise = exercises[rand];
let counter = 0;
for (let i = 0; i < numbers.length; i++) {
if (isGood(numbers[i])) counter++;
}
return counter;
};
const isFinish = () => {
let c = task();
if (player.score === c) {
return true;
}
return false;
}
const fillMap = () => {
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
map[i][j] = ' ';
if (player.x === i && player.y === j) {
map[i][j] = 'P';
}
for (let k = 0; k < bullets.length; k++) {
if (i === bullets[k].x && j === bullets[k].y) {
map[i][j] = 'B';
}
}
for (let k = 0; k < numbers.length; k++) {
if (i === numbers[k].x && j === numbers[k].y) {
map[i][j] = numbers[k].num;
}
}
}
}
};
const printMap = () => {
console.clear();
console.log(actualExercise);
console.log(rand);
console.log(player);
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
process.stdout.write(map[i][j] + ' ');
}
console.log();
}
};
const playerMove = (isRight) => {
if (isRight && player.y < map[0].length - 1) {
player.y++;
} else if (isRight === false && player.y > 0) {
player.y--;
}
};
const isHit = () => {
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < bullets.length; j++) {
if (bullets[j].x === numbers[i].x && bullets[j].y === numbers[i].y && isGood(numbers[i].num)) {
hit(numbers[i].x, numbers[i].y);
player.score++;
}
else if (bullets[j].x === numbers[i].x && bullets[j].y === numbers[i].y) {
player.life--;
bullets.splice(j, 1);
}
}
};
}
const hit = (x, y) => {
for (let i = 0; i < numbers.length; i++) {
if (numbers[i].x === x && numbers[i].y === y) {
numbers.splice(i, 1);
}
}
for (let i = 0; i < bullets.length; i++) {
for (let j = 0; j < numbers.length; j++) {
if (numbers[j].x === bullets[i].x && numbers[j].y === bullets[i].y) {
numbers.splice(j, 1);
bullets.splice(i, 1);
console.log(numbers[j].x, bullets[i].x, numbers[j].y, bullets[i].y);
};
};
};
};
const gamerator = () => {
const arr = [];
for (let i = 0; i < 15; i++) {
let object = { x: 0, y: 0, num: 0 };
let random = Math.floor(Math.random() * (100 - 0) + 0);
if (arr.includes(random) === false) {
arr[i] = random;
object.num = random;
if (i < 5) object.x = 0;
else object.x = 1;
object.y = i * 3;
numbers.push(object);
}
else i--;
}
};
const numbersMove = () => {
for (let i = 0; i < numbers.length; i++) {
if (numbers[i].x < map.length - 2) {
numbers[i].x++;
}
else {
if (player.life > 0) player.life--;
};
};
};
const bulletsMove = () => {
for (let i = 0; i < bullets.length; i++) {
if (bullets[i].x === 0) {
bullets.splice(i, 1);
};
};
for (let i = 0; i < bullets.length; i++) {
bullets[i].x--;
};
};
const shoot = () => {
bullets.push({ x: player.x - 1, y: player.y });
};
module.exports = {
player,
generateMap,
fillMap,
printMap,
playerMove,
hit,
gamerator,
numbersMove,
bulletsMove,
shoot,
isHit,
task,
isGood,
isFinish
};
|
import React from 'react';
import PropTypes from 'prop-types';
const QuestionCard = ({ title, category, type, difficulty }) => {
return (
<div className="inline card questionCard">
<ul className="questionCard--attr">
<li>{category}</li>
<li>{difficulty}</li>
<li>{type}</li>
</ul>
<div className="questionCard--attr">
<p><strong>{title}</strong></p>
</div>
</div>
);
};
QuestionCard.propTypes = {
title: PropTypes.string.isRequired,
category: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
difficulty: PropTypes.string.isRequired,
};
export default QuestionCard;
|
var path = require("path");
var gulp = require("gulp");
var gulpU = require("gulp-util");
var webpack = require("webpack");
var del = require("del");
var gulpSequence = require("gulp-sequence");
var WebpackDevServer = require("webpack-dev-server");
var DEV_PORT = 3000;
gulp.task('server', function (cb) {
var myConfig = require('./webpack.config');
myConfig.entry.main.unshift('webpack/hot/only-dev-server');
myConfig.entry.main.unshift('webpack-dev-server/client?http://localhost:' + DEV_PORT);
myConfig.plugins.unshift(new webpack.HotModuleReplacementPlugin());
new WebpackDevServer(webpack(myConfig), {
noInfo: false,
hot: true,
inline: true,
historyApiFallback: true,
publicPath: myConfig.output.publicPath,
stats: {
colors: true
}
}).listen(DEV_PORT, "localhost", function (err) {
if (err) throw new gulpU.PluginError("webpack-dev-server", err)
gulpU.log("[webpack-dev-server]", "==> http://localhost:" + DEV_PORT)
});
});
gulp.task('clean', function () {
del.sync([path.join(__dirname, '/dist/*')])
});
gulp.task('webpack', function (cb) {
var webpackConfig = require('./webpack.config');
webpack(webpackConfig, function (err, stats) {
if (err) throw new gulpU.PluginError("webpack", err)
gulpU.log("[webpack]", stats.toString({
// output options
}))
cb()
});
});
gulp.task('build', gulpSequence('clean', 'webpack'));
gulp.task('default', ["server"]);
|
/**
* Module for the controller definition of the user api.
* The UserController is handling /api/users requests.
* @module {user:controller~UserController} user:controller
* @requires {@link module:config}
* @requires {@link ParamController}
*/
'use strict';
var _ = require('lodash');
var ParamController = require('../../lib/controllers/param.controller');
var config = require('../../config');
var formidable = require('formidable');
var fs = require('fs');
var path = require('path');
/**
* The User model instance
* @type {user:model~User}
*/
var Docs = require('./docs.model').model;
exports = module.exports = DocsController;
/**
* UserController constructor
* @classdesc Controller that handles /api/users route requests
* for the user api.
* Uses the 'id' parameter and the 'user' request property
* to operate with the [main user API Model]{@link user:model~User} model.
* @constructor
* @inherits ParamController
* @see user:model~User
*/
function DocsController(router) {
ParamController.call(this, Docs, 'id', 'docsDocument', router);
}
DocsController.prototype = {
/**
* Set our own constructor property for instanceof checks
* @private
*/
constructor: DocsController,
create: function (req, res) {
var self = this;
this.model.create(req.body, function (err, document) {
if (err) {
return res.handleError(err);
}
return res.created(self.getResponseObject(document));
});
},
jiaowuchuNotHandle: function (req, res) {
var self = this;
this.model.find({type: 1, status: 1}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
jiaowuchuApproved: function (req, res) {
var self = this;
this.model.find({type: 1, status: 2}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
jiaowuchuRejected: function (req, res) {
var self = this;
this.model.find({type: 1, status: 9}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
xueshengchuNotHandle: function (req, res) {
var self = this;
this.model.find({type: 2, status: 1}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
xueshengchuApproved: function (req, res) {
var self = this;
this.model.find({type: 2, status: 2}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
xueshengchuRejected: function (req, res) {
var self = this;
this.model.find({type: 2, status: 9}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
wenyinshiNotHandle: function (req, res) {
var self = this;
this.model.find({status: 2}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
wenyinshiPrinted: function (req, res) {
var self = this;
this.model.find({status: 3}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
wenyinshiReceived: function (req, res) {
var self = this;
this.model.find({status: 4}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
myNotHandle: function (req, res) {
var self = this;
var id = req.params["id"];
this.model.find({submitterId: id, status: 1}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
myApproved: function (req, res) {
var self = this;
var id = req.params["id"];
this.model.find({submitterId: id, status: 2}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
myRejected: function (req, res) {
var self = this;
var id = req.params["id"];
this.model.find({submitterId: id, status: 9}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
myPrinted: function (req, res) {
var self = this;
var id = req.params["id"];
this.model.find({submitterId: id, status: 3}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
myReceived: function (req, res) {
var self = this;
var id = req.params["id"];
this.model.find({submitterId: id, status: 4}, null, {sort: {modified: -1}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
approve: function (req, res) {
var self = this;
var docsId = req.params["docsId"];
this.model.update({_id: docsId}, {$set: {status: 2}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
reject: function (req, res) {
var self = this;
var docsId = req.params["docsId"];
this.model.update({_id: docsId}, {$set: {status: 9}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
print: function (req, res) {
var self = this;
var docsId = req.params["docsId"];
this.model.update({_id: docsId}, {$set: {status: 3}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
receive: function (req, res) {
var self = this;
var docsId = req.params["docsId"];
this.model.update({_id: docsId}, {$set: {status: 4}}, function (err, document) {
if (err) {
return res.handleError(err);
}
if (!document) {
return res.notFound();
}
return res.ok(self.getResponseObject(document));
});
},
upload: function(req, res){
var urlPath = "";
var form = new formidable.IncomingForm();
var id = req.params["userId"];
form.keepExtensions = true;
var baseDir = process.cwd();
var storeDir = "/upload/docs/" + id + "/";
var urlBaseDir = "/docs/" + id + "/";
var fileDir = path.join(baseDir, storeDir);
if (!fs.existsSync(fileDir)) {
fs.mkdirSync(fileDir);
}
form.uploadDir = fileDir;
var i = 0;
form.on("error", function (err) {
console.log('-> err', err.message);
return res.send({code: 500, status: "error", msg: "上传文件失败"});
});
form.on("end", function () {
if(urlPath) {
return res.send({code: 200, status: 'ok', data: urlPath});
} else {
return res.send({code: 500, status: "error", msg: "上传文件失败"});
}
});
form.on('file', function (field, file) {
//rename files and save file url
if (!file) res.send({code: 500, status: "error", msg: "上传文件失败"});
var tempString = file.name.split('.');
var timestamp = new Date().getTime();
var index = ++i;
var originName = file.name.substring(0, file.name.length - tempString[tempString.length - 1].length - 1);
var fileName = originName + '_' + timestamp + '_' + index + '.' + tempString[tempString.length - 1];
file.name = fileName;
fs.rename(file.path, form.uploadDir + file.name);
urlPath = urlBaseDir + fileName;
});
form.parse(req, function (err, fields, files) {
console.log(err);
});
}
};
DocsController.prototype = _.create(ParamController.prototype, DocsController.prototype);
|
import React from 'react';
import UserMenu from './UserMenu';
import { connect } from 'react-redux';
import {getAuthUserData, logout} from '../../redux/authReducer'
class UserMenuContainer extends React.Component {
componentDidMount() {
this.props.getAuthUserData();
}
render() {
return <UserMenu {...this.props} />
}
}
const mapStateToProps = (state) => ({
isAuth: state.auth.isAuth,
login: state.auth.login,
});
export default connect(mapStateToProps, {
getAuthUserData,
logout
}) (UserMenuContainer);
|
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'serversideRenderer.php',
data: { key: 'public' },
success: function(data) {
$('#choices').append(data).fadeIn('fast');
$('#preloader').fadeOut('fast').remove();
},
});
});
|
import React, { PureComponent } from "react";
import CordaService from "~/services/CordaService";
import { Collapse } from "~/components/page";
import { toBigNumber } from "~/helpers/app";
class Index extends PureComponent {
constructor(props) {
super(props);
this.cordaService = new CordaService();
this.state = {
creditNoteSettled: [],
creditNoteSettledItemLength: 0
};
}
async componentDidMount() {
await this.getSettledCreditNote();
}
async componentDidUpdate(prevProps, prevState) {
if (prevProps.taggedCreditNotes !== this.props.taggedCreditNotes) {
await this.getSettledCreditNote();
}
}
formatCurrency(amount) {
return Intl.NumberFormat("th-TH", {
useGrouping: true,
maximumFractionDigits: 2,
minimumFractionDigits: 2
}).format(amount);
}
generateRowTableForCreditNoteSettled(creditnoteSettled) {
const { taggedCreditNotes } = this.props;
const { creditNoteSettledItemLength } = this.state;
if (creditNoteSettledItemLength > 0) {
return _.map(
creditnoteSettled,
(
{
externalId,
linearId,
adjustmentType,
reason,
creditNoteDate,
total,
status,
currency,
invoiceExternalId,
invoiceLinearId
},
index
) =>
<React.Fragment>
{/* Desktop Version - Start */}
<tr className="d-none d-lg-table-row">
<td>
{index + 1}
</td>
<td>
{externalId && linearId
? <a
href={`/credit-note-detail?linearId=${linearId}&ref=inv,${invoiceLinearId}&invoiceNumber=${invoiceExternalId}`}
data-href={`/credit-note-detail?linearId=${linearId}&ref=inv,${invoiceLinearId}&invoiceNumber=${invoiceExternalId}`}
className="link list-link"
>
{externalId}
</a>
: externalId}
</td>
<td>
{adjustmentType
? adjustmentType === "Goods Return"
? "Qty Adjustment"
: adjustmentType
: "-"}
</td>
<td>
{reason ? reason : "-"}
</td>
<td>
{creditNoteDate
? moment(creditNoteDate).format("DD/MM/YYYY").toString()
: "-"}
</td>
<td>
{total
? this.formatCurrency(toBigNumber(total).toNumber(), 2)
: "-"}
</td>
<td>
{taggedCreditNotes
? taggedCreditNotes.map(taggedCreditNote => {
if (taggedCreditNote.linearId === linearId) {
return this.formatCurrency(
toBigNumber(
taggedCreditNote.knockedAmount
).toNumber(),
2
);
}
})
: "-"}
</td>
<td>
{status ? status : "-"}
</td>
<td>
{currency ? currency : "-"}
</td>
</tr>
{/* Desktop Version - End */}
{/* Mobile Version - Start */}
<tr className="d-table-row d-lg-none">
<td>
{externalId && linearId
? <a
href={`/credit-note-detail?linearId=${linearId}&ref=inv,${invoiceLinearId}&invoiceNumber=${invoiceExternalId}`}
data-href={`/credit-note-detail?linearId=${linearId}&ref=inv,${invoiceLinearId}&invoiceNumber=${invoiceExternalId}`}
className="link list-link"
>
{externalId}
</a>
: externalId}
</td>
<td>
{adjustmentType
? adjustmentType === "Goods Return"
? "Qty Adjustment"
: adjustmentType
: "-"}
</td>
<td>
{status ? status : "-"}
</td>
<td className="control">
<a
href={`#cn-detail-${index}`}
data-toggle="collapse"
role="button"
aria-expanded="false"
area-controls={`#cn-detail-${index}`}
className="d-flex w-100 purple btnTableToggle"
>
<strong className="textOnHide">
<i className="fa fa-ellipsis-h purple mx-auto" />
</strong>
<strong className="textOnShow">
<i className="fa fa-times purple mx-auto" />
</strong>
</a>
</td>
</tr>
<tr id={`cn-detail-${index}`} className="collapse multi-collapse">
<td colSpan="4">
<div className="d-flex flex-wrap w-100">
<div className="col-6 px-0 text-right">CN Reason: </div>
<div className="col-6 text-left">
{reason ? reason : "-"}
</div>
<div className="col-6 px-0 pt-3 text-right">CN Date: </div>
<div className="col-6 pt-3 text-left">
{creditNoteDate
? moment(creditNoteDate).format("DD/MM/YYYY").toString()
: "-"}
</div>
<div className="col-6 px-0 pt-3 text-right">
CN Amount (Inc. VAT):{" "}
</div>
<div className="col-6 pt-3 text-left">
{total
? this.formatCurrency(toBigNumber(total).toNumber(), 2)
: "-"}
</div>
<div className="col-6 px-0 py-3 text-right">Currency: </div>
<div className="col-6 py-3 text-left">
{currency ? currency : "-"}
</div>
</div>
</td>
</tr>
{/* Mobile Version - End */}
</React.Fragment>
);
} else {
return (
<React.Fragment>
{/* Desktop Version - Start */}
<tr className="d-none d-lg-table-row">
<td colSpan="9" className="text-center">
No Item Found
</td>
</tr>
{/* Desktop Version - End */}
{/* Mobile Version - Start */}
<tr className="d-table-row d-md-none d-lg-none d-xl-none">
<td colSpan="4" className="text-center">
No Item Found
</td>
</tr>
{/* Mobile Version - End */}
</React.Fragment>
);
}
}
getSettledCreditNote = async () => {
const { taggedCreditNotes } = this.props;
if (taggedCreditNotes && taggedCreditNotes.length > 0) {
const linearIds = taggedCreditNotes
.map(taggedCreditNote => taggedCreditNote.linearId)
.join(",");
const requestParams = {
linearIds: linearIds
};
const { status, data } = await this.cordaService.callApi({
group: "credit",
action: "getCreditNotes",
requestParams: requestParams
});
if (status) {
const results = data.rows ? data.rows : data;
this.setState({
creditNoteSettledItemLength: results.length,
creditNoteSettled: results
});
}
} else {
this.setState({
creditNoteSettledItemLength: 0,
creditNoteSettled: []
});
}
};
render() {
const { creditNoteSettledItemLength, creditNoteSettled } = this.state;
return (
<Collapse
id="creditnoteSettled"
key="creditnoteSettled"
expanded="true"
collapseHeader={[
`Credit Note Settled to this Debit Note ( ${creditNoteSettledItemLength} Item${creditNoteSettledItemLength >
1
? "s"
: ""} )`
]}
>
{/* Desktop Version - Start */}
<div className="table_warpper d-none d-lg-inline-block">
<table className="table table-1 dataTable">
<thead>
<tr>
<th>No.</th>
<th>
CN
<br /> No.
</th>
<th>
Type of
<br /> CN
</th>
<th>
CN
<br /> Reason
</th>
<th>
CN
<br /> Date
</th>
<th>
CN Amount
<br /> (Inc. VAT)
</th>
<th>Settle Value</th>
<th>
CN
<br /> Status
</th>
<th>Currency</th>
</tr>
</thead>
<tbody>
{this.generateRowTableForCreditNoteSettled(creditNoteSettled)}
</tbody>
</table>
</div>
{/* Desktop Version - End */}
{/* Mobile Version - Start */}
<div className="table_warpper d-inline-block d-lg-none">
<table className="table table-1 dataTable mobile_dataTable">
<thead>
<tr>
<th>CN No.</th>
<th>Type of CN</th>
<th>CN Status</th>
<th className="control">More</th>
</tr>
</thead>
<tbody>
{this.generateRowTableForCreditNoteSettled(creditNoteSettled)}
</tbody>
</table>
</div>
{/* Mobile Version - End */}
</Collapse>
);
}
}
export default Index;
|
function getJSON(url, callback) {
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
callback(null, data);
});
};
let url = "http://localhost:8080/SimpleWebApp_war/"
document.body.onload = getFanfics;
function getFanfics(){
getJSON(url+"allfanfics",
(err, data)=>{
let divexp = document.getElementById("expl");
divexp.innerHTML = '';
for(let fanfic in data){
let pp = document.createElement('div');
pp.innerHTML = `<a href ="javascript::" onclick="getOneFanfic(${data[fanfic].fanficId})">${data[fanfic].title}</a>`
divexp.append(pp);
}
});
}
function getOneFanfic(id){
getJSON(url+"oneFanfic/"+id,
(err, data)=> {
let divexp = document.getElementById("expl");
divexp.innerHTML = '';
let pp = document.createElement('div');
pp.innerHTML = `<a href ="javascript::" onclick="getFanfics()">Back</a>`+
`<h1>${data.title}</h1>`+
`<p>${data.content}`
divexp.append(pp);
})
}
|
import "./../public/fonts/BebasNeueBold.otf"
|
import t from 'tcomb';
import _ from '//src/nodash';
import { NonEmptyString, UpperCaseString } from './string.js';
import { nonEmptyList } from './list.js';
/**
* create a type that just wraps a specific value. `is()` uses `===`.
*/
export function value(value, name) {
return t.irreducible(
name || `Value<${ value }>`,
v => v === value,
);
}
/**
* `values()` creates a union type for each of the values in the provided
* object.
*/
export function values(obj, name) {
const valueTypes = _.mapValues(t.Object(obj), (v) => value(v));
const type = t.union(_.values(valueTypes));
type.types = valueTypes;
type.values = {};
_.each(obj, (v, k) => {
UpperCaseString(k);
// shouldn't happen since props are not upper case
if (_.has(type, k)) {
throw new errors.ValueError(squish(`
can\'t provide key ' + k + ' because union type defines the property
`));
}
// convenient accessor, like VALUES.X
type[k] = v;
// nice for iteration of the values
type.values[k] = v;
});
return type;
}
values.of = function (array) {
nonEmptyList(NonEmptyString)(array);
var obj = {};
for (var i = 0, len = array.length; i < len; i++) {
obj[array[i].toUpperCase()] = array[i];
}
return values(obj);
};
|
// ---------- ---------- ---------- ---------- ---------- //
// Configurações //
let edges = {
arrows: {
to: { enabled: true },
},
arrowStrikethrough: true,
color: {
color: "#4a4a4a",
highlight: "#4a4a4a",
hover: "#4a4a4a",
inherit: "from",
opacity: 1.0,
},
};
let nodes = {
shape: "circle",
size: 20,
color: {
border: "#2B7CE9",
background: "#5faeE9",
highlight: {
border: "#000",
background: "#fff",
},
},
};
let interaction = {
hover: true,
// hoverConnectedEdges: false,
selectConnectedEdges: true,
};
let manipulation = {
enabled: false,
// initiallyActive: true
addNode: function (nodeData, callback) {
let maxId = nodesData.max("id");
let id = maxId != null ? maxId.id + 1 : 1;
nodeData.id = id;
nodeData.label = "q" + id;
callback(nodeData);
},
addEdge: async function (edgeData, callback) {
let input = await Swal.fire({
title: "Qual o simbolo que será validado?",
input: "text",
inputValidator: (value) => {
if (value.split(";").length != 3) {
//return "A fita precisa ser do formato: leitura;escrita;direção";
}
},
type: "question",
});
let maxId = edgesData.max("id");
let id = maxId != null ? maxId.id + 1 : 1;
edgeData.label = input.value;
edgeData.id = id;
callback(edgeData);
},
};
let physics = {
enabled: true,
barnesHut: {
gravitationalConstant: -5000,
springLength: 175,
},
maxVelocity: 2,
};
let options = {
height: "100%",
width: "100%",
locale: "pt-br",
clickToUse: true,
edges,
nodes,
interaction,
manipulation,
physics,
};
// ---------- ---------- ---------- ---------- ---------- //
// Criando arrey de nós(estados)
let nodesData = new vis.DataSet();
let nodesAux = {
initial: null,
final: new Array(),
};
let clickedNode = null;
// Criando arrey de arestas(transições)
let edgesData = new vis.DataSet();
let container = document.getElementById("canvasvis");
let data = {
nodes: nodesData,
edges: edgesData,
};
let network = new vis.Network(container, data, options);
// ---------- ---------- ---------- ---------- ---------- //
// Controlando os botões
let addNodeButton = $("#addNode").tooltip();
let addEdgeButton = $("#addEdge").tooltip();
let deleteButton = $("#delete").tooltip();
let initialButton = $("#initial").tooltip();
let finalButton = $("#final").tooltip();
addNodeButton.on("click", () => {
network.addNodeMode();
});
addEdgeButton.on("click", () => {
network.addEdgeMode();
});
deleteButton.on("click", () => {
network.deleteSelected();
});
initialButton.on("click", (event) => {
if (nodesAux.initial) {
let isFinal = nodesAux.final.filter((node) => {
return node.id === nodesAux.initial.id;
});
if (isFinal.length) {
nodesAux.initial.color = {
border: "#ff0000",
background: "#cc5555",
highlight: {
border: "#550000",
background: "#aa2222",
},
};
} else {
nodesAux.initial.color = {
border: "#2B7CE9",
background: "#5faeE9",
highlight: {
border: "#000",
background: "#fff",
},
};
}
nodesData.update(nodesAux.initial);
}
let isFinal = nodesAux.final.filter((node) => {
return node.id === clickedNode.id;
});
if (isFinal.length) {
clickedNode.color = {
border: "#eba134",
background: "#ffc570",
highlight: {
border: "#b56e04",
background: "#ff9f12",
},
};
} else {
clickedNode.color = {
border: "#555",
background: "#ccc",
highlight: {
border: "#000",
background: "#fff",
},
};
}
nodesAux.initial = clickedNode;
nodesData.update(nodesAux.initial);
});
finalButton.on("click", (event) => {
let toggle = nodesAux.final.filter((node) => {
return node.id === clickedNode.id;
});
if (toggle.length) {
let index;
if (clickedNode.id === nodesAux.initial.id) {
index = nodesAux.final.indexOf(nodesAux.initial);
clickedNode.color = {
border: "#555",
background: "#ccc",
highlight: {
border: "#000",
background: "#fff",
},
};
} else {
index = nodesAux.final.indexOf(toggle);
clickedNode.color = {
border: "#2B7CE9",
background: "#5faeE9",
highlight: {
border: "#000",
background: "#fff",
},
};
}
nodesData.update(clickedNode);
nodesAux.final.splice(index, 1);
} else {
if (clickedNode.id === (nodesAux.initial ? nodesAux.initial.id : -1)) {
clickedNode.color = {
border: "#eba134",
background: "#ffc570",
highlight: {
border: "#b56e04",
background: "#ff9f12",
},
};
} else {
clickedNode.color = {
border: "#ff0000",
background: "#cc5555",
highlight: {
border: "#550000",
background: "#aa2222",
},
};
}
nodesData.update(clickedNode);
nodesAux.final.push(clickedNode);
}
});
nodesData.on("*", function (event, properties, senderId) {});
initialButton.hide();
finalButton.hide();
network.on("click", function (properties) {
var ids = parseInt(properties.nodes.toString());
if (ids) {
initialButton.show();
finalButton.show();
clickedNode = nodesData.get(ids);
} else {
initialButton.hide();
finalButton.hide();
}
});
// ---------- ---------- ---------- ---------- ---------- //
// Testando Strings
const inputStringUnica = $("#stringUnica");
const buttonStringUnica = $("#confirmaUnica");
const inputStringPassoAPasso = $("#stringPassoAPasso");
const buttonStringPassoAPasso = $("#confirmaPassoAPasso");
const inputString1 = $("#string1");
const inputString2 = $("#string2");
const inputString3 = $("#string3");
const inputString4 = $("#string4");
const buttonStringMultipla = $("#confirmaMultipla");
const validateString = (arreyString, stepByStep = false) => {
// Se estiver validando apenas 1 string, o arrey terá apenas um item, se for para multipla, será 4 strings
Printer.clear();
let nodeInicial = nodesAux.initial;
if (nodeInicial) {
let nodesFinal = nodesAux.final;
if (nodesFinal.length > 0) {
if (stepByStep) {
if (checkString(arreyString[0], nodeInicial.id, stepByStep))
Swal.fire({
title: "Uhuuuuuu",
text: `Sua string ${arreyString[0]} foi aceita!`,
type: "success",
});
else
Swal.fire({
title: "Ah, que pena!",
text: `Sua string ${arreyString[0]} foi rejeitada :(`,
type: "error",
});
} else if (arreyString.length === 1) {
// Unica
if (checkString(arreyString[0], nodeInicial.id))
Swal.fire({
title: "Uhuuuuuu",
text: `Sua string ${arreyString[0]} foi aceita!`,
type: "success",
});
else
Swal.fire({
title: "Ah, que pena!",
text: `Sua string ${arreyString[0]} foi rejeitada :(`,
type: "error",
});
} else if (arreyString.length === 4) {
// Multipla
let accepted = [];
for (let string of arreyString) {
if (checkString(string, nodeInicial.id)) {
accepted.push(string);
} else {
}
}
if (accepted.length) {
let text = "";
text = accepted[0];
if (accepted.length > 1)
for (let i = 1; i < accepted.length; i++)
text = text + ", " + accepted[i];
Swal.fire({
title: "Uhuuuuuu",
text: `Suas strings ${text} foi aceita!`,
type: "success",
});
} else {
Swal.fire({
title: "Ah, que pena!",
text: `Suas strings foram rejeitadas :(`,
type: "error",
});
}
}
} else {
Swal.fire({
title: "Sem estados finais!",
text: "Defina ao menos um estado final",
type: "error",
});
}
} else {
Swal.fire({
title: "Sem estados iniciais!",
text: "Defina um estado incial",
type: "error",
});
}
};
buttonStringUnica.click(function () {
validateString([inputStringUnica.val()]);
});
buttonStringMultipla.click(function () {
validateString([
inputString1.val(),
inputString2.val(),
inputString3.val(),
inputString4.val(),
]);
});
buttonStringPassoAPasso.click(function () {
validateString([inputStringPassoAPasso.val()], true);
});
const hasTransition = (nodeId) => {
let result = [];
for (var i in edgesData._data) {
let transition = edgesData._data[i];
if (transition.from === nodeId) result.push(transition);
}
return result;
};
const isFinal = (nodeId) => {
for (let i = 0; i < nodesAux.final.length; i++) {
if (nodesAux.final[i].id === nodeId) return true;
}
return false;
};
const isFinalLabel = (label) => {
for (let i = 0; i < nodesAux.final.length; i++) {
if (nodesAux.final[i].label === label) return true;
}
return false;
};
const parseRuleset = (aux) => {
let ruleset = {};
for (var i in nodesData._data) {
let node = nodesData._data[i];
ruleset[node.label] = {};
let transitions = hasTransition(node.id);
if (transitions.length > 0)
transitions.forEach((transition) => {
let fitas = transition.label.split("|");
let inputs = fitas[aux].split(";");
ruleset[node.label][inputs[0]] = [
nodesData._data[transition.to].label,
inputs[1],
inputs[2],
];
});
}
return ruleset;
};
const parseTape = (text) => {
let string = "";
for (let i = 0; i < text.length; i++) {
string += text[i] + " ";
}
return string;
};
function contarQuantidadeFitas(id) {
//let node = nodesData._data[0].id;
let transitions = hasTransition(id);
let quantFitas = 0;
if (transitions.length > 0)
quantFitas = transitions[0].label.split("|").length;
return quantFitas;
}
const checkString = (text, nodeId, stepByStep = false) => {
let quantFitas = contarQuantidadeFitas(nodeId);
let ruleset = parseRuleset(0);
let state = nodesData._data[nodeId].label;
let tape = new Tape(parseTape(text));
let head = new Head(state + " 0");
let machines = [];
for (let i = 0; i < quantFitas - 1; i++) {
let ruleset = parseRuleset(i + 1);
let tape = new Tape(parseTape("&"));
machines[i] = new Machine(i + 1, ruleset, tape, new Head(state + " 0"));
}
m = new Machine(0, ruleset, tape, head, machines);
return m.run(stepByStep);
};
const describe = () => {
console.info("Describing");
console.log("Nodes", nodesData);
console.log("Edges", edgesData);
console.warn("Edges data", edgesData._data);
// let ids = nodesData.getIds();
// console.log(ids);
// nodesData.add({
// id: ids[ids.length - 1] + 1,
// label: "q" + (ids[ids.length - 1] + 1)
// });
};
const exportAf = async (event) => {
if (nodesData.length > 0) {
let conteudo = json2xml(
nodesData,
edgesData,
nodesAux.initial,
nodesAux.final,
);
let blob = new Blob([conteudo], { type: "text/plain;charset=utf-8" });
let input = await Swal.fire({
title: "Qual o nome do arquivo?",
input: "text",
inputValidator: (value) => {
if (!value.length) {
return "Insira um nome";
}
},
type: "question",
});
let titulo = input.value;
saveAs(blob, titulo + ".jff");
} else {
Swal.fire({
title: "Erro!",
text: "Não há nenhuma máquina definida!",
type: "error",
});
}
};
const openFile = (event) => {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
if (reader.result) {
var text = reader.result;
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
let json = JSON.parse(xml2json(xmlDoc, " "));
delete json.structure.automaton["#comment"];
if (json.structure.type === "turing") {
let nodes = json.structure.automaton.state;
let edges = json.structure.automaton.transition;
let numOfTapes = json.structure.tapes
? json.structure.tapes
: 1;
if (numOfTapes > 1)
edges.forEach((edge) => {
let reads = [];
let writes = [];
let moves = [];
let max = edge.read.length;
for (let index = 0; index < max; index++) {
let arreyRead = edge.read;
let arreyWrite = edge.write;
let arreyMove = edge.move;
reads[index] = arreyRead[index]["#text"]
? arreyRead[index]["#text"]
: "&";
writes[index] = arreyWrite[index]["#text"]
? arreyWrite[index]["#text"]
: "&";
moves[index] = arreyMove[index]["#text"]
? arreyMove[index]["#text"]
: "S";
}
edge.read = reads;
edge.write = writes;
edge.move = moves;
});
buildMT(nodes, edges, numOfTapes);
let jsonConvertedAsXml = json2xml(json, "");
} else {
Swal.fire({
title: "Arquivo inválido!",
text:
"O arquivo selecionado não é uma MT exportada pelo JFLAP",
type: "error",
});
}
}
};
reader.readAsText(input.files[0]);
};
const buildMT = (nodes, edges, numOfTapes) => {
nodes.forEach((node) => {
nodesData.add({
id: node["@id"],
label: node["@name"],
x: node.x,
y: node.y,
});
if (node.hasOwnProperty("initial")) {
if (node.hasOwnProperty("final")) {
let config = {
id: node["@id"],
label: node["@name"],
color: {
border: "#eba134",
background: "#ffc570",
highlight: {
border: "#b56e04",
background: "#ff9f12",
},
},
};
nodesAux.final.push(config);
nodesAux.initial = config;
} else {
nodesAux.initial = {
id: node["@id"],
label: node["@name"],
color: {
border: "#555",
background: "#ccc",
highlight: {
border: "#000",
background: "#fff",
},
},
};
}
nodesData.update(nodesAux.initial);
} else if (node.hasOwnProperty("final")) {
nodesAux.final.push({
id: node["@id"],
label: node["@name"],
color: {
border: "#ff0000",
background: "#cc5555",
highlight: {
border: "#550000",
background: "#aa2222",
},
},
});
var index = nodesAux.final.findIndex(
(nodeAux) => nodeAux.id === node["@id"]
);
nodesData.update(nodesAux.final[index]);
}
});
let i = 1;
edges.forEach((edge) => {
var ids = edgesData.getIds();
let label = "";
if (numOfTapes > 1)
for (let index = 0; index < numOfTapes; index++) {
label +=
(edge.read[index] !== null ? edge.read[index] : "&") +
";" +
(edge.write[index] !== null ? edge.write[index] : "&") +
";" +
edge.move[index] +
(index + 1 < numOfTapes ? "|" : "");
}
else
for (let index = 0; index < numOfTapes; index++) {
label +=
(edge.read !== null ? edge.read : "&") +
";" +
(edge.write !== null ? edge.write : "&") +
";" +
edge.move;
}
edgesData.update({
id: ids.length > 0 ? ids[ids.length - 1] + 1 : i,
from: edge.from,
to: edge.to,
label,
});
i++;
});
};
|
(function() {
'use strict';
angular.module('app')
.factory("Blogs", function($firebaseArray, FURL) {
var blogsRef = new Firebase(FURL + "blogs")
return $firebaseArray(blogsRef);
})
.factory('BlogsService', function($firebaseArray, $firebaseObject, FURL) {
var ref = new Firebase(FURL);
return {
getBlogs: function() {
return $firebaseArray(ref.child('blog'));
},
getBlog: function(blogId) {
return $firebaseObject(ref.child('blog').child(blogId));
}
}
})
.controller('BlogsCtrl', BlogsCtrl);
function BlogsCtrl($state, $ionicHistory, Blogs, $scope, FURL, ionicToast, BlogsService) {
// $scope.blogs = Blogs;
// console.log(Blogs);
$scope.blogs = BlogsService.getBlogs();
$scope.blogs = Blogs;
console.log(Blogs);
$scope.refresh = function() {
$scope.blogs = Blogs;
console.log(Blogs);
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
};
var ref = new Firebase(FURL);
var authData = ref.getAuth();
//toast maneno's
$scope.hideToast = function() {
ionicToast.hide();
};
$scope.showToast = function() {
ionicToast.show('Thanks, You Blog has been posted', 'bottom', false, 2500);
};
//
$scope.browse = function(v) {
window.open(v, "_system", "location=yes");
}
$scope.addBlog = function(blog) {
Blogs.$add({
title: blog.title,
date: Date(),
url: blog.url,
description: blog.description,
user: authData
});
blog.title = "";
blog.url = "";
blog.description = "";
// $scope.goBack();
$state.go('app.blogs');
$scope.showToast();
};
}
})();
|
require('./bootstrap');
// Vue
import Vue from 'vue'
// Adding router to Vue
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// Idenitify app root element
const app = new Vue({
el: '#app-root',
components: {
'page-header': require('./components/header.vue').default,
'lists': require('./components/lists.vue').default,
'success-message': require('./components/success.vue').default
}
});
|
const ENV = require('dotenv');
ENV.config();
const Discord = require('discord.js');
const client = new Discord.Client();
const messageHandler = require('./handlers/messageHandler.js');
const GENERAL_CHANNEL_NAME = 'general';
const BOT_TOKEN = process.env.DISCORD_CLIENT_SECRET;
client.on('guildMemberAdd', newMember => {
const channel = member.guild.channels.cache.find(ch => ch.name === GENERAL_CHANNEL_NAME);
if(channel){
channel.send(`Welcome ${newMember}`);
}
});
client.on('message',(message)=>{
messageHandler.handleMessage(client,message);
});
client.login(BOT_TOKEN);
|
import React from 'react';
import { View, Text, StyleSheet, TouchableHighlight, Dimensions, Image } from 'react-native';
const width_ = Math.round(Dimensions.get('window').width)
const cardHeight = Math.round(width_/6)
const cardWidth = cardHeight*4.5
const name = ["English","Spanish","Arabic","French","German","Indonesian","Hindi","Italian","Portuguese","Russian","Turkish"]
const imagePath = [require('../../../images/en512.png'), require('../../../images/es512.png'), require('../../../images/ar512.png'), require('../../../images/fr512.png'), require('../../../images/gr512.png'), require('../../../images/id512.png'), require('../../../images/in512.png'), require('../../../images/it512.png'), require('../../../images/pr512.png'), require('../../../images/rs512.png'), require('../../../images/tr512.png')]
class WordCard extends React.PureComponent {
gotoWordListScreen(id){
this.props.goWordListScreen(id);
}
render() {
return (
<TouchableHighlight onPress={() => this.gotoWordListScreen(this.props.id)} underlayColor="#e6e6e6" activeOpacity={0.8} style={[styles.card]}>
<View style={{flexDirection:'row'}}>
<View style={{flex:1}}>
<Image style={{flex:1 , resizeMode:'contain', width: cardHeight, height: cardHeight }}
source={imagePath[this.props.id]}
/>
</View>
<View style={{flex:3}}>
<Text style={styles.text}>{name[this.props.id]}</Text>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
card: {
backgroundColor: '#fff',
height: cardHeight,
width: cardWidth,
marginLeft: 20,
marginRight: 20,
marginTop: 10,
marginBottom: 10,
borderColor: '#e6e6e6',
borderWidth: 1,
borderRadius: 15,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 25,
color: '#000',
fontWeight: 'bold',
}
})
export default WordCard;
|
var gulp = require('gulp');
var hologram = require('gulp-hologram');
var copy = require('gulp-copy');
var sync = require('run-sequence');
var browser = require('browser-sync');
/*
map of paths for using with the tasks below
*/
var paths = {
copyFiles: ['app/assets/images/**/*', 'app/index.html']
};
gulp.task('copyimages', function() {
return gulp.src(paths.copyFiles)
.pipe(gulp.dest('dist/images'));
});
gulp.task('copyindex', function() {
return gulp.src('app/index.html')
.pipe(gulp.dest('dist'));
});
gulp.task('copy', ['copyindex', 'copyimages']);
gulp.task('hologram', function() {
gulp.src('hologram_config.yml')
.pipe(hologram({logging:true}));
});
gulp.task('serve', function() {
browser({
port: process.env.PORT || 4500,
open: false,
ghostMode: false,
server: {
baseDir: 'dist'
}
});
});
gulp.task('default', function() {
sync('copy');
});
|
'use strict';
angular.module('Zip.services', [])
.factory('zipFactory', function() {
var factory = {};
var contents = [];
factory.getContents = function() {
return contents;
};
return factory;
});
|
import React from 'react';
import { NavLink } from 'react-router-dom';
const CategoryItem = ({ category, setShow, offcanvas }) => {
// Active link style
const activeLinkStyle = {
fontWeight: "bold",
}
return (
<li key={category._id} className="dropdown-item">
<NavLink exact
className="nav-link text-dark text-wrap"
activeStyle={activeLinkStyle}
to={`/category/${category.categoryName}`}
onClick={() => offcanvas && setShow(false)} >
{category.categoryName}
</NavLink>
</li>
);
}
export default CategoryItem;
|
import React, { PropTypes } from 'react'
import { Provider } from 'react-partflux'
import moment from 'moment'
import Main from '../components/Main'
import reducers from '../reducers/index'
class DaterApp extends React.Component {
static defaultProps = {
value: moment().startOf('minutes'),
showTime: false,
defaultTimeType: 'cur',
timeStep: 30,
}
static propTypes = {
format: PropTypes.object,
}
constructor(props) {
super(props)
let format = props.format
if (!format) {
format = props.showTime ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD'
}
const value = moment(props.value).startOf('minutes')
if (this.props.defaultTimeType === 'start') {
value.startOf('day')
} else if (props.defaultTimeType === 'end') {
value.endOf('day')
}
this.state = {
value,
open: false,
format,
}
}
render() {
const {
showTime,
showOk,
timeStep,
} = this.props
const {
format
} = this.state
const global = {
format,
showTime,
showOk,
timeStep,
}
return(
<Provider
host={this}
global={global}
reducers={reducers}
>
<Main />
</Provider>
)
}
}
export default DaterApp
|
// @flow strict
import * as React from 'react';
import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay';
import LocationPopupButton from '../LocationPopupButton';
import type { LocationItem as LocationItemType } from './__generated__/LocationItem.graphql';
import type { HotelData } from './HotelMenuItem';
type Props = {|
+data: LocationItemType,
+onPress: (hotelData: HotelData) => void,
|};
class LocationItem extends React.Component<Props> {
onPress = () => {
const { data } = this.props;
const cityId = data.hotelCity?.id ?? '';
const cityName = data.hotelCity?.name ?? '';
const checkin = data.checkin ?? null;
const checkout = data.checkout ?? null;
this.props.onPress({
cityId,
cityName,
checkin,
checkout,
});
};
render() {
const location = this.props.data.location;
if (!location) {
return null;
}
return (
<LocationPopupButton
data={location}
onPress={this.onPress}
displayIata={false}
/>
);
}
}
export default createFragmentContainer(
LocationItem,
graphql`
fragment LocationItem on HotelServiceRelevantLocation {
checkin
checkout
hotelCity {
id
name
}
location {
...LocationPopupButton
}
}
`,
);
|
var logger = require("winston");
var nconf = require("nconf");
var fs = require("fs");
nconf.env().argv().file("./config/config.json");
var rtorrent = require("./lib/rtorrent");
logger.add(logger.transports.File, { filename: "nodejs-rtorrent.log"});
logger.exitOnError = false;
logger.info("Initializing nodejs-rtorrent server.");
if (nconf.get("app:database") === "tingodb") {
require('tungus');
}
var mongoose = require("mongoose");
var express = require("express");
var io = require("socket.io");
var passport = require("passport")
require("./config/passport-strategy");
var socketAuthorization = require('./config/socket-authorization');
var app = express();
// Setup server options
if( nconf.get("app:ssl") ) {
var serverOptions = {};
serverOptions.cert = fs.readFileSync( nconf.get("ssl:cert"), 'utf-8');
serverOptions.key = fs.readFileSync( nconf.get("ssl:key"), 'utf-8');
var http = require('https');
var server = http.createServer(serverOptions, app);
} else {
var http = require("http");
var server = http.createServer(app);
}
var io = io.listen(server);
// Check for config setting if app database is tingodb.
// By default app setting should be tingodb
if (nconf.get("app:database") === "mongodb") {
logger.info('Using mongodb for database.');
var connectionString = nconf.get("mongodb:prefix") + nconf.get("mongodb:uri") + "/" + nconf.get("mongodb:database");
logger.info("Connecting to ", connectionString);
mongoose.connect(connectionString, function (err) {
if (err) {
logger.error(err.message);
throw err;
}
});
} else {
logger.info('Using tingodb for database.');
logger.info('Connecting to tingodb');
mongoose.connect("tingodb://" + __dirname + "/../../data", function (err) {
if (err) {
logger.error(err.message);
throw err;
}
});
}
logger.info('Connected successfully to database.');
logger.info("Configuring default user");
var users = require("./models/users");
users.add(nconf.get("app:defaultUser")).then(function(data) {
logger.info(data);
logger.info("Successfully created default user");
}, function(err) {
logger.error(err);
});
io.configure(function() {
io.set("origins", nconf.get("app:hostname") + ":" + nconf.get("app:port"));
io.set("log level", 1);
io.set("authorization", socketAuthorization);
});
logger.info("Configuring express.");
app.configure(function() {
app.use(express.bodyParser());
app.use(express.multipart());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(app.router);
// need to configure option to allow for static or separate hosting
app.use(express.static("../../dist"));
});
require("./controllers/socket").init(io);
require("./controllers/login")(app);
require("./controllers/feeds")(app);
require("./controllers/torrent")(app);
require("./controllers/rss-subscriptions")();
logger.info("Listening on hostname and port: %s:%s", nconf.get("app:hostname"), nconf.get("app:port"));
rtorrent.init();
server.listen(nconf.get("app:port"));
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import webpush from 'web-push';
import _ from 'lodash';
import db from './db';
import logger from './logger';
import Album from './models/Album';
import Subscription from './models/Subscription';
import asyncMiddleware from './middlewares/asyncMiddleware';
import apiAuthMiddleware from './middlewares/apiAuthMiddleware';
import StarMusiqAlbumsFetcher from '../client/src/lib/CORSEnabledStarMusiqAlbumFetcher';
const app = express();
const port = process.env.PORT || 5000;
const Raven = require('raven');
Raven.config('https://accf8e03679e4ddd8b5bb9338bd4786c@sentry.io/1296762').install();
const Sentry = require('@sentry/node');
Sentry.init({ dsn: 'https://accf8e03679e4ddd8b5bb9338bd4786c@sentry.io/1296762' });
// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());
// The error handler must be before any other error middleware
app.use(Sentry.Handlers.errorHandler());
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, '../client')));
app.use((_req, res, next) => {
res.header("Access-Control-Allow-Origin", process.env.CORS_ORIGIN);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Api-Secret-Token");
next();
});
// For all GET requests except for internal API's (starts with /api/), handle with client files
// Handle React routing, return all requests to React app
app.get(/^((?!\/api\/).)*$/, function (_req, res) {
res.sendFile(path.join(__dirname, '../client', 'index.html'));
});
} else {
app.use((_req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Api-Secret-Token");
next();
});
}
app.use(bodyParser.json());
app.get('/api/get_albums', asyncMiddleware(async (_req, res, _next) => {
const albums = await Album.find().sort([['weightage', 'descending']]);
res.json({
albums,
status: 'success',
});
}));
app.post('/api/hydrate_albums', apiAuthMiddleware, asyncMiddleware(async (_req, res, _next) => {
const reversedPageNumbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
// get albums from page 1 to 10
const scrapedAlbumsCollection = await Promise.all(_.map(reversedPageNumbers, async (pageNumber) => {
const response = await (new StarMusiqAlbumsFetcher().fetchAlbums(pageNumber));
return ({
pageNumber: pageNumber,
albums: response.albums || [],
});
}));
// filter collections which have non-empty albums
const nonEmptyAlbumsCollection = _.filter(scrapedAlbumsCollection, (albumCollectionWithPageNumber) => (
!_.isEmpty(albumCollectionWithPageNumber.albums)
));
const sortedPagesWithAlbums = _.sortBy(nonEmptyAlbumsCollection, 'pageNumber');
// // get highest page number which have album collections
const farthestPageWithAlbums = _.last(sortedPagesWithAlbums)['pageNumber'];
const reversedContentPageNumbers = _.slice(reversedPageNumbers, _.indexOf(reversedPageNumbers, farthestPageWithAlbums));
const createdAlbums = await Promise.all(_.map(reversedContentPageNumbers, async (pageNumber, pageNumberIdx) => {
const albumsCollectionForCurrPageNumber = _.find(nonEmptyAlbumsCollection, { pageNumber: pageNumber});
// reversing albums since first album in the page should be created latest
const scrapedAlbums = _.reverse(albumsCollectionForCurrPageNumber['albums']);
const upsertedAlbums = await Promise.all(_.map(scrapedAlbums, async (scrapedAlbum, scrapedAlbumIdx) => {
const similarScrapedAlbumInDb = await Album.findOneAndUpdate({ movieId: scrapedAlbum.movieId }, { movieIconUrl: scrapedAlbum.movieIconUrl });
if (similarScrapedAlbumInDb) {
return similarScrapedAlbumInDb;
} else {
const createdScrapedAlbum = await Album.create({
...scrapedAlbum,
weightage: (((pageNumberIdx + 1) * 50) + (scrapedAlbumIdx + 1)),
});
return createdScrapedAlbum;
}
}));
return upsertedAlbums;
}));
res.json({ albums: createdAlbums });
}));
app.post('/api/refresh_albums', apiAuthMiddleware, asyncMiddleware(async (_req, res, _next) => {
const starMusiqAlbumsRetriever = new StarMusiqAlbumsFetcher();
const latestAlbumsPageNumber = 1;
const dbAlbums = await Album.find().sort([['weightage', 'descending']]);
const highestPersistedWeightage = _.head(dbAlbums)['weightage'] || 100000;
const fetchedAlbumsPayload = await starMusiqAlbumsRetriever.fetchAlbums(latestAlbumsPageNumber);
const { albums: scrapedAlbums } = fetchedAlbumsPayload;
const newestScrapedAlbums = _.reverse(scrapedAlbums);
const refreshedAlbums = await Promise.all(_.map(newestScrapedAlbums, async (scrapedAlbum, scrapedAlbumIdx) => {
const existingAlbum = await Album.findOne({ movieId: scrapedAlbum.movieId });
const existingAlbumPublishedStatus = _.get(existingAlbum || {}, 'published', false);
await Album.findOneAndDelete({ movieId: scrapedAlbum.movieId });
const refreshedAlbum = await Album.create({
...scrapedAlbum,
published: !!existingAlbumPublishedStatus,
weightage: (highestPersistedWeightage + scrapedAlbumIdx + 1),
});
return refreshedAlbum;
}));
res.json({ refreshedAlbums: refreshedAlbums });
}));
app.post('/api/save_subscription', asyncMiddleware(async (req, res, _next) => {
const reqSubscriptionObject = req.body;
const createdSubscriptionObject = await Subscription.create({
payload: {
...reqSubscriptionObject,
},
});
res.json({
sub: createdSubscriptionObject,
success: true,
});
}));
app.post('/api/push_to_subscribers', apiAuthMiddleware, asyncMiddleware(async (_req, res, _next) => {
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
webpush.setVapidDetails(
process.env.WEB_PUSH_MAIL_TO_URL,
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
const latestAlbums = await Album.find({}).sort([['weightage', 'descending']]);
const latestAlbum = _.head(latestAlbums);
const latestUnpublishedAlbum = latestAlbum.published ? null : latestAlbum;
if(!_.isNil(latestUnpublishedAlbum)) {
const userSubscriptions = await Subscription.find({});
_.forEach(userSubscriptions, (userSubscription) => {
const pushSubscriptionMap = userSubscription.get('payload');
webpush.sendNotification(pushSubscriptionMap.toJSON(), JSON.stringify(latestUnpublishedAlbum));
});
await Album.findOneAndUpdate({ _id: latestUnpublishedAlbum['_id'] }, { published: true });
res.json({ status: "success", usersNotifiedCount: _.size(userSubscriptions), publishedAlbum: latestUnpublishedAlbum.albumName });
} else {
res.json({ status: "no-op", message: "No unpublished albums found"});
}
}));
app.listen(port, () => {
logger(`Listening on port ${port}`);
db.on('connected', () => {
logger('DB connected');
});
});
// handle all uncaught exceptions
// see - https://nodejs.org/api/process.html#process_event_uncaughtexception
process.on('uncaughtException', err => {
console.error('uncaught exception:', err);
Raven.captureException(err);
});
// handle all unhandled promise rejections
// see - http://bluebirdjs.com/docs/api/error-management-configuration.html#global-rejection-events
// or for latest node - https://nodejs.org/api/process.html#process_event_unhandledrejection
process.on('unhandledRejection', error => {
console.error('unhandled rejection:', error);
Raven.captureException(error);
});
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// EXPRESS
const express_1 = require("express");
// MODELS
const usuarioModel_1 = require("../models/usuarioModel");
const gruposModel_1 = require("../models/gruposModel");
// ENRIPT PASSWORD
const bcrypt_1 = __importDefault(require("bcrypt"));
// JSONWEBTOKENS
const jwt_decode_1 = __importDefault(require("jwt-decode"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const config_1 = require("../config/config");
// MIDDLEWARES
const autenticacion_1 = require("../middlewares/autenticacion");
// CONFG ROUTER
const usuariosRouter = express_1.Router();
// =================================================================
//-- Obtener los usuarios registrados
// =================================================================
usuariosRouter.get('/', (req, resp) => {
usuarioModel_1.usuarioModel.find()
.populate('grupos', 'nombre hora grupo maestro')
.exec((error, usuarios) => {
if (error) {
return resp.status(400).json({
ok: false,
errors: error,
mensaje: 'Error al obtener los usuarios'
});
}
usuarioModel_1.usuarioModel.count({}, (error, usuariosTotales) => {
if (error) {
return resp.status(400).json({
ok: false,
errors: error,
message: 'Error al contar usuarios'
});
}
resp.status(200).json({
ok: true,
totalUsuarios: usuariosTotales,
usuarios: usuarios
});
});
});
});
// =================================================================
//-- Obtener usuario por ID
// =================================================================
usuariosRouter.get('/:id', (req, resp) => {
var id = req.params.id;
usuarioModel_1.usuarioModel.findById(id, (error, usuarioDB) => {
if (error) {
return resp.status(400).json({
ok: false,
mensaje: 'Error al busca usuario por id',
errors: error
});
}
if (!usuarioDB) {
return resp.json({
ok: false,
mensaje: `No existe un usuario con el id: ${id}`
});
}
resp.status(200).json({
ok: true,
usuario: usuarioDB
});
});
});
// =================================================================
//-- Actualizar un usuario
// =================================================================
usuariosRouter.put('/:id', [autenticacion_1.verificarToken, autenticacion_1.MismoUsuario], (req, res) => {
var id = req.params.id;
var body = req.body;
usuarioModel_1.usuarioModel.findById(id, (err, usuario) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar usuario',
errors: err
});
}
if (!usuario) {
return res.status(400).json({
ok: false,
mensaje: 'El usuario con el id' + id + 'no existe',
errors: { message: 'No existe un usuario con este id' }
});
}
usuario.nombre = body.nombre;
usuario.correo = body.correo;
usuario.role = body.role;
usuario.descripcion = body.descripcion;
usuario.semestre = parseInt(body.semestre, 10);
usuario.save((err, usuarioGuardado) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: 'Error al actualizar usuario',
errors: err
});
}
res.status(200).json({
ok: true,
usuario: usuarioGuardado,
});
});
});
});
// =================================================================
//-- Crear Usuario Nuevo
// =================================================================
usuariosRouter.post('/', (req, resp) => {
var body = req.body;
var usuario = new usuarioModel_1.usuarioModel({
nombre: body.nombre,
correo: body.correo,
password: bcrypt_1.default.hashSync(body.password, 10),
img: body.img,
portada: body.portada,
role: body.role
});
usuario.save((error, usuarioGuardado) => {
if (error) {
return resp.status(400).json({
ok: false,
errors: error,
mensaje: 'Error al crear usuario'
});
}
resp.status(200).json({
ok: true,
usuarioGuardado: usuarioGuardado
});
});
});
// =================================================================
//-- Eliminar usuario
// =================================================================
usuariosRouter.delete('/:id', (req, resp) => {
var id = req.params.id;
usuarioModel_1.usuarioModel.findByIdAndRemove(id, (error, usuarioEliminado) => {
if (error) {
return resp.status(400).json({
ok: false,
errors: error,
mensaje: 'Error al eliminar usuario'
});
}
if (!usuarioEliminado) {
return resp.status(400).json({
ok: false,
mensaje: 'No existe un usuario con ese id'
});
}
resp.status(200).json({
ok: true,
eliminado: usuarioEliminado
});
});
});
// =================================================================
//-- Obtener grupos a los que estan registrados
// =================================================================
usuariosRouter.get('/grupos/:idUsuario', (req, resp) => {
var idUsuario = req.params.idUsuario;
gruposModel_1.gruposModel.find({ usuarios: idUsuario }, 'nombre id')
.exec((err, usuarios) => {
resp.json({
grupos: usuarios
});
});
});
// =================================================================
//-- Obtener informacion del usuario por ID
// =================================================================
usuariosRouter.get('/:id', (req, resp) => {
var id = req.params.id;
usuarioModel_1.usuarioModel.findById(id, (error, usuario) => {
if (error) {
return resp.status(500).json({
ok: false,
mensaje: `Error al buscar usuario con el id: ${id}`,
errors: error
});
}
resp.status(200).json({
ok: true,
usuario: usuario
});
});
});
// =================================================================
//-- Decodificar Token para detectar informacion
// =================================================================
usuariosRouter.post('/token', (req, resp) => {
var body = req.body;
var token = body.token;
var decoded = jwt_decode_1.default(token);
resp.status(200).json({
ok: true,
informacion: decoded
});
});
// =================================================================
//-- Actualizar informacion de nuevos usuarios
// =================================================================
usuariosRouter.put('/nuevoUsuario/:id', (req, resp, next) => {
var body = req.body;
var id = req.params.id;
usuarioModel_1.usuarioModel.findById(id, (error, usuario) => {
if (error) {
return resp.status(401).json({
mensaje: 'Error al buscar usuario',
errors: error
});
}
if (!usuario) {
return resp.status(401).json({
mensaje: `No existe un usuario con el id ${id}`
});
}
usuario.puntual = body.puntual;
usuario.responsable = body.responsable;
usuario.trabajador = body.trabajador;
usuario.semestre = body.semestre;
usuario.universidad = body.universidad;
usuario.save((error, usuarioActualizado) => {
if (error) {
return resp.status(400).json({
mensaje: 'Error al actualizar usuario',
errors: error
});
}
// RENOVAR TOKEN DEL USUARIO ACTUALMENTE LOGEADO
usuarioActualizado.password = 'encryptpassword';
var token = jsonwebtoken_1.default.sign({ usuario: usuarioActualizado }, config_1.SEED, { expiresIn: 36000 });
resp.status(200).json({
ok: true,
usuario: usuarioActualizado,
token: token
});
});
});
});
exports.default = usuariosRouter;
|
'use strict';
export const NAMED_COLORS = {
transparent: '#00000000',
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkgrey: '#a9a9a9',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
grey: '#808080',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32'
};
/**
* 格式化成标准的 rgba
*
* @export
* @param {any} r red 色值
* @param {any} g green 色值
* @param {any} b blue 色值
* @param {any} a alpha 值
* @returns {Array}
*/
export function RGBtoRGB(r, g, b, a) {
if (a == null || a === '') a = 1;
r = parseFloat(r);
g = parseFloat(g);
b = parseFloat(b);
a = parseFloat(a);
if (
!(
r <= 255 &&
r >= 0 &&
g <= 255 &&
g >= 0 &&
b <= 255 &&
b >= 0 &&
a <= 1 &&
a >= 0
)
)
return null;
return [Math.round(r), Math.round(g), Math.round(b), a];
}
/**
* 将 16 进制色值表达式转换成 RGBa 格式
*
* @export
* @param {any} hex 16 进制色值表达式
* @returns {Array}
*/
export function hexToRGB(hex) {
if (hex.length === 3) hex += 'f';
if (hex.length === 4) {
let h0 = hex.charAt(0),
h1 = hex.charAt(1),
h2 = hex.charAt(2),
h3 = hex.charAt(3);
hex = h0 + h0 + h1 + h1 + h2 + h2 + h3 + h3;
}
if (hex.length === 6) hex += 'ff';
let rgb = [];
for (let i = 0, l = hex.length; i < l; i += 2)
rgb.push(parseInt(hex.substr(i, 2), 16) / (i === 6 ? 255 : 1));
return rgb;
}
/**
* 将 色调(hue)值转换成 RGB
*
* @export
* @param {any} p
* @param {any} q
* @param {any} t
* @returns
*/
export function hueToRGB(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
/**
* 将 hsl 色值表达式转换成 rgba
*
* @export
* @param {any} h 色调
* @param {any} s 饱和度
* @param {any} l 亮度
* @param {any} a alpha
* @returns
*/
export function hslToRGB(h, s, l, a) {
let r, b, g;
if (a == null || a === '') a = 1;
h = parseFloat(h) / 360;
s = parseFloat(s) / 100;
l = parseFloat(l) / 100;
a = parseFloat(a) / 1;
if (h > 1 || h < 0 || s > 1 || s < 0 || l > 1 || l < 0 || a > 1 || a < 0)
return null;
if (s === 0) {
r = b = g = l;
} else {
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hueToRGB(p, q, h + 1 / 3);
g = hueToRGB(p, q, h);
b = hueToRGB(p, q, h - 1 / 3);
}
return [r * 255, g * 255, b * 255, a];
}
let shex = '(?:#([a-f0-9]{3,8}))',
sval = '\\s*([.\\d%]+)\\s*',
sop = '(?:,\\s*([.\\d]+)\\s*)?',
slist = '\\(' + [sval, sval, sval] + sop + '\\)',
srgb = '(?:rgb)a?',
shsl = '(?:hsl)a?';
let xhex = RegExp(shex, 'i'),
xrgb = RegExp(srgb + slist, 'i'),
xhsl = RegExp(shsl + slist, 'i');
export default function normalizeColor(value) {
if (value == null) return null;
value = (value + '').replace(/\s+/, '');
let match;
if (NAMED_COLORS.hasOwnProperty(value)) {
return value;
} else if ((match = value.match(xhex))) {
value = hexToRGB(match[1]);
} else if ((match = value.match(xrgb))) {
value = match.slice(1);
} else if ((match = value.match(xhsl))) {
value = hslToRGB.apply(null, match.slice(1));
}
if (typeof value === 'string') value = [value];
if (!(value && (value = RGBtoRGB.apply(null, value)))) return value;
if (value[3] === 1) value.splice(3, 1);
return 'rgb' + (value.length === 4 ? 'a' : '') + '(' + value + ')';
}
|
// FreeCodeCamp :: Bonfire
// [03] Factorialize a Number
/*
Instructions:
Return the factorial of the provided integer.
Tests:
expect(factorialize(20)).to.equal(2432902008176640000);
expect(factorialize(10)).to.equal(3628800);
expect(factorialize(5)).to.equal(120);
expect(factorialize(5)).to.be.a("Number");
*/
function factorialize(num) {
var result = 1;
for(i = 1; i <= num; i++) {
result = result * i;
}
num = result;
return num;
}
factorialize(5);
|
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import CategoryElement from './CategoryElement.js';
import EditCategoryContainer from './EditCategoryContainer.js';
import AddCategoryContainer from './AddCategoryContainer.js';
import * as actionCreators from '../../actions/actionCreators';
class Categories extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
this.props.onMount();
}
render(){
var categories, admin;
if(this.props.params && this.props.params.areaName){
categories = this.props.categories[this.props.params.areaName];
if(this.props.areas && this.props.areas[this.props.params.areaName])
admin = this.props.areas[this.props.params.areaName].admin;
} else {
categories = null;
admin = false;
}
var header = (
<div className="row">
<div className="col">
<h2>Priorities</h2>
</div>
</div>
)
if(this.props.params.areaName){
if(!categories || categories.length === 0){
header = (
<div className="row">
<div className="col">
<h2>No priorities defined in selected region</h2>
</div>
</div>
)
}
} else {
header = (
<div className="row">
<div className="col">
<p>To get started, please click the "access a region" button above.</p>
</div>
</div>
)
}
return (
<div className="row">
<div className="col">
{header}
{admin &&
<div className="row">
<div className="col">
<p>These priorities let you divide issues to discuss with shareholders into concrete topics related to the development priorities in the area. <br/>
For example Public health & security, Service innovation, or Resource efficiency </p>
</div>
</div>
}
{ categories && categories.filter(category => {return category !== null}).sort((category1, category2) => category1.id - category2.id).map((category) => {
if(!category.editing){
return <CategoryElement
key={category.id}
area={this.props.params.areaName}
id={category.id}
title={category.title}
description={category.description}
url={`/region/${this.props.params.areaName}/${category.id}`}>
</CategoryElement>
} else {
return <EditCategoryContainer
key={category.id}
area={this.props.params.areaName}
id={category.id}
title={category.title}
description={category.description}
url={`/region/${this.props.params.areaName}/${category.id}`}>
</EditCategoryContainer>
}
})}
{admin &&
<AddCategoryContainer params={this.props.params} update={this.addNew}></AddCategoryContainer>
}
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
categories: state.categories,
areas: state.areas
//categories: state.areas.selected ? state.categories[state.areas.selected.name] : []
}
}
function mapDispatchToProps(dispatch) {
return {
onMount() {
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Categories);
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({ user_id : { type: String, default:''},
name : { type: String, required:false},
email : { type: String, required:false},
message : { type: String, required:false},
address : { type: String, required:false},
date : { type: Number, default: new Date().getTime()},
newMail : { type: Boolean,default: true},
answer : { type: String, default: undefined},
samata : { type: Array, required:false},
});
var MessageModel = mongoose.model('UserMail', schema);
module.exports = MessageModel;
|
Ext.define('InvoiceApp.view.Invoices',{
extend:'Ext.List',
xtype:'invoices',
requires:['InvoiceApp.store.InvoiceStore'],
config:{
items:[
{
xtype:'toolbar',
docked:'top',
title:'Invoice',
items:[
{
text:'New',
action:'newinvoice'
}
]
}
],
iconCls:'home',
title:'Projects',
store: 'InvoiceStore',
itemTpl: '<div>{id}:{first_name}</div>'
}
});
|
require('dotenv').config();
const nconf = require('nconf');
nconf.env(['PORT', 'NODE_ENV'])
.argv({
e: {
alias: 'NODE_ENV',
describe: 'Set production or development mode.',
demand: false,
default: 'development'
},
p: {
alias: 'PORT',
describe: 'Port to run on.',
demand: false,
default: 3001
},
n: {
alias: 'redis',
describe: 'Use local or remote redis instance',
demand: false,
default: 'local'
}
})
.defaults({
REDIS_HOST: process.env.REDIS_CLOUD_HOST,
REDIS_PORT: process.env.REDIS_CLOUD_PORT,
REDIS_PASSWORD: process.env.REDIS_CLOUD_PASSWORD,
GRAPH_NAME: process.env.GRAPH_NAME,
base_url: 'http://localhost:3001',
api_path: '/'
});
module.exports = nconf;
|
$(document).ready(function() {
var city = $('#usersearch-city_id'),
country = $('#usersearch-country_id'),
searchForm = $('#user-search-form');
country.select2({
placeholder: 'Не указана',
allowClear: true
});
city.prop('disabled', true);
select2Init();
country.change(function () {
city.prop('disabled', !country.val());
city.val('');
city.select2('destroy');
select2Init();
updateUserList();
});
city.change(function() {
updateUserList();
});
$('#usersearch-birthday').change(function() {
updateUserList();
});
$('#usersearch-searchstring').keyup(function() {
updateUserList();
});
$('input[name="UserSearch[gender]"]').click(function(){
updateUserList();
});
$('input[name="UserSearch[is_musician]"]').click(function(){
updateUserList();
});
function select2Init() {
city.select2({
ajax: {
url: '/site/country-cities/',
data: function (params) {
return {
q: params.term,
country: country.val()
};
},
processResults: function (data) {
return {
results: data
};
},
dataType: 'json',
delay: 250,
cache: true
},
minimumInputLength: 2,
placeholder: 'Не указан',
allowClear: true
});
}
function updateUserList() {
$.get(
searchForm.attr('action'),
searchForm.serializeArray(),
function(data) {
$('.users-block').html(data);
}
);
}
});
|
module.exports = async (client, error) => {
console.log(`Client error emitted: ${new Date(Date.now())}`)
}
|
var searchData=
[
['dllte1_0',['DllTE1',['../md__r_e_a_d_m_e.html',1,'']]]
];
|
'use strict';
angular.module('galimbertiCrmApp')
.factory('HighRiseDeal', function ($resource) {
return $resource('/api/hrdeals/:id', {
id: '@_id'
},
{
update: {
method: 'PUT',
}
});
})
.factory('HighRisePeople', function ($resource) {
return $resource('/api/hrpeople', { }, { } );
})
.factory('HighRiseDealCategory', function ($resource) {
return $resource('/api/hrdealcategories', { }, { } );
})
.factory('HighRiseNotes', function ($resource) {
return $resource('/api/hrdealnotes/:id', {
id: '@_id'
},
{
update: {
method: 'PUT',
}
});
})
.factory('HighRiseCustomFields', function ($resource) {
return $resource('/api/hrdealcustomfields/:id', {
id: '@_id'
},
{
update: {
method: 'PUT',
}
});
});
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
var isiPhone = navigator.userAgent.indexOf("iPhone") != -1;
var isChromeAndroid = navigator.userAgent.indexOf("Chrome") != -1 &&
navigator.userAgent.indexOf("Android") != -1;
var crappyMobileBrowser = isiPhone || isChromeAndroid;
var useVideo = document.createElement("video").canPlayType('video/mp4;codecs="avc1.42E01E, mp4a.40.2"') in {"probably": true, "maybe": true} && !crappyMobileBrowser ;
var gifs = [];
// Don't keep more than this many gifs in rotation.
var MAX_GIFS = 10;
// If a gif is shorter than this let it loop until it plays at least
// this long.
var MIN_DURATION = 5000;
// Also let gifs loop at least this many times.
var MIN_LOOPS = 2;
var current_gif = -1;
var es;
var queue = [];
var loading;
function preloadNextImage() {
if (queue.length == 0)
return;
var src = queue[0].url;
var event = "load";
if (src.substr(0, 18) == "http://i.imgur.com" && useVideo) {
src = src.substr(0, src.length - 4) + ".mp4";
loading = document.createElement("video");
loading.loop = true;
loading.preload = "auto";
event = "canplaythrough";
loading.addEventListener("loadedmetadata", function meta() {
loading.removeEventListener("loadedmetadata", meta);
checkLoadImmediately(loading);
});
} else {
loading = new Image();
}
function checkLoadImmediately(e) {
if (current_gif == -1) {
gifs.push(e);
e.displayed = true;
loadNextGif();
}
}
// HTMLMediaElement has .duration...
loading.duration_ = queue[0].duration;
loading.addEventListener(event, function doneloading() {
loading.removeEventListener(event, doneloading);
queue.shift();
console.log("loaded %s, duration %d", loading.src, loading.duration_);
loading.loaded = true;
if (!loading.displayed) {
gifs.push(loading);
// Prune the set of gifs
while (gifs.length > MAX_GIFS) {
gifs.shift();
}
if (current_gif == -1) {
loadNextGif();
}
}
loading = null;
setTimeout(preloadNextImage, 0);
});
loading.src = src;
console.log("preloading %s", loading.src);
// Can't stick Image in the DOM right away because we need
// its dimensions to position it.
}
function center(element) {
if (!element.naturalWidth) {
if (element instanceof HTMLVideoElement) {
element.naturalWidth = element.videoWidth;
element.naturalHeight = element.videoHeight;
} else {
element.naturalWidth = element.width;
element.naturalHeight = element.height;
}
}
var elRatio = element.naturalWidth / element.naturalHeight;
var winRatio = window.innerWidth / window.innerHeight;
// Not sure if this is all perfect.
if (elRatio > winRatio) {
element.style.width = "100%";
element.style.height = "auto";
element.style.position = "absolute";
var newHeight = window.innerWidth/elRatio;
element.style.top = (window.innerHeight - newHeight)/2 + "px";
element.style.margin = "";
} else {
element.style.width = "auto";
element.style.height = "100%";
element.style.position = "";
element.style.top = "";
element.style.margin = "auto";
}
}
function loadNextGif() {
if (current_gif == -1) {
current_gif = 0;
} else {
if (gifs.length == 1 || !gifs[current_gif].loaded) {
// Only one gif or it hasn't fully loaded, don't bother changing.
setTimeout(loadNextGif, Math.min(5000, gifs[current_gif].duration_));
return;
}
current_gif = (current_gif + 1) % gifs.length;
}
var gif = gifs[current_gif];
center(gif);
var old = document.body.firstChild;
if (old instanceof HTMLVideoElement) {
old.pause();
}
if (gif instanceof HTMLVideoElement) {
gif.play();
}
document.body.replaceChild(gif, old);
// Let gifs loop at least MIN_LOOPS times, but maybe more if they're short.
var duration = 0;
var loops = 0;
while (duration < MIN_DURATION || loops < MIN_LOOPS) {
duration += gif.duration_;
loops++;
}
console.log("using gif %s for %ds", gif.src, duration);
setTimeout(loadNextGif, duration);
}
addEventListener("DOMContentLoaded", function() {
center(document.getElementById("i"));
es = new EventSource("/feed");
es.addEventListener("gif", function(e) {
var data = JSON.parse(e.data);
console.log("got img url %s, duration %d", data.url, data.duration);
queue.push(data);
if (queue.length == 1) {
preloadNextImage();
}
});
es.addEventListener("ping", function(e) {
console.log("server ping");
});
});
addEventListener("resize", function() {
center(document.body.firstChild);
});
|
import { connect } from 'react-redux'
//import { highlightAnswer } from '../actions'
import { addConversation, isLoading, removeConversation, highlightAnswer, highlightMultipleChoice } from '../actions/index.js'
import Conversation from '../components/Conversation'
import store from '../index'
const mapStateToProps = state => {
return {
context: state.context,
isLoading: state.isLoading
}
}
const mapDispatchToProps = dispatch => {
return {
onChoiceClick: (url, choiceIndex, id) => {
let highestQnA = store.getState().context.length - 1
// highlight answer chosen
dispatch(highlightAnswer(choiceIndex,id))
// if clicked qna is not most recent, remove conversation above
if (highestQnA >= id) {
for (var i = highestQnA; i > id; i--) {
dispatch(removeConversation(i))
}
}
// show loading indicator
dispatch(isLoading(true))
fetch(url)
.then(res => {
return res.json()
})
.then(result => {
let conv = result[result.length -1]
conv.id = store.getState().context.length
dispatch(addConversation(conv))
// since its async, isloading has to be called in scope of fetch
dispatch(isLoading(false))
})
},
onMultipleChoiceClick: (choiceIndex, id) => {
dispatch(highlightMultipleChoice(choiceIndex, id))
},
onMultipleChoiceSubmit: (id) => {
let qna = store.getState().context[id]
let url = qna.choices[0].url.replace('answer=1', 'answer=' + qna.chosenAnswers.toString())
console.log(url)
console.log(qna.chosenAnswers)
fetch(url)
.then(res => {
return res.json()
})
.then(result => {
let conv = result[result.length -1]
conv.id = store.getState().context.length
dispatch(addConversation(conv))
// since its async, isloading has to be called in scope of fetch
dispatch(isLoading(false))
})
}
}
}
const ChatBot = connect(
mapStateToProps,
mapDispatchToProps
)(Conversation)
export default ChatBot
|
import React from "react"
const ResidentInfo = (props) => {
return (
<div className="resident-card" key={props.key}>
<img src={props.image} />
{/* <div className="text-container"> */}
<p className="card-location-title"><i className="fas fa-user-circle"></i> {props.name}</p>
<hr></hr>
{
props.status === "Alive" ?
<p><i className="fas fa-circle green"></i> {props.status}</p>
:
props.status === "Dead" ?
<p><i className="fas fa-circle red"></i> {props.status}</p>
:
<p><i className="fas fa-circle yellow"></i> {props.status}</p>
}
<p><i className="fas fa-street-view"></i> {props.species}</p>
<p><i className="fas fa-globe-europe"></i> {props.location}</p>
<p><i className="fab fa-youtube"></i> {props.episodes} episodes</p>
{/* </div> */}
</div>
)
}
export default ResidentInfo
|
import React from 'react';
export const InlineLogo = () => (
<img src="https://i.ibb.co/4KtPvDx/image.png" height="32" style={{ verticalAlign: 'middle', marginRight: 5 }} />
);
|
function scenario() {
const scenarioText = lab.mode.spawn( dna.hud.TextView, {
Z: 1,
name: 'scenarioView',
adjust: function() {
const tx = this.__
this.y = 0
this.x = 0
this.w = tx.tw
this.h = tx.th * .7
},
})
const menu = lab.mode.spawn(dna.hud.Menu, {
Z: 11,
name: 'scenarioMenu',
hidden: true,
silentOpen: true,
itemStep: 1,
adjust: function() {
const tx = this.__
this.y = floor(tx.th * .7)
this.x = 0
this.w = tx.tw
this.h = tx.th - this.y
},
})
menu.defineItems({
items: [
{
name: env.msg.accept,
action: function(menu) {
trap('newGame', menu.opt)
//lab.mode.mainMenu.defineItems(lib.menu.main)
//lab.control.state.fadeTo('game')
},
},
{
name: env.msg.back,
action: function(menu) {
lab.mode.mainMenu.defineItems(
lib.menu.listScenarios( _.sce.land, true )
)
lab.control.state.fadeTo('menu')
},
},
],
})
lab.control.state.define('scenario', [
lab.mode.background, scenarioText, menu,
])
return this
}
|
import React, { Component } from 'react';
import {
ResponsiveContainer,
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts';
const color_coding = {
BAD: 'red',
GOOD: 'green',
STANDBY: 'yellow',
EXCLUDED: 'grey',
NOTSET: 'white',
EMPTY: 'black',
ARTIFICIALLY_EMPTY: 'transparent',
true: 'green',
false: 'red',
null: 'black',
};
class BarPlot extends Component {
render() {
const {
ls_ranges_lengths,
lumisection_ranges,
height,
margin,
} = this.props;
return (
<ResponsiveContainer width="99%" aspect={30.0 / 3.0}>
<BarChart
barCategoryGap={-1}
layout="vertical"
height={height || 10}
data={ls_ranges_lengths}
margin={
margin || {
top: 10,
right: 30,
left: 20,
bottom: 10,
}
}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
domain={['dataMin', 'dataMax']}
type="number"
interval="preserveStartEnd"
/>
<YAxis type="category" dataKey="title" />
<Tooltip
formatter={(value, name, props) => {
// Get the respective status of this range:
let selected_status;
lumisection_ranges.forEach((range) => {
const { start, end, status } = range;
const formatted_range = `${start} - ${end}`;
if (name === formatted_range) {
selected_status = `${status}`;
}
});
return selected_status;
}}
/>
{lumisection_ranges.map(({ start, end, status }) => {
const key = `${start} - ${end}`;
return (
<Bar
key={key}
dataKey={key}
stackId="a"
fill={color_coding[`${status}`]}
/>
);
})}
</BarChart>
</ResponsiveContainer>
);
}
}
export default BarPlot;
|
import React from 'react';
import NProgress from 'nprogress';
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom';
import App from './App';
import NotFound from './NotFound';
import Home from './Home';
import Rankings from './Rankings';
import Matches from './Matches';
const routes = [
{
title: 'Home',
path: '/',
exact: true,
component: Home
},
{
title: 'Register',
path: '/register',
component: Home
},
{
title: 'Rankings',
path: '/Rankings',
component: Rankings
},
{
title: 'Matches',
path: '/matches',
component: Matches
}
];
class Path extends React.Component {
componentWillMount () {
NProgress.start()
};
componentDidMount () {
NProgress.done()
};
render() {
return (
<Route {...this.props} />
);
};
};
export default class Routes extends React.Component {
componentWillMount () {
NProgress.start()
};
componentDidMount () {
NProgress.done()
};
render() {
return (
<Router>
<App>
<Switch>
{routes.map((route, i) =>
<Path key={i} {...route} />
)}
<Route path='*' exact={true} component={NotFound} />
</Switch>
</App>
</Router>
);
};
};
|
import BrowserDetector from "../Detector/BrowserDetector";
/***
* @extends AElement
* @constructor
*/
export function AttachHook() {
this._attached = false;
this.on('error', function (event) {
if (!this._attached && this.isDescendantOf(document.body)) {
this._attached = true;
this.emit('attached', event, this);
}
});
this.waitAttaching();
}
AttachHook.render = function (data, domInstance) {
var attributes = {};
var tag;
if (domInstance.defaultTag === 'div') {
attributes.src = '';
tag = 'img';
}
else {
tag = 'image';
attributes.href = '';
}
return domInstance._({
tag: tag,
class: 'absol-attachhook',
extendEvent: ['attached'],
style: {
display: 'none'
},
attr: attributes,
props: { domInstance: domInstance }
});
};
AttachHook.prototype.waitAttaching = function () {
var self = this;
if (BrowserDetector.browser.type.startsWith('chrome') && parseInt((BrowserDetector.browser.version || '').split('.').shift()) >= 113) {
if (this.waitTimeout > 0) clearTimeout(this.waitTimeout);
this.waitTimeout = setTimeout(function wait() {
self.waitTimeout = -1;
if (!self._attached && self.isDescendantOf(document.body)) {
self._attached = true;
self.emit('attached', { target: this }, self);
}
else if (!self._attached) {
self.waitTimeout = setTimeout(wait, 10);
}
}, 0);
}
};
AttachHook.prototype.resetState = function () {
this._attached = false;
if (this.tagName.toLowerCase() === 'img') {
this.src = '';
}
else {
this.href = '';
}
this.waitAttaching();
};
AttachHook.property = {
attached: {
get: function () {
return !!this._attached;
}
}
};
export default AttachHook;
|
import React from 'react';
import ReactDOM from 'react-dom';
import './style/index.css';
import {BrowserRouter} from "react-router-dom";
import AppRouter from './router/Approuter';
import {Provider} from "unistore/react";
import {store} from './components/store';
import * as serviceWorker from './serviceWorker';
const render = Component =>{
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Component />
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
}
render(AppRouter);
serviceWorker.unregister();
|
var request = require('superagent');
module.exports = function(RED){
function cobotServerNode(config) {
RED.nodes.createNode(this,config);
this.name = config.name;
this.subDomain = config.subDomain;
this.token = config.token;
}
RED.httpAdmin.get('/node-cobot/resources', function(req,res){
if(!req.query.server){
res.status(500).send("Missing arguments");
return;
}
var server = RED.nodes.getNode(req.query.server);
if(server && server.subDomain && server.token){
var URL = "https://"+server.subDomain+".cobot.me/api/resources"
request
.get(URL)
.set('Authorization', 'Bearer '+server.token)
.end(function(err, response){
if(err){
res.status(500).send("Internal Server Error: "+err);
}else{
var body = response.body;
try{
res.set({'content-type': 'application/json; charset=utf-8'})
res.end(JSON.stringify(body));
}catch (e){
res.status(500).send("Internal Server Error: "+e);
}
}
})
}
});
RED.nodes.registerType("cobot-server", cobotServerNode);
}
|
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var salary = $('.salary-input').val().replace(/[$,]/g, '');
var salaryCalc = (parseInt(salary) / 52) / 40;
var hourlyRate = salaryCalc.toFixed(2);
if ($.isNumeric(salary)) {
$('.error-message').css({ 'display' : 'none' })
$('.hourly-rate').html(hourlyRate);
$('.result').fadeIn(300);
} else {
if ($('.hourly-rate').is(':visible')) {
$('.salary-input').val('');
$('.result').css({ 'display' : 'none'});
}
$('.error-message').css({ 'display': 'block'});
}
});
});
|
$(document).ready(function(){
$('.colorbox-popup').colorbox({scalePhotos: true , maxHeight: '600px', maxWidth: '800px'});
});
|
const data = [
{
id: 1,
artistName: "Billie Eilish",
songName: "Bad Guy",
language: "English",
lyric: `White shirt now red, my bloody nose Sleepin', you're on your tippy toes Creepin' around like no one knowsThink you're so criminal Bruises on both my knees for youDon't say thank you or pleaseI do what I want when I'm wanting to My soul? So cynical`,
translation: `White shirt now red, my bloody nose Sleepin', you're on your tippy toes Creepin' around like no one knowsThink you're so criminal Bruises on both my knees for youDon't say thank you or pleaseI do what I want when I'm wanting to My soul? So cynical`,
},
{
id: 2,
artistName: "Kendrick Lamar",
songName: "HUMBLE.",
language: "English",
lyric: `Nobody pray for me
It been that day for me
Way (Yeah, yeah)
Ayy, I remember syrup sandwiches and crime allowances
Finesse a nigga with some counterfeits, but now I'm countin' this
Parmesan where my accountant lives, in fact I'm downin' this
D'USSÉ with my boo bae tastes like Kool-Aid for the analysts
Girl, I can buy your ass the world with my paystub
Ooh, that pussy good, won't you sit it on my taste bloods?`,
translation: `White shirt now red, my bloody nose Sleepin', you're on your tippy toes Creepin' around like no one knowsThink you're so criminal Bruises on both my knees for youDon't say thank you or pleaseI do what I want when I'm wanting to My soul? So cynical`,
},
{
id: 3,
artistName: "Billie Eilish",
songName: "Bad Guy",
language: "English",
lyric: `White shirt now red, my bloody nose Sleepin', you're on your tippy toes Creepin' around like no one knowsThink you're so criminal Bruises on both my knees for youDon't say thank you or pleaseI do what I want when I'm wanting to My soul? So cynical`,
translation: `White shirt now red, my bloody nose Sleepin', you're on your tippy toes Creepin' around like no one knowsThink you're so criminal Bruises on both my knees for youDon't say thank you or pleaseI do what I want when I'm wanting to My soul? So cynical`,
},
];
export default data;
|
import {AppConfig} from "./appConfig.service";
import {AuthService} from "./auth.service";
import {Contacts, Folders, Messages} from "./dataSources.service";
import {dialog} from "./dialog.directive";
import {DialogService} from "./dialog.service";
import {LoadingIndicatorService} from "./loadingIndicator.service";
import {authHookRunBlock} from "./requiresAuth.hook";
import {loadingIndicatorHookRunBlock} from "./loadingIndicator.hook";
export const GLOBAL_MODULE = angular.module('global', []);
GLOBAL_MODULE.directive('dialog', dialog);
GLOBAL_MODULE.service('AppConfig', AppConfig);
GLOBAL_MODULE.service('AuthService', AuthService);
GLOBAL_MODULE.service('Contacts', Contacts);
GLOBAL_MODULE.service('Folders', Folders);
GLOBAL_MODULE.service('Messages', Messages);
GLOBAL_MODULE.service('DialogService', DialogService);
GLOBAL_MODULE.service('LoadingIndicatorService', LoadingIndicatorService);
GLOBAL_MODULE.run(authHookRunBlock);
GLOBAL_MODULE.run(loadingIndicatorHookRunBlock);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.