text
stringlengths 7
3.69M
|
|---|
import React from "react"
import { Link } from 'gatsby'
import Header from "../components/Header"
export default () => (
<div>
<Link to="/">Home</Link>
<Header />
<h1>about us</h1>
<p>Our purpose is to grow the membership dentistry movement. That goes beyond creating the best membership experiences in the market; it means revolutionizing the way people think about dental care.</p>
</div>
)
|
module.exports = [
{
id: 1,
name: 'THE CAPTAINS 5.5',
price: 44.5,
description: 'The short of authority on the high seas.',
imageUrl: 'https://cdn.shopify.com/s/files/1/0077/0432/products/PP-captains_1024x1024.jpg?v=1517944878'
},
{
id: 2,
name: 'The Neon Lights',
price: 64.50,
description: 'Out best-selling swim trunk of all time now available in out state-of-the-art stretch fabric.',
imageUrl: 'https://cdn.shopify.com/s/files/1/0077/0432/products/NeonLights_SWIM_M_OB_5_CUTOUT_STRETCH_web_1024x1024.jpg?v=1518730466'
},
{
id: 3,
name: 'The Me Likely The Stripey',
price: 64.50,
description: 'Infused with patented, trademarked, copyrighted, state of the art, 4-way future fabric.',
imageUrl: 'https://cdn.shopify.com/s/files/1/0077/0432/products/MeLikeytheStripey5_1024x1024.jpg?v=1518489870'
},
{
id: 4,
name: 'The Go TO\'s 5.5"',
price: 44.50,
description: 'As Michael Jordan was to basketball, these Chubbies are to the world of men\'s shortswear.',
imageUrl: 'https://cdn.shopify.com/s/files/1/0077/0432/products/GoTos-Prod-1_1024x1024.jpg?v=1517944936'
}
]
|
const input = require('./day5-input.js')
let jumpOffsets = input.split('\n').map(v => parseInt(v, 10))
let steps = 1
let index = 0
while (index >= 0 && index < jumpOffsets.length) {
// console.log(jumpOffsets)
const number = jumpOffsets[index]
jumpOffsets[index] += number >= 3 ? -1 : 1
if (number !== 0) {
index = index + number;
}
steps++
}
console.log(steps - 1)
|
const Discord = require('discord.js');
const client = new Discord.Client();
require('dotenv').config();
const fs = require('fs');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("Type twitch emote");
});
const emotes = JSON.parse(fs.readFileSync('emotes.json'));
console.log(emotes);
client.on('message', msg => {
if(emotes.hasOwnProperty(msg.content)) {
try {
msg.delete();
} catch(e) {}
const emoteAttachment = new Discord.MessageAttachment('./emotes/' + emotes[msg.content], emotes[msg.content]);
const msgEmbed = new Discord.MessageEmbed()
.setColor('#FFFFFF')
.setAuthor(msg.author.username, msg.author.avatarURL())
.attachFiles(emoteAttachment)
.setImage('attachment://' + emotes[msg.content])
.setFooter(msg.content);
try {
msg.channel.send(msgEmbed);
} catch(e) {}
}
});
client.login(process.env.DC_KEY);
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MyUserSchema = new Schema({
name: String,
email: String,
message: String,
password: String,
facebookId: String,
googleId: String,
});
module.exports = mongoose.model('MyUser', MyUserSchema);
|
var assert = require('assert')
var proxyquire = require('proxyquire')
/* global describe, it */
describe('lang', function () {
describe('+ getLanguage()', function () {
describe('> when nothing is set', function () {
it('should default to en', function () {
var stubs = {
'../atom': {
'@noCallThru': true
},
'../window': {
'@noCallThru': true
}
}
var lang = proxyquire('../lang', stubs)
assert.equal(lang.getLanguage(), 'en')
})
})
describe('> when browser language is set and not settings', function () {
it('should return browser language', function () {
var stubs = {
'../atom': {
'@noCallThru': true
},
'../window': {
navigator: {
language: 'es-MX'
},
'@noCallThru': true
}
}
var lang = proxyquire('../lang', stubs)
assert.equal(lang.getLanguage(), 'es')
})
})
describe('> when config/settings', function () {
it('should always use config', function () {
var stubs = {
'../atom': {
CONFIG: {
settings: {
language: 'zh-CN'
}
},
'@noCallThru': true
},
'../window': {
navigator: {
language: 'es-MX'
},
'@noCallThru': true
}
}
var lang = proxyquire('../lang', stubs)
assert.equal(lang.getLanguage(), 'zh')
})
})
})
})
|
import sensorData from "../../services/sensor-data";
import SensorChart from "../sensor-chart"
/**
* This is stand alone component showing sensor data only.
* Eventually it will grow to show more data.
*/
export default {
components: {
SensorChart
},
props: ["spot", "spotName"],
data: () => ({
showMore: false
}),
//monitoring the change
watch: {
'spot': function () {
this.initChart();
}
},
created: function () {},
mounted: function () {
this.initChart();
},
methods: {
initChart: function () {
$("#chart").css('height', '50px').html("<div class='my-4 text-center'>Loading data...</div>");
sensorData.getChartData(this.spot.sensor_id, {
start: this.$moment.utc().add(-24, 'hour').toISOString(),
end: this.$moment.utc().toISOString(),
}, '').then(response => {
if (response.data.length) {
$("#chart").css('height', '250px').html("<svg> </svg>")
this.createChart(response.data);
} else {
$("#chart").css('height', '50px').html("<div class='my-4 text-center'>No data available.</div>");
}
});
},
formatNumber: function (num) {
return Number(num).toFixed(1);
},
spotTemperature: function () {
return (this.spot.temperature * (9 / 5)) + 32;
},
closeIt: function () {
this.$emit('close');
},
createChart: function (data) {
//formats the data for the chart
var sensorValues = [];
for (var i = 0; i < data.length; i++) {
sensorValues.push({
x: this.$moment.utc(data[i].timestamp).local().toDate(),
y: data[i].pm2_5
});
}
//define values of different color
var maxYValue = Math.max.apply(Math, sensorValues.map(function(o) { return o.y; }))
var yellowValue = 0;
var orangeValue = 0;
var redValue = 0;
var purpleValue = 0;
var maroonValue = 0;
//different color will have different value depending on the maxYValue
if (maxYValue < 10) {
yellowValue = maxYValue;
} else if (maxYValue < 20) {
yellowValue = 10;
orangeValue = maxYValue - yellowValue;
} else if (maxYValue < 50) {
yellowValue = 10;
orangeValue = 10;
redValue = maxYValue - (yellowValue + orangeValue);
} else if (maxYValue < 100) {
yellowValue = 10;
orangeValue = 10;
redValue = 30;
purpleValue = maxYValue - (yellowValue + orangeValue + redValue);
} else {
yellowValue = 10;
orangeValue = 10;
redValue = 30;
purpleValue = 50;
maroonValue = maxYValue - (yellowValue + orangeValue + redValue + purpleValue);
}
var chartData = [
//data
{
key: "PM 2.5",
values: [{}]
},
//color ranges of µg/m³
{ //0-10µg/m³ yellow
key: "0-10µg/m³",
values: [{
x: sensorValues[0].x,
y: yellowValue
},
{
x: sensorValues[sensorValues.length - 1].x,
y: yellowValue
}
],
color: '#ffff44'
},
{ //10-20/m³ orange
key: "10-20µg/m³",
values: [{
x: sensorValues[0].x,
y: orangeValue
},
{
x: sensorValues[sensorValues.length - 1].x,
y: orangeValue
}
],
color: '#ff5500'
},
{ //20-50µg/m³ red
key: "20-50µg/m³",
values: [{
x: sensorValues[0].x,
y: redValue
},
{
x: sensorValues[sensorValues.length - 1].x,
y: redValue
}
],
color: '#cc0000'
},
{ //50-100µg/m³ purple
key: "50-100µg/m³",
values: [{
x: sensorValues[0].x,
y: purpleValue
},
{
x: sensorValues[sensorValues.length - 1].x,
y: purpleValue
}
],
color: '#990099'
},
{ //100+µg/m³ maroon
key: "100+µg/m³",
values: [{
x: sensorValues[0].x,
y: maroonValue
},
{
x: sensorValues[sensorValues.length - 1].x,
y: maroonValue
}
],
color: '#aa2626'
}
];
//sets the chart types among other things
chartData[0].type = "line";
chartData[0].yAxis = 1;
chartData[0].values = sensorValues; //sets the data from sensor
chartData[1].type = "area";
chartData[1].yAxis = 1;
chartData[2].type = "area";
chartData[2].yAxis = 1;
chartData[3].type = "area";
chartData[3].yAxis = 1;
chartData[4].type = "area";
chartData[4].yAxis = 1;
chartData[5].type = "area";
chartData[5].yAxis = 1;
//this graph function will change the color of the node depending on the value of data.
nv.addGraph(function () {
var maxYValue = Math.max.apply(Math, chartData[0].values.map(function(o) { return o.y; }))
var chart = nv.models.multiChart()
.margin({
top: 30,
right: 30,
bottom: 30,
left: 90
})
.showLegend(false)
.color(d3.scale.category10().range())
.yDomain1([0, maxYValue]);
chart.xAxis
.tickFormat(function (d) {
return d3.time.format('%I:%M%p')(new Date(d))
})
.tickValues([]);
chart.yAxis1
.tickFormat(function (d) {
return d3.format(',.1f')(d) + 'µg/m³'
})
.showMaxMin(false);
d3.select('#chart svg')
.datum(chartData)
.transition()
.duration(500)
.call(chart);
return chart;
});
}
}
}
|
import React from 'react';
import { StyleSheet, View, Text, TextInput } from 'react-native';
import AddButton from '../elements/AddButton';
class MemoEditScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<TextInput value="hi" multiline style={styles.textStyle} />
<AddButton position={styles.buttonLocation}>f</AddButton>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
},
textStyle: {
flex: 1,
paddingTop: 22,
paddingLeft: 22,
paddingRight: 22,
paddingBottom: 22,
fontSize: 22,
},
buttonLocation: {
top: 5,
},
});
export default MemoEditScreen;
|
import React, { useState } from 'react'
import { useStoreActions, useStoreState } from 'easy-peasy'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { useHistory } from 'react-router-dom'
import InputField from 'Components/Form-control/InputField'
import ProductCart from 'Components/PageHelper/ProductCart'
import { DollarCircleOutlined } from 'Components/UI-Library/Icons'
import { Button, Col, message, Radio, Row } from 'Components/UI-Library'
import { ROUTER } from 'Constants/CommonConstants'
import schema from './Payment.Yup'
const PaymentForm = () => {
const history = useHistory()
// Store
const subTotal = useStoreState((state) => state.cart.subTotal)
const checkoutCart = useStoreActions((action) => action.cart.checkoutCart)
const total = useStoreState((state) => state.cart.total)
const defaultValuesStore = useStoreState((state) => state.auth.defaultValues)
// State
const [payment, setPayment] = useState(null)
// Form
const form = useForm({
resolver: yupResolver(schema),
defaultValues: defaultValuesStore,
})
// Function
const onHandleChange = (e) => {
setPayment(e.target.value)
}
const handleSubmit = (reciver) => {
if (payment) {
checkoutCart({ reciver, payment, total, fnCallback })
} else message.error('Please choose method payment')
}
const fnCallback = (success) => {
if (success) {
message.success('Order is successful')
history.push(ROUTER.OrderSuccess)
} else {
message.error('Failed')
}
}
return (
<form onSubmit={form.handleSubmit(handleSubmit)}>
<Row gutter={[{ sm: 40, xl: 60 }]}>
<Col xs={24} md={16}>
<div className="sub-title">Billing Information</div>
<Row gutter={[48, 6]}>
<Col xs={24} md={12}>
<InputField
label="First Name"
name="firstName"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={12}>
<InputField
label="Last Name"
name="lastName"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={12}>
<InputField label="Email" name="email" form={form} isRequired />
</Col>
<Col xs={24} md={12}>
<InputField
label="Phone Number"
name="phoneNumber"
type="number"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={24}>
<InputField
label="Address"
name="address"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={24}>
<InputField
label="Order Notes"
name="message"
form={form}
textArea
/>
</Col>
</Row>
</Col>
<Col xs={24} md={8}>
<div className="sub-title">Your Order</div>
<ProductCart total={false} removeIcon={false} />
<Row justify="space-between">
<Col>Subtotal</Col>
<Col>${subTotal}</Col>
</Row>
<Row justify="space-between" className="shipping">
<Col>Shipping</Col>
<Col>$0</Col>
</Row>
<Row align="middle" justify="space-between" className="total">
<Col className="sub-total">Total</Col>
<Col className="price-total">${total}</Col>
</Row>
<div className="payment-methods">
<Radio.Group onChange={onHandleChange} value={payment}>
<Row gutter={[12, 12]}>
<Col>
<Radio value="momo">Payment via Momo</Radio>
</Col>
<Col>
<Radio value="delivery">Payment on delivery</Radio>
</Col>
</Row>
</Radio.Group>
</div>
<Button type="primary" htmlType="submit" className="btn-payment">
<DollarCircleOutlined />
Payment
</Button>
</Col>
</Row>
</form>
)
}
export default PaymentForm
|
'use strict';
var SERVER_ENDPOINT = '' // override if API server is different from web server
if (SERVER_ENDPOINT = '') {
SERVER_ENDPOINT = location.protocol +'//'
+ location.hostname
+ (location.port ? ':' + location.port: '') + '/';
}
angular
.module('frontApp', [
'ngRoute',
'ngTagsInput',
'file-model',
])
.value('config', {
server: SERVER_ENDPOINT,
baseURL: SERVER_ENDPOINT + "/api",
refreshTime: 5000 // Timer to update info from server
})
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'view/overview.htm',
controller: 'OverviewCtrl',
title: "Overview",
})
.when('/node', {
templateUrl: 'view/node.htm',
controller: 'NodeManagerCtrl',
title: "Node Manager",
})
.when('/crash', {
templateUrl: 'view/crash.htm',
controller: 'CrashManagerCtrl',
title: "Crash Manager",
})
.when('/job', {
templateUrl: 'view/job.htm',
controller: 'JobManagerCtrl',
title: "Job Manager",
})
.when('/err', {
templateUrl: 'view/err.htm',
controller: 'ErrLogCtrl',
title: "Error Log",
})
.when('/config', {
templateUrl: 'view/config.htm',
controller: 'ConfigManagerCtrl',
title: "Configuration",
})
.otherwise({
redirectTo: '/'
});
})
.run(['$location', '$rootScope', '$interval',
function($location, $rootScope, $interval) {
$rootScope.navActiveLink = function(path){
return ($location.$$path === path) ? 'active' : '';
}
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$interval.cancel($rootScope.nodeManagerTimer);
$interval.cancel($rootScope.overviewTimer);
$interval.cancel($rootScope.jobManagerTimer);
$interval.cancel($rootScope.crashManagerTimer);
$interval.cancel($rootScope.errLogTimer);
if (current.hasOwnProperty('$$route')) {
$rootScope.title = current.$$route.title;
}
});
}]);
|
export { asyncSearchUsers, closeSearchUser, disableSearchInput, enableSearchInput } from './searchUser';
export { asyncUserData } from './userDetail';
|
let actions ={
add(obj){
console.log(obj);
debugger
obj.commit("Aadd");
}
}
let mutations ={
Aadd(state){
state.count++;
}
}
const state ={
count:1
}
export default{
namespaced: true,
state,
actions,
mutations
}
|
import { Provider } from "react-redux";
import { reduxStore } from "store/redux";
const AppProvider = ({ children }) => (
<Provider store={reduxStore}>{children}</Provider>
);
export default AppProvider;
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
const ALERT_TYPE_DANGER = 'danger';
const ALERT_TYPE_WARNING = 'warning';
const ALERT_TYPE_INFO = 'info';
const ALERT_TYPE_SUCCESS = 'success';
class Alert extends Component {
constructor(props) {
super(props);
}
get icon() {
switch (this.props.type) {
case ALERT_TYPE_INFO:
return 'info-circle';
case ALERT_TYPE_WARNING:
return 'exclamation-triangle';
case ALERT_TYPE_DANGER:
return 'exclamation-circle';
case ALERT_TYPE_SUCCESS:
return 'check';
default:
return '';
}
}
render() {
if(!this.props.isOpen) {
return null;
}
return <div className={`alert alert-${this.props.type}`}>
<div className="container-fluid">
<div className="alert-icon">
<i className={`fa fa-${this.icon}`}/>
</div>
<button type="button" className="close" aria-label="Close">
<span aria-hidden="true" onClick={this.props.onClean}><i className="fa fa-clear"/></span>
</button>
{this.props.children}
</div>
</div>;
}
}
Alert.defaultProps = {
onClean: () => {
},
};
Alert.propTypes = {
isOpen: PropTypes.bool.isRequired,
type: PropTypes.oneOf([
ALERT_TYPE_DANGER,
ALERT_TYPE_WARNING,
ALERT_TYPE_SUCCESS,
ALERT_TYPE_INFO,
]).isRequired,
};
export default Alert;
|
const { authenticate } = require('@feathersjs/authentication/lib').hooks
const linkTo = require('../../hooks/linkTo')
const unlinkFrom = require('../../hooks/unlinkFrom')
const idExists = require('../../hooks/idExists')
const injectUserId = require('../../hooks/injectUserId')
const reviewLinks = [{
targetService: 'products',
sourceIdKey: 'productId',
targetKey: 'reviewIds'
}]
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [
authenticate('jwt'),
idExists('productId', 'products'),
injectUserId(),
],
update: [],
patch: [],
remove: [unlinkFrom(reviewLinks)]
},
after: {
all: [],
find: [],
get: [],
create: [linkTo(reviewLinks)],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
}
|
var fs = require('fs'),
server = require('http').createServer(),
io = require('socket.io').listen(server),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'crewfac_development',
port : 3306
}),
POLLING_INTERVAL = 15000,
pollingTimer;
server.listen(8002);
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
console.log( err );
});
// on server ready we can load our client.html page
/*function handler ( req, res ) {
fs.readFile( __dirname + '/client.html' , function ( err, data ) {
if ( err ) {
console.log( err );
res.writeHead(500);
return res.end( 'Error loading client.html' );
}
res.writeHead( 200 );
res.end( data );
console.log("Ujjval Herer"+data);
});
}*/
/*
*
* HERE IT IS THE COOL PART
* This function loops on itself since there are sockets connected to the page
* sending the result of the database query after a constant interval
*
*/
var pollingLoop = function () {
// Make the database query
//var query = connection.query('SELECT C.id as `cid`,C.name,R.staff_id as `uid`,R.id as `rid` FROM `reservations` R, `clients` C, `user` U WHERE R.is_notified = 0 AND R.client_id = C.id AND (R.staff_id IS NOT NULL OR R.staff_id != 0) GROUP BY R.id');
var query = connection.query('SELECT w.id,r.id as res_id,r.created_date,w.notification_type,w.notified,w.read,r.reservation_no,c.name,CONCAT_WS(" ",u.first_name, u.last_name) as full_name, u.id as uid from web_notification as w JOIN reservations r ON w.reservation_id = r.id JOIN clients c ON c.id = w.client_id JOIN user u ON u.id = w.assigned_to where w.read = 0');
users = []; // this array will contain the result of our db query
// set up the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log( err );
updateSockets( err );
})
.on('result', function( user ) {
// it fills our array looping on each user row inside the db
users.push( user );
})
.on('end',function(){
// loop on itself only if there are sockets still connected
if(connectionsArray.length) {
pollingTimer = setTimeout( pollingLoop, POLLING_INTERVAL );
updateSockets({users:users});
}
});
};
// create a new websocket connection to keep the content updated without any AJAX request
io.sockets.on( 'connection', function ( socket ) {
console.log('Number of connections:' + connectionsArray.length);
// start the polling loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function () {
var socketIndex = connectionsArray.indexOf( socket );
console.log('socket = ' + socketIndex + ' disconnected');
if (socketIndex >= 0) {
connectionsArray.splice( socketIndex, 1 );
}
});
console.log( 'A new socket is connected!' );
connectionsArray.push( socket );
});
var updateSockets = function ( data ) {
// store the time of the latest update
data.time = new Date();
// send new data to all the sockets connected
connectionsArray.forEach(function( tmpSocket ){
tmpSocket.volatile.emit( 'notification' , data );
});
};
|
import React, { Component } from 'react';
import DataTable from './DataTable';
import './Homepage.css';
import Search from './Search';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import axios from 'axios';
var serverURL = "https://servlet-1.herokuapp.com/home"
// var serverURL = "http://localhost:8080/LectureServlet/home"
// Declare rows as a global variable to be used by all methods
var rows = [];
class Homepage extends Component {
// State of the homepage component is just the list
// of patients and their info
// Therefore the state just contains an empty array, which is filled later
state = {
patients: [null]
};
// we need to bind this in the handleget method to the homepage
// component otherwise it returns a reference to the window object
// instead
constructor(props) {
super(props);
this.handleGet = this.handleGet.bind(this);
}
// make a GET request for the table info as soon as page opens
componentDidMount(){
this.handleGet();
}
// make GET request to the server
async handleGet(){
axios.get(serverURL, 'Access-Control-Allow-Origin', '*').then(({data}) => {
// each line comes in as string, we parse the lines
// using split
const lines = data.split("\n");
// make an empty array
var list = []
console.log(data);
// since the data comes in as a string, we have to convert the
// string to JSON to access the patient fields.
// we use JSON.parse to do this
// we create a patient object for each input line and add it to a list
for(var i=0;i<lines.length-1;i++){
var patient = JSON.parse(lines[i]);
list.push(patient);
}
// here we create the rows of the table, each contains the info about
// each patient and the action buttons
for(var i = 0; i<list.length; i++){
// rows is an array that contains information about each patient
// each patient is itself an array that contains that patient's information
// as its elements (rows is a 2D array)
// we append each patient's information and action buttons to the rows array, as an array
rows.push(
[
String(list[i].id),
String(list[i].sex),
String(list[i].DOB),
String(list[i].latestSeverityScore),
String(list[i].lastUpdated),
<div className="btn-group" role="group" aria-label="Basic example">
<Router forceRefresh = {true}>
<Link to="/viewpage">
<button type="button" className="btn btn-primary">View</button>
</Link>
</Router>
<Router forceRefresh = {true}>
<Link to="/upload">
<button type="button" className="btn btn-primary">Upload</button>
</Link>
</Router>
</div>
]);
}
// we set the state of the homepage component to the rows we just made
this.setState({patients: rows});
}).catch(error => {
console.log(error.response)
})
}
setPatientID(){
}
render() {
const headings = [
'Patient id',
'Sex',
'Date of Birth',
'Latest Severity Score',
'Last Updated',
'Actions'
];
return (
<React.Fragment>
<div className = "TopBar">
<Search/>
</div>
<div className = "App-header">
<DataTable headings = {headings} rows = {rows}></DataTable>
</div>
</React.Fragment>
);
}
}
export default Homepage;
|
const filters = {
toFriendlyTime: function (timestamp) {
// var nowTimestamp = Math.round(new Date().getTime() / 1000)// js返回的是毫秒数,现转为秒
var nowTimestamp = 1469695314;// 2016-7-28 16:41:54
var distance = nowTimestamp - timestamp;// 相差的时间,秒
var getday = parseInt(distance / 86400);// 多少天
var timeFriendly = '';
if (getday >= 180) {
if (getday <= 360) {
timeFriendly = '半年前'
} else {
timeFriendly = Math.ceil(getday / 360) + '年前'
}
} else if (getday > 30) {
timeFriendly = parseInt(getday / 30) + '个月前'
} else if (getday >= 7 && getday <= 30) {
timeFriendly = parseInt(getday / 7) + '周前'
} else if (distance < 30) {
timeFriendly = '刚刚';
} else if (distance < 60) {
timeFriendly = Math.floor(distance) + '秒前'
} else if (distance < 3600) {
timeFriendly = Math.floor(distance / 60) + '分钟前';
} else if (distance < 86400) {
// 小于1天
timeFriendly = Math.floor(distance / 3600) + '小时前'
} else if (distance < 604800) {
// 小于7天
if (getday < 2) {
timeFriendly = '昨天'
} else if (getday < 3) {
timeFriendly = '前天'
} else {
timeFriendly = getday + '天前'
}
}
return timeFriendly
}
}
module.exports = filters
|
import React, { useState } from "react";
import data from "../data/footer";
import { FaGlobe } from "react-icons/fa";
const Footer = () => {
const [links] = useState(data);
return (
<>
<footer className="bg-gray-200 px-8 py-4 md:grid grid-cols-2 xl:grid-cols-6 xl:pl-20">
{links.map((link) => {
const { id, title, hrefs } = link;
return (
<div key={id}>
<div className="mb-10">
<h4 className="font-semibold text-gray-600">{title}</h4>
{hrefs.map((href) => {
return (
<li key={hrefs} className="text-gray-600 text-sm my-2">
{href}
</li>
);
})}
</div>
</div>
);
})}
</footer>
<div className="bg-gray-200 px-8 pb-4 md:flex items-center justify-between xl:px-20">
<div className="flex items-center text-gray-600">
<FaGlobe className="mr-3" />
<p className="text-sm">English (United States)</p>
</div>
<div>
<ul className="flex flex-wrap text-sm mt-4 text-gray-600">
<li className="mr-4">Sitemap</li>
<li className="mr-4">Contact Microsoft</li>
<li className="mr-4">Privacy</li>
<li className="mr-4">Terms of Use</li>
<li className="mr-4">Trademarks</li>
<li className="mr-4">Safety & eco</li>
<li className="mr-4">About our ads</li>
<li>© Microsoft 2020</li>
</ul>
</div>
</div>
</>
);
};
export default Footer;
|
let numero1 = 1;
let numero2 = 2;
console.log(numero1+numero2);
console.log(1+1);
var soma = 10+5;
console.log(soma);
|
/**
* Extjs 与后台交互统一类
*
* @author peixere@qq.com
* @version 2015-06-17
*/
var Common = {
show : function(conf)
{
var p = Ext.getCmp('app-viewport');
if (!Ext.isEmpty(p))
{
p.showNotice(conf);
}
},
addTabURL : function(conf)
{
var p = Ext.getCmp('app-viewport');
if (!Ext.isEmpty(p))
{
var panel = '';
var tabPanel = p.tabPanel;
for (var i = 0; i < tabPanel.items.length; i++)
{
if (tabPanel.items.get(i).id === conf.id)
{
panel = tabPanel.items.get(i);
break;
}
}
if (panel === '')
{
panel = Ext.create('Ext.panel.Panel', {
id : conf.id,
title : conf.title,
closable : true,
// iconCls : 'icon-activity',
html : '<iframe width="100%" height="100%" frameborder="0" src="' + conf.url + '"></iframe>'
});
tabPanel.add(panel);
}
tabPanel.setActiveTab(panel);
}
},
addTabPanel : function(conf)
{
var p = Ext.getCmp('app-viewport');
if (!Ext.isEmpty(p))
{
p.addTabPanel(conf.component, conf.id, conf.title);
}
else
{
Common.alert({
title : '操作提示',
msg : '操作失败,请重试!',
buttons : Ext.Msg.OK,
icon : Ext.MessageBox.ERROR
});
}
},
removeTab : function(component)
{
var p = Ext.getCmp('app-viewport');
if (!Ext.isEmpty(p))
{
p.removeTab(component);
}
},
onException : function(response, component)
{
if (!Ext.isEmpty(component))
{
if (response.status === 403)
{
component.close();
}
}
if (response.status === 0)
{
Common.setLoading({
title : '连接服务器失败',
msg : '连接服务器失败'
});
return;
}
else if (response.status === 200)
{
var json = Common.JSONdecode(response.responseText);
var msg = json.msg;
if (json.rows)
{
msg = msg + '<br>' + json.rows;
}
/*
* Common.show({ title : '操作提示', html : msg });
*/
Common.alert({
title : '操作提示',
msg : msg,
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
}
else if (response.status === 401)
{
window.location.href = ctxp + '/index.html?' + Math.random();
}
else if (response.status === 403)
{
if (!Ext.isEmpty(response.responseText))
{
Common.alert({
title : '无操作权限',
buttons : Ext.Msg.OK,
msg : '你的访问受限!'
});
}
}
else
{
if (!Ext.isEmpty(response.responseText))
{
Common.show({
title : '操作提示',
html : response.responseText
});
}
}
},
bindPageSize : function(component)
{
var store = Ext.create('Ext.data.Store', {
fields : [ 'text' ],
data : [ {
"text" : 5
}, {
"text" : 10
}, {
"text" : 20
}, {
"text" : 25
}, {
"text" : 50
}, {
"text" : 100
}, {
"text" : 500
}, {
"text" : 1000
} ]
});
component.setValue(25);
component.bindStore(store);
},
loadStore : function(conf)
{
try
{
var comp = conf.component;
var model = conf.model;
var fields = conf.fields;
var url = conf.url;
var pageSize = conf.pageSize;
var params = conf.params;
var root = 'rows';
if (!Ext.isEmpty(conf.root))
{
root = conf.root;
}
if (Ext.isEmpty(pageSize))
{
pageSize = 20;
}
if (Ext.isEmpty(model))
{
model = '';
}
if (Ext.isEmpty(fields))
{
fields = [];
}
var myStore = Ext.create('Ext.data.JsonStore', {
model : model,
fields : fields,
pageSize : pageSize,
autoLoad : true,
proxy : {
type : 'ajax',
actionMethods : 'post',
url : url,
reader : {
type : 'json',
root : root
},
listeners : {
exception : function(proxy, response, operation, eOpts)
{
try
{
loadMask.hide();
var json = Common.JSONdecode(response.responseText);
if (json.needCheck)
{
Common.showCheckWindow({
component : conf.component,
callback : function(result)
{
Common.loadStore(conf);
}
});
}
else
{
Common.onException(response, comp);
}
}
catch (err)
{
// alert(err);
}
}
}
},
listeners : {
load : {
fn : function()
{
if (!Ext.isEmpty(comp.pagingToolbar))
{
var pageData = comp.pagingToolbar.getPageData();
if (pageData.currentPage > pageData.pageCount && pageData.pageCount > 0)
{
comp.pagingToolbar.moveLast();
}
}
try
{
conf.callback();
}
catch (ex)
{
}
}
},
beforeload : {
fn : function()
{
loadMask.show();
}
}
}
});
var loadMask = new Ext.LoadMask(comp, {
msg : '正在加载中...',
store : myStore
});
if (!Ext.isEmpty(params))
{
Ext.apply(myStore.proxy.extraParams, params);
}
if (!Ext.isEmpty(comp.pagingToolbar))
{
comp.pagingToolbar.bindStore(myStore);
}
comp.bindStore(myStore);
}
catch (error)
{
// alert(error.toString());
}
},
loadLocalStore : function(conf)
{
try
{
var comp = conf.component;
var fields = conf.fields;
if (Ext.isEmpty(fields))
{
fields = [];
}
var jsondata = conf.data;
if (Ext.isEmpty(jsondata))
{
jsondata = [];
}
var myStore = new Ext.data.JsonStore({
data : jsondata,
autoLoad : true, // 自动 加载(不能用store.load())
fields : fields
});
comp.bindStore(myStore);
}
catch (error)
{
// alert(error.toString());
}
},
getSelectionIds : function(gridPanel)
{
var ids = [];
try
{
var selecteditems = gridPanel.getSelectionModel().selected.items;
if (selecteditems.length > 0)
{
Ext.each(selecteditems, function()
{
var nd = this;
ids.push(nd.data.id);
});
}
}
catch (error)
{
// alert(error.toString());
}
return ids;
},
ajaxSelectionIds : function(conf)
{
try
{
if (Ext.isEmpty(conf.confirm))
{
conf.confirm = '确定要执行选中的数据吗?';
}
if (Ext.isEmpty(conf.msg))
{
conf.msg = '操作成功';
}
var ids = Common.getSelectionIds(conf.component);
if (ids.length === 0)
{
Common.alert({
title : "操作提示",
msg : "请选择要操作的节点!",
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
return;
}
Ext.Msg.confirm('确认提示', conf.confirm, function(button)
{
if (button == 'yes')
{
try
{
Common.ajax({
component : conf.component,
params : {
'id' : ids.join(',')
},
message : '正执行...',
url : conf.url,
callback : function(result)
{
if (!Ext.isEmpty(conf.callback))
{
conf.callback(result);
}
else if (!Ext.isEmpty(conf.component))
{
if (!Ext.isEmpty(conf.component.pagingToolbar))
{
conf.component.pagingToolbar.getStore().reload();
}
else
{
conf.component.getStore().reload();
}
}
if (result.rows === true)
{
result.rows = conf.msg;
}
var msg = result.msg + result.rows;
if (Ext.isEmpty(msg))
msg = conf.msg;
if (!Ext.isEmpty(msg))
{
Common.alert({
title : '操作提示',
msg : msg,
buttons : Ext.Msg.OK,
icon : Ext.Msg.INFO
});
}
}
});
}
catch (error)
{
Common.alert({
title : '操作提示',
msg : error,
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
}
}
});
}
catch (error)
{
Common.alert({
title : '操作提示',
msg : error,
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
}
},
deleteSelectionIds : function(gridPanel, url)
{
Common.ajaxSelectionIds({
component : gridPanel,
url : url,
confirm : '确定要删除选中的数据吗?',
msg : '删除成功'
});
},
redirect : function(conf)
{
conf.callback = function(result)
{
if (!result.rows)
{
location.href = conf.href;
}
};
Common.hidden(conf);
},
hidden : function(conf)
{
if (Ext.isEmpty(conf.url))
{
conf.url = 'home/disabled';
}
Common.ajax({
url : conf.url,
params : conf.params,
callback : function(result)
{
try
{
if (!Ext.isEmpty(conf.component))
{
if (result.rows)
{
conf.component.hide();
}
else
{
conf.component.show();
}
}
if (!Ext.isEmpty(conf.callback))
{
conf.callback(result);
}
}
catch (error)
{
Common.show({
title : '信息提示',
html : error.toString()
});
}
}
});
},
ajax : function(config)
{
if (config.component)
{
if (config.msg)
{
config.message = config.msg;
}
if (config.message)
{
config.component.setLoading(config.message);
}
else
{
var lock = true;
if (!Ext.isEmpty(config.lock))
{
lock = config.lock;
}
if (lock)
config.component.setLoading('正在下载...');
}
}
Ext.Ajax.request({
url : config.url,
params : config.params,
method : 'post',
callback : function(options, success, response)
{
try
{
if (config.component)
{
config.component.setLoading(false);
}
if (success)
{
var json = Common.JSONdecode(response.responseText);
if (!Ext.isEmpty(json.success))
{
if (json.success)
{
config.callback(json, options, success, response);
}
else if (json.needCheck)
{
Common.showCheckWindow({
component : config.component,
callback : function(result)
{
Common.ajax(config);
}
});
}
else
{
Common.onException(response, config.component);
}
}
else
{
config.callback(json, options, success, response);
}
}
else
{
Common.onException(response, config.component);
}
}
catch (err)
{
Common.log(err);
}
}
});
},
isWindow : function(component)
{
try
{
while (!Ext.isEmpty(component))
{
if (component.isWindow)
{
return component;
}
component = component.ownerCt;
}
}
catch (error)
{
// alert(error);
return false;
}
return false;
},
showCheckWindow : function(conf)
{
var component = conf.component;
var checkWin = Ext.create('Gotom.view.CheckWindow');
var win = Common.isWindow(component);
if (win)
{
var x = win.getX();
var y = win.getY() + win.getHeight();
checkWin.setPosition(x, y);
checkWin.width = win.width;
}
if (!Ext.isEmpty(conf.title))
{
checkWin.title = conf.title;
}
if (!Ext.isEmpty(conf.url))
{
checkWin.url = conf.url;
}
checkWin.show();
if (!Ext.isEmpty(conf.username))
{
checkWin.setUsername(conf.username);
}
checkWin.addListener('close', function(panel, opts)
{
try
{
if (component)
{
component.setLoading(false);
}
if (checkWin.result.success)
{
conf.callback(checkWin.result);
}
else if (!Ext.isEmpty(component) && component.isWindow)
{
component.close();
}
}
catch (ee)
{
Common.setLoading({
comp : conf.component,
msg : '异常提示:' + ee
});
}
});
},
showTreeSelect : function(conf)
{
var treeSelect = Ext.create('Gotom.view.TreeSelect');
treeSelect.showTree(conf);
},
formSubmit : function(conf)
{
if (!conf.form.isValid())
{
return false;
}
var isValid = false;
var msg = '确认要提交数据吗?';
if (!Ext.isEmpty(conf.msg))
{
msg = conf.msg;
}
Ext.Msg.confirm("确认提示", msg, function(button)
{
if (button == "yes")
{
isValid = Common.submit(conf);
}
});
return isValid;
},
submit : function(conf)
{
if (conf.form.isValid())
{
var msg = '正在保存数据,稍后...';
if (conf.msg)
{
msg = conf.msg;
}
conf.form.submit({
url : conf.url,
method : 'POST',
waitMsg : msg,
success : function(f, action)
{
if (action.result.success)
{
conf.callback(action.result);// 调用回调函数
}
else if (action.result.needCheck)
{
Common.showCheckWindow({
component : conf.form,
callback : function(result)
{
Common.submit(conf);
}
});
}
else
{
Common.onException(action.response);
}
},
failure : function(f, action)
{
if (action.response.status === 200 && action.result.needCheck)
{
Common.showCheckWindow({
component : conf.form,
callback : function(result)
{
Common.submit(conf);
}
});
}
else if (action.response.status === 200)
{
var msg = action.result.msg;
if (!Ext.isEmpty(action.result.rows))
{
if (Ext.isEmpty(msg))
{
msg = action.result.rows;
}
else
{
msg = msg + '<br>' + action.result.rows;
}
}
Common.setLoading({
comp : conf.form,
msg : msg
});
}
else
{
Common.onException(action.response);
}
}
});
return true;
}
else
{
return false;
}
},
bindTree : function(conf)
{
try
{
var comp = conf.component;
var store = Ext.create("Ext.data.TreeStore", {
defaultRootId : conf.pid,
clearOnLoad : true,
nodeParam : 'id',
fields : conf.fields,
proxy : {
type : 'ajax',
actionMethods : 'post',
url : conf.url,
reader : {
type : 'json',
root : 'rows'
},
listeners : {
exception : function(proxy, response, operation, eOpts)
{
Common.onException(response, comp);
}
}
},
listeners : {
load : {
fn : function(treestore, node, records, successful, eOpts)
{
try
{
if (conf.onload)
conf.onload(treestore, node, records, successful, eOpts);
}
catch (ex)
{
Common.log(ex);
}
}
}
}
});
if (!Ext.isEmpty(conf.params))
{
Ext.apply(store.proxy.extraParams, conf.params);
}
conf.treePanel.bindStore(store);
conf.treePanel.getStore().reload();
}
catch (error)
{
// alert(error.toString());
}
},
createMenuTreeStore : function(URL, pid)
{
try
{
var store = Ext.create("Ext.data.TreeStore", {
defaultRootId : pid,
clearOnLoad : true,
nodeParam : 'id',
fields : [ {
name : 'id'
}, {
name : 'sort',
type : 'int'
}, {
name : 'text'
}, {
name : 'icon'
}, {
name : 'iconCls'
}, {
name : 'leaf',
type : 'boolean'
}, {
name : 'type'
}, {
name : 'url'
}, {
name : 'resource'
}, {
name : 'component'
}, {
name : 'parentId'
} ],
proxy : {
type : 'ajax',
actionMethods : 'post',
url : URL,
reader : {
type : 'json',
root : 'rows'
},
listeners : {
exception : function(proxy, response, operation, eOpts)
{
Common.onException(response);
}
}
}
});
return store;
}
catch (error)
{
// alert(error.toString());
}
},
storeToJson : function(jsondata)
{
try
{
var listRecord;
if (jsondata instanceof Ext.data.Store)
{
listRecord = new Array();
jsondata.each(function(record)
{
listRecord.push(record.data);
});
}
else if (jsondata instanceof Array)
{
listRecord = new Array();
Ext.each(jsondata, function(record)
{
listRecord.push(record.data);
});
}
return Ext.encode(listRecord);
}
catch (error)
{
// alert(error.toString());
}
},
getQueryParam : function(name)
{
var regex = RegExp('[?&]' + name + '=([^&]*)');
var scriptEls = document.getElementsByTagName('script');
var path = scriptEls[scriptEls.length - 1].src;
var match = regex.exec(location.search) || regex.exec(path);
return match && decodeURIComponent(match[1]);
},
addQueryParam : function(url, name, value)
{
var path = url;
if (value !== null && value.length > 0)
{
if (url.indexOf('?') >= 0)
{
path = url + '&' + name + '=' + value;
}
else
{
path = url + '?' + name + '=' + value;
}
}
return path;
},
onTreeParentNodeChecked : function(node, checked)
{
if (node.parentNode !== null)
{
var childNodes = node.parentNode.childNodes;
var parentCheck = false;
if (childNodes.length > 0)
{
Ext.each(childNodes, function(childNode)
{
if (childNode.data.checked)
{
parentCheck = true;
}
});
}
node.parentNode.set('checked', parentCheck);
Common.onTreeParentNodeChecked(node.parentNode, checked);
}
},
setTreeParentNodeChecked : function(node, checked)
{
if (node.parentNode !== null)
{
node.parentNode.set('checked', checked);
Common.onTreeParentNodeChecked(node.parentNode, checked);
}
},
onTreeChildNodesChecked : function(node, checked)
{
Ext.each(node.childNodes, function(childNode)
{
childNode.set('checked', checked);
if (childNode.childNodes.length > 0)
{
Common.onTreeChildNodesChecked(childNode, checked);
}
});
},
onTreePanelSingleChange : function(node)
{
var parentNode = node;
while (parentNode.parentNode !== null)
{
parentNode = parentNode.parentNode;
}
Common.onTreeChildNodesChecked(parentNode, false);
},
onTreePanelCheckChange : function(node, checked)
{
if (!checked)
Common.onTreeChildNodesChecked(node, checked);
if (checked)
Common.onTreeParentNodeChecked(node, checked);
},
commRemoveCallback : function()
{
if (!Ext.isEmpty(Common.commCallback))
{
ocxComm.remove(Common.commCallback);
}
},
comm : function(conf)
{
var initiative = true;
if (!Ext.isEmpty(conf.initiative))
{
initiative = conf.initiative;
}
if (Ext.isEmpty(conf.params))
{
conf.params = {};
}
Common.commRemoveCallback(Common.commCallback);
Common.commCallback = {
id : 'commCallback',
callback : function(hexString)
{
conf.params.hexString = hexString;
Common.ajax({
component : conf.component,
msg : conf.msg,
url : conf.url,
params : conf.params,
callback : function(result)
{
try
{
if (!Ext.isEmpty(result.rows) && !Ext.isEmpty(result.rows.hexString))
{
if (!ocxComm.send(result.rows.hexString))
{
ocxComm.remove(Common.commCallback);
Common.alert({
title : '操作提示',
msg : '发送数据失败,请重试!',
buttons : Ext.Msg.OK,
icon : Ext.MessageBox.ERROR
});
if (!Ext.isEmpty(conf.callback))
{
conf.callback(result.rows);
}
}
}
Common.setLoading({
comp : conf.component,
msg : '正在通信...'// result.msg
});
if (result.code !== 0)
{
ocxComm.remove(Common.commCallback);
if (!Ext.isEmpty(conf.callback))
{
conf.callback(result.rows);
}
if (!Ext.isEmpty(result.msg))
{
Common.alert({
msg : result.msg
});
}
}
if (!Ext.isEmpty(result.rows) && !Ext.isEmpty(result.rows.promptMessage))
{
Common.show({
title : '提示信息',
html : result.rows.promptMessage
});
}
}
catch (ex)
{
if (!Ext.isEmpty(conf.component) && conf.component.isWindow)
{
conf.component.close();
}
Common.alert({
title : '操作提示',
msg : '操作错误,请重新操作!',
buttons : Ext.Msg.OK,
icon : Ext.MessageBox.ERROR
});
}
}
});
}
};
ocxComm.add(Common.commCallback);
if (initiative)
{// 主动触发
Common.ajax({
component : conf.component,
msg : conf.msg,
url : conf.url,
params : conf.params,
callback : function(result)
{
if (Ext.isEmpty(result.rows))
{
ocxComm.remove(Common.commCallback);
if (result.code !== 0)
{
if (!Ext.isEmpty(result.msg))
{
Common.alert({
msg : result.msg
});
}
}
}
else if (!ocxComm.send(result.rows.hexString))
{
Common.alert({
title : '操作提示',
msg : '发送数据失败,请检查设备是否已连接!',
buttons : Ext.Msg.OK,
icon : Ext.MessageBox.ERROR
});
ocxComm.remove(Common.commCallback);
if (!Ext.isEmpty(conf.callback))
{
conf.callback(result.rows);
}
}
if (!Ext.isEmpty(result.rows) && !Ext.isEmpty(result.rows.promptMessage))
{
Common.show({
title : '提示信息',
html : result.rows.promptMessage
});
}
}
});
}
},
/*
* 文件上传,params:{suffix:'',callback:function(result){}}
* suffix:允许的文件类型,值为文件后缀名(不包含点),多类型可用半角, ; | 分隔, callback:上传完成的回调方法
*/
upload : function(params)
{
if (Ext.isEmpty(params.title))
{
params.title = '文件上传';
}
var form = new Ext.form.Panel({
xtype : 'form',
region : 'center',
border : false,
hideLabel : true,
bodyPadding : 10,
header : false,
title : params.title,
items : [ {
xtype : 'filefield',
anchor : '100%',
fieldLabel : '文件',
labelAlign : 'right',
labelWidth : 50,
buttonText : '选择文件'
} ]
});
var win = new Ext.Window({
width : 300,
height : 100,
resizable : false,
draggable : false,
modal : true,
layout : 'border',
title : params.title,
items : [ form ],
dockedItems : [ {
xtype : 'toolbar',
dock : 'bottom',
layout : {
type : 'hbox',
align : 'middle',
pack : 'end'
},
items : [ {
text : '确 定',
xtype : 'button',
iconCls : 'icon-save',
handler : function()
{
if (form.form.isValid())
{
if (params.suffix)
{
var allow = false;
var suffix = params.suffix;
var file = form.items.items[0];
var name = file.getValue();
name = name.toUpperCase();
var array = params.suffix.split(/,|;|\|/);
for (var i = 0; i < array.length; i++)
{
var val = array[i].toUpperCase();
var regExp = new RegExp("\\." + val + "$", 'gi');
var match = regExp.test(name);
if (match)
{
allow = true;
break;
}
}
if (!allow)
{
Ext.Msg.alert({
title : '提示',
msg : "只允许上传如下文件类型:" + params.suffix,
icon : Ext.Msg.WARNING
});
file.setValue("");
return;
}
}
if (Ext.isEmpty(params.url))
{
params.url = ctxp + '/home/upload';
}
Common.submit({
form : form,
url : params.url,
msg : '正在上传,请稍候...',
callback : function(result)
{
if (result.success)
{
win.close();
params.callback(result);
}
else
{
Common.alert({
title : '操作提示',
msg : result.msg,
icon : Ext.Msg.WARNING
});
}
}
});
}
}
}, {
text : '取 消',
xtype : 'button',
iconCls : 'icon-cancel',
handler : function()
{
win.close();
}
} ]
} ]
});
win.show();
},
// 文件下载
getDownloadURL : function(id)
{
return 'home/download?id=' + id;
},
alert : function(conf)
{
if (Ext.isEmpty(conf.msg))
{
return;
}
if (!conf.millis)
{
conf.millis = 5000;
}
if (!conf.buttons)
{
conf.buttons = Ext.MessageBox.OK;
}
if (!conf.icon)
{
conf.icon = Ext.MessageBox.INFO;
}
if (!conf.title)
{
conf.title = '操作提示';
}
var box = Ext.Msg.show({
title : conf.title,
msg : conf.msg,
buttons : conf.buttons,
icon : conf.icon
});
Ext.defer(function()
{
box.close();
}, conf.millis);
},
info : function(message)
{
try
{
console.info(message);
}
catch (ex)
{
}
},
debug : function(message)
{
try
{
console.debug(message);
}
catch (ex)
{
}
},
warn : function(message)
{
try
{
console.warn(message);
}
catch (ex)
{
}
},
error : function(message)
{
try
{
console.error(message);
}
catch (ex)
{
}
},
log : function(message)
{
try
{
console.log(message);
}
catch (ex)
{
}
},
isIE : function()
{
var userAgent = window.navigator.userAgent;
if (userAgent.indexOf("MSIE") >= 0)
{
return true;
}
else
{
false;
}
},
paramStr : function(jsonobj)
{
var rst = '';
for ( var key in jsonobj)
{
var vv = jsonobj[key];
if ("undefined" == typeof (vv))
{
vv = '';
}
rst = rst + '&' + key + '=' + vv;
}
if (rst.length > 0 && rst.substring(0, 1) == '&')
{
return rst.substring(1);
}
else
{
return rst;
}
},
JSONdecode : function(value)
{
try
{
return Ext.JSON.decode(value);
}
catch (err)
{
return {
needCheck : false,
success : false,
rows : ''
};
}
},
setLoading : function(conf)
{
try
{
if (Ext.isEmpty(conf.comp))
{
conf.comp = Ext.getCmp('app-viewport');
}
if (!Ext.isEmpty(conf.comp))
{
if (Ext.isEmpty(conf.msg))
{
conf.msg = "正在加载...";
}
if (Ext.isEmpty(conf.ms))
{
conf.ms = 5000;
}
if (Ext.isEmpty(conf.color))
{
conf.color = '#ff3300';
}
conf.comp.setLoading('<font color=' + conf.color + ' onclick=Common.hideCmpLoading(\'' + conf.comp.id + '\');>' + conf.msg + '<font>');
Ext.defer(function()
{
conf.comp.setLoading(false);
}, conf.ms);
}
}
catch (ex)
{
}
},
hideCmpLoading : function(id)
{
var cmp = Ext.getCmp(id);
cmp.hideLoading = true;
cmp.setLoading(false);
},
waitLoadingCancel : function(id)
{
Ext.Msg.confirm('确认提示', '确认取消等待?', function(button)
{
if (button == 'yes')
{
var cmp = Ext.getCmp(id);
cmp.hideLoading = true;
cmp.setLoading(false);
if (!Ext.isEmpty(Common.waitLoadingConf) && !Ext.isEmpty(Common.waitLoadingConf.callback))
Common.waitLoadingConf.callback('取消操作');
}
});
},
waitLoading : function(conf)
{
try
{
if (Ext.isEmpty(conf.comp))
{
conf.comp = Ext.getCmp('app-viewport');
}
if (!Ext.isEmpty(conf.comp))
{
conf.comp.hideLoading = false;
if (Ext.isEmpty(conf.msg))
{
conf.msg = "正在加载...";
}
if (Ext.isEmpty(conf.ms))
{
conf.ms = 1000;
}
if (Ext.isEmpty(conf.color))
{
conf.color = '#ff3300';
}
Common.waitLoadingConf = conf;
Common.waitLoadingCallback(conf);
}
}
catch (ex)
{
Common.log(ex.toString());
}
},
waitLoadingCallback : function(conf)
{
try
{
if (conf.comp.hideLoading)
{
return;
}
conf.comp.setLoading('<font color=' + conf.color + ' onclick=Common.waitLoadingCancel(\'' + conf.comp.id + '\');>' + conf.msg + '<font>');
Common.ajax({
component : conf.comp,
message : conf.msg,
url : conf.url,
callback : function(result)
{
try
{
conf.msg = result.msg + result.rows;
conf.comp.setLoading('<font color=' + conf.color + ' onclick=Common.waitLoadingCancel(\'' + conf.comp.id + '\');>' + conf.msg + '<font>');
if (result.code === 0)
{
Ext.defer(function()
{
Common.waitLoadingCallback(conf);
}, conf.ms);
}
else
{
conf.comp.setLoading(false);
if (!Ext.isEmpty(conf.callback))
conf.callback(conf.msg);
}
}
catch (ex)
{
Common.log(ex.toString());
}
}
});
}
catch (ex)
{
Common.log(ex.toString());
}
}
};
|
import React from "react";
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import FormControl from "@material-ui/core/FormControl";
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Link from '@material-ui/core/Link';
import DetailsTable from './detailsTable';
import SearchByDoctor from './SearchByDoctor';
import './SearchDoctor.css';
import AddDoctorBtn from "./AddDoctorBtn";
function handleClick(event) {
event.preventDefault();
}
const styles = theme => ({
formControl: {
margin: theme.spacing(4),
minWidth: 120
}
});
class SearchDoctor extends React.Component {
render() {
const { classes } = this.props;
return (
<form className={classes.root} autoComplete="on">
<React.Fragment>
<Grid container spacing={3}>
<Breadcrumbs aria-label="breadcrumb">
<Typography color="textPrimary">Home</Typography>
</Breadcrumbs>
<Grid item xs={10} sm={10}>
<SearchByDoctor />
</Grid>
<Grid item xs={12} sm={1}>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<AddDoctorBtn />
</Grid>
</Grid>
</Grid>
<Typography component="h5" variant="h5" align="left">
Search Doctor
</Typography>
<Grid item xs={12} sm={12}>
<DetailsTable />
</Grid>
</Grid>
</React.Fragment>
</form>
);
}
}
SearchDoctor.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(SearchDoctor);
|
import React, { Component } from 'react';
import * as actions from "../../actions/authActions";
import { connect } from 'react-redux';
import Button from '../Generic/button';
import { google, facebook, twitter } from "../../config/firebase";
import './userbar.css';
class UserBar extends Component {
constructor() {
super();
this.state = ({
displayName: '',
photoURL: ''
});
}
componentWillReceiveProps(nextProps) {
if(nextProps.auth) {
this.setState({
displayName: nextProps.auth.displayName,
photoURL: nextProps.auth.photoURL
})
}
}
render() {
const { auth } = this.props;
if(this.auth === 'loading') {
return "<p>Loading...</p>"
}
if(auth) {
return(
<div className="userbar">
<img src={this.state.photoURL} className="avatar" />
{this.state.displayName}
<Button
clickHandler={this.props.signOut}
label="Sign out"
/>
</div>
)
}
return(
<div className="userbar">
Sign in to join a game
<Button
clickHandler={() => this.props.signIn(google)}
label="Sign in with Google"
/>
<Button
clickHandler={() => this.props.signIn(facebook)}
label="Sign in with Facebook"
/>
<Button
clickHandler={() => this.props.signIn(twitter)}
label="Sign in with Twitter"
/>
</div>
)
}
}
const mapStateToProps = ({auth}) => {
return {
auth
};
};
export default connect(mapStateToProps, actions)(UserBar)
|
import { observable, computed, action } from 'mobx';
class Store {
name = 'Mercado Libre';
placheSearch = 'Nunca dejes de buscar';
description = 'web ui Mercado Libre para test práctico';
}
export default Store;
|
const express = require ( 'express' );
const massive = require ( 'massive' );
const cloudinary = require ('cloudinary');
const axios = require ( 'axios' );
const session = require ( 'express-session' );
require( 'dotenv' ).config();
const bodyParser = require ( 'body-parser' );
const PORT = 3579;
const auth0 = require('./authController/auth0');
const products = require('./authController/products');
const createReactClass = require('create-react-class');
const app = express();
//Zeit
app.use( express.static( `${__dirname}/../build` ) );
app.use(bodyParser.json());
app.use(session({
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 14
},
secret: process.env.SESSION_SECRET
}))
massive( process.env.CONNECTION_STRING ).then( db => {
app.set( 'db', db )
})
// cloudinary set up
app.get('/api/upload', (req, res) => {
const timestamp = Math.round((new Date()).getTime() / 1000);
const api_secret = process.env.CLOUDINARY_SECRET_API;
const signature = cloudinary.utils.api_sign_request({ timestamp: timestamp }, api_secret)
const payload = {
signature: signature,
timestamp: timestamp
}
res.json(payload)
})
//auth0
app.get('/callback', auth0.login)
app.get('/api/user', auth0.getUser)
app.post('/api/logout', auth0.logout)
app.post('/api/createorder', products.create)
//Zeit
const path = require('path')
app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, '../build/index.html'));
})
app.listen( PORT, () => console.log( `I got ${PORT} problems and this personal project is one of them`))
|
import { useState } from 'react';
import './Todo.css';
import Items from './Items';
export default function Todo(){
const [state,setState] = useState({input:'',items: []});
//Four essential methods - input handling,add to list,edit and delete from list
const handleChange = event =>{
const {items} = state;
setState({
input:event.target.value,
items:items
});
}
const addItem = event => {
event.preventDefault();
const {input} = state;
setState({
items:[...state.items,input],
input:''
});
}
const deleteItem = key => {
const {input} = state;
setState({
items:state.items.filter((item,index) => key!==index),
input:input
});
}
const editItem = (index,value) => {
const {input,items} = state;
items.splice(index,1,value);
setState({
items: items,
input:input
});
}
const allProps = {
deleteItem:deleteItem,
editItem:editItem,
items:state.items
}
return (
<div className="todo-container">
<form onSubmit={addItem} className="input-section">
<h1>Todo App</h1>
<input value={state.input} onChange={handleChange} type="text" placeholder="Enter Todo..." />
</form>
<Items {...allProps} />
</div>
)
}
|
var inputName=document.getElementById("name");
var inputMail=document.getElementById("email");
var inputPhone=document.getElementById("phone");
var inputMessage=document.getElementById("message");
var sendBtn=document.getElementById("send");
var nav=document.getElementsByClassName("nav-link")
$(nav[0]).css("color","#f25454")
var clientMessages;
var check=localStorage.getItem("allMessages");
if(check==null){
clientMessages=[];
}
else{
clientMessages=JSON.parse(localStorage.getItem("allMessages"));
}
sendBtn.onclick=function(){
saveMessage();
alert("your message has been recieved successfully!")
}
function saveMessage(){
var clientMessage=
{
name:inputName.value,
mail:inputMail.value,
phone:inputPhone.value,
message:inputMessage.value
};
clientMessages.push(clientMessage);
localStorage.setItem("allMessage",JSON.stringify(clientMessages));
}
let offSet=[$("#brand").offset().top,$("#design").offset().top,$("#graphic").offset().top,$("#dev").offset().top];
var sectionsTop=[$("#home").offset().top,$("#About").offset().top,$("#team").offset().top,$("#Services").offset().top,$("#contact").offset().top]
document.addEventListener("scroll",function(){
if ($(window).scrollTop() > offSet[0] * 0.3) {
$("#brand").animate({ "width": "80%" }, 2)
}
if ($(window).scrollTop() > offSet[1] * 0.35) {
$("#design").animate({ "width": "60%" }, 2)
}
if ($(window).scrollTop() > offSet[2] * 0.40) {
$("#graphic").animate({ "width": "40%" }, 2)
}
if ($(window).scrollTop() > offSet[3] * 0.45) {
$("#dev").animate({ "width": "80%" }, 2)
}
for (var i=0;i<nav.length;i++){
if(window.outerWidth<=600&& $(window).scrollTop()>sectionsTop[i]-sectionsTop[i]*0.1){
$(".nav-link").css("color","rgba(0,0,0,.9)")
$(nav[i]).css("color","#f25454")
}
else if($(window).scrollTop()>sectionsTop[i]-sectionsTop[i]*0.2){
$(".nav-link").css("color","rgba(0,0,0,.9)")
$(nav[i]).css("color","#f25454")
}
}
})
|
'use strict'
const rp = require('minimal-request-promise')
const vbTemplate = require('claudia-bot-builder').viberTemplate
module.exports = function iss() {
return rp.get('https://api.wheretheiss.at/v1/satellites/25544')
.then(response => {
const ISS = JSON.parse(response.body)
return [
new vbTemplate.Text(`International Space station is currently at `).get(),
new vbTemplate.Location(ISS.latitude, ISS.longitude).get(),
new vbTemplate.Text(`You can zoom out a bit to get a better ISS position overview`)
.addReplyKeyboard(true)
.addKeyboardButton(`<font color="#FFFFFF"><b>Website</b></font>`, 'http://iss.astroviewer.net', 6, 2, {
TextSize: 'large',
BgColor: '#f6d95e',
BgMediaType: 'picture',
BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/galaxy.jpeg'
})
.addKeyboardButton(`<font color="#FFFFFF"><b>Back to start</b></font>`, 'Start', 6, 2, {
TextSize: 'large',
BgColor: '#000000'
})
.get()
]
})
}
|
import { Link } from 'react-router-dom'
import LoginForm from '../components/LoginForm'
function Login()
{
return(
<div className='container'>
<LoginForm />
<div className='sec-footer'>
<div style={{width: 'max-content'}}>
<p>Don't have account <Link to='/register'>goto registration</Link> </p>
</div>
</div>
</div>
)
}
export default Login
|
/*
* @Description: 接送机路由
* @Author: 彭善智
* @LastEditors: 彭善智
* @Date: 2019-05-07 11:15:53
* @LastEditTime: 2019-05-15 16:16:34
*/
const carTranRouter = {
path: '/carTran',
component: ()=> import( '@/views/carTran/carTranHome'),
redirect: "/carTran/carTranIndex",
name: "carTranHome",
children: [
{
path:"carTranIndex",
component: ()=> import('@/views/carTran/carTranIndex'),
name: "carTranIndex",
meta: { title: "接送机首页", requireAuth: false}
},
{
path:"carTranInfo",
component: ()=> import('@/views/carTran/carTranInfo'),
name: "carTranInfo",
meta: { title: "接送机详情", requireAuth: false}
},
{
path:"carTranSure",
component: ()=> import('@/views/carTran/carTranSure'),
name: "carTranSure",
meta: { title: "接送机订单确定", requireAuth: true}
},
{
path:"carTranPay",
component: ()=> import('@/views/carTran/carTranPay'),
name: "carTranPay",
meta: { title: "接送机订单支付", requireAuth: true}
},
{
path:"carTranSuccess",
component: ()=> import('@/views/carTran/carTranSuccess'),
name: "carTranSuccess",
meta: { title: "接送机订单支付成功", requireAuth: true}
},
]
}
export default carTranRouter
|
import React from 'react';
const GuessRow = (props) => {
return (
<div>
GuessRow Component
</div>
);
}
export default GuessRow;
|
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
TouchableWithoutFeedback,
} from 'react-native';
import {Card, Icon} from 'react-native-elements';
import Tts from 'react-native-tts';
class Activity extends Component {
speak = () => {
Tts.speak(this.props.textActivity ? this.props.textActivity : 'No input');
};
render() {
return (
<TouchableWithoutFeedback onPress={this.speak}>
<View style={styles.activity}>
<Text style={styles.timeText}>{this.props.moments}</Text>
<View style={styles.textView}>
<Text style={styles.timeText}>{this.props.time} </Text>
<Card
containerStyle={this.props.ActivityStyle}
// image={require('./../../images/taxi.png')}
image={{uri: `data:image/png;base64,${this.props.imagePath}`}}
imageStyle={this.props.ImageStyle}>
<View style={styles.textView}>
<Text style={styles.activityText}>
{this.props.textActivity}
</Text>
</View>
</Card>
</View>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
activity: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 30,
},
timeText: {
fontSize: 40,
color: '#393939',
fontFamily: 'FredokaOne-Regular',
},
activityText: {
fontSize: 30,
marginBottom: 10,
marginHorizontal: 10,
color: '#393939',
textAlign: 'left',
fontWeight: 'bold',
fontFamily: 'FredokaOne-Regular',
},
textView: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
},
nextActivity: {
backgroundColor: '#F07E7E',
width: Dimensions.get('window').width - 300,
},
});
export default Activity;
|
import camera from './camera'
import {
S2,
VIEWPORT_REFERENCE_WIDTH,
VIEWPORT_REFERENCE_HEIGHT,
DEGREES_TO_RAD,
M33
} from "../utils/utils"
import geofs from "../geofs"
function Overlay(a, b) {
this.definition = {
url: '',
anchor: {
x: 0,
y: 0,
},
position: {
x: 0,
y: 0,
},
rotation: 0,
size: {
x: 0,
y: 0,
},
offset: {
x: 0,
y: 0,
},
visibility: !0,
opacity: b ? b.definition.opacity : 1,
scale: {
x: 1,
y: 1,
},
rescale: b ? b.definition.rescale : !1,
rescalePosition: !1,
alignment: {
x: 'left',
y: 'bottom',
},
overlays: [],
};
this.children = [];
this.definition = $.extend(!0, {}, this.definition, a);
this.position = this.definition.position;
this.size = this.definition.size;
this.iconFrame = {
x: 0,
y: 0,
};
this.scale = this.definition.scale;
this.positionOffset = this.definition.offset;
this._offset = {
x: 0,
y: 0,
};
this._sizeScale = 1;
this.rotation = this.definition.rotation;
this.opacity = this.definition.opacity;
this.anchor = this.definition.anchor;
this.visibility = this.definition.visibility;
this.overlay = new geofs.api.cssTransform();
this.overlay.setUrl(this.definition.url);
this.overlay.setText(this.definition.text);
this.overlay.setClass(this.definition.class);
this.overlay.setStyle(this.definition.style);
this.overlay.setDrawOrder(this.definition.drawOrder || 0);
const c = this;
$(this.overlay).on('load', function() {
const a = c.definition.size.x / this.naturalSize.x;
c.definition.size = this.naturalSize;
c._sizeScale = a;
c.scaleAndPlace();
});
this.overlay.setVisibility(this.definition.visibility);
if (this.definition.animations) {
for (a = 0,
b = this.definition.animations.length; a < b; a++) {
const d = this.definition.animations[a];
d.type == 'rotate' && (this.definition.animateRotation = !0);
d.type == 'show' && (this.animateVisibility = !0,
this.animationVisibility = this.definition.visibility);
}
}
for (a = 0; a < this.definition.overlays.length; a++) {
b = new Overlay(this.definition.overlays[a], this),
b.parent = this,
this.children[a] = b;
}
}
Overlay.prototype.setVisibility = function(a) {
this.animateVisibility && !this.animationVisibility || this.overlay.setVisibility(a);
this.visibility = a;
for (let b = 0; b < this.children.length; b++) { this.children[b].setVisibility(a); }
};
Overlay.prototype.setOpacity = function(a) {
this.overlay.setOpacity(a);
this.opacity = a;
for (let b = 0; b < this.children.length; b++) { this.children[b].setOpacity(a); }
};
Overlay.prototype.scaleAllProperties = function(a) {
a = a || this.scale;
let b = 1,
c = 1,
d = {
x: 1 * this._sizeScale,
y: 1 * this._sizeScale,
};
this.definition.rescalePosition && (b = a.x,
c = a.y);
this.definition.rescale && (d = {
x: d.x * a.x,
y: d.y * a.y,
});
this.position = {
x: this.definition.position.x * b,
y: this.definition.position.y * c,
};
this.size = {
x: this.definition.size.x * d.x,
y: this.definition.size.y * d.y,
};
this.overlay.setSize(this.size);
this.positionOffset = {
x: this.definition.offset.x * d.x,
y: this.definition.offset.y * d.y,
};
this.overlay.setPositionOffset(this.positionOffset);
this.definition.iconFrame ? (this.iconFrame = {
x: this.definition.iconFrame.x * d.x,
y: this.definition.iconFrame.y * d.y,
},
this.overlay.setFrameSize(this.iconFrame)) : (this.iconFrame = this.size,
this.overlay.setFrameSize(this.size));
this.anchor = {
x: this.definition.anchor.x * d.x,
y: this.definition.anchor.y * d.y,
};
this.overlay.setAnchor(this.anchor);
this.rotationCenter = {
x: this.anchor.x,
y: this.iconFrame.y - this.anchor.y,
};
this.overlay.setRotationCenter(this.rotationCenter);
};
function clamp(a, b, c) {
return a > c ? c : a < b ? b : a;
}
Overlay.prototype.scaleAndPlace = function(a, b, c) {
(this.definition.rescale && !this.parent || this.definition.rescalePosition) && !c ? (this.scale = this.scaleFromParent(a),
a = clamp(geofs.viewportWidth / VIEWPORT_REFERENCE_WIDTH, 0.3, 1),
c = clamp(geofs.viewportHeight / VIEWPORT_REFERENCE_HEIGHT, 0.3, 1),
this.scale = S2.scale(this.scale, Math.min(a, c))) : this.scale = this.scaleFromParent(a);
this.offset = {
x: 0,
y: 0,
};
this.scaleAllProperties();
this.place(b);
for (b = 0; b < this.children.length; b++) { this.children[b].scaleAndPlace(); }
};
Overlay.prototype.place = function(a) {
this.parent ? (this.definition.animateRotation || (this.rotation = this.definition.rotation + this.parent.rotation),
this.position = {
x: this.parent.position.x + this.definition.position.x * this.scale.x,
y: this.parent.position.y + this.definition.position.y * this.scale.y,
}) : (a = a || this.definition.position,
camera.currentModeName == 'cockpit' && this.definition.cockpit ? this.position = a : this.definition.alignment && (this.definition.alignment.x == 'right' && (this.position.x = geofs.viewportWidth - a.x * this.scale.x),
this.definition.alignment.x == 'center' && (this.position.x = geofs.viewportWidth / 2 - a.x * this.scale.x),
this.definition.alignment.y == 'top' && (this.position.y = geofs.viewportHeight - a.y * this.scale.y),
this.definition.alignment.y == 'center' && (this.position.y = geofs.viewportHeight / 2 - a.y * this.scale.y)));
this.overlay.setPosition(this.position);
this.overlay.setOpacity(this.opacity);
this.overlay.setRotation(this.rotation);
};
Overlay.prototype.scaleFromParent = function(a) {
a = a || {
x: 1,
y: 1,
};
const b = this.parent ? this.parent.scale : a;
return {
x: this.definition.scale.x * b.x * a.x,
y: this.definition.scale.y * b.y * a.y,
};
};
Overlay.prototype.positionFromParentRotation = function() {
let a = [this.position.x, this.position.y, 0],
b = M33.identity();
b = M33.rotationZ(b, -this.parent.rotation * DEGREES_TO_RAD);
a = M33.transform(b, a);
return {
x: a[0],
y: a[1],
};
};
Overlay.prototype.animate = function(a) {
if (this.definition.animations) {
for (var b = 0; b < this.definition.animations.length; b++) {
let animation = this.definition.animations[b],
d = geofs.animation.filter(animation);
if (animation.lastValue != d || a) {
switch (animation.lastValue = d,
animation.type) {
case 'moveY':
this.visibility && this.overlay.setPositionY(this.position.y + d * this.scale.y);
break;
case 'translateY':
this.visibility && this.translateIcon(d, 'Y');
break;
case 'translateX':
this.visibility && this.translateIcon(d, 'X');
break;
case 'scaleX':
this.visibility && (this.size.x = d * this.scale.x,
this.overlay.setSize(this.size));
break;
case 'text':
this.overlay.setText(d);
break;
case 'title':
this.overlay.setTitle(d);
break;
case 'opacity':
this.setOpacity(d);
case 'show':
this.visibility && this.overlay.setVisibility(d);
this.animationVisibility = d;
break;
default:
d && this.visibility && this.rotate(d);
}
}
}
}
for (b = 0; b < this.children.length; b++) { this.children[b].animate(a); }
};
Overlay.prototype.translateIcon = function(a, b) {
b == 'Y' ? this._offset.y = a * this.scale.y * this._sizeScale - this.size.y + this.iconFrame.y : this._offset.x = a * this.scale.x * this._sizeScale;
this.overlay.setPositionOffset(S2.add(this.positionOffset, this._offset));
};
Overlay.prototype.rotate = function(a) {
this.rotation = a;
this.parent && (this.rotation += this.parent.rotation);
this.overlay.setRotation(this.rotation);
};
Overlay.prototype.setText = function(a) {
this.overlay.setText(a);
};
Overlay.prototype.setTitle = function(a) {
this.overlay.setTitle(a);
};
Overlay.prototype.destroy = function() {
geofs.removeResizeHandler(this.resizeHandler);
this.overlay && this.overlay.destroy();
};
export default Overlay
|
var Book = require('./models/book');
function getBooks(res){
Book.find(function(err, books) {
if (err)
res.send(err);
res.json(books);
});
};
module.exports = function(app) {
app.get('/api/books', function(req, res) {
getBooks(res);
});
app.post('/api/books', function(req, res) {
Book.create({
text : req.body.text,
done : false
}, function(err, book) {
if (err)
res.send(err);
getBooks(res);
});
});
app.checkout('/api/books/:book_id', function(req, res) {
Book.remove({
_id : req.params.book_id
}, function(err, book) {
if (err)
res.send(err);
getBooks(res);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
};
|
var calcAreaMod = calcAreaMod || {};
calcAreaMod = (function (){
"use strict";
var inputPerCheck = function (input) {
if (input.value.length > 5) {
input.value = input.value.slice(0, 5);
}
};
return {
inputPerCheck: inputPerCheck
};
}());
formMod.npMagnification.addEventListener('input', function () {
if (formMod.npMagnification.value.length > 5) {
formMod.npMagnification.value = formMod.npMagnification.value.slice(0, 5);
}
}, false);
formMod.npBuff1None.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff1.value = 0;
formMod.npBuff1.disabled = true;
formMod.npBuffSel1.value = 0;
formMod.npBuffSel1.disabled = true;
}
}, false);
formMod.npBuff2None.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff2.value = 0;
formMod.npBuff2.disabled = true;
formMod.npBuffSel2.value = 0;
formMod.npBuffSel2.disabled = true;
}
}, false);
formMod.npBuff1Before.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff1.disabled = false;
formMod.npBuffSel1.disabled = false;
}
}, false);
formMod.npBuff2Before.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff2.disabled = false;
formMod.npBuffSel2.disabled = false;
}
}, false);
formMod.npBuff1After.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff1.disabled = false;
formMod.npBuffSel1.disabled = false;
}
}, false);
formMod.npBuff2After.addEventListener('change', function(e){
if (this.checked) {
formMod.npBuff2.disabled = false;
formMod.npBuffSel2.disabled = false;
}
}, false);
formMod.atkUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.dfcDown.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.bstUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.artUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.qckUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.bstDown.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.artDown.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.qckDown.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.npUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.crtUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.spGrant.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.npSp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.bCrtUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.aCrtUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
formMod.qCrtUp.addEventListener('input', function(){
calcAreaMod.inputPerCheck(this);
}, false);
|
module.exports = {
rules: {
/* shared custom rules */
'array-element-newline': ['error', 'consistent'],
'arrow-parens': ['error', 'as-needed'],
'comma-dangle': ['error', 'always-multiline'],
'comma-spacing': 'error',
'curly': ['error', 'all'],
'eol-last': ['error'],
'func-style': ['error', 'expression'],
'import/prefer-default-export': 0,
'import/no-duplicates': 'error',
// 'indent': ['error', 2, { 'SwitchCase': 1 }],
'key-spacing': 'error',
'keyword-spacing': [2, {'before': true, 'after': true}],
'no-extra-parens': 'error',
'no-multi-spaces': 'error',
'no-multiple-empty-lines': ['error', {'max': 1}],
'no-shadow': 'error',
'no-trailing-spaces': 'error',
'object-curly-spacing': ['error', 'always'],
'object-property-newline': 'error',
'object-shorthand': 'error',
'padded-blocks': 'error',
'prefer-const': 'error',
'prefer-template': 'error',
'quotes': ['error', 'single'],
'quote-props': ['error', 'as-needed'],
'require-await': 'error',
'semi': ['error', 'never'],
'space-before-function-paren': 'error',
'space-infix-ops': ['error', {'int32Hint': false}],
// PTR rules
'import/default': 0,
'import/extensions': 'error',
'import/first': 'error',
'import/no-unresolved': 'error',
// 'sort-imports': 'warn',
'max-lines': 'warn',
'max-len': 0,
'no-console': 0,
'no-undef': 'error',
'no-tabs': 2,
'no-unused-vars': 'error',
'no-underscore-dangle': 0,
// es6
'no-confusing-arrow': "off",
'no-mixed-operators': "off"
},
};
|
'use strict';
module.exports = (sequelize, DataTypes) => {
var Address = sequelize.define('Address', {
street: DataTypes.STRING,
number: DataTypes.INTEGER,
type: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Address;
};
|
const express = require('express');
const router = express.Router();
const controller = require('../controllers/student');
router.get('/', controller.listStudents);
router.post('/addStudent', controller.addStudent);
module.exports = router;
|
import {ADD2, MINUS2} from '../action-types';
let initState = {num: 0};
export default function reducers(state=initState, action){
switch(action.type){
case ADD2:
return {num: state.num + 1};
case MINUS2:
return {num: state.num -1};
default:
return state;
}
}
|
(function($){
/**
URL Parsing Function v1.6
by DJDavid98 - created for EQReverb.com ("site").
2013 (c) DJDavid98
You may not copy or redistribute this script in parts or in whole
without permission from the original author.
@requires jQuery
Short documentation:
$.parseURL(string str)
Accepts one parameter - a string - containing a valid URL.
**/
$.parseURL = function(str) {
if (typeof str === 'undefined' && typeof window.location.href !== 'undefined') str = window.location.href;
var check = {
whole: /^((http|https):\/\/)?((.*\.)?.*\..*|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/.*/,
protocol: /^(http|https):\/\//,
absolute: /^\/\/((.*\.)?.*\..*|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\//,
ip: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/,
relative: /^(#|(\.?\.)?[\/](?!\/).*(\..*|\/)?)?.*$/,
params: /\?(.*=.*(\&)?)+/g,
},
r = {
protocol: undefined,
hostname: undefined,
hash: undefined,
href: {
original: undefined,
noparams: undefined,
},
parentDomain: undefined,
parameters: null,
pathname: {
nohash: undefined,
withhash: undefined,
},
type: undefined,
};
if (typeof str !== 'string') throw new TypeError('Argument must be a string!');
else if (!check.whole.test(str) && !check.absolute.test(str) && !check.relative.test(str)) throw new Error('Invalid string');
r.href.original = str;
if (str.indexOf('#') !== -1){
r.hash = str.substring(str.indexOf('#'));
str = str.substring(0,str.indexOf('#'));
}
if (check.params.test(str)){
r.parameters = {};
var urlparams = str.match(check.params)[0].substring(1).split("&");
for (var i=0,l=urlparams.length; i<l; i++){
var item = urlparams[i].split('=');
r.parameters[item[0]] = item[1];
}
str = str.replace(check.params,'');
}
r.href.noparams = str+(typeof r.hash !== 'undefined' ? r.hash : '');
if (check.protocol.test(str)){
r.protocol = str.match(check.protocol)[0];
r.hostname = str.replace(check.protocol,'');
r.hostname = r.hostname.substring(0,r.hostname.indexOf('/'));
if (!check.ip.test(str)){
r.parentDomain = r.hostname.split('.');
r.parentDomain.splice(0,1);
r.parentDomain = r.parentDomain.join('.');
}
if (!r.parentDomain) r.parentDomain = r.hostname;
var tmp = str.replace(check.protocol,'');
r.pathname.nohash = tmp.substring(tmp.indexOf('/'));
tmp = undefined;
r.type = 'normal';
}
else {
r.protocol = window.location.href.match(check.protocol)[0];
if (check.absolute.test(str)){ //Link starts with "//"
var tmp = str.replace(/^\/\//,'');
r.hostname = tmp.substring(0,tmp.indexOf('/'));
r.pathname.nohash = tmp.substring(tmp.indexOf('/'));
r.type = 'absolute';
r.href.original = r.href.original.replace(/^\/\//g,r.protocol);
}
else if (check.relative.test(str)){
r.hostname = window.location.href.replace(check.protocol,'');
r.hostname = r.hostname.substring(0,r.hostname.indexOf('/'));
if (/^\.?\..*(\/|\.).*/.test(r.href.original)){
var traversalTimes = r.href.original.match(/\.\.\//g).length;
if (traversalTimes > 0){
var wlpn = window.location.pathname;
r.pathname.nohash = wlpn.substring(0,(wlpn.indexOf('#') !== -1 ? wlpn.indexOf('#') : wlpn.length));
r.pathname.nohash = r.pathname.nohash.split('/');
for (var i=0,l=r.pathname.nohash.length; i<l; i++) if (r.pathname.nohash[i] === "") r.pathname.nohash.splice(i,1);
r.pathname.nohash.splice(0,traversalTimes);
}
}
else if (/^#*/.test(r.href.original)){
r.pathname.nohash = window.location.pathname;
}
else r.pathname.nohash = r.href.original;
r.type = 'relative';
}
else {
throw new Error('Invalid string');
}
}
r.pathname.withhash = r.pathname.nohash+(typeof r.hash !== 'undefined' ? r.hash : '');
if (r.pathname.withhash === r.hash+r.hash) r.pathname.withhash = r.hash;
return r;
};
/**
Page Slider v1.2
by DJDavid98 - created for EQReverb.com ("site").
2013 (c) DJDavid98
You may not copy or redistribute this script in parts or in whole
without permission from the original author.
@requires jQuery
**/
$.pageSlider = function(todo,callback){
if (typeof callback !== 'function') callback = undefined;
if (todo === 'update'){
var $toUnActive = [
$('.pageSlider a.active:not([href="'+$.parseURL().pathname.withhash+'"])'),
$('.pageSlider a.active:not([href="'+$.parseURL().pathname.withhash.replace(window.location.pathname,'')+'"])')
];
if (typeof $toUnActive[0][0] !== 'undefined') $toUnActive[0].removeClass('active');
else if (typeof $toUnActive[1][0] !== 'undefined') $toUnActive[1].removeClass('active');
var $toBeActive = [
$('.pageSlider a[href="'+$.parseURL().pathname.withhash+'"]'),
$('.pageSlider a[href="'+$.parseURL().pathname.withhash.replace(window.location.pathname,'')+'"]')
];
if (typeof $toBeActive[0][0] !== 'undefined') $toBeActive[0].addClass('active');
else if (typeof $toBeActive[1][0] !== 'undefined') $toBeActive[1].addClass('active');
$('.pageSlider').each(function(){
var $this = $(this);
var $slideBtn = $this.find('a.slide-button');
if (typeof $slideBtn[0] !== 'undefined'){
var $navs = $this.find('a[href]');
var navsSize = $navs.size();
var percent = 100/navsSize;
var actNavIndx = $this.find('a.active').index();
if (actNavIndx < 0) return false;
$navs.css('width',percent+'%');
$slideBtn.css('width',percent+'%').animate({left:((actNavIndx)*percent)+'%'},500,callback);
}
});
return $('.pageSlider').size()+" sliders updated";
}
};
$(window).on('hashchange',function(){ $.pageSlider("update") });
$(document).ready(function(){
$('.pageSlider').on('click','a.active',function(e){
e.preventDefault();
return false;
});
$(window).scroll();
});
/*$(window).scroll(function(){
if ($('footer')[0].offsetTop <= 708 && $('footer').css('position') !== 'fixed') $('footer').css('position','fixed');
else if ($('footer').css('position') === 'fixed') $('footer').css('position','');
});*/
/*$.ajax({
type: "GET",
url: ('/pages/footer.php'),
async: false,
}).done(function(data){
$(data).insertBefore('script:eq(0)');
$.pageSlider("update");
});*/
$('img').on('contextmenu',function(){
return false;
});
})(jQuery);
|
"use strict";
const { defaults } = require("../lib/index"); ///
const { DEFAULT_QUIETLY } = defaults;
const DEFAULT_PORT = 3000,
DEFAULT_HELP = false,
DEFAULT_VERSION = false,
DEFAULT_WATCH_PATTERN = null,
DEFAULT_ALLOWED_ORIGIN = null;
module.exports = {
DEFAULT_PORT,
DEFAULT_HELP,
DEFAULT_QUIETLY,
DEFAULT_VERSION,
DEFAULT_WATCH_PATTERN,
DEFAULT_ALLOWED_ORIGIN
};
|
describe("@abstract tag", function() {
var docSet = jasmine.getDocSetFromFile('test/fixtures/abstracttag.js'),
type = docSet.getByLongname('Thingy')[0],
pez = docSet.getByLongname('Thingy#pez')[0];
it("should have an undefined 'virtual' property with no '@abstract' tag", function() {
expect(type.virtual).toBeUndefined();
});
it("should set the doclet's 'virtual' property to true when ' @abstract tag is present", function() {
expect(pez.virtual).toBe(true);
});
// same as...
it("should set the doclet's 'virtual' property to true when ' @abstract tag is present", function() {
pez = docSet.getByLongname('OtherThingy#pez')[0];
expect(pez.virtual).toBe(true);
});
});
|
var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var circle;
var point;
var graphics;
var a = 0;
function create ()
{
graphics = this.add.graphics({ lineStyle: { width: 2, color: 0x00ff00 }, fillStyle: { color: 0xff0000 }});
circle = new Phaser.Geom.Circle(400, 300, 200);
point = new Phaser.Geom.Rectangle(0, 0, 16, 16);
}
function update ()
{
a += 0.01;
if (a > Math.PI * 2)
{
a -= Math.PI * 2;
}
point.x = 400 - Math.cos(a) * 400;
point.y = 300 - Math.sin(a * 2) * 300;
graphics.clear();
graphics.strokeCircleShape(circle);
if(circle.contains(point.x, point.y))
{
graphics.fillStyle(0xff0000);
}
else
{
graphics.fillStyle(0x0000ff);
}
graphics.fillRect(point.x - 8, point.y - 8, point.width, point.height);
}
|
export default function stringFromHTML(selector, exceptSelectors) {
let html = document.querySelector(selector).cloneNode(true)
for (let exceptSelector of exceptSelectors) {
let excepts = html.querySelectorAll(exceptSelector)
for (let i = 0; i < excepts.length; i++) {
excepts[i].remove()
}
}
return html.outerHTML
}
|
(function () {
'use strict';
angular
.module('accountModule')
.factory('accountDataservice', accountDataservice);
accountDataservice.$inject = ['$http', 'appSettings'];
/* @ngInject */
function accountDataservice($http, appSettings) {
var url = appSettings.serverPath + 'token';
var _login = function (username, password) {
return $http.post(url, {
'grant_type': 'password',
username: username,
password: password
}, {
transformRequest: function (obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
}
return str.join('&');
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
};
return {
login: _login
};
}
})();
|
//player 1 dice
var randomNumber1 = Math.floor(Math.random() * 6) + 1; //1-6
var randomDiceImage = "images/dice" + randomNumber1 + ".png"; //dice1.png - dice2.png
var image1 = document.querySelectorAll("img")[0].setAttribute("src", randomDiceImage); //[0] - taps into first image in array when using querySelectorAll
//player 2 dice
var randomNumber2 = Math.floor(Math.random() * 6) + 1; //1-6
var randomDiceImage2 = "images/dice" + randomNumber2 + ".png"; //dice1.png - dice2.png
var image2 = document.querySelector(".img2").setAttribute("src", randomDiceImage2);
//h1 change depending on winning dice
if (randomNumber1 > randomNumber2) {
document.querySelector("h1").innerHTML = ("Player 1 Wins!");
} else if (randomNumber1 < randomNumber2) {
document.querySelector("h1").innerHTML = ("Player 2 Wins!");
} else if (randomNumber1 === randomNumber2) {
document.querySelector("h1").innerHTML = ("draw!");
}
|
describe("sumOfPositive", function () {
it("Test 1 , numbers", function () {
assert.deepEqual(sumOfPositive([-100, -50, 60]), {count: 1, sum: 60 });
});
it('Test 2, number', () => {
const result = sumOfPositive([91, 93]);
assert.deepEqual(result, { count: 2, sum: 184 });
});
it('Test 3, приведение типов', () => {
const result = sumOfPositive([-1, -2, 0, '3']);
assert.deepEqual(result, { count: 1, sum: 3 });
});
it('Test 4, нулевые значения', () => {
const result = sumOfPositive([-0, -0, 0, 3]);
assert.deepEqual(result, { count: 1, sum: 3 });
});
it('Test 5, все значения отрицательные', () => {
const result = sumOfPositive([-1, -1, -1, -3]);
assert.deepEqual(result, { count: 0, sum: 0 });
});
it('Test 6, строки ,считаем только цифры', () => {
const result = sumOfPositive(["/", -1, -1, -3]);
assert.deepEqual(result, { count: 0, sum: 0 });
});
});
|
/**
* @ngdoc controller
* @name client.controllers
*
* @description
* _Please update the description and dependencies._
*
* @requires $scope
* */
angular.module('theranest.client.controllers', [])
.controller('ClientCtrl',
function ($scope
, Clients
, $ionicModal) {
$scope.clients = Clients.all();
$scope.remove = function (chat) {
Clients.remove(chat);
}
initModal();
function initModal() {
$ionicModal.fromTemplateUrl('modules/clients/templates/modal-client-add.html', {
scope: $scope,
animation: 'scale-in'
}).then(function (modal) {
$scope.modal = modal;
});
$scope.openModal = function () {
$scope.modal.show();
};
$scope.closeModal = function () {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function () {
$scope.modal.remove();
});
}
$scope.hasFilters = false;
$scope.openFilters = function (hasFilters) {
console.log(hasFilters);
$scope.hasFilters = hasFilters ? false : true;
}
//@TODO Create a factory
$scope.staff = [
{
status: 'active',
name: 'staff1'
},
{
status: 'active',
name: 'staff2'
},
{
status: 'inactive',
name: 'staff3'
},
{
status: 'inactive',
name: 'staff4'
}
]
$scope.project = {
description: 'Nuclear Missile Defense System',
rate: 500
};
$scope.serviceTypes = [
{
id: "97537",
name: "FAMILY"
},
{
id: "90847",
name: "Family pyscotherapy"
},
{
id: "90847",
name: "Family pyscotherapy"
},
{
id: "90836",
name: "Group Session"
},
{
id: "99075",
name: "Group Therapy"
},
{
id: "90845",
name: "H0002-52 Addendum to H0002"
},
{
id: "90834",
name: "Intensive Short-Term Dynamic Psychotherapy"
},
{
id: "99404",
name: "Preventive medicine"
},
{
id: "90840",
name: "Psychotherapy"
},
{
id: "90839",
name: "Psychotherapy"
},
{
id: "90837",
name: "Psycotherapy"
},
{
id: "90791",
name: "Stress Management $100"
},
{
id: "90791",
name: "Stress Management $200"
}
];
$scope.client = {};
$scope.locations = [
{
id:"1",
name:"NY OFFICE"
},
{
id:"2",
name:"CA OFFICE"
}
]
});
|
function solve(num1, num2, op) {
function calculator(num1, num2, op) {
let result = 0;
switch (op){
case'+':
result = num1 + num2;
break;
case'-':
result = num1 - num2;
break;
case'*':
result = num1 * num2;
break;
case'/':
result = num1 / num2;
break;
}
return result;
}
let result = calculator(num1, num2, op);
console.log(result);
}
solve(2, 4, '+');
solve(3, 3, '/');
solve(18, -1, '*');
|
import Accordion from "./accordion"
import Description from "./description"
export default { Accordion, Description }
|
import React, {PropTypes} from "react"
const Service = ({title}) => {
return (
<div>{title}</div>
)
}
Service.propTypes = {
title: PropTypes.string,
}
Service.defaultProps = {
title: PropTypes.string,
}
export default Service
|
$( document ).ready( function() {
$( 'table.tablesorter' ).tablesorter();
} );
|
const lectureExists = (db, lecture_id, class_id) => {
return new Promise((resolve, reject) => {
db.select("lecture_id")
.from("lecture")
.where({
lecture_id,
class_id,
})
.then((table) => resolve(table.length != 0))
.catch(reject);
});
};
module.exports = { lectureExists };
|
import {
PossibleInputPageAC,
SelectCommunityPageAC,
StartFollowingAction,
StopFollowingAction, ToggleIsFetchingAC
} from "../../redux/connect/communityReducer";
import ConnectDecoratorFactory from "./ConnectDecoratorFactory";
let mapStateToProps = (state) =>
{
return {
/** List of community members in page */
users: state.community.users,
pagination: {
/** Number of users showed in single page */
usersPerPage: state.community.usersPerPage,
/** Total number of community members */
totalUsers: state.community.totalUsers,
/** Current page value */
currentPage: state.community.currentPage,
/** Data isFetching from remote server status */
isFetching: state.community.isFetching,
/** Temporary page value which is used for pagination */
possiblePage: state.community.possiblePage
}
}
}
let mapDispatchToProps = (dispatch) =>
{
return {
/** Follow member with given id */
follow: (id) =>
{
dispatch(StartFollowingAction(id))
},
/** Unfollow member with given id */
unfollow: (id) =>
{
dispatch(StopFollowingAction(id))
},
/** Show community members depends on current page */
selectPage: (members, pageNumber, totalUsers) =>
{
dispatch(SelectCommunityPageAC(members, pageNumber, totalUsers))
},
/** Set current isFetching data from remote server status */
toggleIsFetching: isFetching =>
{
dispatch(ToggleIsFetchingAC(isFetching))
},
/** Change temporary input page in pagination widget */
possiblePageInput: possiblePage =>
{
dispatch(PossibleInputPageAC(possiblePage))
}
}
}
/** Connect community with reducer */
const connectCommunity = ConnectDecoratorFactory.MakeDecorator(mapStateToProps, mapDispatchToProps)
export default connectCommunity
|
// = require jquery
// = require jquery_ujs
// = require jquery.ui.all
// = require bootstrap.min
// = require jquery.jplayer
// = require jquery.cookie
// = require jquery.mCustomScrollbar.concat.min
// = require simple-slider.min
// = require_tree .
|
import { expect, request, sinon } from '../../test-helper'
import app from '../../../app'
import UpdateChapter from '../../../src/use_cases/update-chapter'
import UpdateArticle from '../../../src/use_cases/update-article'
import UpdateArticles from '../../../src/use_cases/update-articles'
describe('Integration | Routes | admin route', () => {
describe('/admin/articles/:id', () => {
beforeEach(() => {
sinon.stub(UpdateArticle, 'sync').resolves()
})
afterEach(() => {
UpdateArticle.sync.restore()
})
it('should call update article and send 204', done => {
// Given
const stringIdArticle = '59'
// When
request(app)
.patch(`/api/admin/articles/${stringIdArticle}`)
.end((err, response) => {
// Then
expect(UpdateArticle.sync).to.have.been.calledWith(stringIdArticle)
expect(response.status).to.deep.equal(204)
if (err) {
done(err)
}
done()
})
})
})
describe('/admin/articles/', () => {
beforeEach(() => {
sinon.stub(UpdateArticles, 'sync').resolves()
})
afterEach(() => {
UpdateArticles.sync.restore()
})
it('should call update articles and send 204', done => {
// When
request(app)
.patch('/api/admin/articles')
.end((err, response) => {
// Then
expect(UpdateArticles.sync).to.have.been.calledWith()
expect(response.status).to.deep.equal(204)
if (err) {
done(err)
}
done()
})
})
})
describe('/admin/articles/:id/chapters/:position', () => {
beforeEach(() => {
sinon.stub(UpdateChapter, 'sync').resolves()
})
afterEach(() => {
UpdateChapter.sync.restore()
})
it('should call update article and send 204', done => {
// Given
const stringIdArticle = '59'
const position = '3'
// When
request(app)
.patch(`/api/admin/articles/${stringIdArticle}/chapters/${position}`)
.end((err, response) => {
// Then
expect(UpdateChapter.sync).to.have.been.calledWith({ dropboxId: stringIdArticle, chapterPosition: position })
expect(response.status).to.deep.equal(204)
if (err) {
done(err)
}
done()
})
})
})
})
|
import React, { useState } from "react";
import PropTypes from "prop-types";
import clsx from "clsx";
import { makeStyles, useTheme } from "@material-ui/styles";
import { useMediaQuery } from "@material-ui/core";
import { Topbar, Footer } from "./common";
import Sidebar from "./common/Sidebar";
const useStyles = makeStyles((theme) => ({
root: {
paddingTop: 56,
height: "100%",
[theme.breakpoints.up("sm")]: {
paddingTop: 64,
},
},
shiftContent: {
paddingLeft: 240,
},
content: {
minHeight: "calc(100vh - 114px)",
},
}));
const Main = (props) => {
const { children } = props;
const classes = useStyles();
const theme = useTheme();
const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
defaultMatches: true,
});
const [openSidebar, setOpenSidebar] = useState(false);
const toggleSidebar = () => {
setOpenSidebar(!openSidebar);
};
const handleSidebarClose = () => {
setOpenSidebar(false);
};
const shouldOpenSidebar = isDesktop ? true : openSidebar;
return (
<div
className={clsx({
[classes.root]: true,
[classes.shiftContent]: isDesktop,
})}
>
<Topbar toggleSidebar={toggleSidebar} />
<Sidebar
onClose={handleSidebarClose}
open={shouldOpenSidebar}
variant={isDesktop ? "persistent" : "temporary"}
/>
<main className={classes.content}>{children}</main>
<Footer />
</div>
);
};
Main.propTypes = {
children: PropTypes.node,
};
export default Main;
|
'use strict';
describe('Filter: seatPrice', function () {
// load the filter's module
beforeEach(module('manaTicketApp'));
// initialize a new instance of the filter before each test
var seatPrice;
beforeEach(inject(function ($filter) {
seatPrice = $filter('seatPrice');
}));
it('should return the input prefixed with "seatPrice filter:"', function () {
expect(1).toBe(1);
});
});
|
var $add = $('.task-add');
var $list = $('.todo > .list > ul');
var $complete = $('.todo > .complete > ul');
var db = firebase.firestore();
firebase.auth().onAuthStateChanged(user => {
var person = db.collection("users").doc(user.uid).get()
person.then(got => {
var data = got.data();
data['tasks'].forEach(task => {
var $newTask = $('<li>');
$newTask.append($('<span>').text(task));
var $donebtn = $('<button>').attr('type', 'button').addClass('done-btn');
var $icon = $('<i>').text('check_circle').addClass('material-icons');
$donebtn.append($icon);
$newTask.append($donebtn);
$list.append($newTask);
});
data['tasks-c'].forEach(completed => {
$completedTask = $('<li>');
$completedTask.text(completed);
$complete.append($completedTask);
});
});
});
|
const asyncHandler = require('express-async-handler')
const Post = require('../models/PostModel')
const getAllTags = asyncHandler(async (req, res) => {
try {
const tags = await Post.aggregate([
{ "$unwind": "$tags" },
{
"$group": {
"_id": "$tags",
"count": { "$sum": 1 }
}
},
{ "$sort": { "_id": -1 } },
{ "$limit": 5 }
])
res.json(tags)
} catch (e) {
res.status(400).json({ "message": "Something goes wrong" })
}
})
module.exports = { getAllTags }
|
var currentPhotoId;
var listening = new Array();
function UPG_onPhotoLoad(id)
{
currentPhotoId = id;
for (var i=0;i<listening.length ;i++ )
{
var func = listening[i] + "();";
eval (func);
}
}
function UPG_listen(func)
{
listening.push(func);
}
|
import {
getLanguage,
getProtocol,
getCurrency,
myInfor,
getHotCity,
getComNavigation,
} from 'getData';
import router from "../router/index";
const actions = {
//登录
addLogin({dispatch, commit}, obj) {
commit("STATE_CHANGE", {
loginFlag: 0,
loginUid: obj.uid,
loginKey: obj.uid,
loginTime: obj.uid,
loginType: 2,
})
dispatch('buy/getCarNum', {}, {root: true})
let path = obj.route.query.redirect
router.push({path: path == '/' || path == undefined ? '/home' : path});
},
//退出登录
removeLogin({commit, dispatch},route) {
commit("STATE_CHANGE", {
loginUid: "",
loginKey: "",
loginTime: "",
loginType: 1,
})
dispatch('buy/getCarNum', {}, {root: true})
//判断是否需要登录 如果需要登录重新跳回首页
if(route.meta.requireAuth){
router.push("/")
}
},
//首次加载页面
craeteInit({dispatch, commit}) {
commit("STATE_CHANGE",{
loginFlag: 0
})
dispatch("myInfor")
dispatch("getProtocol")
dispatch("getLanguage")
dispatch("getCurrency")
dispatch("getHotCity")
dispatch("getComNavigation")
dispatch('buy/getCarNum', {}, {root: true})
},
//获取会员信息
myInfor({commit, state}){
if (state.loginType == 2) {
myInfor().then( res => {
commit("STATE_CHANGE",{
member: res
})
})
}
},
//获取网站基本参数
getProtocol({commit}) {
getProtocol().then( res => {
commit("STATE_CHANGE",{
comProtocol: res
})
})
},
//获取语言
getLanguage({commit}) {
getLanguage().then( res => {
commit("STATE_CHANGE",{
languageList: res
})
})
},
//获取货币
getCurrency({commit}) {
getCurrency().then( res => {
commit("STATE_CHANGE",{
currencyList: res
})
})
},
//获取热门城市
getHotCity({commit}){
getHotCity().then( res => {
for (const list of res) {
Vue.set(list, "flag", false);
}
commit("STATE_CHANGE",{
hotCityList: res
})
})
},
//获取导航栏
getComNavigation({commit}){
getComNavigation().then( res => {
for (const list of res) {
Vue.set(list, "flag", false);
}
commit("STATE_CHANGE",{
comNavigationList: res
})
})
},
}
export default actions
|
/** @jsx jsx */
import styled from '@emotion/styled';
import { jsx } from 'theme-ui';
const OutletContainer = styled.div`
width: 25px;
height: 40px;
position: absolute;
background-color: #fff;
border-radius: 2px;
`;
const OutletFace = styled.div`
width: 17px;
height: 12px;
margin-left: 4px;
margin-top: 5px;
position: relative;
background-color: #d9edee;
border-radius: 5px;
&::before {
content: '';
position: absolute;
margin-top: 3px;
margin-left: 3px;
width: 6px;
height: 5px;
border-left: #87a3a7 2px solid;
border-right: #87a3a7 2px solid;
}
`;
const Outlet = (props) => (
<OutletContainer {...props}>
<OutletFace />
<OutletFace />
</OutletContainer>
);
export default Outlet;
|
var nodes = null;
var edges = null;
var network = null;
var data = null;
var seed = 2;
function destroy() {
if (network !== null) {
network.destroy();
network = null;
}
}
function getGraph(callback) {
$.get('/api/nodes', function (nodes) {
$.get('/api/edges', function (edges) {
return callback(false, { nodes: nodes, edges: edges });
});
});
}
function draw() {
destroy();
// create a network
var container = document.getElementById('my_network');
var options = {
locale: 'es',
edges: {
arrows: {
to: true,
}
},
interaction: {
navigationButtons: true,
hoverConnectedEdges: false
},
manipulation: {
addNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Agregar nodo";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = clearPopUp.bind();
document.getElementById('network-popUp').style.display = 'block';
},
editNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Editar Nodo";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = cancelEdit.bind(this, callback);
document.getElementById('network-popUp').style.display = 'block';
},
addEdge: function (data, callback) {
if (data.from == data.to) {
var r = confirm("¿Quiere conectarse a si mismo?");
if (r == true)
callback(data);
}
else {
callback(data);
}
}
}
};
getGraph(function (err, result) {
data = result
network = new vis.Network(container, data, options);
});
}
function clearPopUp() {
document.getElementById('saveButton').onclick = null;
document.getElementById('cancelButton').onclick = null;
document.getElementById('network-popUp').style.display = 'none';
}
function cancelEdit(callback) {
clearPopUp();
callback(null);
}
function saveData(data, callback) {
data.id = document.getElementById('node-id').value;
data.label = document.getElementById('node-label').value;
clearPopUp();
callback(data);
}
function init() {
draw();
}
|
let btnCalcular = document.querySelector("#btnCalcular");
btnCalcular.addEventListener("click", calcular);
let btnVolver = document.querySelector("#btnVolver");
btnVolver.addEventListener("click", volver);
let calculos = [];
load();
function calcular() {
console.log("Función Calcular");
let num1 = parseInt(document.querySelector('#num1').value);
let operador = document.querySelector('#operador').value;
let num2 = parseInt(document.querySelector('#num2').value);
switch (operador) {
case '+':
resultado = num1 + num2;
break;
case '-':
resultado = num1 - num2;
break;
case '*':
resultado = num1 * num2;
break;
case '/':
resultado = num1 / num2;
break;
case '^':
resultado = Math.pow(num1, num2);
break;
default:
resultado = 0;
break;
}
document.querySelector('#num1').value = "";
document.querySelector('#num2').value = "";
let renglon = {
"num1": num1,
"operador": operador,
"num2": num2,
"resultado": resultado
}
calculos.push(renglon);
mostrarTablaCalculos();
}
function mostrarTablaCalculos() {
html = "";
for (let r of calculos) {
html += `
<tr>
<td>${r.num1}</td>
<td>${r.operador}</td>
<td>${r.num2}</td>
<td>${r.resultado}</td>
</tr>
`;
}
document.querySelector("#tblCalculos").innerHTML = html;
}
function volver() {
history.go(-1);
}
|
var totalScore = 0;
var checkAnswer = function(correctAnswer){
var id = correctAnswer + window.location.hash.substring(4, 6);
var response = "response" + window.location.hash.substring(4, 6);
var answer = document.getElementById(id).checked;
if (answer === true){
$("." + response).html("Correct!").addClass("font-size");
if(document.URL.indexOf("#tab01") > -1 || window.location.hash.indexOf("#tab02") > -1 || window.location.hash.indexOf("#tab03") > -1 || window.location.hash.indexOf("#tab04") > -1){
totalScore = totalScore + 200;
console.log("200");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab05") > -1 || window.location.hash.indexOf("#tab06") > -1 || window.location.hash.indexOf("#tab07") > -1 || window.location.hash.indexOf("#tab08") > -1){
totalScore = totalScore + 400;
console.log("400");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab09") > -1 || window.location.hash.indexOf("#tab10") > -1 || window.location.hash.indexOf("#tab11") > -1 || window.location.hash.indexOf("#tab12") > -1){
totalScore = totalScore + 600;
console.log("600");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab13") > -1 || window.location.hash.indexOf("#tab14") > -1 || window.location.hash.indexOf("#tab15") > -1 || window.location.hash.indexOf("#tab16") > -1){
totalScore = totalScore + 800;
console.log("800");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab17") > -1 || window.location.hash.indexOf("#tab18") > -1 || window.location.hash.indexOf("#tab19") > -1 || window.location.hash.indexOf("#tab20") > -1){
totalScore = totalScore + 1000;
console.log("1000");
$("#score").html("Score: " + totalScore);
}
}
else{
$("." + response).html("Wrong.").addClass("font-size");
if(document.URL.indexOf("#tab01") > -1 || window.location.hash.indexOf("#tab02") > -1 || window.location.hash.indexOf("#tab03") > -1 || window.location.hash.indexOf("#tab04") > -1){
totalScore = totalScore - 200;
console.log("200");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab05") > -1 || window.location.hash.indexOf("#tab06") > -1 || window.location.hash.indexOf("#tab07") > -1 || window.location.hash.indexOf("#tab08") > -1){
totalScore = totalScore - 400;
console.log("400");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab11") > -1 || window.location.hash.indexOf("#tab10") > -1 || window.location.hash.indexOf("#tab11") > -1 || window.location.hash.indexOf("#tab12") > -1){
totalScore = totalScore - 600;
console.log("600");
$("#score").html("Score:" + totalScore);
}
if(document.URL.indexOf("#tab13") > -1 || window.location.hash.indexOf("#tab14") > -1 || window.location.hash.indexOf("#tab15") > -1 || window.location.hash.indexOf("#tab16") > -1){
totalScore = totalScore - 800;
console.log("800");
$("#score").html("Score: " + totalScore);
}
if(document.URL.indexOf("#tab17") > -1 || window.location.hash.indexOf("#tab18") > -1 || window.location.hash.indexOf("#tab19") > -1 || window.location.hash.indexOf("#tab20") > -1){
totalScore = totalScore - 1000;
console.log("1000");
$("#score").html("Score: " + totalScore);
}
}
};
|
import React from 'react';
import DataLineIcon from './DataLineIcon';
class ProductDataFunding extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div className="GroupOfDecisions">
<h3 className="HeadlineDecision">מימון</h3>
<DataLineIcon ValueOfField={this.props.LongTimeLoan} Datatext={"הלוואה לזמן ארוך"} handleChange={this.props.handleChange} name={"LongTimeLoan"} SerialNum={22} iconText={'dollar'}/>
<DataLineIcon ValueOfField={this.props.ShortTimeLoan} Datatext={"הלוואה לזמן קצר"} handleChange={this.props.handleChange} name={"ShortTimeLoan"} SerialNum={23} iconText={'dollar'}/>
<DataLineIcon ValueOfField={this.props.BillsDeposit} Datatext={"ניכיון שטרות"} handleChange={this.props.handleChange} name={"BillsDeposit"} SerialNum={24} iconText={'dollar'}/>
<DataLineIcon ValueOfField={this.props.ShortLoanPay} Datatext={"החזר הלוואה לזמן ארוך"} handleChange={this.props.handleChange} name={"ShortLoanPay"} SerialNum={25} iconText={'dollar'}/>
</div>
)
}
}
export default ProductDataFunding;
|
import React from "react"
import PropTypes from "prop-types"
import {layoutWrapper} from "./layout.module.scss"
const Layout = ({ children }) => (
<main className={layoutWrapper}>{children}</main>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
import * as yup from 'yup';
export const signUpItemsArray = [
{
title: 'first name',
type: 'text',
tag: 'input',
},
{
title: 'last name',
type: 'text',
tag: 'input',
},
{
title: 'email',
type: 'text',
tag: 'input',
},
{
title: 'send me email in plane text',
type: 'checkbox',
tag: 'input',
},
{
title: 'personal phone number',
type: '',
tag: 'select',
},
{
title: 'company name',
type: 'text',
tag: 'input',
},
{
title: 'company address',
type: 'text',
tag: 'input',
},
{
title: 'company phone number',
type: '',
tag: 'select',
},
{
title: 'job title',
type: 'text',
tag: 'input',
},
{
title: 'password',
type: 'password',
tag: 'input',
},
{
title: 'confirm password',
type: 'password',
tag: 'input',
},
{
title: 'accept privacy policy',
type: 'checkbox',
tag: 'input',
},
];
export const passwordComplexity = {
light: /^((?=.*[a-z])([a-z])){10,}|((?=.*[A-Z])([A-Z])){10,}|((?=.*[\d])([\d])){10,}|((?=.*[!-/:-@[-`{-~]))([!-/:-@[-`{-~]){10,}$/g,
medium: /^(?=.*[a-z])(?=.*[A-Z])([a-zA-Z]){10,}|(?=.*[a-z])(?=.*[\d])([a-z\d]){10,}|(?=.*[a-z])(?=.*[!-/:-@[-`{-~])([a-z!-/:-@[-`{-~]){10,}|(?=.*[\d])(?=.*[A-Z])([\dA-Z]){10,}|(?=.*[\d])(?=.*[!-/:-@[-`{-~])([\d!-/:-@[-`{-~]){10,}|(?=.*[A-Z])(?=.*[!-/:-@[-`{-~])([A-Z!-/:-@[-`{-~]){10,}$/g,
strong: /^(?=.*[!-/:-@[-`{-~\d])(?=.*[\w])([\w!-/:-@[-`{-~]){10,}$/g,
}
export const signUpValidationSchema = (phoneMaskLength) => yup.object().shape({
firstName: yup.string().required('First name is required'),
lastName: yup.string().required('Last name is required'),
email: yup.string().email().required('Email is required'),
sendMeEmailInPlaneText: yup.boolean(),
personalPhoneNumber: yup.string().required('Personal phone number is required'),
personalPhoneNumberField: yup.string().required('This field is required'),
companyName: yup.string().required('Company name is required'),
companyAddress: yup.string().required('Company address is required'),
companyPhoneNumber: yup.string().required('Company phone number is required'),
companyPhoneNumberField: yup.string().required('This field is required'),
jobTitle: yup.string().required('Job title is required'),
password: yup.string().min(10).required('Password is required'),
confirmPassword: yup.string().oneOf([yup.ref('password'), null]).required('Confirm password is required'),
acceptPrivacyPolicy: yup.boolean().oneOf([true], 'Accept privacy policy is required'),
});
|
//= require rails_jskit
App.createController("Pages", {
actions: ['index'],
index: function(data) {
console.log(arguments);
}
});
|
function every(arr, check) {
var isEvery = true;
arr.forEach(function(val, i, arr) {
if (!check(val)) isEvery = false;
});
return isEvery;
}
function some(arr, check) {
var isSome = false;
arr.forEach(function(val, i, arr) {
if (check(val)) isSome = true;
});
return isSome;
}
console.log(every([NaN, NaN, NaN], isNaN));
// → true
console.log(every([NaN, NaN, 4], isNaN));
// → false
console.log(some([NaN, 3, 4], isNaN));
// → true
console.log(some([2, 3, 4], isNaN));
// → false
|
// TODO: Use some generalized event dispatcher, probably from one of my libs
// TODO: Revamp event dispatching to use signals/slots and more performant approach
var SystemEventSource = (function() {
function SystemEventSource() {
this.listeners = {};
}
SystemEventSource.prototype = {
constructor: SystemEventSource,
addListener: function(event_type, callback) {
if (!this.listeners[event_type]) {
this.listeners[event_type] = [];
}
// Useless when using bind() on callbacks
if (this.listeners[event_type].indexOf(callback) >= 0 && event_type === 'onCollisionEnter') {
throw new Error('Callback is already registered');
}
// TODO: DO BETTER? HANDLE UNBOUND CALLBACKS?
this.listeners[event_type].push(callback);
},
removeListener: function(event_type, callback) {
var idx = this.listeners[event_type].indexOf(callback);
if (idx >= 0) {
this.listeners[event_type].splice(idx, 1);
}
},
trigger: function(event_type, args) {
if (!this.listeners[event_type]) return;
for (var i = 0; i < this.listeners[event_type].length; ++i) {
// TODO: Passing null context to bound function is unclean
this.listeners[event_type][i].apply(null, args);
}
}
}
return SystemEventSource;
})();
var System = (function() {
function isEventHandlerName(property_name) {
return property_name.length >= 3 &&
property_name.substr(0, 2) === 'on' &&
Util.String.isUpper(property_name.charAt(2));
}
function System() {
this.eventSource = new SystemEventSource();
if (!this.name) {
if (typeof this.constructor.name === 'string' && this.constructor.name.length > 0) {
this.name = this.constructor.name;
} else {
throw new Error("System must define its 'name' or have a constructor with valid 'name' property ");
}
}
}
System.prototype = {
constructor: System,
onInit: function(ecs) {
this.ecs = ecs;
},
bindEvents: function(system) {
for (var property_name in system) {
var property = system[property_name];
if (typeof property !== 'function') continue;
if (!isEventHandlerName(property_name)) continue;
this.eventSource.addListener(property_name, property.bind(system));
}
},
onEntityAdded: function(entity) {
},
onEntityRemoved: function(entity) {
}
};
System.extend = function(name, constructor, prototype) {
// To make debugger show actual function name.
// Makes debugging easier.
// TODO: Test if it affects performance or anything; if it does, remove in production builds
var constructor_wrapped = eval('(function(){ function ' + name + '() { System.call(this); constructor.apply(this, arguments); } return ' + name + '; })();');
/*var constructor_wrapped = function() {
System.call(this);
constructor.apply(this, arguments);
};*/
constructor_wrapped.name = name;
var proto = Object.create(System.prototype);
proto.constructor = constructor_wrapped;
proto.name = name;
for (var key in prototype) {
proto[key] = prototype[key];
}
constructor_wrapped.prototype = proto;
return constructor_wrapped;
}
return System;
})();
|
import React from "react";
import classnames from "classnames";
import Track from "utils/Track";
import StoreService from "utils/StoreService";
export default class FeelingInspired extends React.PureComponent {
state = {
emotion: null,
};
componentDidMount() {
this.setState({
emotion: StoreService.getItem(`Feeling-${this.props.name}`),
});
}
onClick(emotion) {
this.setState({
emotion,
});
StoreService.setItem(`Feeling-${this.props.name}`, emotion);
Track("Successful Resumes", "Reaction", `${this.props.name} ${emotion}`);
}
render() {
const { name, dark } = this.props;
const { emotion } = this.state;
return (
<div
className={classnames("component--feeling m-md-top-13 m-sm-top-4 m-sm-right-2", {
"feeling-box-dark": dark,
"feeling-box-light": !dark,
})}>
<span className="m-right-1 m-left-1">Feeling inspired?</span>
<span
onClick={() => this.onClick("neutral")}
className={classnames("component--feeling-emotion emotion-neutral", {
active: emotion === "neutral",
})}
/>
<span
onClick={() => this.onClick("smilling")}
className={classnames("component--feeling-emotion emotion-smiling", {
active: emotion === "smilling",
})}
/>
<span
onClick={() => this.onClick("happy")}
className={classnames("component--feeling-emotion emotion-happy", {
active: emotion === "happy",
})}
/>
</div>
);
}
}
|
({
makeWhereCondition: function (parentId, recordType, status, subStatus, bulkResponseSent, customerReplied, caseOwnerId, hasEmail) {
var whereCondition = 'WHERE ParentId = ' + "'" + parentId + "' ";
if (recordType === 'Standard') {
whereCondition += ' AND RecordTypeId = ' + "'" + $A.get('$Label.c.XCTN_StandardCaseRecordTypeId') + "' ";
} else if (recordType === 'Xero Central') {
whereCondition += ' AND RecordTypeId = ' + "'" + $A.get('$Label.c.XCTN_XeroCentralCaseRecordTypeId') + "' ";
}
if (status && status !== '--- None ---') {
whereCondition += ' AND Status = ' + "'" + status + "' ";
}
if (subStatus && subStatus !== '--- None ---') {
whereCondition += ' AND Sub_Status__c = ' + "'" + subStatus + "' ";
}
if (bulkResponseSent) {
if (bulkResponseSent !== 'All') {
whereCondition += ' AND Bulk_Response_Sent__c = ';
if (bulkResponseSent === 'Yes') {
whereCondition += 'true ';
} else {
whereCondition += 'false ';
}
}
}
if (customerReplied) {
if (customerReplied !== 'All') {
whereCondition += ' AND Customer_Replied__c = ';
if (customerReplied === 'Yes') {
whereCondition += 'true ';
} else {
whereCondition += 'false ';
}
}
}
if (caseOwnerId) {
whereCondition += ' AND OwnerId = ' + "'" + caseOwnerId + "' ";
}
if (hasEmail) {
whereCondition += ' AND (ContactId != NULL OR SuppliedEmail != NULL) ';
} else {
whereCondition += ' AND (ContactId = NULL AND SuppliedEmail = NULL) ';
}
return whereCondition;
},
fireFilterEvent: function (whereCondition, parentId) {
var appEvent = $A.get("e.c:XCTN_CaseFilterEvent");
appEvent.setParams({
"whereCondition": whereCondition,
"parentCaseRecordId": parentId
});
appEvent.fire();
//console.log('whereCondition: ', whereCondition);
},
fireViewAllCasesEvent: function (whereCondition, parentId) {
var appEvent = $A.get("e.c:XCTN_ViewAllCasesEvent");
appEvent.setParams({
"whereCondition": whereCondition,
"parentCaseRecordId": parentId
});
appEvent.fire();
//console.log('whereCondition: ', whereCondition);
},
fetchPicklistValues: function (component, objDetails, controllerField, dependentField) {
// call the server side function
var action = component.get("c.getDependentMap");
// pass parameters [object definition , controller field name ,dependent field name] -
// to server side function
action.setParams({
'objDetail': objDetails,
'contrfieldApiName': controllerField,
'depfieldApiName': dependentField
});
//set callback
action.setCallback(this, function (response) {
if (response.getState() === "SUCCESS") {
//store the return response from server (map<string,List<string>>)
var StoreResponse = response.getReturnValue();
// once set #StoreResponse to depnedentFieldMap attribute
component.set("v.dependentFieldMap", StoreResponse);
// create a empty array for store map keys(@@--->which is controller picklist values)
var listOfkeys = []; // for store all map keys (controller picklist values)
var ControllerField = []; // for store controller picklist value to set on lightning:select.
// play a for loop on Return map
// and fill the all map key on listOfkeys variable.
for (var singlekey in StoreResponse) {
listOfkeys.push(singlekey);
}
//set the controller field value for lightning:select
if (listOfkeys != undefined && listOfkeys.length > 0) {
ControllerField.push('--- None ---');
}
for (var i = 0; i < listOfkeys.length; i++) {
ControllerField.push(listOfkeys[i]);
}
// set the ControllerField variable values to country(controller picklist field)
component.set("v.listControllingValues", ControllerField);
} else {
console.error('Dependent picklist failed');
}
});
$A.enqueueAction(action);
},
fetchDepValues: function (component, ListOfDependentFields) {
// create a empty array var for store dependent picklist values for controller field
var dependentFields = [];
dependentFields.push('--- None ---');
for (var i = 0; i < ListOfDependentFields.length; i++) {
dependentFields.push(ListOfDependentFields[i]);
}
// set the dependentFields variable values to store(dependent picklist field) on lightning:select
component.set("v.listDependingValues", dependentFields);
},
})
|
baidu.frontia.personalStorage = baidu.frontia.personalStorage || {};
(function(namespace_){
var Error = baidu.frontia.error;
var ErrConst = baidu.frontia.ERR_MSG;
var PCSUriPrefixs = namespace_.DomainManager.getPCSDomain() + '/rest/2.0/pcs/';
var PBLOGUriPrefixs = namespace_.DomainManager.getPBLogDomain() + '/pushlog';
var apiKey = namespace_.apiKey;
var personalStorage = {}
/** @namespace baidu.frontia.personalStorage */
personalStorage = /** @lends baidu.frontia.personalStorage*/{
options: {
error: function(){},
success: function(){}
},
_configure: function(options) {
options = options || {};
options.error && (this.options.error = options.error);
options.success && (this.options.success = options.success);
},
_checkParams: function(params, prompt) {
var self = this;
/*
if (!accessToken) {
self.options.error(new Error(ErrConst.INVALID_PARAMS, '[' + prompt + ']: accessToken is invaild'));
return false;
}
*/
return params.every(function(elem) {
if (elem.type === 'file' && !(elem.value && elem.value instanceof File)) {
self.options.error(new Error(ErrConst.INVALID_PARAMS, '['+ prompt + ']: file is null or not typeof File of DOM'));
return false;
}
if (elem.type === 'string' && !(elem.value && typeof elem.value === 'string')) {
self.options.error(new Error(ErrConst.INVALID_PARAMS, '['+ prompt +']: target is invalid'));
return false;
}
if ( elem.type === 'array' && !(elem.value && Object.prototype.toString.call(elem.value).slice(8, -1) === 'Array')){
self.options.error(new Error(ErrConst.INVALID_PARAMS, '[' + prompt + ']: targets is invalid'));
return false;
}
return true;
});
},
_createAjaxOpt: function(frontia_action, options) {
var self = this;
var deafaultOpt = {
callback: function(data) {
if (data.error_code) {
var error = new Error(data);
self.options.error(error);
frontia_action.err_code = error.code;
frontia_action.err_msg = error.message;
} else {
self.options.success(data);
frontia_action.err_code = 0;
}
frontia_action.restimestamp = _getTimestamp();
_sendPBLog(frontia_action);
},
onerror: function(xhr, error) {
try {
var err_data = namespace_.util.parseJSON(xhr.responseText);
} catch(ex) {
self.options.error(ex, xhr);
return;
}
var error = new Error(err_data);
self.options.error(error, xhr);
frontia_action.err_code = error.code;
frontia_action.err_msg = error.message;
frontia_action.restimestamp = _getTimestamp();
_sendPBLog(frontia_action);
}
}
return namespace_.util.mix(deafaultOpt, options);
},
/**
* 上传文件
*
* @param {Object(window.File)} file 本地浏览器DOM的file对象
* @param {string} target 上传到云存储上文件名,包含全路径
* @param {Object} options
* @param {string(personalStorage.Constant)} [options.ondup] 如果ondup值为constant.ONDUP_OVERWRITE,表示同名覆盖; 为constant.ONDUP_NEWCOPY, 表示生成文件副本并进行重命名,命名规则为“文件名_日期.后缀”
* @param {function(result)} [options.success] 上传成功后callback
* @param {function(error, xhr)} [options.error] 上传失败后callback
*/
uploadFile: function(file, target, options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.uploadFile';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([{value: file, type: 'file'}, {value: target, type: 'string'}], 'personalStorage.uploadFile')) return;
options.method = 'upload';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(target, options, ['success', 'error']);
var url = _generatePCSUrl('file?', request.query);
var ajaxOpt = self._createAjaxOpt(frontia_action, {
contentType: 'multipart/form-data'
});
var ajax = namespace_.ajax;
var formData = new FormData();
formData.append('baidu_frontia_file', file);
ajax.post(url, formData, 'json', ajaxOpt);
},
/**
* 获取云存储文件URL
*
* @param {string} target 云存储上文件路径
* @param {Object} options
* @param {function(result)} [options.success] 下载成功后callback, result为云存储文件Url
* @param {function(error, xhr)} [options.error] 下载失败后callback
*/
getFileUrl: function(target, options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.getFileUrl';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([{value: target, type: 'string'}], 'personalStorage.getFileUrl')) return;
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
options.method = 'download';
var request = _createRequest(target, options, ['success', 'error']);
var download_url = _generatePCSUrl('file?', request.query);
options.method = 'meta';
request = _createRequest(target, options, ['success', 'error']);
var meta_url = _generatePCSUrl('file?', request.query);
var ajaxOpt = {
callback: function(data) {
if (data.error_code) {
var error = new Error(data);
self.options.error(error);
frontia_action.err_code = error.code;
frontia_action.err_msg = error.message;
} else {
self.options.success(download_url);
frontia_action.err_code = 0;
}
frontia_action.restimestamp = _getTimestamp();
_sendPBLog(frontia_action);
},
onerror: function(xhr, error) {
try {
var err_data = namespace_.util.parseJSON(xhr.responseText);
} catch(ex) {
self.options.error(ex, xhr);
return;
}
var error = new Error(err_data);
self.options.error(error, xhr);
frontia_action.err_code = error.code;
frontia_action.err_msg = error.message;
frontia_action.restimestamp = _getTimestamp();
_sendPBLog(frontia_action);
},
dataType: 'json'
}
var ajax = namespace_.ajax;
ajax.get(meta_url, {}, ajaxOpt);
},
/**
* 删除目录或文件
*
* @param {Array} targets 需要删除的文件或目录数组,targets.length长度大于等于1
* @param {Object} options
* @param {function(result)} [options.success] 删除成功后callback
* @param {function(error, xhr)} [options.error] 删除失败后callback
*/
deleteFile: function(targets, options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.deleteFile';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([{value: targets, type: 'array'}], 'personalStorage.deleteFile')) return;
options.method = 'delete';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(targets, options, ['success', 'error']);
var url = _generatePCSUrl('file?', request.query);
var ajaxOpt = self._createAjaxOpt(frontia_action);
var ajax = namespace_.ajax;
ajax.post(url, {param:request.body}, 'json', ajaxOpt);
},
/**
* 获取指定路径下的文件列表
*
* @param {string} target 云存储上文件路径
* @param {Object} options
* @param {Number} [options.limit] 返回条目控制,参数格式为:n1-n2. 返回结果集的[n1, n2)之间的条目,缺省返回所有条目;n1从0开始
* @param {string(personalStorage.constant)} [options.by] 返回列表按指定type排序,包括time(修改时间)/name(文件名)/size(注意文件名没有大小),默认按类型排序. 取值类型:constant.BY_TIME/constant.BY_NAME/constant.BY_SIZE
* @param {string(personalStorage.constant)} [options.order] 返回列表的是升序/降序排列,默认是降序. 取值类型:constant.ORDER_ASC/constant.ORDER_DESC
* @param {function(result)} [options.success] 下载成功后callback
* @param {function(error, xhr)} [options.error] 下载失败后callback
*/
listFile: function(target, options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.listFile';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([{value: target, type: 'string'}], 'personalStorage.listFile')) return;
options.method = 'list';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(target, options, ['success', 'error']);
var url = _generatePCSUrl('file?', request.query);
var ajaxOpt = self._createAjaxOpt(frontia_action, {
dataType: 'json'
});
var ajax = namespace_.ajax;
ajax.get(url, {}, ajaxOpt);
},
/**
* 获取所有的流式文件列表,包括视频、音频、图片及文档四种类型的视图
*
* @param {Object} options
* @param {Number} [options.start] 返回列表的起始位置, 默认为0
* @param {Number} [options.limit] 返回列表的数目, 默认为1000
* @param {Number} [options.filter_path] 需过滤的前缀路径, 即不会列出该路径下的文件
* @param {string(personalStorage.constant)} options.type 返回列表的类型,包括video(视频)/audio(音频)/image(图片)/doc(文档) 4种类型. 取值类型:constant.TYPE_STREAM_VIDEO/constant.TYPE_STREAM_AUDIO/constant.TYPE_STREAM_IMAGE/constant.TYPE_STREAM_DOC
* @param {function(result)} [options.success] 获取成功后callback
* @param {function(error, xhr)} [options.error] 获取失败后callback
*/
listStreamFile: function(options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.listStreamFile';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
options.method = 'list';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(null, options, ['success', 'error']);
if (options.filter_path) {
request.query.filter_path = options.filter_path;
}
var url = _generatePCSUrl('stream?', request.query);
var ajaxOpt = self._createAjaxOpt(frontia_action, {
dataType: 'json'
});
var ajax = namespace_.ajax;
ajax.get(url, {}, ajaxOpt);
},
/**
* 创建目录
*
* @param {string} target 待创建云存储上的目录路径
* @param {Object} options
* @param {function(result)} [options.success] 下载成功后callback, result为云存储文件Url
* @param {function(error, xhr)} [options.error] 下载失败后callback
*/
makeDir: function(target, options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.makeDir';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([{value: target, type: 'string'}], 'personalStorage.makeDir')) return;
options.method = 'mkdir';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(target, options, ['success', 'error']);
var url = _generatePCSUrl('file?', request.query);
var ajaxOpt = self._createAjaxOpt({
dataType: 'json'
});
var ajax = namespace_.ajax;
ajax.post(url, {}, 'json', ajaxOpt);
},
/**
* 获取当前用户空间配额信息
*
* @param {Object} options
* @param {function(result)} [options.success] 下载成功后callback, result为云存储文件Url
* @param {function(error, xhr)} [options.error] 下载失败后callback
*/
getQuota: function(options) {
var frontia_action = {};
frontia_action['action_name'] = 'personalStorage.getQuota';
frontia_action['timestamp'] = _getTimestamp();
var self = this;
options = options || {};
self._configure(options);
if (!self._checkParams([], 'psersonalStorage.getQuota')) return;
options.method = 'info';
var access_token = '';
var currentAccount = namespace_.getCurrentAccount();
if (currentAccount) {
accessToken = currentAccount.getAccessToken();
}
options.access_token = accessToken;
var request = _createRequest(null, options, ['success', 'error']);
var url = _generatePCSUrl('quota?', request.query);
var ajaxOpt = self._createAjaxOpt(frontia_action, {
dataType: 'json'
});
var ajax = namespace_.ajax;
ajax.get(url, {}, ajaxOpt);
}
}
/**
* personalStorage常量
*
* @name baidu.frontia.personalStorage.constant
* @property {string} ONDUP_OVERWRITE 覆盖当前同名文件
* @property {string} ONDUP_NEWCOPY 新建一份拷贝
* @property {string} BY_NAME 名字排序
* @property {string} BY_TIME 时间排序
* @property {string} BY_SIZE 大小排序
* @property {string} ORDER_ASC 升序
* @property {string} ORDER_DESC 降序
* @property {string} TYPE_STREAM_VIDEO 视频
* @property {string} TYPE_STREAM_AUDIO 音频
* @property {string} TYPE_STREAM_IMAGE 图像
* @property {string} TYPE_STREAM_DOC 文档
*/
personalStorage.constant = /** @lends baidu.frontia.personalStorage.constant */{
ONDUP_OVERWRITE: 'overwrite',
ONDUP_NEWCOPY: 'newcopy',
BY_NAME: 'name',
BY_TIME: 'time',
BY_SIZE: 'size',
ORDER_ASC: 'asc',
ORDER_DESC: 'desc',
TYPE_STREAM_VIDEO: 'video',
TYPE_STREAM_AUDIO: 'audio',
TYPE_STREAM_IMAGE: 'image',
TYPE_STREAM_DOC: 'doc'
};
function _generateAuth(ak) {
var base64_ak = namespace_.util.toBase64('Application:' + ak);
return 'Basic' + ' ' + base64_ak;
}
function _createRequest(target, options, except) {
var opt = {}, i;
var path = null;
var data = null;
options = options || {};
if (typeof target === 'string') {
path = target.slice(0, 1) === '/' ? target : '/'.concat(target);
opt.path = path;
} else if (!target) {
// do nothing
} else {
data = {list:[]};
target.forEach(function(ele) {
path = ele.slice(0, 1) === '/' ? ele : '/'.concat(ele);
data.list.push({path: path});
})
data = JSON.stringify(data);
}
for(i in options) {
if (options.hasOwnProperty(i) && except.indexOf(i) === -1) {
opt[i] = options[i];
}
}
return {query: opt, body: data};
}
function _generatePCSUrl(op, options) {
var url = [PCSUriPrefixs, op, namespace_.util.serializeURL(options)].join('');
return url;
}
function _generateMCSUrl(op, options) {
var url = [MCSUriPrefixs, op, namespace_.util.serializeURL(options)].join('');
return url;
}
function _sendPBLog(action) {
var frontiaClient = {
application_info: [{
app_frontia_version: namespace_.version,
app_appid: namespace_.getApiKey(),
user_id: namespace_.getCurrentAccount().getId() || '',
frontia_action: [{
action_name: '',
timestamp: null,
restimestamp: null,
err_code: '',
err_msg: ''
}]
}]
}
frontiaClient['application_info'][0]['frontia_action'][0] = action;
var body = {};
var deflate = new Zlib.Gzip(new Uint8Array(JSON.stringify(frontiaClient).split("").map(function(c) {
return c.charCodeAt(0); })));
var deflate_str = deflate.compress();
body['stats'] = btoa(String.fromCharCode.apply(null, deflate_str));
var ajax = namespace_.ajax;
ajax.post(PBLOGUriPrefixs, JSON.stringify(body), 'json', { contentType: 'application/json'});
}
function _getTimestamp() {
var timestamp = Math.floor(new Date().getTime() / 1000);
return timestamp;
}
namespace_.personalStorage = personalStorage;
})(baidu.frontia);
|
import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import { RoutesConfig } from "../../configs/RoutesConfigs";
import Layout from "../../layouts/layout/Layout";
import Css from "./confirmPage.module.css";
const ConfirmPage = () => {
const { push } = useHistory();
const { pendingOder, confirmedOrder } = useSelector(({ cart }) => cart);
useEffect(() => {
if (!pendingOder) {
push(RoutesConfig.main);
}
console.log(confirmedOrder);
});
return (
<Layout withoutHeader>
<div className={Css.confirmMarkContainer}>
<div className={Css.confirmMark}></div>
<span>Done</span>
<span>Please Open the console</span>
</div>
</Layout>
);
};
export default ConfirmPage;
|
'use strict';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-karma');
var ciOptions = {
singleRun: true,
browserStack: {
username: process.env.BS_USERNAME,
accessKey: process.env.BS_ACCESS_KEY,
retryLimit: 2,
},
// define browsers
customLaunchers: {
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
browser_version: '21.0',
os: 'OS X',
os_version: 'Mountain Lion',
},
bs_chrome_windows: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: '48',
os: 'Windows',
os_version: '8.1',
},
bs_ie_windows: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '10.0',
os: 'Windows',
os_version: '8',
},
bs_iphone5: {
base: 'BrowserStack',
device: 'iPhone 5',
os: 'ios',
os_version: '6.0',
},
bs_iphone6: {
base: 'BrowserStack',
device: 'iPhone 6',
os: 'ios',
os_version: '8.0',
},
// Commenting these out because they aren't working right now.
// I'm not sure if it's browserstack or us... -gnarf
//
// bs_ipad2: {
// base: 'BrowserStack',
// device: 'iPad 2 (5.0)',
// os: 'ios',
// os_version: '5.0',
// },
// bs_samsung_galaxy_s3: {
// base: 'BrowserStack',
// device: 'Samsung Galaxy S3',
// os: 'android',
// os_version: '4.1',
// },
// bs_samsung_galaxy_tab_4_10_1: {
// base: 'BrowserStack',
// device: 'Samsung Galaxy Tab 4 10.1',
// os: 'android',
// os_version: '4.4',
// },
// bs_google_nexus_5: {
// base: 'BrowserStack',
// device: 'Google Nexus 5',
// os: 'android',
// os_version: '5.0',
// },
},
};
if (process.env.BS_USERNAME) {
ciOptions.browsers = Object.keys(ciOptions.customLaunchers);
}
if (process.env.BROWSERS) {
ciOptions.browsers = process.env.BROWSERS.split(' ');
}
grunt.config.set('karma', {
dev: {
configFile: 'karma.conf.js',
},
ci: {
options: ciOptions,
configFile: 'karma.conf.js',
},
});
};
|
$(function() {
var layers= {};
var ticketurl= '/getticket';
$.ajax({
url: ticketurl
})
.then( function ( ticket ) {
//visOSMKort(ticket);
visKort(ticket);
map.fitBounds([
[57.751949, 15.193240],
[54.559132, 8.074720]
]);
var options= {text: 'Zoom til data', callback: zoomtildata};
map.contextmenu.addItem(options);
})
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('Ingen ticket: ' + jqXHR.statusCode() + ", " + textStatus + ", " + jqXHR.responseText);
});
function zoomtildata (e) {
var ls= [];
var keys= Object.keys(layers);
for (var i= 0; i<keys.length; i++) {
ls.push(layers[keys[i]].layer);
}
var layergroup= L.featureGroup(ls);
map.fitBounds(layergroup.getBounds());
}
$('#layers').dropdown();
$("#urls").on("click", "li", function(event){
var url= this.innerText.trim();
$('#url').val(url);
setStyle(layers[url].style);
})
$("#danwebside").on("click", function(event){
var parser = document.createElement('a');
parser.href = window.location.href;
var url= "https://"+parser.host+"/advvis?lag=";
var keys= Object.keys(layers);
var value= "";
for (var i= 0; i<keys.length; i++) {
var element= absoluteURL(keys[i])+"$"+JSON.stringify(layers[keys[i]].style);
if (i<keys.length-1) element= element+"@";
value= value+element;
}
url= url+encodeURIComponent(value);
window.open(url);
})
var style= defaultpointstyle;
function setStyle(style) {
$('#linjevises').prop('checked', style.stroke);
$('#linjefarve').val(style.color);
$('#linjetykkelse').val(style.weight);
$('#linjeopacitet').val(style.opacity);
$('#fyldvises').prop('checked', style.fill);
$('#fyldfarve').val(style.fillColor);
$('#fyldopacitet').val(style.fillOpacity);
$('#husnr').prop('checked', style.husnr);
$('#radius').val(style.radius);
}
function getStyle() { //skal den bruges?
var style= {};
style.stroke= $('#linjevises').is(':checked');
}
setStyle(style);
$('#linjevises').on('change', function() {
style.stroke= $('#linjevises').is(':checked');
var url= $('#url').val();
layers[url].style.stroke= style.stroke;
layers[url].layer.setStyle(layers[url].style);
});
$('#linjefarve').on('change', function() {
style.color= this.value;
var url= $('#url').val();
layers[url].style.color= this.value;
layers[url].layer.setStyle(layers[url].style);
});
$('#linjetykkelse').on('change', function() {
style.weight= this.value;
var url= $('#url').val();
layers[url].style.weight= this.value;
layers[url].layer.setStyle(layers[url].style);
});
$('#linjeopacitet').on('change', function() {
style.opacity= this.value;
var url= $('#url').val();
layers[url].style.opacity= this.value;
layers[url].layer.setStyle(layers[url].style);
});
$('#fyldvises').on('change', function() {
style.fill= $('#fyldvises').is(':checked');
var url= $('#url').val();
layers[url].style.fill= style.fill;
layers[url].layer.setStyle(layers[url].style);
});
$('#fyldfarve').on('change', function() {
style.fillColor= this.value;
var url= $('#url').val();
layers[url].style.fillColor= this.value;
layers[url].layer.setStyle(layers[url].style);
});
$('#fyldopacitet').on('change', function() {
style.fillOpacity= this.value;
var url= $('#url').val();
layers[url].style.fillOpacity= this.value;
layers[url].layer.setStyle(layers[url].style);
});
$('#husnr').on('change', function() {
style.husnr= $('#husnr').is(':checked');
var url= $('#url').val();
layers[url].style.husnr= style.husnr;
gentegn(layers[url]);
});
$('#radius').on('change', function() {
style.radius= this.value;
var url= $('#url').val();
layers[url].style.radius= this.value;
gentegn(layers[url]);
});
$('#tilføj').on("click", tilføj);
$('#fjern').on("click", fjern);
function absoluteURL(url) {
return url.substr(0,7).toLowerCase().indexOf('http',0)===0?url:"https://dawa.aws.dk/" + url;
}
function tilføj(event) {
event.preventDefault();
var url= $('#url').val().trim();
if (layers[url]) return;
var options= {};
options.data= {format: 'geojson'};
options.url= encodeURI(absoluteURL(url));
if (corssupported()) {
options.dataType= "json";
options.jsonp= false;
}
else {
options.dataType= "jsonp";
}
$.ajax(options)
.then( function ( data ) {
for (var i= data.features.length-1; i>=0; i--) {
if (data.features[i].geometry && (data.features[i].geometry.coordinates[0] == 0 || data.features[i].geometry.coordinates[1] == 0)) {
data.features.splice(i, 1)
}
}
if (data.geometri || data.features && data.features.length === 0) {
alert('Søgning gav intet resultat');
return;
}
style= getDefaultStyle(getFeature(data));
var geojsonlayer= L.geoJson(data, {style: getDefaultStyle, onEachFeature: eachFeature, pointToLayer: pointToLayer(style)});
if (!layers[url]) {
var info= $("#urls");
info.append("<li><a href='#'>"+url+"</a></li>");
};
layers[url]= {layer: geojsonlayer, style: jQuery.extend({}, style), data: data};;
setStyle(style);
geojsonlayer.addTo(map);
map.fitBounds(geojsonlayer.getBounds())
})
.fail(function( jqXHR, textStatus, errorThrown ) {
alert(errorThrown)
});
};
function getFeature(data) {
if (data.type === 'Feature') {
return data;
}
else if (data.type === 'FeatureCollection') {
return data.features[0];
}
return data;
}
function fjern(event) {
event.preventDefault();
var url= $('#url').val();
map.removeLayer(layers[url].layer);
var urls= $('#urls li:contains("' + url + '")');
urls.remove();
delete layers[url];
};
function gentegn(layer) {
map.removeLayer(layer.layer);
var geojsonlayer= L.geoJson(layer.data, {style: style, onEachFeature: eachFeature, pointToLayer: pointToLayer(style)});
layer.layer= geojsonlayer;
geojsonlayer.addTo(map);
map.fitBounds(geojsonlayer.getBounds())
}
});
|
import {
loadItem,
storeItem,
loadDate,
storeDate,
} from "../utils/dom-utils.js";
const onTestNewsletterPage = !!window.location.href.match(/debug=newsletter/);
const LAST_VISIT_KEY = "last-visit";
const SAW_NEWSLETTER_MODAL_KEY = "saw-newsletter-modal";
const FROM_MC_KEY = "originated-from-mailchimp";
const SAW_DONATE_MODAL_KEY = "saw-donate-modal-totebag";
const SIGNED_UP_FOR_NEWSLETTER_KEY = "signed-up-for-newsletter";
const PRIOR_FUNNEL_STATUS_KEY = "funnel-status";
const SAW_TAKEOVER_MODAL_KEY = "saw-takeover-modal";
const SHOW_INTERVAL = 7 * 24 * 60 * 60 * 1000; // 1 week
const TAKEOVER_INTERVAL = 10 * 60 * 1000; // 10 minutes
let now = new Date();
export const statusNewUser = 0,
statusReturner = 1,
statusSubscriber = 2,
statusMember = 3;
export let funnelStatus = loadItem(PRIOR_FUNNEL_STATUS_KEY) || statusNewUser;
let lastVist = loadDate(LAST_VISIT_KEY);
let lastSession = loadDate(LAST_VISIT_KEY, { useSession: true });
// It's a "new" session if there is a last visit but the session is new
// and it's been more than an hour since the last visit
// (not just opening articles new tabs)
let newSession = lastVist && !lastSession && now - lastVist > 1000 * 60 * 60;
storeDate(LAST_VISIT_KEY, now);
storeDate(LAST_VISIT_KEY, now, { useSession: true });
// TODO: Figure out who is a donor now that donation is offsite
// If we're on the donate page now, don't show donate screen later
if (window.location.pathname.match(/donate/)) {
storeDate(SAW_DONATE_MODAL_KEY, now);
funnelStatus = statusMember;
}
if (newSession) {
funnelStatus = Math.max(funnelStatus, statusReturner);
}
if (
window.location.href.match(/utm_source=email/) ||
document.referrer.match(/campaign-archive/)
) {
storeDate(FROM_MC_KEY, now);
}
// And didn't previously sign up
if (loadDate(SIGNED_UP_FOR_NEWSLETTER_KEY)) {
funnelStatus = Math.max(funnelStatus, statusSubscriber);
}
storeItem(PRIOR_FUNNEL_STATUS_KEY, funnelStatus);
let shouldShowModalNewsletter = (() => {
// Does this page even have a newsletter to pop up?
if (!document.querySelector("[data-modal-kind=newsletter]")) {
return false;
}
if (onTestNewsletterPage) {
return true;
}
// show new users the modal if they haven't seen it recently
if (funnelStatus >= statusSubscriber) {
return false;
}
let cameFromMCOn = loadDate(FROM_MC_KEY) || 0;
let sawNLModalOn = loadDate(SAW_NEWSLETTER_MODAL_KEY) || 0;
if (!cameFromMCOn && !sawNLModalOn) {
return true;
}
let lastPrompt = Math.max(cameFromMCOn, sawNLModalOn);
return now - lastPrompt > SHOW_INTERVAL;
})();
let shouldShowModalTakeover = (() => {
// Does this page even have a takeover to pop up?
if (!document.querySelector("[data-modal-kind=takeover]")) {
return false;
}
if (onTestNewsletterPage) {
return true;
}
let sawTakeoverModalOn = loadDate(SAW_TAKEOVER_MODAL_KEY) || 0;
return now - sawTakeoverModalOn > TAKEOVER_INTERVAL;
})();
export let modalKind = (() => {
if (window.matchMedia("(prefers-reduced-motion), (speech)").matches) {
// eslint-disable-next-line no-console
console.warn("prefers-reduced-motion; aborting modal display");
return "none";
}
if (shouldShowModalTakeover) {
return "takeover";
}
if (shouldShowModalNewsletter) {
return "newsletter";
}
return "sticky";
})();
export function recordModalNewsletterView() {
storeDate(SAW_NEWSLETTER_MODAL_KEY, now);
}
export function recordNewsletterSignup() {
storeDate(SIGNED_UP_FOR_NEWSLETTER_KEY, now);
}
export function recordModalTakeoverView() {
storeDate(SAW_TAKEOVER_MODAL_KEY, now);
}
|
CKEDITOR.replace('text-editor');
CKEDITOR.replace('text-editor-2');
/* Begin when loading page first tab opened */
$(function(){
$('.nav-tabs li:first').addClass('active');
$('.tab-content div:first').addClass('active');
});
function removePhone(phone) {
$('.controls' + phone).remove();
}
/* Begin Tabs NEXT & PREV buttons */
$('.btnNext').click(function(){
$('.nav-tabs > .active').next('li').find('a').trigger('click');
});
$('.btnPrevious').click(function(){
$('.nav-tabs > .active').prev('li').find('a').trigger('click');
});
var csrfToken = $('meta[name="csrf-token"]').attr('content');
var c1 = true;
$('.onevalid1').click(function() {
if($('#test').val()==1)
{
return false;
}
if($('#test1').val()==1)
{
return false;
}
if($('#vendor-vendor_name').val()=='')
{
$('.field-vendor-vendor_name').addClass('has-error');
$('.field-vendor-vendor_name').find('.help-block').html('Vendor name cannot be blank.');
c1=false;
}
if($('#vendor-vendor_contact_email').val()=='')
{
$('.field-vendor-vendor_contact_email').addClass('has-error');
$('.field-vendor-vendor_contact_email').find('.help-block').html('Email cannot be blank.');
c1=false;
}
// check only if its new record
if($('#vendor-vendor_password').val()=='')
{
$('.field-vendor-vendor_password').addClass('has-error');
$('.field-vendor-vendor_password').find('.help-block').html('Password cannot be blank');
c1=false;
}
if($('#vendor-vendor_contact_name').val()=='')
{
$('.field-vendor-vendor_contact_name').addClass('has-error');
$('.field-vendor-vendor_contact_name').find('.help-block').html('Contact name cannot be blank.');
c1=false;
}
if($('#vendor-vendor_contact_number').val()=='')
{
$('.field-vendor-vendor_contact_number').addClass('has-error');
$('.field-vendor-vendor_contact_number').find('.help-block').html('Contact number cannot be blank.');
c1=false;
}
if($('#vendor-vendor_contact_address').val()=='')
{
$('.field-vendor-vendor_contact_address').addClass('has-error');
$('.field-vendor-vendor_contact_address').find('.help-block').html('Contact address cannot be blank.');
c1=false;
} else {
$('.field-vendor-vendor_contact_address').removeClass('has-error');
$('.field-vendor-vendor_contact_address').addClass('has-success');
c1=true;
}
if(c1==false)
{
c1='';
return false;
}
var item_len = $('#vendor-vendor_name').val().length;
if($('#vendor-vendor_name').val()=='') {
$('.field-vendor-vendor_name').addClass('has-error');
$('.field-vendor-vendor_name').find('.help-block').html('Item name cannot be blank.');
c1=false;
} else if(item_len < 3){
$('.field-vendor-vendor_name').addClass('has-error');
$('.field-vendor-vendor_name').find('.help-block').html('Item name minimum 4 letters.');
c1=false;
}
return c1;
});
$('.twovalid2').click(function() {
if($('#vendor-vendor_name').val()=='')
{
$('.field-vendor-vendor_name').addClass('has-error');
$('.field-vendor-vendor_name').find('.help-block').html('Vendor name cannot be blank.');
return false;
}
if($('#vendor-vendor_contact_email').val()=='')
{
$('.field-vendor-vendor_contact_email').addClass('has-error');
$('.field-vendor-vendor_contact_email').find('.help-block').html('Email cannot be blank.');
return false;
}
if($('#vendor-vendor_contact_name').val()=='')
{
$('.field-vendor-vendor_contact_name').addClass('has-error');
$('.field-vendor-vendor_contact_name').find('.help-block').html('Contact name cannot be blank.');
return false;
}
if($('#vendor-vendor_contact_number').val()=='')
{
$('.field-vendor-vendor_contact_number').addClass('has-error');
$('.field-vendor-vendor_contact_number').find('.help-block').html('Contact number cannot be blank.');
return false;
}
if($('#vendor-vendor_contact_address').val()=='')
{
$('.field-vendor-vendor_contact_address').addClass('has-error');
$('.field-vendor-vendor_contact_address').find('.help-block').html('Contact address cannot be blank.');
return false;
} else {
return true;
}
});//twovalid2 click
var j= ".($count_vendor + 1).";
function addPhone(current)
{
$('#addnumber').before('<div class="controls'+j+'"><input type="text" id="vendor-vendor_contact_number'+j+'" class="form-control" name="Vendor[vendor_contact_number][]" multiple = "multiple" maxlength="15" Placeholder="Phone Number" style="margin:5px 0px;"><input type="button" name="remove" id="remove" value="Remove" onClick="removePhone('+j+')" style="margin:5px;" /></div>');
j++;
$("#vendor-vendor_contact_number2").keypress(function (e) {
if (e.which != 43 && e.which != 45 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57 )) {
$(".field-vendor-vendor_contact_number").find('.help-block').html('Contact number digits only+.').animate({ color: "#a94442" }).show().fadeOut(2000);
return false;
}
});
$("#vendor-vendor_contact_number3").keypress(function (e) {
if ( e.which != 43 && e.which != 45 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$(".field-vendor-vendor_contact_number").find('.help-block').html('Contact number digits only.').animate({ color: "#a94442" }).show().fadeOut(2000);
return false;
}
});
$("#vendor-vendor_contact_number4").keypress(function (e) {
if (e.which != 43 && e.which != 45 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$(".field-vendor-vendor_contact_number").find('.help-block').html('Contact number digits only.').animate({ color: "#a94442" }).show().fadeOut(2000);
return false;
}
});
$("#vendor-vendor_contact_number5").keypress(function (e) {
if (e.which != 43 && e.which != 45 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$(".field-vendor-vendor_contact_number").find('.help-block').html('Contact number digits only.').animate({ color: "#a94442" }).show().fadeOut(2000);
return false;
}
});
}
|
import React from 'react'
import { Title, Surface } from 'react-native-paper'
import { observer } from 'mobx-react'
//stores
import profileStore from '../../stores/profileStore'
//components
import BackButton from '../../components/BackButton'
//styles
import { ProfileImage, ProfileBio, ProfileTrips } from './styles'
import { Spinner } from 'native-base'
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native'
import tripStore from '../../stores/tripStore'
import MiniTripItem from '../../components/trip/MiniTripItem'
const ProfileScreen = ({ route, navigation }) => {
const { userId } = route.params;
console.log("user id", userId);
if (!profileStore.profile) {
return <Spinner />;
}
const profile = profileStore.profile
const totalTrips = tripStore.trips.filter((trip) => trip.userId === userId)
console.log(
"🚀 ~ file: ProfileScreen.js ~ line 34 ~ ProfileScreen ~ totalTrips",
totalTrips
);
const tripsList = tripStore.trips
.filter((trip) => trip.userId === userId)
.map((trip) => (
<MiniTripItem trip={trip} key={trip.id} navigation={navigation} />
));
return (
<SafeAreaView>
<Surface style={styles.surface}>
<BackButton goBack={navigation.goBack} />
<Title>Profile</Title>
{authStore.user?.profileId === profile.id && (
<Title
onPress={() =>
navigation.navigate("EditProfileScreen", { profile: profile })
}
>
Edit
</Title>
)}
<ProfileImage
source={{ uri: profile.image }}
style={{ borderRadius: '100%' }}
/>
<ProfileBio>{profile.bio}</ProfileBio>
<ProfileTrips>{totalTrips.length} trips </ProfileTrips>
<ScrollView horizontal={true}>{tripsList}</ScrollView>
</Surface>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
surface: {
padding: 70,
},
})
export default observer(ProfileScreen)
|
import React from 'react'
import Status from './Status'
import Item from './Item'
const Support = ({ status, supportSystem = {}, animate, decorated }) => (
<Status status={status} animate={animate} decorated={decorated}>
<Item active={supportSystem.o === 1}>
{__i18n('COM.MANAGERS.OWNER')}
</Item>
<Item active={supportSystem.a === 1}>
{__i18n('COM.MANAGERS.ADMIN')}
</Item>
<Item active={supportSystem.s === 1}>
{__i18n('COM.MANAGERS.SUPPORT')}
</Item>
</Status>
)
export default Support
|
import React from "react";
import Nav from "react-bootstrap/Nav";
// import assets
import google_cloud from "../../../assets/images/Google_cloud.png";
import twilio from "../../../assets/images/twilio.png";
import algolia from "../../../assets/images/Algolia.png";
import talend from "../../../assets/images/Talend.png";
import spluck from "../../../assets/images/Spluck.png";
import aws from "../../../assets/images/AWS.png";
const TechStack = () => {
return (
<div className="container">
<div className="tech-stack-heading">
<h2>Tech Stacks</h2>
</div>
<div className="tech-tabs">
<Nav className="tabs">
<Nav.Link href="#home" className="navbar-tab-links">
Backend
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
Frontend
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
Databases
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
CMS
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
Cloud
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
Testing
</Nav.Link>
<Nav.Link href="#link" className="navbar-tab-links">
DevOps
</Nav.Link>
</Nav>
</div>
<div className="tech-stack-images">
<div className="row">
<div className="col-md-2">
<div className="tech-stack-icon">
<img
src={google_cloud}
className="img-fluid"
alt="google_cloud"
width="35"
/>
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={twilio} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={algolia} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={talend} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={spluck} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img
src={aws}
className="img-fluid"
alt="google_cloud"
width="35"
/>
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img
src={google_cloud}
className="img-fluid"
alt="google_cloud"
width="35"
/>
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={twilio} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={algolia} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={talend} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img src={spluck} className="img-fluid" alt="google_cloud" />
</div>
</div>
<div className="col-md-2">
<div className="tech-stack-icon">
<img
src={aws}
className="img-fluid"
alt="google_cloud"
width="35"
/>
</div>
</div>
</div>
</div>
</div>
);
};
export default TechStack;
|
var btn = document.getElementById("btn");
btn.addEventListener("click" , function(){
console.log("Hello People");
alert( "Im a box!")
});
|
$(window).resize(function(){
//Media queries on resize
if ($(window).innerWidth() >= 1200){
$('.tableheader4 h1').css("margin-left", "80px");
if ($(window).innerWidth() >= 1200 && $(window).innerWidth() < 1300){
marginleft = '110';
marginleft6 = '60';
}
else if ($(window).innerWidth() >= 1300 && $(window).innerWidth() < 1400){
marginleft = '90';
marginleft6 = '50';
}
else if ($(window).innerWidth() >= 1400 && $(window).innerWidth() < 1500){
marginleft = '80';
marginleft6 = '40';
}
else if ($(window).innerWidth() >= 1500 && $(window).innerWidth() < 1600){
marginleft = '60';
marginleft6 = '30';
}
else if ($(window).innerWidth() >= 1600 && $(window).innerWidth() < 1700){
marginleft = '45';
marginleft6 = '20';
}
else if ($(window).innerWidth() >= 1700 && $(window).innerWidth() < 1800){
marginleft = '30';
marginleft6 = '10';
}
else if ($(window).innerWidth() >= 1800){
marginleft = '0';
marginleft6 = '0';
}
var appendedstring = '<th class="tableheader3" style="width: 17.7%;"><p style="padding-left: 0; margin: 16px 0 0 ' + marginleft + 'px; color: rgb(41,144,216);"><strong class="item"><span>Players Alive: </span></strong><em>{{ct_alive_count}}/{{ct_player_count}}</em></p></th>';
var appendedstring2 = '<th class="tableheader6" style="width: 23.8%;"><p style="padding-left: 0; margin: 16px 0 0 ' + marginleft6 + 'px; color: rgb(216,144,41);"><strong class="item"><span> Players Alive: </span></strong><em>{{t_alive_count}}/{{t_player_count}}</em></p></th>'
$('.scoreboard-header').empty();
$('.scoreboard-header').append('<th class="tableheader1" style="width: 14%;"></th>');
$('.scoreboard-header').append('<th class="tableheader2" style="width: 16%; padding-right: 4px;"><h1 style="margin: 0"> <span id="ct-title" class="ct-wins">{{scoreboard.teams.3}}</span></h1></th>');
$('.scoreboard-header').append(appendedstring);
$('.scoreboard-header').append('<th class="tableheader4" style="width: 20%;"><h1 style="margin: 0 0 0 80px;"> <span id="ct-round-wins" class="ct-wins">{{ct_round_wins}}</span> : <span id="t-round-wins" class="t-wins">{{t_round_wins}}</span></h1></th>');
$('.scoreboard-header').append('<th class="tableheader5" style="width: 8.5%; padding-right: 4px;"><h1 style="margin: 0"> <span id="t-title" class="t-wins">{{scoreboard.teams.2}}</span></h1></th>');
$('.scoreboard-header').append(appendedstring2);
if ($(window).innerWidth() >= 1800){
$('.tableheader3 p').css("margin-left", "0");
$('.tableheader6 p').css("margin-left", "0");
}
}
if($(window).innerWidth() >= 1500){
$('.tableheader4 h1').css("margin-left", "0");
}
if ($(window).innerWidth() > 1280) {
if($('.left-head-ct').length == 0){
$('.ct-head-row').prepend('<th class="left-head-ct"></th>');
$('.ct-player').prepend('<td class="left-col-ct"></td>');
$('.t-head-row').prepend('<th class="left-head-t"></th>');
$('.t-player').prepend('<td class="left-col-t"></td>');
}
}
if ($(window).innerWidth() <= 1280) {
$('.left-head-ct').remove();
$('.left-col-ct').remove();
$('.left-head-t').remove();
$('.left-col-t').remove();
}
if ($(window).innerWidth() <= 1199) {
if($('.tableheader1').length != 0)
{
$('.tableheader1').remove();
$('.tableheader2').css("width", "50%");
$('.tableheader2').css("padding-top", "12px");
$('.tableheader2').css("padding-right", "35px");
$('.tableheader2').append("<p style='margin:0; color: rgb(41,144,216);'><strong class='item'><span>Players Alive: </span></strong><em>{{ct_alive_count}}/{{ct_player_count}}</em></p>");
$('.tableheader3').remove();
$('.tableheader4').css("width", "25%");
$('.tableheader4 h1').css("margin-left", "0");
$('.tableheader4').css("padding-bottom", "18px");
$('.tableheader5').css("width", "25%");
$('.tableheader5').css("padding-top", "12px");
$('.tableheader5').css("padding-left", "0");
$('.tableheader5').append('<p style="margin: 0; color: rgb(216,144,41);"><strong class="item"><span> Players Alive: </span></strong><em>{{t_alive_count}}/{{t_player_count}}</em></p>');
$('.tableheader6').remove();
}
}
if ($(window).innerWidth() <= 680) {
$('.tableheader2').css("width", "50%");
$('.tableheader4').css("width", "22%");
$('.tableheader4 h1').css("margin-left", "0");
$('.tableheader5').css("width", "28%");
$('.ct-name-head').css("padding-left", "4%");
$('.t-name-head').css("padding-left", "4%");
$('.ct-name').css("padding-left", "4%");
$('.t-name').css("padding-left", "4%");
}
});
|
var ghpages = require('gh-pages');
var path = require('path');
ghpages.publish('_book', function(err) {
throw err;
});
|
class CountdownTimer {
constructor({ selector, targetDate }) {
this.intervalId = null;
this.selector = selector;
this.targetDate = targetDate;
this.init();
}
init() {
let prevTime = this.getTimeComponents(this.targetDate - new Date());
this.creatEl(prevTime);
this.intervalId = setInterval(() => {
const currentTime = new Date();
const deltaTime = this.targetDate - currentTime;
const time = this.getTimeComponents(deltaTime);
for (const key in time) {
const valueEl = document.querySelector(`[data-value="${key}"]`);
const valueOldEl = document.querySelector(`[data-value="${key}Old"]`);
const newValue = time[key];
const currentValue = prevTime[key];
const parent = valueEl.parentNode;
if (newValue !== currentValue) {
parent.classList.remove('anim');
valueEl.textContent = newValue;
valueOldEl.textContent = currentValue;
const foo = parent.offsetWidth; // reflow hack
parent.classList.add('anim');
}
}
prevTime = { ...time };
if (deltaTime < 1000) {
clearInterval(this.intervalId);
}
}, 1000);
}
getTimeComponents(time) {
const days = Math.floor(time / (1000 * 60 * 60 * 24));
const hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((time % (1000 * 60)) / 1000);
return { days, hours, minutes, seconds };
}
pad(value) {
return String(value).padStart(2, '0');
}
creatEl(time = {}) {
const timer1 = document.querySelector(this.selector);
const timeEl = [];
for (const key in time) {
timeEl.push(`<div class="field">
<div class="values">
<span class="value" data-value="${key}">${time[key]}</span>
<span class="valueOld" data-value="${key}Old">${time[key]}</span>
</div>
<span class="label">${key[0].toUpperCase() + key.slice(1)}</span>
</div>`);
timer1.innerHTML = timeEl.join('');
}
}
}
const timer = new CountdownTimer({
selector: '#timer-1',
targetDate: new Date('Apr 21, 2022'),
});
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { Component } from "react";
import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import {
ACTIVE,
ADD_ITEM,
NO_PRODUCTS_TO_SHOW_MESSAGE,
SOLD_ITEMS,
} from "../../constants/messages";
import { ADD_ITEM_ROUTE, SINGLE_PRODUCT_ROUTE } from "../../constants/routes";
import CustomerService from "../../services/customerService";
import ProductService from "../../services/productService";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import styles from "./Seller.css";
import AddItem from "../addItem/AddItem";
export class Seller extends Component {
state = { products: null, activeChosen: true };
productService = new ProductService();
componentDidMount = async () => {
const { token, userEmail, isLoggedIn } = this.props;
var productList = null;
if (this.state.activeChosen) {
productList = await this.productService.getActiveProducts(
userEmail,
token
);
} else {
productList = await this.productService.getSoldProducts(userEmail, token);
}
this.setState({ products: productList });
};
chooseActive = async () => {
const { token, userEmail } = this.props;
var productList = await this.productService.getActiveProducts(
userEmail,
token
);
this.setState({ products: productList, activeChosen: true });
};
chooseSold = async () => {
const { token, userEmail } = this.props;
var productList = await this.productService.getSoldProducts(
userEmail,
token
);
this.setState({ products: productList, activeChosen: false });
};
render() {
const { activeChosen, products } = this.state;
const { userEmail, token, isLoggedIn } = this.props;
return (
<div>
<div className="sellerOptionsDiv">
<div className="activeSoldOptionsDiv">
<div
className={
activeChosen ? "activeSoldOptionActive" : "activeSoldOption"
}
onClick={this.chooseActive}
>
{ACTIVE}
</div>
<div
className={
activeChosen ? "activeSoldOption" : "activeSoldOptionActive"
}
onClick={this.chooseSold}
>
{SOLD_ITEMS}
</div>
</div>
<Link
className="addItemOptionLink"
to={{
pathname: ADD_ITEM_ROUTE,
state: {
isLoggedIn: isLoggedIn,
email: userEmail,
token: token,
},
}}
>
<div className="addItemOptionDiv">
<FontAwesomeIcon
className="tabDivIcon"
icon={faPlus}
size={"sm"}
></FontAwesomeIcon>{" "}
{ADD_ITEM}
</div>
</Link>
</div>
{products !== null && products.length > 0 && (
<div className="activeSoldProductsDiv">
<Table responsive className="activeSoldTable">
<thead>
<tr className="headingTr">
<td>Item</td>
<td>Name</td>
{activeChosen && <td>Time left</td>}
<td align="center">Start price</td>
<td align="center">No. bids</td>
<td align="center">Highest bid</td>
<td align="center"></td>
</tr>
</thead>
<tbody>
{products.map(function (product, index) {
return (
<tr className="no-border" key={index}>
<td>
<img
className="activeSoldProductImages"
src={`data:image/png;base64, ${product.image}`}
></img>
</td>
<td>
<Link
className="activeSoldProductName"
to={{
pathname: SINGLE_PRODUCT_ROUTE.replace(
":prodId",
product.id
),
state: {
chosenProduct: product.id,
isLoggedIn: isLoggedIn,
email: userEmail,
token: token,
},
}}
>
{product.name}
</Link>
</td>
{activeChosen && <td>{product.timeLeft} days</td>}
<td align="center">$ {product.startPrice}</td>
<td align="center">{product.numberOfBids}</td>
<td
align="center"
className={
product.bidHighest ? "highestBidTd" : "bidTd"
}
>
$ {product.highestBid}
</td>
<td align="center">
<Link
className="activeSoldProductName"
to={{
pathname: SINGLE_PRODUCT_ROUTE.replace(
":prodId",
product.id
),
state: {
chosenProduct: product.id,
isLoggedIn: isLoggedIn,
email: userEmail,
token: token,
},
}}
>
<button className="activeSoldViewButton">VIEW</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</Table>
</div>
)}
{(products == null || products.length <= 0) && (
<div className="activeSoldNoProductsMessage">
{NO_PRODUCTS_TO_SHOW_MESSAGE}
</div>
)}
</div>
);
}
}
export default Seller;
|
import { _MiddlewareActions, differBoth } from '../actions/index';
const common = store => {
return next => {
return action => {
const { type, payload } =action;
const isCatchedMiddleware = _MiddlewareActions[type];
if (isCatchedMiddleware){
try {
const middlewareAc = require(`@store/middleware/middlewareActions/${isCatchedMiddleware['path']}`);
const newState = differBoth(isCatchedMiddleware.payload, payload);
if ( typeof middlewareAc === 'function' ) {
return middlewareAc({ payload:newState, next, ...store });
}
} catch (error) {
return Promise.reject(error);
}
}
return next(action);
};
};
};
export default common;
|
var geekHubControllers = angular.module('geekHubControllers', []);
geekHubControllers.controller('GoodsListCtrl', ['$scope', 'Goods',
function($scope, Goods) {
$scope.data = Goods.query();
$scope.brands = ["GoPro", "DOD", "Aspiring", "Globex", "Falcon"];
$scope.filter = { brand: [] }
// Goods.save({"title":"GoPro HERO3+ Black Edition","price":6000,"brand":"GoPro","resolution":12})
}]);
|
export { default as CarBookingModalWindow } from './CarBookingModalWindow.vue';
|
import axios from 'axios';
import {url} from '../../urlConfig';
const token = localStorage.getItem('token');
const axiosInstance = axios.create({
baseURL:url,
headers:{
'Authorization': token ? `Bearer ${token}` : ''
}
});
export default axiosInstance;
|
console.log('1212312');
module.exports = {
a: 1
};
|
'use strict';
module.exports = {
client: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
'public/lib/fullcalendar/dist/fullcalendar.min.css',
'public/lib/angular-motion/dist/angular-motion.min.css',
'public/lib/jquery-timepicker-jt/jquery.timepicker.css',
'public/lib/angular-material/angular-material.min.css',
'public/lib/font-awesome/css/font-awesome.min.css',
'public/lib/angular-input-stars-directive/angular-input-stars.css',
'public/lib/angularMultipleSelect/build/multiple-select.min.css'
],
js: [
'public/lib/jquery/dist/jquery.min.js',
'public/lib/jquery-ui/jquery-ui.js',
'public/lib/angular/angular.js',
'public/lib/angular-route/angular-route.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/angular-file-upload/dist/angular-file-upload.js',
'public/lib/angular-ui-calendar/src/calendar.js',
'public/lib/moment/moment.js',
'public/lib/angular-moment/angular-moment.js',
'public/lib/fullcalendar/dist/fullcalendar.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-filter/dist/angular-filter.min.js',
'public/lib/angular-multi-select-alexandernst/dist/angular-multi-select.js',
'public/lib/jquery-timepicker-jt/jquery.timepicker.min.js',
'public/lib/angular-jquery-timepicker/src/timepickerdirective.js',
'public/lib/angular-aria/angular-aria.js',
'public/lib/angular-material/angular-material.js',
'public/lib/angular-input-stars-directive/angular-input-stars.js',
'public/lib/angularMultipleSelect/build/multiple-select.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
}
};
|
$(document).ready(function () {
var $trBase = $('#trBase');
var $tabla = $('table');
var modoEditar = false;
var contadorId;
var idAux;
var URL_JSON = "http://localhost:3000/alumnos/";
$.getJSON(URL_JSON, function (alumnos) { // obtengo los alumnos del JSON
for (var i = 0; i < alumnos.length; i++) { // recorro la lista de alumnos
agregarAlumnoATabla(alumnos[i]); // voy agregandolos uno a uno a la tabla, configurándo todo lo necesario
if (i == alumnos.length - 1) // obtengo el id del último alumno y lo almaceno en una variable para cuando vaya a agregar usar el contador como id del nuevo alumno.
contadorId = parseInt(alumnos[i].id) + 1;
}
});
function agregarAlumnoATabla(alumno) {
var $nuevaFila = $trBase.clone(); // clono la fila base creada en el html
$nuevaFila = cargarAlumnoEnFila($nuevaFila, alumno); // cargo los datos del alumno en la fila que le paso como argumento a la función, en este caso, la fila clonada.
$nuevaFila.children('td').get(7).innerHTML = '<img class="btnEditar" src="imagenes/editar.png" alt="editar" data-alumno="' + alumno.id + '" data-toggle="modal" data-target="#myModal"/>';
$nuevaFila.children('td').get(8).innerHTML = '<img class="btnBorrar" src="imagenes/borrar.png" alt="borrar" data-alumno="' + alumno.id + '"/>';
$tabla.append($nuevaFila); // agrego la fila clonada a la tabla.
$nuevaFila.show(800); // la muestro.
}
function cargarAlumnoEnFila(fila, alumno) {
var repetidor = "No";
if (alumno.repetidor)
repetidor = "Sí";
fila.children('td').get(0).innerHTML = '<img alt="foto" src="' + alumno.foto + '"/>'; // obtengo la primera columna de la fila clonada e introduzco la foto del alumno
fila.children('td').get(1).textContent = alumno.nombre; // obtengo la segunda columna de la fila clonada e introduzco el nombre del alumno
fila.children('td').get(2).textContent = alumno.telefono; // ... e introduzco el teléfono ...
fila.children('td').get(3).textContent = alumno.direccion; // ... e introduzco la dirección ...
fila.children('td').get(4).textContent = alumno.edad; // ... e introduzco el edad ...
fila.children('td').get(5).textContent = alumno.curso; // ... e introduzco el curso ...
fila.children('td').get(6).textContent = repetidor; // ... e introduzco su condición (repetidor o no) ...
return fila;
}
// Configuro el evento "click" de los botones "btnBorrar" para que eliminen el alumno que llevan asociado del fichero JSON y elimine la fila de la tabla.
$(document).on('click', '.btnBorrar', function () {
eliminarAlumnoDeJSON($(this).data("alumno"));
$(this).closest('tr').remove();
});
// Elimina el alumno del fichero JSON. Si la operación se realizó con éxito muestra un Toast.
function eliminarAlumnoDeJSON(idAlumno) {
$.ajax({
url: URL_JSON + idAlumno,
type: "DELETE",
success: function (response) {
configAndShowToast(0);
}
});
}
// Cuando se haga click en el botón de editar, establezco a true el la variable modoEditar y cargo los datos del alumno en la ventana modal.
$(document).on('click', '.btnEditar', function () {
modoEditar = true;
cargarAlumnoEnModal($(this).data("alumno")); // paso el id del alumno que tiene asociado el botón como argumento.
});
// Obtengo los datos del alumno del fichero JSON. Hago una petición al servidor para que me devuelva los datos del alumno que indica "idAlumno" y relleno los campos del formulario de la ventada modal con sus datos.
function cargarAlumnoEnModal(idAlumno) {
resetCamposForm();
$.getJSON(URL_JSON + idAlumno, function (alumno) {
idAux = alumno.id; // almaceno el id del alumno que se pretende modificar en una variable global auxiliar, por si se realizan cambios, poder mantener el id del alumno.
$('#txtFoto').val(alumno.foto);
$('#txtNombre').val(alumno.nombre);
$('#txtCur').val(alumno.curso);
$('#txtTel').val(alumno.telefono);
$('#txtDir').val(alumno.direccion);
$('#txtEdad').val(alumno.edad);
if (alumno.repetidor)
$('#cbRep').prop("checked", true);
else
$('#cbRep').prop("checked", false);
});
}
// Configuro el botón de aceptar que aparece en la ventana modal de tal modo que:
$('#btnModal').click(function () {
if (camposRellenosCorrectamente()) {
if (!modoEditar) // si el modoEditar no está activado, significa que el modal fue lanzado desde el botón "agregarAlumno" y por tanto
agregarNuevoAlumno(); // agrego un nuevo alumno
else // en caso contrario, el modal fue lanzado desde el boton "btnEditar" y por tanto
modificarAlumno(); // modifico los datos de ese alumno
modoEditar = false; // establezco el valor del atributo modoEditar a false.
} else {
configAndShowToast(-1);
}
});
function agregarNuevoAlumno() {
var alumno = obtenerDatosForm(); // obtengo los datos del alumno del formulario de la ventana modal e introduzco el nuevo alumno en el fichero JSON.
$.post(
URL_JSON,
alumno,
function (respuesta) {
configAndShowToast(1);
}
);
contadorId++; // incremento el contador de ID
agregarAlumnoATabla(alumno); // agrego el alumno a la tabla
}
function modificarAlumno() {
var alumno = obtenerDatosForm(); // obtengo los datos del alumno del formulario y me creo el objeto alumno. Después, sobreescribo el alumno.
$.ajax({
url: URL_JSON + idAux,
type: 'PUT',
data: alumno,
success: function (data) {
configAndShowToast(2); // muestro un Toast.
}
});
cargarAlumnoEnFila($('[data-alumno="' + idAux + '"]').closest('tr'), alumno); // vuelvo a cargar los datos del alumno en su correspondiente fila.
}
function obtenerDatosForm() {
var aux;
var alumno;
if (modoEditar) // Si estoy en modo editar
aux = idAux; // el id del alumno será el almacenado en el auxiliar
else // en caso contrario
aux = contadorId; // el id del alumno será el que indique el contador
alumno = { // creo un nuevo objeto alumno con los valores del formulario
id: aux,
foto: $('#txtFoto').val(),
nombre: $('#txtNombre').val(),
curso: $('#txtCur').val(),
telefono: $('#txtTel').val(),
direccion: $('#txtDir').val(),
edad: $('#txtEdad').val(),
repetidor: $('#cbRep').prop("checked")
}
return alumno;
}
function configAndShowToast(num) { // Configuro las opciones del Toast.
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
if (num == 0)
toastr.success("El alumno ha sido eliminado.", "Operación realizada con éxito.");
else if (num == 1)
toastr.success("El nuevo alumno ha sido agregado.", "Operación realizada con éxito.");
else if (num == -1)
toastr.error("Debe rellenar los campos.", "Operación fallida");
else
toastr.success("El alumno ha sido modificado.", "Operación realizada con éxito.");
}
$('#btnCerrarModal').click(function () { // Si la ventana modal se cierra sin darle al botón aceptar
modoEditar = false; // establezco a false el valor del modoEditar
});
$('#btnAgregar').click(function () {
resetCamposForm();
});
function resetCamposForm() {
$('#txtFoto').val("");
$('#txtNombre').val("");
$('#txtCur').val("");
$('#txtTel').val("");
$('#txtDir').val("");
$('#txtEdad').val("");
$('#cbRep').prop("checked", false);
$(':input').removeClass("error");
}
function camposRellenosCorrectamente() {
var resp = true;
var $camposTexto = $(':text');
var $edad = $('#txtEdad');
if ($edad.val() == "" || $edad.val() <= 0)
resp = false;
for (var i = 0; resp && i < $camposTexto.length; i++)
if ($camposTexto[i].value === "")
resp = false;
return resp;
}
$(':text').on('input', function () {
var $this = $(this);
if ($this.val() == "")
$this.addClass("error");
else
$this.removeClass("error");
});
$('#txtEdad').on('input', function () {
var $this = $(this);
if ($this.val() == "" || $this.val() <= 0)
$this.addClass("error");
else
$this.removeClass("error");
});
});
|
import React, { Component } from 'react'
import { StyleSheet, View, Text, ActivityIndicator } from 'react-native';
import { Image, Button, SocialIcon, Divider, Icon } from 'react-native-elements'
import Toaste, { DURATION } from 'react-native-easy-toast'
import t from 'tcomb-form-native';
import { LoginOptions, LoginStruct } from '../../forms/Login'
import * as firebase from 'firebase';
import { FacebookAPI } from '../../utils/Social'
import Toast from 'react-native-easy-toast';
import * as Facebook from 'expo-facebook';
const Form = t.form.Form;
export default class Login extends Component {
constructor() {
super();
this.state = {
loginStruct: LoginStruct,
loginOptions: LoginOptions,
loginData: {
email: '',
password: ''
},
formErrorMessage: ''
}
}
login = () => {
const validate = this.refs.loginForm.getValue();
if (validate) {
this.setState({
formErrorMessage: ''
});
firebase.auth()
.signInWithEmailAndPassword(validate.email, validate.password)
.then(() => {
this.refs.toastLogin.show('Login Correcto', 2000, () => {
this.props.navigation.goBack();
});
})
.catch(error => {
console.log('Login Incorrecto')
this.refs.toastLogin.show('Login Incorrecto', 2000);
})
} else {
this.setState({
formErrorMessage: 'Formulario incorrecto'
})
}
}
loginFacebook = async () => {
const { type, token } = await Facebook.logInWithReadPermissionsAsync(FacebookAPI.applicationId,
{permissions: FacebookAPI.permissions})
if (type == 'success') {
const credentials = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth()
.signInWithCredential(credentials)
.then(() => {
this.refs.toastLogin.show('Login correcto', 100, () => {
this.props.navigation.goBack();
})
})
.catch(error => {
console.log(error)
this.refs.toastLogin.show('Error accediendo con Facebook, intentelo mas tarde')
})
} else if (type == 'cancel') {
this.refs.toastLogin.show('Inicio de sesión cancelada', 300)
} else {
this.refs.toastLogin.show('Error desconocido, intentelo mas tarde')
}
}
goToScreen = (nameScreen) => {
this.props.navigation.navigate(nameScreen)
}
onChangeFormLogin = (formValue) => {
this.setState({
loginData: formValue
})
}
render () {
const { loginStruct, loginOptions, formErrorMessage } = this.state;
return (
<View style={styles.viewBody}>
<Image source={require('../../../assets/img/5-tenedores-letras-icono-logo.png')}
style={styles.imageStyle}
PlaceholderContent={
<ActivityIndicator />
}
containerStyle={styles.containerLogo}
resizeMode='contain'/>
<View style={styles.viewForm}>
<Form ref='loginForm'
type={loginStruct}
options={loginOptions}
value={this.state.loginData}
onChange={formValue => this.onChangeFormLogin(formValue)}/>
<Button title='Login'
onPress={() => this.login()}
// onChange
buttonStyle={styles.loginButton}/>
<Text style={styles.textRegister}>¿Aún no tienes cuenta?{' '}
<Text style={styles.btnRegister}
onPress={() => this.goToScreen('Register')}>
Registrate
</Text>
</Text>
<Text style={styles.formErrorMessage}>{formErrorMessage}</Text>
</View>
<Divider style={styles.divider}/>
<SocialIcon title='Iniciar con Facebook'
button
type='facebook'
onPress={() => this.loginFacebook()}/>
<Toast ref='toastLogin'
position='bottom'
positionValue={300}
fadeInDuration={1000}
fadeOutDuration={100}
opacity={0.8}
textStyle={{
color: '#fff'
}}/>
</View>
)
}
}
const styles = StyleSheet.create({
viewBody: {
flex: 1,
marginLeft: 30,
marginRight: 30,
marginTop: 40,
// alignItems: 'center'
},
containerLogo: {
alignItems: 'center'
},
viewForm: {
marginTop: 20
},
imageStyle: {
width: 300,
height: 150,
marginBottom: 30,
// backgroundColor: '#000'
},
loginButton: {
backgroundColor: '#00A680',
marginTop: 20,
marginLeft: 10,
marginRight: 10
},
formErrorMessage: {
color: '#F00',
textAlign: 'center',
marginTop: 10,
marginBottom: 10
},
divider: {
backgroundColor: '#00A680',
marginBottom: 20
},
textRegister: {
marginTop: 20,
marginRight: 10,
marginLeft: 10
},
btnRegister: {
fontWeight: 'bold',
color: '#00A680'
}
})
|
import React, { PropTypes } from 'react'
import Log from 'Log'
import { Grid, Cell } from 'Grid'
var NotificationPage = React.createClass({
render() {
return (
<div className="container notification-page">
<Grid>
<Cell>
<Log />
</Cell>
</Grid>
</div>
)
}
})
export default NotificationPage
|
import KeyCodes from 'keycodes-enum';
import AccessibilityModule from '../../index';
describe('AccessibilityObject', () => {
describe('register role', () => {
let cjsDummy;
let accessibleOptions;
let mainEl;
let shouldEnableKeyEvents;
beforeEach(() => {
cjsDummy = new createjs.Shape();
shouldEnableKeyEvents = true;
accessibleOptions = {
enableKeyEvents: shouldEnableKeyEvents,
accessKey: 'M',
atomic: true,
busy: true,
dir: 'rtl',
dropEffects: 'move',
grabbed: true,
hasPopUp: 'tree',
hidden: true,
invalid: 'spelling',
label: 'my_label',
lang: 'en',
live: 'polite',
relevant: 'text',
spellcheck: true,
tabIndex: -1,
title: 'my_title',
visible: true,
};
// set init props and re-render
Object.keys(accessibleOptions).forEach((key) => {
container.accessible[key] = accessibleOptions[key];
});
stage.accessibilityTranslator.update();
mainEl = parentEl.querySelector(
`main[aria-atomic=${accessibleOptions.atomic}]` +
`[aria-busy=${accessibleOptions.busy}]` +
`[dir=${accessibleOptions.dir}]` +
`[aria-dropeffect=${accessibleOptions.dropEffects}]` +
`[aria-grabbed=${accessibleOptions.grabbed}]` +
`[aria-haspopup=${accessibleOptions.hasPopUp}]` +
`[aria-hidden=${accessibleOptions.hidden}]` +
`[aria-invalid=${accessibleOptions.invalid}]` +
`[aria-label=${accessibleOptions.label}]` +
`[lang=${accessibleOptions.lang}]` +
`[aria-live=${accessibleOptions.live}]` +
`[aria-relevant=${accessibleOptions.relevant}]` +
`[spellcheck=${accessibleOptions.spellcheck}]` +
`[tabindex=${accessibleOptions.tabIndex}]` +
`[title=${accessibleOptions.title}]`
);
});
describe('rendering', () => {
it('creates main element', () => {
expect(mainEl).not.toBeNull();
});
});
describe('children checking', () => {
describe('prohibited children', () => {
let errorObj;
beforeEach(() => {
errorObj =
/DisplayObjects added to the accessibility tree must have accessibility information when being added to the tree/;
stage.accessibilityTranslator.update();
});
it('throws error attempting to add prohibited child using addChild() ', () => {
expect(() => {
container.accessible.addChild({});
}).toThrowError(errorObj);
});
it('throws error attempting to add prohibited child using addChildAt()', () => {
expect(() => {
container.accessible.addChildAt({}, 0);
}).toThrowError(errorObj);
});
});
describe('permitted children', () => {
beforeEach(() => {
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
stage.accessibilityTranslator.update();
});
it('throws NO error when adding permitted child using addChild', () => {
expect(() => {
container.accessible.addChild(cjsDummy);
}).not.toThrowError();
});
it('throws NO error when adding permitted child using addChildAt()', () => {
expect(() => {
container.accessible.addChildAt(cjsDummy, 0);
}).not.toThrowError();
});
it('can remove all children', () => {
container.accessible.addChild(cjsDummy);
expect(container.accessible.children.length).toEqual(1);
container.accessible.removeAllChildren();
expect(container.accessible.children.length).toEqual(0);
expect(container.accessible.children).toEqual([]);
});
it('can reparent', () => {
container.accessible.addChild(cjsDummy);
expect(container.accessible.children.length).toEqual(1);
container.accessible.addChild(cjsDummy);
expect(container.accessible.children).toEqual([cjsDummy]);
container.accessible.addChildAt(cjsDummy, 0);
expect(container.accessible.children).toEqual([cjsDummy]);
});
});
});
describe('accessible options getters and setters', () => {
[
{ property: 'atomic', ariaAttr: 'aria-atomic', newVal: false },
{ property: 'busy', ariaAttr: 'aria-busy', newVal: false },
{
property: 'dropEffects',
ariaAttr: 'aria-dropeffect',
newVal: 'copy',
},
{ property: 'grabbed', ariaAttr: 'aria-grabbed', newVal: 'listbox' },
{ property: 'hasPopUp', ariaAttr: 'aria-haspopup', newVal: 'listbox' },
{ property: 'hidden', ariaAttr: 'aria-hidden', newVal: false },
{ property: 'invalid', ariaAttr: 'aria-invalid', newVal: 'grammar' },
{ property: 'label', ariaAttr: 'aria-label', newVal: 'new_label' },
{ property: 'live', ariaAttr: 'aria-live', newVal: 'assertive' },
{ property: 'relevant', ariaAttr: 'aria-relevant', newVal: 'all' },
].forEach(({ property, ariaAttr, newVal }) => {
it(`can set and read "${property}" property [for "${ariaAttr}"]`, () => {
expect(container.accessible[property]).toBe(
accessibleOptions[property]
);
container.accessible[property] = newVal;
expect(container.accessible[property]).toBe(newVal);
});
});
it('can read "controlsId" property and read, set and clear "controls" property [for "aria-controls"]', () => {
expect(() => {
container.accessible.controls = cjsDummy;
}).toThrowError(
/DisplayObject being controlled by another must have accessibility information/
);
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
container.accessible.controls = cjsDummy;
expect(container.accessible.controls).toEqual(cjsDummy);
expect(container.accessible.controlsId).toMatch(/^acc_?/);
container.accessible.controls = undefined;
expect(container.accessible.controls).toEqual(undefined);
});
it('can read "describedById" property and read, set and clear "describedBy" property [for "aria-describedby"]', () => {
expect(() => {
container.accessible.describedBy = cjsDummy;
}).toThrowError(
/DisplayObject describing another must have accessibility information/
);
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
container.accessible.describedBy = cjsDummy;
expect(container.accessible.describedBy).toEqual(cjsDummy);
expect(container.accessible.describedById).toMatch(/^acc_?/);
container.accessible.describedBy = undefined;
expect(container.accessible.describedBy).toEqual(undefined);
});
it('can clear "enabled" property [for "aria-disabled"]', () => {
container.accessible.enabled = undefined;
expect(container.accessible.enabled).toEqual(undefined);
});
it('can read "flowToId" property and read, set and clear "flowTo" property [for "aria-flowto"]', () => {
expect(() => {
container.accessible.flowTo = cjsDummy;
}).toThrowError(
/DisplayObject to flow to must have accessibility information/
);
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
container.accessible.flowTo = cjsDummy;
expect(container.accessible.flowTo).toEqual(cjsDummy);
expect(container.accessible.flowToId).toMatch(/^acc_?/);
container.accessible.flowTo = undefined;
expect(container.accessible.flowTo).toEqual(undefined);
});
it('can read "labelledById" property and read, set and clear "labelledBy" property [for "aria-labelledby"]', () => {
expect(() => {
container.accessible.labelledBy = cjsDummy;
}).toThrowError(
/DisplayObjects used to label another DisplayObject must have accessibility information when being provided as a label/
);
expect(() => {
container.accessible.labelledBy = container;
}).toThrowError(/An object cannot be used as its own labelledBy/);
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
container.accessible.labelledBy = cjsDummy;
expect(container.accessible.labelledBy).toEqual(cjsDummy);
expect(container.accessible.labelledById).toMatch(/^acc_?/);
container.accessible.labelledBy = undefined;
expect(container.accessible.labelledBy).toEqual(undefined);
});
it('can read "ownsIds" property and read, set and clear "owns" property [for "aria-owns"]', () => {
expect(() => {
container.accessible.owns = [cjsDummy];
}).toThrowError(
/DisplayObjects owned by another DisplayObject must have accessibility information/
);
AccessibilityModule.register({
displayObject: cjsDummy,
role: AccessibilityModule.ROLES.SPAN,
});
container.accessible.owns = [cjsDummy];
expect(container.accessible.owns).toEqual([cjsDummy]);
expect(container.accessible.ownsIds).toMatch(/^ acc_?/);
container.accessible.owns = undefined;
expect(container.accessible.owns).toEqual(undefined);
});
});
describe('other options getters and setters', () => {
[
{ property: 'accessKey', newVal: 'V' },
{ property: 'dir', newVal: 'ltr' },
{ property: 'lang', newVal: 'es' },
{ property: 'spellcheck', newVal: false },
{ property: 'tabIndex', newVal: 0 },
{ property: 'title', newVal: 'new_title' },
{ property: 'visible', newVal: false },
].forEach(({ property, newVal }) => {
it(`can set and read "${property}" property`, () => {
expect(container.accessible[property]).toBe(
accessibleOptions[property]
);
container.accessible[property] = newVal;
expect(container.accessible[property]).toBe(newVal);
});
});
it('can read and set "enableKeyEvents" property', () => {
expect(container.accessible.enableKeyEvents).toEqual(
shouldEnableKeyEvents
);
const newVal = false;
container.accessible.enableKeyEvents = newVal;
expect(container.accessible.enableKeyEvents).toEqual(newVal);
});
it('can read "displayObject" property', () => {
expect(container.accessible.displayObject).toEqual(container);
});
it('can read "disabledWithInference" property', () => {
const pressUp = jest.fn();
container.accessible.enabled = true;
expect(container.accessible.disabledWithInference).toEqual(false);
container.accessible.enabled = undefined;
container.mouseEnabled = false; // easeljs/createjs specific property
container.on('pressup', pressUp);
expect(container.accessible.disabledWithInference).toEqual(true);
});
it('can reset "hidden" property and read "hiddenWithInference" property', () => {
container.accessible.hidden = undefined;
expect(container.accessible.hidden).toEqual(undefined);
container.visible = false;
expect(container.accessible.hiddenWithInference).toEqual(true);
});
it('can read "parent" property', () => {
expect(container.accessible.parent).toEqual(undefined);
});
it('can read "visibleWithInference" property', () => {
container.accessible.visible = undefined;
expect(container.accessible.visibleWithInference).toEqual(
accessibleOptions.visible
);
container.accessible.visible = true;
expect(container.accessible.visibleWithInference).toEqual(true);
container.accessible.visible = false;
expect(container.accessible.visibleWithInference).toEqual(false);
});
});
describe('event listeners', () => {
it('Accessibility Object should provide event and keycode with the event', () => {
const keyDownListener = jest.fn();
container.on('keydown', keyDownListener);
[
['Enter', 13],
['a', 65],
['t', 84],
['Tab', 9],
].forEach(([key, keyCode], i) => {
mainEl.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode }));
const keyDownReturn = keyDownListener.mock.calls[i][0];
const keyReturned = keyDownReturn.key;
const keyCodeReturned = keyDownReturn.keyCode;
expect(keyReturned).toBe(key);
expect(keyCodeReturned).toBe(keyCode);
});
});
it('can request focus', () => {
jest.spyOn(mainEl, 'focus');
document.getElementById = (query) => {
return parentEl.querySelector(`#${query}`);
};
mainEl.setAttribute('disabled', true);
mainEl.removeAttribute('tabindex');
container.accessible.enabled = true;
container.accessible.requestFocus();
expect(mainEl.focus).toHaveBeenCalled();
mainEl.style.display = 'none';
container.accessible.requestFocus();
expect(mainEl.focus).toHaveBeenCalled();
});
describe('"onKeyUp" event listener', () => {
let onKeyUp;
beforeEach(() => {
onKeyUp = jest.fn();
container.on('keyup', onKeyUp);
});
it('can dispatch "keyUp" event', () => {
const keyCode = KeyCodes.up;
mainEl.dispatchEvent(
new KeyboardEvent('keyup', { keyCode, cancelable: true })
);
expect(onKeyUp).toBeCalledTimes(1);
const keyCodeReturned = onKeyUp.mock.calls[0][0].keyCode;
expect(keyCodeReturned).toBe(keyCode);
});
});
});
});
});
|
define([
'/BrainAcademy-examples/node_modules/backbone/backbone.js'
], function(Backbone){
return Backbone.View.extend({
options: null,
initialize: function(options){
this.options = options;
var model = this.model;
this.options.model.on('change', function(){
var el = document.getElementById(model.cid);
if(model.get('isSelected')){
el.style.backgroundColor = "red";
} else {
el.style.backgroundColor = '';
}
});
},
render: function(){
var model = this.options.model,
text = model.get('text'),
author = model.get('author');
return "<p id='" + model.cid + "'>>"+author + ": " + text + "</p>";
}
});
});
|
var express = require('express');
var logger = require('morgan');
var status = require('./status');
var instance_name=process.env.INSTANCE_NAME || "local"
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Setup Probe interface
var probes = express.Router();
probes.get('/liveness', function(req, res, next) {
console.info(instance_name + "liveness");
status.livenessProbe(function(data){
res.json(data);
}, function(errorData){
res.status(503)
res.json(errorData);
});
});
probes.get('/readiness', function(req, res, next) {
console.info(instance_name + "readiness");
status.readinessProbe(function(data){
res.json(data);
}, function(errorData){
res.status(503)
res.json(errorData);
});
});
probes.get('/startup', function(req, res, next) {
console.info(instance_name + "startup");
status.startupProbe(function(data){
res.json(data);
}, function(errorData){
res.status(503)
res.json(errorData);
});
});
probes.get("/", function(req, res, next){
res.json(status);
});
probes.get("/startup/break", function(req, res, next){
status.startup = false;
res.json(status);
});
probes.get("/startup/fix", function(req, res, next){
status.startup = true;
res.json(status);
});
probes.get("/liveness/break", function(req, res, next){
status.liveness = false;
res.json(status);
});
probes.get("/liveness/fix", function(req, res, next){
status.liveness = true;
res.json(status);
});
probes.get("/readiness/break", function(req, res, next){
status.readiness = false;
res.json(status);
});
probes.get("/readiness/fix", function(req, res, next){
status.readiness = true;
res.json(status);
});
app.use("/probes", probes);
module.exports = app;
// Handle process signals
process.on('SIGINT', () => {
console.log('Received SIGINT. Press Control-D to exit.');
});
// Using a single function to handle multiple signals
function exitApp(signal) {
console.log(`Received ${signal}. Exiting`);
process.exit(0);
}
process.on('SIGINT', exitApp);
process.on('SIGTERM', exitApp);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.