text
stringlengths 7
3.69M
|
|---|
export const heroBarObj = {
title: 'Projects',
description:
'From configuration to security, web apps to big data—whatever the infrastructure needs of your application may be, there is a Spring Project to help you build it. Start small and use just what you need—Spring is modular by design.'
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.AttendPresentComponent = void 0;
var core_1 = require("@angular/core");
var nativescript_modal_datetimepicker_1 = require("nativescript-modal-datetimepicker");
var dayjs = require("dayjs");
var AttendPresentComponent = /** @class */ (function () {
function AttendPresentComponent(page, authService, attendService, datetimeService, presentService, locationService) {
this.page = page;
this.authService = authService;
this.attendService = attendService;
this.datetimeService = datetimeService;
this.presentService = presentService;
this.locationService = locationService;
this.authed = false;
this.date = this.datetimeService.todayDate();
this.records = [];
this.latitude = 22.33615;
this.longitude = 114.17574;
// latitude: number = 22.323457;
// longitude: number = 114.159994;
this.message = "";
this.picker = new nativescript_modal_datetimepicker_1.ModalDatetimepicker();
page.actionBarHidden = true;
// Use the component constructor to inject providers.
}
AttendPresentComponent.prototype.ngOnInit = function () {
// Init your component properties here.
this.getRecord(this.date);
};
AttendPresentComponent.prototype.onTake = function () {
if (this.date !== this.datetimeService.todayDate()) {
this.message = "date must be today";
}
else {
this.addRecord({
user_id: this.authService.getCurrUserId(),
date: this.datetimeService.todayDate(),
start_time: this.datetimeService.nowTime(),
end_time: this.datetimeService.nowTime()
});
}
};
AttendPresentComponent.prototype.getRecord = function (date) {
var _this = this;
this.presentService.getFmtdByDate(date).then(function (response) {
response.forEach(function (element, index) {
element.start_time = dayjs(_this.datetimeService.todayDate() + " " + element.start_time).format("hh:mm:ss A");
element.end_time = dayjs(_this.datetimeService.todayDate() + " " + element.end_time).format("hh:mm:ss A");
});
_this.records = response;
});
};
AttendPresentComponent.prototype.addRecord = function (attendance) {
var _this = this;
this.presentService.insert(attendance).subscribe(function (response) {
if (response.success &&
(response.message == "inserted" || response.message == "updated")) {
_this.getRecord(_this.date);
_this.message = "taken at " + _this.datetimeService.nowTime();
}
else {
_this.message = response.message;
}
});
};
AttendPresentComponent.prototype.callDatePicker = function () {
var _this = this;
this.picker
.pickDate({
title: "Pick a Date",
theme: "light",
maxDate: new Date(),
startingDate: new Date(this.date)
})
.then(function (result) {
// Note the month is 1-12 (unlike js which is 0-11)
_this.date =
result.year +
"-" +
("0" + result.month).slice(-2) +
"-" +
("0" + result.day).slice(-2);
_this.getRecord(_this.date);
})["catch"](function (error) {
console.log("Error: " + error);
});
};
AttendPresentComponent = __decorate([
core_1.Component({
selector: "attend-present",
templateUrl: "./attend-present.component.html",
styleUrls: ["./attend-present.component.css"]
})
], AttendPresentComponent);
return AttendPresentComponent;
}());
exports.AttendPresentComponent = AttendPresentComponent;
|
import React from 'react';
export default class SearchForm extends React.Component {
constructor() {
super();
this.state = {
search: ''
};
}
updateSearch(event) {
this.setState({search: event.target.value.substr(0, 60)})
}
handleSearch(event) {
event.preventDefault();
const search = this.state.search;
// Prevent empty form submission
if (!search) { return; }
this.props.search(search);
}
render() {
return (
<div id="searchBox" className="container">
<form className="input-group input-group-lg col-lg-7 col-sm-9 col-xs-12 center" onSubmit={this.handleSearch.bind(this)}>
<input type="text" onChange={this.updateSearch.bind(this)} value={this.state.search} className="form-control input-lg" placeholder="Ask me anything..." />
<span className="input-group-btn">
<input type="submit" className="btn btn-default btn-lg" value="Ask" />
</span>
</form>
</div>
);
}
}
|
import vuexModule from "./main/vuex.js";
import Injector from "./main/injector";
import Body from "./main/body.vue";
function setup(frontend) {
frontend.store.registerModule("dashboard", vuexModule);
frontend.inject("dashboard", new Injector(frontend));
frontend.worker.import("dashboard/worker.mjs");
frontend.objects.setType({
type: "dashboard",
title: "Dashboard",
list_title: "Dashboards",
icon: "dashboard",
});
frontend.objects.addComponent({
component: Body,
type: "dashboard",
key: "body",
});
if (frontend.info.user != null) {
frontend.objects.addCreator({
key: "dashboard",
title: "Dashboard",
description: "Display data from multiple sources",
icon: "dashboard",
fn: async () => {
let res = await frontend.rest("POST", "/api/objects", {
name: "My Dashboard",
type: "dashboard",
});
if (res.response.ok) {
frontend.router.push({ path: `/objects/${res.data.id}/update` });
} else {
frontend.store.dispatch("errnotify", res.data);
}
},
});
}
}
export default setup;
|
'use strict';
const { resolve } = require('path')
module.exports = {
plugins: [
require('postcss-import')({
path:[resolve(__dirname,'./app/web/asset/css')]
}),
require('postcss-cssnext'),
require('postcss-pxtorem')({ rootValue: 75, propList: ['*', '!font*'] }),
]
};
|
import { assert } from '../assert';
/**
* @param {string=} env
* @returns {typeof DEFAULT}
*/
export const getConfig = (env) => {
assert(
!env || env === 'staging' || env === 'green',
`env: ${env} is not supported`,
);
return {
...DEFAULT,
...(env ? CONFIGS[env] : {}),
};
};
const DEFAULT = {
MAP_API_KEY: `AIzaSyAVZcp3tZikbfWLKqysbMv2jeHfRogn7dw`,
ADDRESS: ['Suite 2.17/203-205 Blackburn Rd', 'Mount Waverley VIC 3149'],
EMAIL: 'info@superintegrity.com.au',
};
/** @type {Record<string, any>} */
const CONFIGS = {
staging: {},
green: {},
};
|
import { createMuiTheme } from '@material-ui/core/styles';
const palette = {
primary: { main: '#1565c0' },
secondary: { main: '#e91e63' }
};
const themeName = 'Jacksons Purple Heliotrope Cardinal';
export default createMuiTheme({ palette, themeName });
|
import { useReducer } from "react"
export default initialState => {
const reducer = (state, action) => {
switch (action.type) {
case "error":
return { ...state, error: action.error }
default:
return { ...state, value: action.value }
}
}
const [state, dispatch] = useReducer(reducer, {
value: initialState,
error: ""
})
return {
...state,
setValue: value => dispatch({ type: "value", value }),
hasError: state.error !== "",
setError: error => dispatch({ type: "error", error })
}
}
|
export const DAI_TOKEN_ADDRESS = '0xf249104DEf3BA2EC205734E5159f1A3d61789C0a';
export const FAUCET_ADDRESS = '0x49261749Cdd32d4f4d403CdBB5179EE5DB6aac59';
const DEPLOYER_ADDRESS = '0xD0CEe0e407bdd1d844bC9061D39873F2a42F1D9b';
export const ETHLEND_CONTRACT_ADDRESS = '0x55C0b8E264EB72D54A99c15820c7C024E4F53657';
//minted 1000000 tokens to faucet contract.
//0x87519059B12349fcDeceB01AbD7DF7496c4B51ce
|
import React from 'react';
import { Provider } from 'react-redux';
import { AppState, Platform, View, Navigator, StyleSheet } from 'react-native';
import configureStore from './store/configureStore';
import Router from './Router';
export default class Application extends React.Component {
state: {
isLoading: boolean;
store: any;
};
constructor() {
super();
this.state = {
isLoading: true,
store: configureStore(() => this.setState({ isLoading: false })),
};
}
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
}
handleAppStateChange(appState) {
if (appState == 'active') {
// resume 될때 할 일 (토큰 가져오거나~)
}
}
render() {
if (this.state.isLoading) {
return null;
}
return(
<Provider store={ this.state.store }>
<Router />
</Provider>
);
}
}
|
import React, {useState} from 'react';
const FunctionState =() => {
const [counter, setCounter] = useState(0)
// useState nous permet d'avoir un state au sein d'une fonction
return (
<div>
<p> Counter : {counter} </p>
<button onClick={()=> setCounter(prevCounter => prevCounter +1)}>Hooks</button>
</div>
)
}
export default FunctionState;
|
var APP_DATA = {
"scenes": [
{
"id": "0-1conv",
"name": "1conv",
"levels": [
{
"tileSize": 256,
"size": 256,
"fallbackOnly": true
},
{
"tileSize": 512,
"size": 512
}
],
"faceSize": 500,
"initialViewParameters": {
"yaw": 0.7797205578231612,
"pitch": 0.22379723674728957,
"fov": 1.3514664571196955
},
"linkHotspots": [
{
"yaw": 0.7004163309778342,
"pitch": 0.14613241628230433,
"rotation": 0,
"target": "1-2conv"
}
],
"infoHotspots": []
},
{
"id": "1-2conv",
"name": "2conv",
"levels": [
{
"tileSize": 256,
"size": 256,
"fallbackOnly": true
},
{
"tileSize": 512,
"size": 512
}
],
"faceSize": 500,
"initialViewParameters": {
"yaw": -2.2588165838829166,
"pitch": 0.1166069475103999,
"fov": 1.3514664571196955
},
"linkHotspots": [
{
"yaw": -2.4652601497918667,
"pitch": 0.3842046482825445,
"rotation": 0,
"target": "2-3conv"
}
],
"infoHotspots": []
},
{
"id": "2-3conv",
"name": "3conv",
"levels": [
{
"tileSize": 256,
"size": 256,
"fallbackOnly": true
},
{
"tileSize": 512,
"size": 512
}
],
"faceSize": 500,
"initialViewParameters": {
"yaw": 0.848360056772238,
"pitch": 0.11149470339783996,
"fov": 1.3514664571196955
},
"linkHotspots": [
{
"yaw": 0.48717349151534073,
"pitch": 0.4422230640386342,
"rotation": 0,
"target": "3-4conv"
}
],
"infoHotspots": []
},
{
"id": "3-4conv",
"name": "4conv",
"levels": [
{
"tileSize": 256,
"size": 256,
"fallbackOnly": true
},
{
"tileSize": 512,
"size": 512
}
],
"faceSize": 500,
"initialViewParameters": {
"yaw": 0.8361533451278316,
"pitch": 0.38392900031552024,
"fov": 1.3514664571196955
},
"linkHotspots": [
{
"yaw": 0.9309542910148281,
"pitch": 0.5858181413187022,
"rotation": 0,
"target": "4-5conv"
}
],
"infoHotspots": []
},
{
"id": "4-5conv",
"name": "5conv",
"levels": [
{
"tileSize": 256,
"size": 256,
"fallbackOnly": true
},
{
"tileSize": 512,
"size": 512
}
],
"faceSize": 500,
"initialViewParameters": {
"yaw": -2.0599411269495906,
"pitch": -0.0011202449560201444,
"fov": 1.3514664571196955
},
"linkHotspots": [],
"infoHotspots": []
}
],
"name": "Project Title",
"settings": {
"mouseViewMode": "drag",
"autorotateEnabled": true,
"fullscreenButton": false,
"viewControlButtons": false
}
};
|
import React from "react";
import { Link } from "react-router-dom";
import pic from "./Travel/Pics/Me_Matterhorn.png";
import './index.css';
import '../node_modules/react-vis/dist/style.css';
const childStyle = {"width": "100%", "height": "100%", "fontSize": "50px"}
function home() {
return (
<div style={{ "height": "100vh", "width": "100%", "display": "flex", "flexDirection": "column" }}>
<Link to="/Bio" style={childStyle}>
<button style={childStyle}>
Resume/CV
</button>
</Link>
<Link to="/Hurricane" style={childStyle}>
<button style={childStyle}>
Hurricanes
</button>
</Link>
<Link to="/RoyalTree" style={childStyle}>
<button style={childStyle}>
RoyalTree
</button>
</Link>
</div>
);
}
export default home;
|
import {pageSize, pageSizeType, paginationConfig, searchConfig} from '../../globalConfig';
import name from '../../dictionary/name';
const filters = [
{key: 'serviceName', title: '所属服务名', type: 'text'},
{key: 'controllerName', title: '所属控制层名称', type: 'text'},
{key: 'url', title: 'URL路径', type: 'text'},
{key: 'urlName', title: 'URL名称', type: 'text'},
{key: 'startTime', title: '创建时间', type: 'date', rule: {type: '<', key: 'insertTimeTo'}},
{key: 'endTime', title: '至', type: 'date', rule: {type: '>', key: 'insertTimeFrom'}}
];
const arr = [
{value: "0" , title : "否"},
{value: "1" , title : "是"},
]
const tableCols = [
{key: "service_serviceName", title: '所属服务名', required: true},
{key: 'controller_controllerName', title: '所属控制层名称', required: true},
{key: 'controller_controllerUrl', title: '所属控制层路径'},
{key: 'url', title: 'URL路径'},
{key: 'urlName', title: 'URL名称'},
{key: 'requestMode', title: '请求方式',required: true},
{key: 'isDistribute', title: '是否已分配', required: true , options: arr},
{key: 'isNeedPermissionController', title: '是否需要URL权限控制',from:'dictionary', options: arr},
{key: 'isOpenApi', title: '是否OPENAPI', from:'dictionary', options: arr },
{key: 'isPublicApi', title: '是否公共 api',from:'dictionary', options: arr},
{key: 'insertUser', title: '创建人'},
{key: 'insertTime', title: '创建时间'}
];
const buttons = [
{key: 'add', title: '新增', bsStyle: 'primary', sign: 'urlResourceLib_add'},
{key: 'edit', title: '编辑', sign: 'urlResourceLib_edit'},
{key: 'del', title: '删除', sign: 'urlResourceLib_del'},
{key: 'distribution', title: '资源分配', sign: 'urlResourceLib_distribution'}
];
const index = {
filters,
buttons,
tableCols,
pageSize,
pageSizeType,
paginationConfig,
searchConfig
};
const controls = [
{key: 'service_serviceName', title: '所属服务名', type: 'search', required: true, props: {searchWhenClick: true, noSearchWhenTypo: true},showAdd:true},
{key: 'controller_controllerName', title: '所属控制层', type: 'search', required: true, props: {searchWhenClick: true, noSearchWhenTypo: true},showAdd:true},
{key: 'urlName', title: 'URL名称', type: 'text',required: true},
{key: 'url', title: 'URL路径', type: 'text',required: true},
{key: 'requestMode', title: '请求方式', type: 'select',dictionary: name.REQUEST_METHOD,required: true},
{key: 'isNeedPermissionController', title: '是否需要URL权限控制', type: 'radioGroup', from:'dictionary',options: arr,required: true},
{key: 'isOpenApi', title: '是否公开API', type: 'radioGroup', from:'dictionary',options: arr,required: true},
{key: 'isPublicApi', title: '是否公共API', type: 'radioGroup', from:'dictionary', options: arr,required: true},
];
const edit = {
controls,
edit: '编辑',
add: '新增',
config: {ok: '确定', cancel: '取消'}
};
const config = {
index,
edit,
dicNames: [name.YES_OR_NO,name.REQUEST_METHOD]
};
export default config;
|
const express = require('express');
const passportRouter = express.Router();
const passport = require('../helpers/passport');
const User = require('../models/User');
passportRouter.get('/login', (req, res, next) => {
res.render('passport/login');
});
passportRouter.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info = {}) => {
const { message: error } = info;
if ( error ) return res.render('passport/login', { error });
req.login(user, err => res.redirect('/') );
console.log(err, user, info);
})(req, res);
});
passportRouter.get('/facebook', passport.authenticate('facebook'));
passportRouter.get('/facebook/callback', passport.authenticate('facebook', {
successRedirect: '/',
failureRedirect: '/login'
}));
passportRouter.get('/signup', (req, res, next) => {
res.render('passport/signup');
});
passportRouter.post('/signup', (req, res, next) => {
const { email, password } = req.body;
let error;
if ( password !== req.body['confirm-password'] ) {
error = 'Make sure to enter the same password';
return res.render('passport/signup', { error });
}
if ( !email || !password ) {
error = 'Please enter email or password';
return res.render('passport/signup', { error });
}
User.register({ email }, password)
.then( user => {
req.login( user, err => res.redirect('/'));
})
.catch( error => res.render('passport/signup', { error }));
});
passportRouter.get('/logout', (req, res, next) => {
req.logout();
res.redirect('/login');
})
module.exports = passportRouter;
|
import React from 'react'
import "./ReporteSistema.css";
import { LeftCircleTwoTone, RightCircleTwoTone, CloseCircleTwoTone } from "@ant-design/icons"
export default function ReporteSistema() {
return (
<>
<div className="row">
<div className="col-2">
<div class="row">
<div class="col-1"></div>
<div class="col-sm" id="bannerRepSis">
<br />
<br />
<h2 class="listLabel">Reporte de Ayuda de Sistema</h2>
<div class="row">
<div id="circle-background">
<img src="https://quanexus.com/wp-content/uploads/2018/08/Info-icon-06.png" alt="" id="imgListRepSis" />
</div>
</div>
</div>
</div>
</div>
<div className="col-sm">
<div class="col-sm">
<textarea name="" id="reporteSistema" cols="151" rows="30"></textarea>
<br /><br />
<div id="buttonReport">
<LeftCircleTwoTone twoToneColor="#780028" id="leftResRep" />
<RightCircleTwoTone twoToneColor="#780028" id="rightResRep" />
<CloseCircleTwoTone twoToneColor="#780028" id="closeResRep" />
</div>
</div>
</div>
</div>
</>
)
}
|
/*globals App Class Events $merge*/
App.ns('App.Messanger');
App.Messanger = new (new Class((function(){
// private
var _message_dict = {};
var _message_stack = [];
var _fire_update_onmove = true;
var _message_stack_limit = 6;
// public
return {
Implements: Events,
/**
* setAuthor
* @param String
*/
setAuthor: function(author) {
this.client_author = author;
},
/**
* setMessage
* updates an existing message or builds a new message
* @param Object message configuration
*/
setMessage: function(config) {
var id = config['id'];
if (id && id in _message_dict) {
this.updateMessage(id, config);
}
else {
id = this.createMessage(config);
}
return id;
},
/**
* createNewMessage
* creates a new message obj
* @param Object message configuration
*/
createMessage: function(config) {
var message;
config['id'] = config['id'] || String(config['author']) + String(Date.now());
message = new App.Message(config);
message.addEvent('afterEdit', function(msg) {
this.fireEvent('update', [msg.options]);
}.bind(this));
message.addEvent('afterMove', function(msg) {
this.fireEvent('update', [msg.options]);
}.bind(this));
message.addEvent('move', function(msg) {
if (_fire_update_onmove) {
this.fireEvent('update', [msg.options]);
_fire_update_onmove = false;
}
(function(){_fire_update_onmove = true;}).delay(100, this);
}.bind(this));
if (this.client_author === config.author) {
message.beginEdit();
}
_message_dict[config.id] = message;
// ageing
if (_message_stack.unshift(message) > _message_stack_limit) {
delete _message_dict[_message_stack.pop().remove().options.id];
}
this._updateAgeing();
return config.id;
},
/**
* updateMessage
* update an existing message with id
* @param String id of message
* @param Object message configuration properties
*/
updateMessage: function(id, config) {
var m = _message_dict[id];
if (m.options.text != config.text) m.setMessage(config.text);
m.moveTo(config.x, config.y);
},
// private methods
// ...............
_updateAgeing: function() {
_message_stack.each(function(m, idx) {
if (idx > 0) {
m.setAge(1 - idx/_message_stack_limit);
}
}, this);
},
dump: function() {
return _message_stack;
}
};
})()))();
|
module.exports = {
STORE_COLLECTION : 'stores',
USER_COLLECTION : 'users'
}
|
import { h, Component } from 'preact'
import { remote } from 'electron'
import hyperx from 'hyperx'
import * as TimeFormat from 'hh-mm-ss'
const hx = hyperx(h)
const refreshInterval = 4000
class BatteryInformation extends Component {
componentWillMount () {
this.translator = remote.getGlobal('translator')
this.setState({
chargingTime: null,
dischargingTime: null
})
navigator.getBattery()
.then(({ charging, chargingTime, dischargingTime }) => {
this.updateBatteryTimes(charging, chargingTime, dischargingTime)
})
}
componentDidMount () {
this.launchAutoRefresh()
}
componentWillUpdate () {
if (this.props.refreshAuto && !this.refreshInterval) {
this.launchAutoRefresh()
} else {
clearInterval(this.refreshInterval)
this.refreshInterval = null
}
}
launchAutoRefresh () {
this.refreshInterval = setInterval(() => {
if (document.hidden) {
return
}
navigator.getBattery()
.then(({ charging, chargingTime, dischargingTime }) => {
this.updateBatteryTimes(charging, chargingTime, dischargingTime)
})
}, refreshInterval)
}
updateBatteryTimes (charging, chargingTime, dischargingTime) {
const format = 'hh:mm'
let time
let key
if (charging && chargingTime === Infinity) {
this.setState({
chargingTime: `${this.translator.translate('loading')}...`
})
return
}
if (!charging && dischargingTime === Infinity) {
this.setState({
dischargingTime: `${this.translator.translate('loading')}...`
})
return
}
if (charging) {
time = chargingTime
key = 'chargingTime'
} else {
time = dischargingTime
key = 'dischargingTime'
}
let formattedTime = TimeFormat.fromS(time, format)
const splittedFormattedTime = formattedTime.split(':')
formattedTime = `${splittedFormattedTime[0]}h ${splittedFormattedTime[1]}min`
this.setState({
[key]: formattedTime
})
}
getBatteryIcon ({ hasbattery, percent, ischarging }) {
if (!hasbattery) {
return 'mdi-battery-unknown'
}
if (ischarging) {
return 'mdi-battery-charging success'
}
if (percent < 10) {
return 'mdi-battery-alert danger'
}
if (percent < 20) {
return 'mdi-battery-10 danger'
}
if (percent < 30) {
return 'mdi-battery-20 danger'
}
if (percent < 40) {
return 'mdi-battery-30 warning'
}
if (percent < 50) {
return 'mdi-battery-40 warning'
}
if (percent < 60) {
return 'mdi-battery-50 warning'
}
if (percent < 70) {
return 'mdi-battery-60 success'
}
if (percent < 80) {
return 'mdi-battery-70 success'
}
if (percent < 90) {
return 'mdi-battery-80 success'
}
if (percent < 100) {
return 'mdi-battery-90 success'
}
return 'mdi-battery success'
}
render ({ data }) {
if (!data.hasbattery) {
return hx`
<div class="alert alert-danger text-center mt-2" role="alert">
<span class="mdi mdi-24px mdi-battery-unknown align-middle"></span>
<span class="align-middle">${this.translator.translate('noBattery')}</span>
</div>
`
}
return hx`
<div class="row mt-3">
<div class="col-12 pl-0 pr-0 text-center">
<div>
<div>
<strong>${this.translator.translate(data.ischarging ? 'charging' : 'discharging')}</strong>
</div>
<div>
${
data.ischarging
? hx`<span>${this.translator.translate('remainingTime')}: <strong>${this.state.chargingTime}</strong></span>`
: hx`<span>${this.translator.translate('remainingTime')}: <strong>${this.state.dischargingTime}</strong></span>`
}
</div>
</div>
<div id="batteryPreview" class="mdi ${this.getBatteryIcon(data)} align-middle"></div>
<div>
<strong>${data.percent}%</strong>
</div>
</div>
</div>
`
}
}
export default BatteryInformation
|
#!/usr/bin/env node
const program = require("../src/main");
program.main();
|
'use strict';
function isEmpty(val) {
return val === undefined || val === null || val.length <= 0 ? true : false;
}
function getCookie(name) {
if (isEmpty(document.cookie))
return null;
const documentCookieArr = document.cookie.split(';');
const nameCookieArr = documentCookieArr.filter(x => x.includes(name))[0].split('=');
if (isEmpty(nameCookieArr))
return null;
const nameValue = nameCookieArr[1];
if (isEmpty(nameValue))
return null;
return nameValue;
}
export {
isEmpty,
getCookie
};
|
var Boxcar = {
/**
* Initialize push module
*
* @param data.clientKey
* @param data.secret
* @param data.server
*/
init: function(data) {
var verifyTo = {clientKey: 0, secret: 0, server: 0, richUrlBase:0};
if (device.platform == 'android' || device.platform == 'Android')
verifyTo.androidSenderID = 0;
this._verifyArgs(data, verifyTo);
this.server = data.server.replace(/\/$/, "");
this.clientKey = data.clientKey;
this.secret = data.secret;
this.androidSenderID = data.androidSenderID;
this.richUrlBase = data.richUrlBase.replace(/\/$/, "");
this.icon = data.icon;
this.iconColor = data.iconColor;
this.initDb();
},
initDb: function() {
if (this.db)
return;
try {
this.db = window.openDatabase("Boxcar", "", "Boxcar db", 1000000);
if (this.db.version == "1.0" || !this.db.version) {
this.db.changeVersion(this.db.version, "1.3", function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS pushes (" +
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
"time INTEGER NOT NULL," +
"body STRING NOT NULL," +
"badge STRING NOT NULL," +
"sound STRING NOT NULL," +
"richPush INTEGER NOT NULL," +
"url STRING," +
"flags INTEGER NOT NULL," +
"extras STRING"+
");");
tx.executeSql("CREATE INDEX pushes_on_time ON pushes (time);");
tx.executeSql("CREATE TABLE IF NOT EXISTS settings (id STRING NOT NULL PRIMARY KEY, val STRING NOT NULL);");
}, function (a) {
console.info(a);
}, function (a) {
console.info(a);
});
} else if (this.db.version == "1.2") {
this.db.changeVersion(this.db.version, "1.3", function (tx) {
tx.executeSql("ALTER TABLE pushes ADD COLUMN extras STRING;");
tx.executeSql("CREATE TABLE IF NOT EXISTS settings (id STRING NOT NULL PRIMARY KEY, val STRING NOT NULL);");
}, function (a) {
console.info(a);
}, function (a) {
console.info(a);
});
} else if (this.db.version == "1.1") {
this.db.changeVersion(this.db.version, "1.2", function (tx) {
tx.executeSql("ALTER TABLE pushes ADD COLUMN extras STRING;");
}, function (a) {
console.info(a);
}, function (a) {
console.info(a);
});
}
this.db.transaction(function(tx) {
tx.executeSql("DELETE FROM pushes WHERE id NOT IN (SELECT id FROM pushes ORDER BY time DESC LIMIT 100)");
});
} catch (ex) {
}
},
_eqObjects: function(obj1, obj2, keys) {
for (var i = 0; i < keys.length; i++)
if (obj1[keys[i]] != obj2[keys[i]])
return false;
return true;
},
registerDevice: function(data) {
var verifyArgs = {mode: 0, onsuccess: 0, onerror: 0};
if (!data.onalert && !data.onnotificationclick)
verifyArgs.onalert = 0;
this._verifyArgs(data, verifyArgs);
if (this._rdData) {
if (this._eqObjects(this._rdData, data, "mode tags udid alias appVersion".split(" "))) {
if (this.regid)
data.onsuccess({ok:"Success", subscribed_to: data.tags});
return;
}
this._rdData = data;
if (this.regid)
this._PNRegSuccess({registrationId: this.regid}, true);
return;
}
this._rdData = data;
this.onalert = data.onalert;
this.onnotificationclick = data.onnotificationclick;
this._push = PushNotification.init({
android: {
senderID: this.androidSenderID,
icon: this.icon,
iconColor: this.iconColor
},
ios: {
alert: "true",
badge: "true",
sound: "true"
}
});
this._push.on("registration", this._PNRegSuccess.bind(this));
this._push.on("error", this._PNRegError.bind(this));
this._push.on("notification", this._Notification.bind(this));
},
unregisterDevice: function(data) {
this._verifyArgs(data, {onsuccess: 0, onerror: 0});
this._rdData = null;
if (!this.regid)
data.onsuccess();
var _this = this;
var regid = this.regid;
this._push.unregister(function() {
_this._sendRequest("DELETE", "/api/device_tokens/"+regid,
{},
data.onsuccess,
data.onerror);
}, data.onerror);
this._setSetting("boxcar_reginfo", null);
this.regid = null;
},
getReceivedMessages: function(data) {
this._verifyArgs(data, {onsuccess: 0, onerror: 0});
this.db.transaction(function(tx) {
var sql = "SELECT id, time, body, badge, sound, richPush, url, flags, extras FROM pushes";
var args = [];
if (data.before) {
sql += " WHERE time < ?";
args.push(data.before);
}
sql += " ORDER BY time DESC";
if (data.limit) {
sql += " LIMIT ?";
args.push(data.limit);
}
tx.executeSql(sql, args, function(tx, results) {
var len = results.rows.length;
var res = [];
for (var i = 0; i < len; i++) {
var rp = results.rows.item(i).richPush;
if (rp == "false")
rp = false;
res.push({
id: results.rows.item(i).id,
time: results.rows.item(i).time,
body: results.rows.item(i).body,
badge: results.rows.item(i).badge,
sound: results.rows.item(i).sound,
richPush: rp,
url: results.rows.item(i).url,
seen: results.rows.item(i).flags == 1,
extras : results.rows.item(i).extras ? JSON.parse(results.rows.item(i).extras) : {}
});
}
data.onsuccess(res);
});
}, function() {}, onerror);
},
getTags: function(data) {
this._verifyArgs(data, {onsuccess: 0, onerror: 0});
if (this._tags)
data.onsuccess(this._tags);
this._sendRequest("GET", "/api/tags",
{},
function(recv) {
try {
if (recv == "")
Boxcar._tags = [];
else
Boxcar._tags = JSON.parse(recv).ok;
data.onsuccess(Boxcar._tags);
} catch (ex) {
data.onerror({error: "Can't parse response"});
}
},
data.onerror);
},
resetBadge: function(data) {
this._verifyArgs(data, {onsuccess: 0, onerror: 0});
if (!this.regid)
data.onerror({error: "Device not registered in push service"});
this._sendRequest("GET", "/api/reset_badge/"+this.regid,
{},
data.onsuccess,
data.onerror);
},
markAsReceived: function(data) {
this._verifyArgs(data, {onsuccess: 0, onerror: 0, id: 0});
if (!this.regid)
data.onerror({error: "Device not registered in push service"});
this.db.transaction(function(tx) {
tx.executeSql("UPDATE pushes SET flags = 1 WHERE id = ?", [data.id]);
}, function() {}, onerror);
this._sendRequest("POST", "/api/receive/"+this.regid,
{id: data.id},
data.onsuccess,
data.onerror);
},
_setSetting: function(id, val) {
this.db.transaction(function(tx) {
if (val == null)
tx.executeSql("DELETE FROM settings WHERE id = ?",
[id]);
else
tx.executeSql("INSERT OR REPLACE INTO settings (id, val) VALUES (?, ?)",
[id, JSON.stringify(val)]);
});
},
_getSetting: function(id, defVal, callback) {
this.db.readTransaction(function(tx) {
tx.executeSql("SELECT val FROM settings WHERE id = ?", [id], function (tx, results) {
try{
if (results.rows.length > 0) {
var data;
try {
data = JSON.parse(results.rows.item(0).val);
} catch(ex) {
callback(defVal);
return;
}
callback(data);
} else
callback(defVal);
}catch (ex) {
console.info("Callback exception", ex);
}
}, function () {
callback(defVal);
});
});
},
_verifyArgs: function(args, names, defaults) {
if (!args)
throw new Error("Invalid Argument");
if (device.platform == 'android' || device.platform == 'Android')
for (var i in args.android || {})
args[i] = args.android[i];
else
for (var i in args.ios || {})
args[i] = args.ios[i];
for (var i in names)
if (!(i in args))
throw new Error("Missing Argument - "+i);
if (defaults)
for (i in defaults)
if (!(i in args))
args[i] = defaults[i];
return null;
},
_PNRegSuccess: function(data, forceRegistration) {
this.regid = data.registrationId;
var _this = this;
console.info("PNRegSucess", data);
this._getSetting("boxcar_reginfo", null, function(regInfo) {
if (!_this._rdData)
return;
var fields = {mode: _this._rdData.mode};
if (_this._rdData.tags)
fields.tags = _this._rdData.tags;
if (_this._rdData.udid)
fields.udid = _this._rdData.udid;
if (_this._rdData.alias)
fields.alias = _this._rdData.alias;
if (_this._rdData.appVersion)
fields.app_version = _this._rdData.appVersion;
fields.os_version = device.version;
fields.name = device.model;
var keys = [];
for (var i in fields) {
var val = i == "tags" ? fields[i].sort().join(" ") : fields[i];
keys.push(i+":"+val);
}
var hash = _this.crypto.sha1(keys.sort().join("\n"));
if (forceRegistration || !regInfo ||
regInfo.regid != _this.regid ||
regInfo.hash != hash ||
regInfo.time < Date.now()-24*60*60*1000)
{
_this._sendRequest("PUT", "/api/device_tokens/"+_this.regid,
fields,
function(data) {
_this._setSetting("boxcar_reginfo", {regid: _this.regid, time: Date.now(), hash: hash});
_this._rdData.onsuccess(data);
},
_this._rdData.onerror);
} else
_this._rdData.onsuccess({ok:"Success", subscribed_to: _this._rdData.tags});
});
},
_PNRegError: function(data) {
console.info("ServiceOp failed: "+data.message);
this._rdData.onerror();
this._rdData = null;
},
_sendRequest: function(method, url, data, success, error, expires) {
if (!expires)
expires = 5*60*1000;
var empty = true;
for (var i in data)
empty = false;
var dataStr;
if (empty) {
dataStr = "";
} else {
expires += Date.now();
data.expires = expires;
dataStr = JSON.stringify(data);
}
var signData = method+"\n"+
this.server.replace(/^(?:\w+:\/\/)?([^:]*?)(?::\d+)?(?:\/.*)?$/, "$1").toLowerCase()+"\n"+
url+"\n"+
dataStr;
var signature = this.crypto.sha1_hmac(this.secret, signData);
console.info("Sending to "+this.server+url+"?clientkey="+this.clientKey+"&signature="+signature+
" data: "+dataStr+ " signData: "+signData);
var req = new XMLHttpRequest();
req.open(method, this.server+url+"?clientkey="+this.clientKey+"&signature="+signature);
req.setRequestHeader("Content-type", "application/json");
req.onreadystatechange = function() {
console.info("GOT RES: "+ req.readyState+", "+req.status+", "+req.responseText);
if (req.readyState == 4) {
if (req.status == 200 || req.status == 0 || req.status == 204)
success(req.responseText);
else
error(req.status, req.responseText);
}
};
req.send(dataStr);
},
_gotMessage: function(msg, fromNotificationClick) {
var _this = this;
msg.seen = false;
this.db.transaction(function(tx) {
tx.executeSql("INSERT INTO pushes (id, time, body, badge, sound, richPush, url, flags, extras) "+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
[+msg.id, msg.time, msg.body||"", msg.badge, msg.sound||"", msg.richPush, msg.url,
0, msg.extras ? JSON.stringify(msg.extras) : null]);
}, function(err) {
if (err.code != err.CONSTRAINT_ERR)
console.info("_gotMessage db error: ("+err.code+") "+err.message);
if (fromNotificationClick && _this.onnotificationclick)
_this.onnotificationclick(msg);
}, function() {
if (_this.onalert)
_this.onalert(msg);
if (fromNotificationClick && _this.onnotificationclick)
_this.onnotificationclick(msg);
});
},
crypto: {
string2bin: function(data) {
var ret = new Array(data.length>>2);
var i;
for (i = 0; i < data.length; i+=4)
ret[i>>2] = ((data.charCodeAt(i) & 0xff) << 24) |
((data.charCodeAt(i+1) & 0xff) << 16) |
((data.charCodeAt(i+2) & 0xff) << 8) |
(data.charCodeAt(i+3) & 0xff);
for (; i < data.length; i++)
ret[i>>2] |= (data.charCodeAt(i) & 0xff) << ((i%4)<<3);
return ret;
},
bin2hex: function(data) {
var hexchars = "0123456789abcdef";
var ret = "";
for (var i = 0; i < data.length; i++) {
ret+= hexchars.charAt((data[i]>>28)&0xf)+hexchars.charAt((data[i]>>24)&0xf)+
hexchars.charAt((data[i]>>20)&0xf)+hexchars.charAt((data[i]>>16)&0xf)+
hexchars.charAt((data[i]>>12)&0xf)+hexchars.charAt((data[i]>>8)&0xf)+
hexchars.charAt((data[i]>>4)&0xf)+hexchars.charAt(data[i]&0xf);
}
return ret;
},
madd: function(x, y) {
return ((x&0x7FFFFFFF) + (y&0x7FFFFFFF)) ^ (x&0x80000000) ^ (y&0x80000000);
},
bitroll: function(x, r) {
return (x << r) | (x >>> (32-r));
},
sha1_ft: function(t, b, c, d) {
if(t < 20)
return (b & c) | ((~b) & d);
if(t < 40)
return b ^ c ^ d;
if(t < 60)
return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
},
sha1_bin: function(data, length) {
var W = new Array(80);
var A, B, C, D, E;
var A2, B2, C2, D2, E2;
var i, t, tmp;
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
data[length >> 5] |= 0x80 << (24 - length % 32);
data[((length + 64 >> 9) << 4) + 15] = length;
A = 0x67452301;
B = 0xefcdab89;
C = 0x98badcfe;
D = 0x10325476;
E = 0xc3d2e1f0;
for (i = 0; i < data.length; i+=16) {
A2 = A;
B2 = B;
C2 = C;
D2 = D;
E2 = E;
for (t = 0; t < 80; t++) {
W[t] = t < 16 ? data[t+i] :
this.bitroll(W[t-3] ^ W[t-8] ^ W[t- 14] ^ W[t-16], 1);
tmp = this.madd(this.madd(this.bitroll(A, 5), this.sha1_ft(t, B, C, D)),
this.madd(this.madd(E, W[t]), K[Math.floor(t/20)]));
E = D;
D = C;
C = this.bitroll(B, 30);
B = A;
A = tmp;
}
A = this.madd(A, A2);
B = this.madd(B, B2);
C = this.madd(C, C2);
D = this.madd(D, D2);
E = this.madd(E, E2);
}
return new Array(A, B, C, D, E);
},
sha1_hmac_bin: function(key, data) {
var bkey = this.string2bin(key, true);
if (bkey.length > 16)
bkey = this.sha1_bin(bkey, key.length * 8);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = this.sha1_bin(ipad.concat(this.string2bin(data)), 512 + data.length * 8);
return this.sha1_bin(opad.concat(hash), 512 + 160);
},
sha1: function sha1(data) {
return this.bin2hex(this.sha1_bin(this.string2bin(data), data.length*8));
},
sha1_hmac: function sha1_hmac(key, data) {
return this.bin2hex(this.sha1_hmac_bin(key, data));
}
},
_Notification: function(data) {
console.log("Notification",data);
var known_fields = {
"i": 1,
"notId": 1,
"f": 1,
"u": 1,
"foreground": 1,
"priority": 1
};
var extras = {};
for (var p in data.additionalData) {
if (!(p in known_fields))
extras[p] = data.additionalData[p];
}
var id = data.additionalData.notId || data.additionalData.i;
var msg = {
id: id,
time: Date.now(),
sound: data.sound,
badge: parseInt(data.count) || 0,
body: data.message,
richPush: data.additionalData.f == "1",
url: data.additionalData.f == "1" ?
this.richUrlBase+"/push-"+id+".html" :
data.additionalData.u,
extras : extras
};
Boxcar._gotMessage(msg, data.notificationclick || data.additionalData.foreground == false);
}
};
if (typeof(module) != "undefined")
module.exports = Boxcar;
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
import DoneIcon from '@material-ui/icons/Done';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
padding: theme.spacing(0.5),
},
chip: {
margin: theme.spacing(0.5),
},
}));
export default function ChipsArray(props) {
const classes = useStyles();
let skills = []
//recibo las skills como props y las mapeo para crear un array de objetos clave valor valido
if(props.skills){
props.skills.map(skill=>{
return skills.unshift({id: skill.id, name: skill.name});
});
}
const [chipData] = React.useState(skills);
return (
<Paper className={classes.root}>
{chipData.map(data => {
return (
<Chip
key={data.id}
icon={<DoneIcon />}
label={data.name}
// onDelete={data.label === 'React' ? undefined : handleDelete(data)}
className={classes.chip}
/>
);
})}
</Paper>
);
}
|
var _ = require("underscore"),
request = require("superagent"),
Promise = require("promise"),
{ DOMParser } = require("xmldom"),
xpath = require("xpath"),
fasta = require("fasta-parser");
const ENTREZ_URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";
const SEARCH_URL = `${ENTREZ_URL}/esearch.fcgi`;
const FETCH_URL = `${ENTREZ_URL}/efetch.fcgi`;
function resolveOrReject(resolve, reject) {
return function (resp) {
if (resp.statusType === 2 || resp.statusType === 3) {
resolve(resp);
} else {
reject(resp);
}
};
}
module.exports = {
loadDna(id) {},
parseFastaSequence(text, many) {
many = many || false;
var fastaText = new Buffer(text),
parser = fasta(),
fastaResults = [];
parser.on("data", (data) => {
fastaResults.push(JSON.parse(data.toString()));
});
parser.write(fastaText);
parser.end();
if (many) {
return fastaResults.map(r => r.seq);
} else {
return fastaResults[0].seq;
}
},
parseGeneMetadata(text) {
var xml, xmlPaths;
xml = new DOMParser().parseFromString(text);
xmlPaths = {
base: [
"//Entrezgene",
],
common: [
"Entrezgene_locus",
"Gene-commentary",
"Gene-commentary_seqs",
"Seq-loc",
"Seq-loc_int",
"Seq-interval"
],
start: ["Seq-interval_from"],
end: ["Seq-interval_to"],
identifier: ["Seq-interval_id", "Seq-id", "Seq-id_gi"],
strand: ["Seq-interval_strand", "Na-strand", "@value"],
lineage: [
// "Entrezgene_source",
// "BioSource",
// "Biosource_org",
// "Org-ref",
// "Org-ref_orgname",
"//OrgName",
"/OrgName_lineage"
],
taxName: [
// "Entrezgene_source",
// "BioSource",
// "Biosource_org",
"//Org-ref",
"/Org-ref_taxname"
],
geneName: [
// "Entrezgene_gene",
"//Gene-ref",
"/Gene-ref_locus"
],
proteinName: [
// "Entrezgene",
// "Entrezgene_prot",
"//Prot-ref",
// "Prot-ref_name",
"/Prot-ref_name_E"
]
};
var extract = (key, xml, opts) => {
var defaults = {
common: true,
type: "data"
};
opts = _.extend({}, defaults, opts);
var path = xmlPaths[key];
if (opts.common) {
path = xmlPaths.common.concat(path);
}
var elem = xpath.select(path.join("/"), xml);
if (opts.type === "data") {
if (elem && elem.length) {
return elem[0].firstChild.data;
} else {
return null;
}
} else {
return elem.value;
}
};
return xpath.select(xmlPaths.base.join("/"), xml).map((gene) => {
try {
return {
seq_start: parseInt(extract("start", gene), 10) + 1,
seq_stop: parseInt(extract("end", gene), 10) + 1,
id: extract("identifier", gene),
strand: extract("strand", gene, { type: "value" }),
lineage: extract("lineage", gene, { common: false }),
taxName: extract("taxName", gene, { common: false }),
geneName: extract("geneName", gene, { common: false }),
proteinName: extract("proteinName", gene, { common: false })
};
} catch (e) {
return null;
}
}).filter((g) => !!g);
},
loadGeneSequence(opts, many) {
many = many || false;
return new Promise((resolve, reject) => {
request.get(FETCH_URL).
query({ db: "nucleotide" }).
query(opts).
query({ rettype: "fasta" }).
query({ retmode: "text" }).
// Needed on server for multipart:
// buffer().
end(resolveOrReject(resolve, reject));
}).then((resp) => this.parseFastaSequence(resp.text, many)).
catch((resp) => console.warn("Request failed", resp));
},
loadGeneMetadata(opts) {
return new Promise((resolve, reject) => {
request.get(FETCH_URL).
query({ db: "gene" }).
query({ term: opts.search }).
query({ retmode: "xml" }).
query({ webenv: opts.cacheInfo.esearchresult.webenv }).
query({ query_key: opts.cacheInfo.esearchresult.querykey }).
end(resolveOrReject(resolve, reject));
}).then((resp) => {
return this.parseGeneMetadata(resp.text)
});
},
loadGenesFromSearch(search) {
return new Promise((resolve, reject) => {
request.get(SEARCH_URL).
query({ db: "gene" }).
query({ term: search }).
query({ usehistory: "y" }).
query({ retmode: "json" }).
end(resolveOrReject(resolve, reject));
}).then((resp) => {
return resp.body;
});
},
loadDnaCollection(search) {
return this.loadGenesFromSearch(search).then((cacheInfo) => {
return this.loadGeneMetadata({
cacheInfo: cacheInfo,
search: search
});
});
}
};
|
import React from 'react';
import LogoAboutPage from '../components/LogoAboutPage';
import AboutPage from '../components/AboutPage';
import '/client/landing.css';
export default class About extends React.Component {
componentDidMount() {
document.title = "OWO - About Us"
}
render() {
return (
<div>
<LogoAboutPage/>
<AboutPage/>
</div>
);
}
}
|
import axios from 'axios'
export default {
// a dummy sever wake up
wakeFileUploadApp() {
axios({
method: 'GET',
url: 'https://core-util.herokuapp.com/'
})
},
sendFileData(imageFile) {
const bodyFormData = new FormData();
bodyFormData.append('upl', imageFile);
return axios({
method: 'POST',
url: 'https://core-util.herokuapp.com/upload',
data: bodyFormData,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
}
}
|
define(['unicorn.tables'], function(){
wgn.console('gateways module loaded','f');
});
|
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var plumber = require('gulp-plumber');
//setting
var settings = require('../gulpfile_settings');
gulp.task('css', function () {
return gulp.src(
[ settings.watch.cssBase.dir ]
)
.pipe(plumber())
.pipe(
postcss(
[
autoprefixer({browsers: ['last 5 version']}),
require('postcss-nested')
]
)
)
.pipe(
gulp.dest( settings.dest.css.dir )
);
});
|
import React, { useEffect, useState } from 'react';
import { emojisService } from '../services/emojisService'
import InsertEmoticonIcon from '@material-ui/icons/InsertEmoticon';
import PetsIcon from '@material-ui/icons/Pets';
import LocalBarIcon from '@material-ui/icons/LocalBar';
import SportsSoccerIcon from '@material-ui/icons/SportsSoccer';
import DriveEtaIcon from '@material-ui/icons/DriveEta';
import EmojiObjectsIcon from '@material-ui/icons/EmojiObjects';
import EmojiSymbolsIcon from '@material-ui/icons/EmojiSymbols';
import AccessTimeIcon from '@material-ui/icons/AccessTime';
import { storageService } from '../services/storageService'
export default function EmojiKeyboard({ addEmoji }) {
const [elContainer, setElContainer] = useState(null);
const [scrollTop, setScrollTop] = useState(0);
const [elEmojisGroup, setElEmojisGroup] = useState({});
const [currDiv, setCurrDiv] = useState(0);
const [recent, setRecent] = useState([]);
const emojis = emojisService.query();
useEffect(() => {
if (elEmojisGroup.animal &&
elEmojisGroup.food &&
elEmojisGroup.sport &&
elEmojisGroup.travel &&
elEmojisGroup.oblect &&
elContainer) {
if (scrollTop < elEmojisGroup.smileys.offsetTop - elContainer.offsetTop) setCurrDiv(0);
else if (scrollTop < elEmojisGroup.animal.offsetTop - elContainer.offsetTop) setCurrDiv(1);
else if (scrollTop < elEmojisGroup.food.offsetTop - elContainer.offsetTop) setCurrDiv(2);
else if (scrollTop < elEmojisGroup.sport.offsetTop - elContainer.offsetTop) setCurrDiv(3);
else if (scrollTop < elEmojisGroup.travel.offsetTop - elContainer.offsetTop) setCurrDiv(4);
else if (scrollTop < elEmojisGroup.oblect.offsetTop - elContainer.offsetTop) setCurrDiv(5);
else if (scrollTop < elEmojisGroup.symbols.offsetTop - elContainer.offsetTop) setCurrDiv(6);
else setCurrDiv(7)
}
}, [scrollTop])
useEffect(() => {
const newRecent = storageService.loadFromStorage('recentEmojis');
if (newRecent) setRecent(newRecent)
}, [])
function onAddEmoji(addedEmoji) {
const idx = recent.findIndex(emoji => emoji === addedEmoji);
if (idx === -1) {
storageService.saveToStorage('recentEmojis', [addedEmoji, ...recent])
setRecent(prevState => [addedEmoji, ...prevState]);
} else {
const newRecent = recent.filter((emoji, emojiIdx) => idx !== emojiIdx);
storageService.saveToStorage('recentEmojis', [addedEmoji, ...newRecent])
setRecent([addedEmoji, ...newRecent]);
}
addEmoji(addedEmoji)
}
return (
<div className='emoji-keyboard'>
<div className="nav flex">
<div className={currDiv === 0 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.recent.offsetTop - elContainer.offsetTop) }} ><AccessTimeIcon /></div>
<div className={currDiv === 1 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.smileys.offsetTop - elContainer.offsetTop) }} ><InsertEmoticonIcon /></div>
<div className={currDiv === 2 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.animal.offsetTop - elContainer.offsetTop) }}><PetsIcon /></div>
<div className={currDiv === 3 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.food.offsetTop - elContainer.offsetTop) }} ><LocalBarIcon /></div>
<div className={currDiv === 4 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.sport.offsetTop - elContainer.offsetTop) }}><SportsSoccerIcon /></div>
<div className={currDiv === 5 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.travel.offsetTop - elContainer.offsetTop) }}><DriveEtaIcon /></div>
<div className={currDiv === 6 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.oblect.offsetTop - elContainer.offsetTop) }}><EmojiObjectsIcon /></div>
<div className={currDiv === 7 ? 'curr' : ''} onClick={() => { elContainer.scrollTo(0, elEmojisGroup.symbols.offsetTop - elContainer.offsetTop) }} ><EmojiSymbolsIcon /></div>
</div>
<div ref={(el) => setElContainer(el)} onScroll={() => { setScrollTop(elContainer.scrollTop); }} className="container">
<div ref={(el) => { if (el && !elEmojisGroup.recent) setElEmojisGroup(prevState => ({ ...prevState, recent: el })) }} ></div>
<p>Recent</p>
<div className="emojies-container">
{recent.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.smileys) setElEmojisGroup(prevState => ({ ...prevState, smileys: el })) }} ></div>
<p>{'Smileys & People'}</p>
<div className="emojies-container">
{emojis.smileys.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
{emojis.bodyParts.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
{emojis.people.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
{emojis.accessories.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.animal) setElEmojisGroup(prevState => ({ ...prevState, animal: el })) }} ></div>
<p>{'Animal & Nature'}</p>
<div className="emojies-container">
{emojis.animal.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.food) setElEmojisGroup(prevState => ({ ...prevState, food: el })) }} ></div>
<p>{'Food & Drink'}</p>
<div className="emojies-container">
{emojis.food.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.sport) setElEmojisGroup(prevState => ({ ...prevState, sport: el })) }} ></div>
<p>Activity</p>
<div className="emojies-container">
{emojis.sport.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.travel) setElEmojisGroup(prevState => ({ ...prevState, travel: el })) }} ></div>
<p>{'Travel & Places'}</p>
<div className="emojies-container">
{emojis.travel.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.oblect) setElEmojisGroup(prevState => ({ ...prevState, oblect: el })) }} ></div>
<p>Objects</p>
<div className="emojies-container">
{emojis.oblect.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
<div ref={(el) => { if (el && !elEmojisGroup.symbols) setElEmojisGroup(prevState => ({ ...prevState, symbols: el })) }} ></div>
<p>Symbols</p>
<div className="emojies-container">
{emojis.symbols.map((emoji, idx) => <span key={idx} onClick={() => { onAddEmoji(emoji) }}>{emoji}</span>)}
</div>
</div>
</div>
)
}
|
// Native dependencies.
const path = require('path');
// Webpack dependencies.
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// Constants defines.
const srcDir = path.resolve('./examples');
const distDir = path.resolve('./examples_dist');
module.exports = (env, {
sourceMap
}) => {
const STYLE_LOADER = [
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: 'css-loader',
options: {
sourceMap
}
}]
}, {
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: 'css-loader',
options: {
sourceMap
}
}, {
loader: 'resolve-url-loader'
}, {
loader: 'sass-loader',
options: {
sourceMap: true
}
}]
}, {
test: /\.less$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: 'css-loader',
options: {
sourceMap
}
}, {
loader: 'less-loader',
options: {
sourceMap
}
}]
}
];
const COMPILER_LOADER = [
{
test: /\.(ts|tsx)$/,
exclude: [/node_modules/, /\.old$/],
use: [{
loader: 'ts-loader'
}]
}, {
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
];
const ASSETS_LOADER = [
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8196,
name: 'assets/img/[name].[hash].[ext]',
fallback: 'file-loader'
}
}]
}, {
test: /\.(eot|ttf|woff)$/,
use: [{
loader: 'file-loader',
options: {
name: 'assets/fonts/[name].[hash].[ext]',
fallback: 'file-loader'
}
}]
}
];
return {
entry: {
app: path.join(srcDir, 'index.tsx'),
vendor: ['react', 'react-dom']
},
output: {
path: distDir,
filename: '[name].[hash].js'
},
resolve: {
alias: {
assets: path.join(srcDir, 'assets'),
'ui-variables.less': path.join(srcDir, 'examples/ui-variables.less'),
},
extensions: ['.ts', '.tsx', '.js', '.json']
},
plugins: [
new HtmlWebPackPlugin({
template: path.join(srcDir, 'index.html'),
filename: './index.html'
})
],
module: {
rules: [
...STYLE_LOADER,
...COMPILER_LOADER,
...ASSETS_LOADER
]
}
}
};
|
var resize________________8js________8js____8js__8js_8js =
[
[ "resize________8js____8js__8js_8js", "resize________________8js________8js____8js__8js_8js.html#ac1dc9ad426416305a4d520de207e5d2b", null ]
];
|
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/interactive-supports-focus */
import React from 'react';
import { withRouter } from 'react-router-dom';
import { defaultPhoto100 } from '../../constants/defaultPhotos';
import {
StyledFollowingsSection,
StyledFollowingsCard
} from '../../containers/ProfilePrivate/styles';
const ProfileFollowers = ({
groupA,
following,
UnfollowFunc,
FollowFunc,
history
}) => {
return (
<StyledFollowingsSection>
{following.map(val => {
let commonGroup = [];
if (groupA) {
commonGroup = groupA.filter(
item => item.followed === val.followed
);
}
return (
<StyledFollowingsCard
key={val.followed}
att={commonGroup.length}
att2={!groupA}
>
<div
role="button"
onClick={() =>
history.push(`/profile/${val.user_public_id}`)
}
>
<img
alt={val.followed}
src={val.user_photo100 || defaultPhoto100}
width="100px"
/>
<p>{val.email}</p>
</div>
<div>
{!groupA ? (
<button
type="button"
onClick={() => UnfollowFunc(val.followed)}
>
Following
</button>
) : commonGroup.length === 1 ? (
<button
type="button"
onClick={() => UnfollowFunc(val.followed)}
>
Following
</button>
) : (
<button
type="button"
onClick={() => FollowFunc(val.followed)}
>
Follow
</button>
)}
</div>
</StyledFollowingsCard>
);
})}
</StyledFollowingsSection>
);
};
export default withRouter(ProfileFollowers);
|
function ObjAjax() {
var xmlhttp = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; }
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); }
return xmlhttp;
}
function BorrarNoticia(id, url) {
$.confirm({
title: 'Confirmación!',
content: '¿Esta seguro que desea eliminar esta noticia?',
buttons: {
Confirmar: function() {
$.alert('Se ha eliminado correctamente');
var result = document.getElementById('tview');
const ajax = new XMLHttpRequest();
ajax.open("POST", "main.php", true);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
result.innerHTML = ajax.responseText;
} else {
console.log("Ups, Me equivoque;");
}
}
};
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("ctrl=noticia&acti=eliminar&id=" + id + "&url=" + url);
},
Cancelar: function() {
$.alert('Has cancelado la eliminación');
}
}
});
}
function InsertNoticia() {
var paquete = new FormData();
paquete.append('archivo', $('#file-news')[0].files[0]);
var destino = "main.php?ctrl=noticia&acti=insertar";
$.ajax({
url: destino,
type: 'POST',
contentType: false,
data: paquete,
processData: false,
cache: false,
success: function(resultado) {
document.getElementById('tview').innerHTML = resultado;
},
error: function() {
alert('Algo anda mal');
}
});
}
var urlEdit;
function EditarNoticia(id, url) {
$.confirm({
title: 'Confirmación!',
content: '¿Esta seguro que desea editar esta noticia?',
buttons: {
Confirmar: function() {
urlEdit = url;
document.formulario.idnews.value = id;
document.getElementById("btnguardar").innerHTML = "Actualizar";
$("#noticiaModal").modal("show");
document.getElementById("titlenoticias").innerHTML = "Actualizar Noticia";
},
Cancelar: function() {
$.alert('Has cancelado la edición');
}
}
});
}
function UpdateNoticia() {
//var result = document.getElementById('tview');
var id = document.formulario.idnews.value;
var paquete = new FormData();
paquete.append('archivo', $('#file-news')[0].files[0]);
var destino = "main.php?ctrl=noticia&acti=actualizar&id=" + id + "&url=" + urlEdit;
$.ajax({
url: destino,
type: 'POST',
contentType: false,
data: paquete,
processData: false,
cache: false,
success: function(resultado) {
document.getElementById('tview').innerHTML = resultado;
},
error: function() {
alert('Algo anda mal');
}
});
$('#noticiaModal').modal('hide');
document.getElementById("btnguardar").innerHTML = "Subir";
document.getElementById("titlenoticias").innerHTML = "Subir Archivo";
urlEdit = "";
}
function CancelarNoticia() {
document.getElementById("titlenoticias").innerHTML = "Subir Archivo";
}
|
import { object, string, number, boolean } from 'yup'
const dogSchema = object().shape({
name: string().max(20).required(),
age: number().min(1).max(20).required(),
isPedigree: boolean().optional().default(false)
})
export default dogSchema
|
import React from "react";
import { Component } from 'react';
import {Trail, config} from 'react-spring/renderprops'
export class Header extends Component {
constructor(props){
super(props);
this.items = [];
for (let i = 0; i < props.text.length; i++){
this.items.push({
item: props.text[i],
key: i
});
}
if (this.props.text.length <= 9){
this.configuration = config.wobbly;
}
else {
this.configuration = config.stiff;
}
}
render(){
return(
<h1>
<strong>
<Trail items={this.items}
keys={item => item.key}
from={{opacity:0}}
to={{opacity:1}}
config={this.configuration}
>
{item => props => <span style={props}>{item.item}</span>}
</Trail>
</strong>
</h1>
);
}
}
|
const config = {
host: '47.95.204.85', // 数据库地址
user: 'root', // 数据库用户
password: '123456', // 数据库密码
database: 'test' // 选中数据库
}
module.exports = config;
|
import { headerMdHeight, headerSmHeight } from '../../assets/themes'
export default (theme) => ({
root: {
width: '90%'
},
button: {
marginTop: theme.spacing.unit,
marginRight: theme.spacing.unit,
[theme.breakpoints.up('md')]: {
marginTop: headerMdHeight
},
[theme.breakpoints.down('sm')]: {
marginTop: headerSmHeight
}
},
actionsContainer: {
marginBottom: theme.spacing.unit * 2
},
resetContainer: {
padding: theme.spacing.unit * 3
},
formControl: {
margin: theme.spacing.unit * 3
},
group: {
margin: `${theme.spacing.unit}px 0`
}
})
|
import React, { Fragment } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
useLocation,
useRouteMatch,
Link,
} from "react-router-dom";
import Usernavbar from "../layouts/userprofilenavbar";
import ProfileHeader from "../layouts/profileheader";
import ProfileAbout from "../layouts/profileabout";
import ProfileImage from "../layouts/profileimage";
import Profilesmallnav from "../layouts/profileaboutphoto";
const Userprofile = () => {
let { path, url } = useRouteMatch();
console.log(path, url);
return (
<Fragment>
<header>
<Usernavbar></Usernavbar>
</header>
<Router>
<main>
<ProfileHeader></ProfileHeader>
{/* <Profilesmallnav ></Profilesmallnav> */}
<div>
<Link to={`${url}/about/`}>About</Link>
<Link to="/userprofile/photos/">Photos</Link>
</div>
<Route
path /* */={`${path}/photos/`} /* "/userprofile/photos/" */
component={ProfileImage}
></Route>
<Route path="/userprofile/about/" component={ProfileAbout}></Route>
</main>
</Router>
</Fragment>
);
};
export default Userprofile;
|
const petOwnerData = require("./petOwner");
const homepageData = require("./homepage");
const petsData = require("./pets");
const messages = require("./messages");
const shelterAndRescueData = require("./shelterAndRescue");
module.exports = {
homepageData: homepageData,
pets: petsData,
petOwnerData: petOwnerData,
messages: messages,
shelterAndRescueData: shelterAndRescueData,
};
|
import React, { useState } from 'react'
import { Card, CardBody, CardTitle } from 'reactstrap';
const Products = ({ products, onCreate }) => {
const [name, setName] = useState("");
const resetForm = () => {
setName("");
}
return (
<div className="dp-card-wrapper">
<Card className="dp-card">
<CardTitle>
<h5 className="dp-card__title">Ürünler</h5>
</CardTitle>
<CardBody className="dp-card__body">
<div className="dp-card__item-list">
{products.map(field => {
return (
<div className="dp-card__item" key={field.id}>
<span>
{field.name}
</span>
</div>
)
})}
</div>
<form className="dp-card__form" onSubmit={(e) => { e.preventDefault(); resetForm(); return onCreate({ name }) }}>
<div class="form-row">
<div className="col">
<input type="text" value={name} onChange={(e) => setName(e.target.value)} className="form-control form-control-sm" id="name" placeholder="Ürün Adı" />
</div>
<button type="submit" className="btn btn-primary btn-sm">+</button>
</div>
</form>
</CardBody>
</Card>
</div>
)
}
export default Products;
|
const { MessageEmbed } = require("discord.js")
module.exports = async (client, guild) => {
const guildDB = await client.database.GuildSchema.findOne({ '_id': guild.id})
if (!guildDB) {
await client.database.GuildSchema.create({ '_id': guild.id })
}
}
|
var language;
var uid;
var selectedLanguage;
$(document).ready(function() {
uid = $('#uid').val();
$.get("/api/v1/getLanguage/" + uid, function(data) {
language = String(JSON.stringify(data.language));
language = language.slice(1, language.length-1)
console.log("language: " + language);
}).then(function() {
$('#language option[value="' + language + '"]').attr("selected", "selected");
});
$.get("./getAbbreviations/" + uid, function(data) {
var html ='';
for (var i = 0; i < data.length; i++) {
var d = data[i];
console.log(d.abbr + " --> " + d.full);
var row = '<tr> <td> <span class="index">' + (i+1) + '</span> </td> <td class="aid" style="display: none">' + d._id + '</td> <td>' + d.abbr + '</td> <td>' + d.full + '</td> <td> <i class="fa fa-minus-square" aria-hidden="true"></i> </td> </tr>'
html += row
}
var form = '<tr> <td> <span class="index">' + (data.length+1) + '</span> </td> <td style="display: none"> </td> <td> <input id="abbr" type="text" class="form-control" placeholder="Abbreviation"> </td> <td> <input id="full" class="form-control" placeholder="Full Term"> </td> <td> <i class="fa fa-plus-square" aria-hidden="true"></i> </td> </tr>';
html += form;
$('#abbrTableBody').html(html);
});
$('#selectLanguageForm').submit(function(e) {
e.preventDefault();
selectedLanguage = $('#language').val();
if (selectedLanguage != language) {
$.ajax({
type: "POST",
url: 'api/v1/selectLanguage' + '/' + uid + '/' + selectedLanguage,
data: { uid: uid, lang: selectedLanguage },
success: function(res) {
console.log('It worked! The language was changed to ' + selectedLanguage)
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
return false;
});
// delete abbreviations
$('#abbrTable').on('click', '.fa-minus-square', function(){
var row = $(this).parent().parent();
var aid = row.find('.aid').text();
$.ajax({
type: "POST",
url: '/api/v1/deleteAbbreviation/' + aid,
data: { aid: aid },
success: function(res) {
console.log('Deleted abbreviation:' + res.abbr + ' --> ' + res.full + '!')
$(row).hide('slow', function() {
$(row).remove();
renumberTable();
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
});
// add abbreviations
$('#abbrTable').on('click', '.fa-plus-square', function() {
var row = $(this).parent().parent();
var index = row.index();
var abbr = $('#abbr').val().trim().toLowerCase();
var full = $('#full').val().trim().toLowerCase();
$.ajax({
type: "POST",
url: '/api/v1/createAbbreviation/' + uid + '/' + abbr + '/' + full,
data: { uid: uid, abbr: abbr, full: full },
success: function(res) {
console.log('Added abbreviation:' + abbr + " --> " + full + '!')
$(row).remove();
var newRow = '<tr> <td> <span class="index">' + (index+1) + '</span> </td> <td class="aid" style="display: none">' + res._id + '</td> <td>' + abbr + '</td> <td>' + full + '</td> <td> <i class="fa fa-minus-square" aria-hidden="true"></i> </td> </tr>';
$('#abbrTable').append(newRow);
var form = '<tr> <td> <span class="index">' + (index+2) + '</span> </td> <td style="display: none"> </td> <td> <input id="abbr" type="text" class="form-control" placeholder="Abbreviation"> </td> <td> <input id="full" class="form-control" placeholder="Full Term"> </td> <td> <i class="fa fa-plus-square" aria-hidden="true"></i> </td> </tr>';
$('#abbrTable').append(form);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
});
});
function renumberTable() {
var renum = 1;
$("#abbrTable .index").each(function() {
$(this).text(renum);
renum += 1;
});
}
|
import React, { Component } from 'react';
import './Home.css';
class Home extends Component{
render() {
return(
<div>
<div>Welcome</div>
<p className='para1'>Tri-tip pork loin rump shank kielbasa swine. Cow andouille pork venison. Boudin landjaeger buffalo, short loin chicken shank tail pig sirloin. Pig tongue picanha, turkey buffalo jerky flank doner spare ribs pork t-bone ribeye fatback landjaeger. Prosciutto capicola drumstick, pork chop ball tip strip steak frankfurter biltong doner. Swine corned beef drumstick meatloaf. Ribeye sirloin bacon, hamburger chicken salami ham hock venison cow shank t-bone short ribs kielbasa tri-tip.</p><br/>
<p className='para2'>Jowl pig meatloaf sausage rump hamburger. Burgdoggen buffalo flank turducken pig kielbasa fatback tri-tip leberkas beef ribs landjaeger pork belly. Beef prosciutto leberkas frankfurter t-bone. Bacon rump ball tip, spare ribs short loin strip steak buffalo corned beef chicken picanha turducken pork chop filet mignon pork loin.</p>
<p className='para2'>Jowl pig meatloaf sausage rump hamburger. Burgdoggen buffalo flank turducken pig kielbasa fatback tri-tip leberkas beef ribs landjaeger pork belly. Beef prosciutto leberkas frankfurter t-bone. Bacon rump ball tip, spare ribs short loin strip steak buffalo corned beef chicken picanha turducken pork chop filet mignon pork loin.</p>
</div>
)
}
}
export default Home;
|
/**
* Created by lavystord on 16/9/10.
*/
module.exports = require("./qiniu.native");
|
const path = require('path');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SRC_DIR = path.resolve(__dirname, '..', 'src');
const DIST_DIR = path.resolve(__dirname, '..', 'dist');
module.exports = {
devtool: 'cheap-source-map',
entry: [
'babel-polyfill',
path.resolve(SRC_DIR, 'index.js')
],
output: {
path: DIST_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel', include: SRC_DIR },
{ test: /\.json$/, loader: 'json' },
{ test: /\.less$/, loader: 'style!css!postcss!less' }
]
},
postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'webpack/template.html',
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify("production")
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
};
|
import * as React from 'react';
import './Canvas.css'
var gameArea = document.getElementById('gameArea');
var widthToHeight = 4 / 3;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
// window width is too wide relative to desired game width
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
// window height is too high relative to desired game height
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = this.refs.canvas;
console.log(gameCanvas)
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
function resizeGame() {
var gameArea = document.getElementById("gameArea");
var widthToHeight = 4 / 3;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = this.refs.canvas;
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
}
window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);
class Canvas extends React.Component {
componentDidMount() {
const canvas = this.refs.canvas;
const context = canvas.getContext('2d');
context.rect(20, 20, 150, 100);
context.fill();
}
render() {
return(
<div id='gameArea' ref='gameArea'>
<canvas ref='canvas' width={400} height={400} />
</div>
)
}
}
export default Canvas
|
/* --------------------------- INTUIT CONFIDENTIAL ---------------------------
spendingOvertime.js
Written by Date
Jason Harris 07/14/10
Revised by Date Summary of changes
Mickey Roberson 08/25/10 [S674] The SOT table is now composed of two separate
adjoining tables. The leftmost is fixed while
the rightmost scrolls horizontally.
Mickey Roberson 08/30/10 [DE1610] Integrated the deferred printing mechanics.
Mickey Roberson 08/30/10 [DE1594] Added stored state for the disclosure acuators.
Mickey Roberson 10/04/10 [DE1788] The clicked date is now passed back to Cocoa.
Mickey Roberson 10/13/10 [DE1799] Now passes back if the clicked amount was an expense.
Mickey Roberson 10/20/10 [DE1799] Correct parent cateogry/expense type is now passed back
Mickey Roberson 10/29/10 [DE1889] Now indicates that the report filter time range should be used
when clicking a category title on the left.
Mickey Roberson 10/29/10 [DE1621] Indented categories/tags will now be truncated with ellipsis
Copyright 2010 Intuit, Inc All rights reserved. Unauthorized
reproduction is a violation of applicable law. This material contains
certain confidential and proprietary information and trade secrets of
Intuit, Inc.
RESTRICTED RIGHTS LEGEND
Use, duplication, or disclosure by the Government is subject to
restrictions as set forth in subdivision (b) (3) (ii) of the Rights in
Technical Data and Computer Software clause at 52.227-7013.
Intuit, Inc
P.O. Box 7850
Mountain View, CA 94039-7850
----------------------------- INTUIT CONFIDENTIAL ------------------------- */
var gSpendingOverTimePrintToken = undefined;
function SpendingOverTimeInit()
{
gSpendingOverTimePrintToken = CreateDeferredPrintingToken();
FilterSettingsInit(true);
InitRows();
InitFixedRows();
}
function GraphHasDisplayed()
{
if(undefined != gSpendingOverTimePrintToken)
CheckInDeferredPrintingToken(gSpendingOverTimePrintToken);
}
function InitFixedRows() {
var rows = $('.tableFixedData tbody tr');
if(rows.length == 0 && undefined != gSpendingOverTimePrintToken)
CheckInDeferredPrintingToken(gSpendingOverTimePrintToken);
rows.each(function() {
var element = $(this);
var level = parseInt(element.attr('level'));
var padding = 14 + level * 14;
var firstTD = element.find("td:first");
var style = firstTD.attr("style");
if (undefined !== style)
style = style + " ";
else
style = "";
style = style + "padding-left: " + padding + "px;";
firstTD.attr("style", style);
// Need to reduce the width for padded cells to make the ellipsis
// work as expected.
if(padding > 14)
{
width = firstTD.css("width");
if(width == undefined)
width = 155; //Reasonable default value
width = parseInt(width);
// All of them are padded at least 14, so only adjust larger widths
width -= (padding-14);
firstTD.css("width", width + "px");
}
if (_ChildRows(element, false).length) {
element.addClass("collapsible");
element.addClass("opened");
//Check if there is stored state for the rows
if( window.viewController )
{
var stateID = _GenerateRowID(element);
var actuatorState = window.viewController.TableState( stateID, actuatorState );
if(actuatorState == "opened")
{
//Open the rows in this table
_OpenRows(element, true, false, false);
//Open the rows in the right side table
var valuesRow = $('#tableData tbody tr');
valuesRow.each(function() {
var valueRow = $(this);
if(valueRow.attr('quickenID') == element.attr('quickenID')) {
_OpenRows(valueRow, false, false, false);
}
});
} else {
//Close the rows in this table
_CloseRows(element, true, true);
//Close the rows in the right side table
var valuesRow = $('#tableData tbody tr');
valuesRow.each(function() {
var valueRow = $(this);
if(valueRow.attr('quickenID') == element.attr('quickenID')) {
_CloseRows(valueRow, true, false, false);
}
});
}
}
element.find("td:first-child").prepend("<span class='actuator'></span>");
element.click(function(e) {
var row =$(this);
var table = $('#tableData tbody');
var tableBody = $('tbody');
var tableOffset = (table.offset().left-table.position().left+tableBody.offset().left);
var disclosurePadding = 14;
//If the disoclure actuator is being clicked expand the rows
if(e.pageX >= tableOffset && e.pageX <= tableOffset+disclosurePadding) {
var childrenIncluded = e.altKey;
if (row.hasClass("closed")) {
_OpenRows(row, true, childrenIncluded, true);
var valuesRow = $('#tableData tbody tr');
valuesRow.each(function() {
var valueRow = $(this);
if(valueRow.attr('quickenID') == row.attr('quickenID')) {
_OpenRows(valueRow, true, childrenIncluded, false);
throw $break;
}
});
} else if (row.hasClass("opened")) {
_CloseRows(row, true, childrenIncluded, true);
var valuesRow = $('#tableData tbody tr');
valuesRow.each(function() {
var valueRow = $(this);
if(valueRow.attr('quickenID') == row.attr('quickenID')) {
_CloseRows(valueRow, true, childrenIncluded, false);
throw $break;
}
});
}
} else { //Otherwise open the selected row or it's parent category in category explorer
var qID = row.attr("quickenID");
if(qID.substring(qID.length-1,qID.length) == "u")
{
var parentCategoryRow = FindParentCategoryRowForChild(this);
CategoryRowClicked(parentCategoryRow.attr("quickenID"), "Total", true);
} else {
CategoryRowClicked(row.attr("quickenID"), "Total", true);
}
}
return false;
});
} else {
element.click(function(e) {
var row = $(this);
var qID = row.attr("quickenID");
if(IsATagID(qID))
{
var parentCategoryRow = FindParentCategoryRowForChild(this);
CategoryRowClicked(parentCategoryRow.attr("quickenID"), "Total", true);
} else {
CategoryRowClicked(row.attr("quickenID"), "Total", true);
}
});
}
});
}
function ColumnHeaderValueForIndex(colIndex)
{
var headerCols = $('#tableData thead td');
return headerCols[colIndex].textContent;
}
function InitRows() {
var rows = $('#tableData tbody tr');
rows.each(function() {
var element = $(this);
if (_ChildRows(element, false).length) {
element.addClass("collapsible");
element.addClass("opened");
}
element.click(function(e) {
var colIndex = $(this).children().index(e.target);
var colDate = ColumnHeaderValueForIndex(colIndex);
var row = $(this);
var qID = row.attr("quickenID");
var isExpense = ($(e.target).hasClass("negative") || $(e.target).hasClass("zero"));
if(IsATagID(qID))
{
var parentCategoryRow = FindParentCategoryRowForChild(this);
var parentElement = $(parentCategoryRow.children()[colIndex]);
// Since the parent category will be displayed, check the parent for isExpense
isExpense = parentElement.hasClass("negative") || parentElement.hasClass("zero");
CategoryRowClicked(parentCategoryRow.attr("quickenID"), colDate, isExpense);
} else {
CategoryRowClicked(row.attr("quickenID"), colDate, isExpense);
}
});
});
}
function IsUncategorizedID(quickenID)
{
return (quickenID == "uncategorized");
}
function IsACategoryID(quickenID)
{
return (quickenID.substring(quickenID.length-1, quickenID.length) == "c");
}
function IsATagID(quickenID)
{
return (quickenID.substring(quickenID.length-1, quickenID.length) == "u");
}
function FindParentCategoryRowForChild(childRowObject)
{
var rows = $('#tableData tbody tr');
var lastCategoryRow;
var indexCounter = 0;
var rowIndex = childRowObject.rowIndex;
var parentLevel = parseInt($(childRowObject).attr("level"), 10) - 1;
rows.each(function() {
if(indexCounter >= rowIndex) {
return false;
}
++indexCounter;
var row = $(this);
var qID = row.attr("quickenID");
var currentLevel = parseInt(row.attr("level"), 10);
//Must be a category and have the correct level
if((IsACategoryID(qID) || IsUncategorizedID(qID)) && (currentLevel == parentLevel))
{
lastCategoryRow = row;
}
});
return lastCategoryRow;
}
// Passing back the value "Total" for colDate will cause the corresponding
// Category Explorer to show the full date range of the report filter.
// Passing null for colDate will show all dates in the Category Explorer.
function CategoryRowClicked(categoryQuickenID, colDate, isExpense)
{
if( window.viewController )
window.viewController.ExploreCategoryWithQuickenIDs(categoryQuickenID, colDate, isExpense);
}
function CloseAllRows(animated) {
var rows = $('#tableData tbody tr.level0');
_CloseRows(rows, animated, true);
var rows = $('.tableFixedData tbody tr.level0');
_CloseRows(rows, animated, true);
}
function _ChildRows(rows, allLevels) {
if (0 == rows.length)
return;
var allRows = $($(rows[0]).parent().find("tr"));
var childRows = [];
rows.each(function () {
var element = $(this);
var level = parseInt(element.attr('level'));
var index = $.inArray(this, allRows);
for (var i = index + 1; i < allRows.length; ++i) {
var testRow = allRows[i];
var testLevel = parseInt($(testRow).attr('level'));
if (testLevel <= level)
break;
if (allLevels || testLevel == level + 1)
childRows.push(testRow);
}
});
return $(childRows);
}
function _OpenChildRows(rows) {
var childRows = _ChildRows(rows);
var allChildren = [];
childRows.each(function() {
allChildren.push(this);
var element = $(this);
if (element.hasClass("opened"))
allChildren = $.merge(allChildren, _OpenChildRows(element));
});
return $(allChildren);
}
// [DE1827] - Lane Roathe - can't use rows.animate because the animation
// which hides/shows the rows happens after printing
function _ShowHideRows(rows, show, animated) {
rows.each(function () {
this.style.display = show ? '' : 'none';
});
}
function _ShowRows(rows, animated) {
_ShowHideRows(rows, true, animated);
}
function _HideRows(rows, animated) {
_ShowHideRows(rows, false, animated);
}
function _OpenRow(row, animated, storeState) {
var childRows = _OpenChildRows(row);
_ShowRows(childRows, animated);
if (row.hasClass("closed"))
row.toggleClass("closed").toggleClass("opened");
if(storeState && window.viewController)
{
var stateID = _GenerateRowID(row);
window.viewController.SetTableState(stateID, "opened");
}
}
function _GenerateRowID(row)
{
var firstTD = row.find("td:first");
var stateID = firstTD[0].textContent + '_' + row.attr("quickenID");
return stateID;
}
function _CloseRow(row, animated, storeState) {
var childRows = _ChildRows(row, true);
_HideRows(childRows, animated);
if(storeState && window.viewController)
{
childRows.each(function() {
var stateID = _GenerateRowID($(this));
window.viewController.SetTableState(stateID, "closed");
});
}
if (row.hasClass("opened"))
row.toggleClass("opened").toggleClass("closed");
if(storeState && window.viewController)
{
var stateID = _GenerateRowID(row);
window.viewController.SetTableState(stateID, "closed");
}
}
function _OpenRows(rows, animated, childrenIncluded, storeState) {
if (0 == rows.length) return;
rows.each(function() {
_OpenRow($(this), animated, storeState);
});
if (childrenIncluded)
_OpenRows(_ChildRows(rows, false), false, childrenIncluded, storeState);
}
function _CloseRows(rows, animated, childrenIncluded, storeState) {
if (0 == rows.length) return;
rows.each(function() {
_CloseRow($(this), animated, storeState);
});
if (childrenIncluded)
_CloseRows(_ChildRows(rows, false), false, childrenIncluded, storeState);
}
|
const { movieLookup } = require("../tmdb/movie");
const { showLookup } = require("../tmdb/show");
const Request = require("../models/request");
const Sonarr = require("../services/sonarr");
const Radarr = require("../services/radarr");
const logger = require("../util/logger");
const Promise = require("bluebird");
async function getRequests(user = false, all = false) {
const requests = await Request.find();
let data = {};
let sonarr = new Sonarr();
let radarr = new Radarr();
try {
let sonarrQ = await sonarr.queue();
let radarrQ = await radarr.queue();
data = {};
await Promise.all(
requests.map(
async (request, i) => {
let children = [];
let media = [];
if (request.users.includes(user) || all) {
if (request.type === "movie" && request.radarrId.length > 0) {
for (let i = 0; i < Object.keys(request.radarrId).length; i++) {
let radarrIds = request.radarrId[i];
let rId = parseInt(radarrIds[Object.keys(radarrIds)[0]]);
let serverUuid = Object.keys(radarrIds)[0];
let server = new Radarr(serverUuid);
children[i] = {};
children[i].id = rId;
try {
children[i].info = await server.movie(rId);
children[i].info.serverName = server.config.title;
} catch {
children[i].info = { message: "NotFound" };
}
children[i].status = [];
if (radarrQ[serverUuid] && radarrQ[serverUuid].records) {
for (let o = 0; o < radarrQ[serverUuid].records.length; o++) {
if (radarrQ[serverUuid].records[o].movieId === rId) {
children[i].status.push(radarrQ[serverUuid].records[o]);
}
}
}
}
}
if (request.type === "tv" && request.sonarrId.length > 0) {
for (let i = 0; i < Object.keys(request.sonarrId).length; i++) {
let sonarrIds = request.sonarrId[i];
let sId = parseInt(sonarrIds[Object.keys(sonarrIds)[0]]);
let serverUuid = Object.keys(sonarrIds)[0];
let server = new Sonarr().serverDetails({ id: serverUuid });
children[i] = {};
children[i].id = sId;
try {
children[i].info = await new Sonarr().series(
{ id: serverUuid },
sId
);
children[i].info.serverName = server.title;
} catch (e) {
children[i].info = { message: "NotFound", error: e };
}
children[i].status = [];
if (sonarrQ[serverUuid] && sonarrQ[serverUuid].records) {
for (let o = 0; o < sonarrQ[serverUuid].records.length; o++) {
if (sonarrQ[serverUuid].records[o].seriesId === sId) {
children[i].status.push(sonarrQ[serverUuid].records[o]);
}
}
}
}
}
if (request.type === "movie") {
media = await movieLookup(request.requestId, true);
} else if (request.type === "tv") {
media = await showLookup(request.requestId, true);
}
data[request.requestId] = {
title: request.title,
children: children,
requestId: request.requestId,
type: request.type,
thumb: request.thumb,
imdb_id: request.imdb_id,
tmdb_id: request.tmdb_id,
tvdb_id: request.tvdb_id,
users: request.users,
sonarrId: request.sonarrId,
radarrId: request.radarrId,
media: media,
approved: request.approved,
manualStatus: request.manualStatus,
process_stage: reqState(request, children),
defaults: request.pendingDefault,
};
if (request.type === "tv") {
data[request.requestId].seasons = request.seasons;
}
}
},
{ concurrency: 20 }
)
);
} catch (err) {
console.log(err.stack);
logger.log("error", `ROUTE: Error getting requests display`);
logger.log({ level: "error", message: err });
data = requests;
}
return data;
}
function reqState(req, children) {
let diff;
if (!req.approved) {
return {
status: "pending",
message: "Pending",
step: 2,
};
}
if (children) {
if (children.length > 0) {
for (let r = 0; r < children.length; r++) {
if (children[r].status.length > 0) {
return {
status: "orange",
message: "Downloading",
step: 3,
};
}
if (children[r].info.downloaded || children[r].info.movieFile) {
return {
status: "good",
message: "Downloaded",
step: 4,
};
}
if (children[r].info.message === "NotFound") {
return {
status: "bad",
message: "Removed",
step: 2,
};
}
if (req.type === "tv" && children[r].info) {
if (
children[r].info.episodeCount ===
children[r].info.episodeFileCount &&
children[r].info.episodeCount > 0
) {
return {
status: "good",
message: "Downloaded",
step: 4,
};
}
if (children[r].info.seasons) {
let missing = false;
for (let season of children[r].info.seasons) {
if (season.monitored) {
if (
season.statistics &&
season.statistics.percentOfEpisodes !== 100
)
missing = true;
}
}
if (!missing && children[r].info.statistics.totalEpisodeCount > 0) {
return {
status: "good",
message: "Downloaded",
step: 4,
};
} else {
let airDate = children[r].info.firstAired;
if (!airDate)
return {
status: "blue",
message: "Awaiting Info",
step: 3,
};
diff = Math.ceil(new Date(airDate) - new Date());
if (diff > 0) {
return {
status: "blue",
message: `~${calcDate(diff)}`,
step: 3,
};
} else {
if (children[r].info.episodeFileCount > 0) {
return {
status: "blue",
message: "Partially Downloaded",
step: 3,
};
}
}
}
}
}
if (req.type === "movie" && children[r].info) {
if (children[r].info.inCinemas || children[r].info.digitalRelease) {
if (children[r].info.inCinemas) {
diff = Math.ceil(
new Date(children[r].info.inCinemas) - new Date()
);
if (diff > 0) {
return {
status: "blue",
message: `~${calcDate(diff)}`,
step: 3,
};
}
}
if (children[r].info.digitalRelease) {
let digitalDate = new Date(children[r].info.digitalRelease);
if (new Date() - digitalDate < 0) {
return {
status: "cinema",
message: "In Cinemas",
step: 3,
};
}
} else {
if (children[r].info.inCinemas) {
diff = Math.ceil(
new Date() - new Date(children[r].info.inCinemas)
);
if (cinemaWindow(diff)) {
return {
status: "cinema",
message: "In Cinemas",
step: 3,
};
}
}
}
}
if (children[r].info.status === "announced") {
return {
status: "blue",
message: "Awaiting Info",
step: 3,
};
}
}
}
return {
status: "bad",
message: "Unavailable",
step: 3,
};
}
}
if (req.manualStatus) {
switch (req.manualStatus) {
case 3:
return {
status: "orange",
message: "Processing",
step: 3,
};
case 4:
return {
status: "good",
message: "Finalising",
step: 4,
};
case 5:
return {
status: "good",
message: "Complete",
step: 5,
};
}
}
return {
status: "manual",
message: "No Status",
step: 3,
};
}
function calcDate(diff) {
var day = 1000 * 60 * 60 * 24;
var days = Math.ceil(diff / day);
var months = Math.floor(days / 31);
var years = Math.floor(months / 12);
days = days - months * 31;
months = months - years * 12;
var message = "";
message += years ? years + " yr " : "";
message += months ? months + " m " : "";
message += days ? days + " d " : "";
return message;
}
function cinemaWindow(diff) {
var day = 1000 * 60 * 60 * 24;
var days = Math.ceil(diff / day);
if (days >= 62) {
return false;
}
return true;
}
module.exports = { getRequests };
|
function filtrar() {
fetch ("http://localhost:8080/intervalo/" +
document.getElementById("txtinicio").value
+ "/" +
document.getElementById("txttermino").value)
.then(res => res.json())
.then(res => {
var tabela =
"<table border='1' align='center' width='100%'>" +
"<tr>" +
"<th align='center'>ID Evt</th>" +
"<th>Data</th>" +
"<th>Equipamento</th>" +
"<th>IP</th>" +
"<th>Alarme</th>" +
"<th>Descrição</th>" +
"</tr>";
for (contador=0;contador<res.length;contador++) {
tabela+=
"<tr>" +
"<td align='center'>" + res[contador].id + "</td>" +
"<td>" + res[contador].data + "</td>" +
"<td>" + res[contador].equipamento.nomeEquipamento + "</td>" +
"<td>" + res[contador].equipamento.numIp + "</td>" +
"<td>" + res[contador].alarme.nomeAlarme + "</td>" +
"<td>" + res[contador].alarme.descricao + "</td>" +
"</tr>";
}
tabela+="</table>";
document.getElementById("resultado").innerHTML = tabela;
})
.catch(err => {
window.alert("Nenhum evento encontrado")
});
}
function validausuario() {
var userstr = localStorage.getItem("userlogado");
if (userstr==null){
window.location = "login.html";
} }
function sair() {
localStorage.removeItem("userlogado");
window.location = "login.html"
}
|
// Packages
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import { connect } from 'react-redux';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
// Action Creators
import { setAuthedUser } from '../actions/authedUser';
// Material UI
import Avatar from '@material-ui/core/Avatar';
import { sarah, johndoe , tylermcginnis } from './Images'
class Navbar extends Component {
handleLogout = () => {
this.props.dispatch(setAuthedUser(null));
}
render() {
const { userName, userAvatar } = this.props;
return (
<div className='nav'>
<ul className='nav-list'>
<li className='nav-item'>
<NavLink to='/home' activeClassName='active'>
Home
</NavLink>
</li>
<li className='nav-item'>
<NavLink to='/add' activeClassName='active'>
New Question
</NavLink>
</li>
<li className='nav-item'>
<NavLink to='/leaderboard' activeClassName='active'>
Leaderboard
</NavLink>
</li>
<div class='space'> </div>
<li className='user-greeting'>
<span>Hey, {userName}!</span>
</li>
<li className='nav-item logout'>
<NavLink to='/' exact activeClassName='active' onClick={this.handleLogout}>
Log out
</NavLink>
</li>
<li className='user-avatar'>
<FontAwesomeIcon icon={userAvatar}/>
<Avatar alt='avatar' src={ [sarah, johndoe, tylermcginnis].find(x => x.includes(userAvatar)) }/>
</li>
</ul>
</div>
);
}
}
const mapStateToProps = ({ users, authedUser }) => {
const user = users[authedUser];
return {
userName: user ? user['name'] : '',
userAvatar: user ? user['avatarURL'] : ''
}
};
export default connect(mapStateToProps)(Navbar);
|
window.onload = function() {
const calc = new Calc();
const n = document.getElementById('n');
const start = document.getElementById('start');
const answer = document.getElementById('answer');
const answer1 = document.getElementById('first');
const answer2 = document.getElementById('second');
function writting () {
answer1.innerHTML = calc.first.join(', ');
answer2.innerHTML = calc.second.join(', ');
}
n.addEventListener('keyup', () => {
if (Math.round(n.value*1) != n.value*1) n.value = 10;
if (n.value*1 > 1) calc.creating(n.value*1);
writting();
});
start.addEventListener('click', () => {
calc.randomize();
writting();
});
}
|
import { GET_CONTACTS_SUCCESS, GET_CONTACTS_LOADING, GET_CONTACTS_FAIL } from "../../constants/actionTypes";
const contacts = (state, { type, payload }) => {
// used because API not authing because login not working
const tempData = [
{id: "1", first_name: 'ting1'},
{id: "2", first_name: 'ting2'},
{id: "3", first_name: 'ting3'},
{id: "4", first_name: 'ting1'},
{id: "5", first_name: 'ting2'},
{id: "6", first_name: 'ting3'},
{id: "7", first_name: 'ting1'},
{id: "8", first_name: 'ting2'},
{id: "9", first_name: 'ting3'},
{id: "10", first_name: 'ting1'},
{id: "11", first_name: 'ting2'},
{id: "12", first_name: 'ting3'},
{id: "13", first_name: 'ting1'},
{id: "14", first_name: 'ting2'},
{id: "15", first_name: 'ting3'},
{id: "16", first_name: 'ting1'},
{id: "17", first_name: 'ting2'},
{id: "18", first_name: 'ting3'},
]
switch (type) {
case GET_CONTACTS_LOADING:
return {
...state,
getContacts: {
...state.getContacts,
loading: true,
error: null
},
};
case GET_CONTACTS_SUCCESS:
return {
...state,
getContacts: {
...state.getContacts,
loading: false,
data: payload,
error: null
},
};
case GET_CONTACTS_FAIL:
return {
...state,
getContacts: {
...state.getContacts,
loading: false,
// error: payload <--- supposed to end with this
// for testing we will return contacts anyways
data: tempData,
error: null
},
};
default:
return state;
}
};
export default contacts;
|
if (typeof HMS == 'undefined' || !HMS) {
var HMS = {};
}
HMS.namespace = function () {
var a = arguments,
o = null,
i, j, d;
for (i = 0; i < a.length; i = i + 1) {
d = ('' + a[i]).split('.');
o = HMS;
for (j = (d[0] == 'HMS') ? 1 : 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
}
return o;
}
HMS.namespace('PhieuMo');
HMS.PhieuMo = function () {
var Global = {
UrlAction: {
},
Data: {
data: []
}
}
this.GetGlobal = function () {
return Global;
}
this.Init = function () {
RegisterEvent();
InitTable();
}
var RegisterEvent = function () {
}
function InitTable( ) {
Global.Data.table = $('#table-phieu-mo').DataTable({
responsive: true,
"data": Global.Data.data,
"dom": '<"top"<"col-sm-3 m-b-0 p-l-0"l><"col-sm-9 m-b-0"f><"clear">>rt<"bottom"<"col-sm-6 p-l-0"i><"col-sm-6 m-b-0"p><"clear">><"clear">',
"oLanguage": {
"sSearch": "Bộ lọc",
"sLengthMenu": "Hiển thị _MENU_ dòng mỗi trang",
"sInfo": "Hiển thị từ _START_ - _END_ trong _TOTAL_ dòng",
'paginate': {
'previous': '<span class="prev-icon"></span>',
'next': '<span class="next-icon"></span>'
}
},
"order": [[9, "desc"]],
"columns": [
{
"data": "Index", "title": "Số phiếu", 'width': '50px',
render: (data, type, full, meta) => {
return `<div>
<div><a href="/Receipt/edit?id=${full.Id}">${full.SoPhieu}</a></div>
<button class="btn-primary"><i class="fa fa-print"></i> In phiếu</button>
</div>`;
}
},
{
"data": "MaKH", "title": "Khách hàng", 'width': '50px', "orderable": false,
render: (data, type, full, meta) => {
return `<div>
<div><a href="/khachhang/detail?id=${full.KHId}">${full.MaKH}</a></div>
<div>${full.KHTen}</div>
<div>${full.KHDThoai}</div>
</div>`;
}
},
{
"data": "Model", "title": "Thông tin xe", 'width': '50px', "orderable": false,
render: (data, type, full, meta) => {
return `<div>
<div>${full.Model}</div>
<div>${full.SoKhung}</div>
<div>${full.SoMay}</div>
<div>${full.BienSo}</div>
</div>`;
}
},
{
"data": "TongGiaNhap", "title": "Giá nhập", 'width': '30px',
render: (data, type, full, meta) => {
return (data ? data : '');
}
},
{ "data": "SLPhuTung", "title": "Số lượng phụ tùng", 'width': '30px' },
{ "data": "TongGiaBan", "title": "Tổng tiền phụ tùng", 'width': '70px' },
{ "data": "TienCong", "title": "Tiền công", 'width': '70px' },
{ "data": "TongTien", "title": "Tổng tiền", 'width': '70px' },
{ "data": "Yeucau", "title": "Yêu cầu khách hàng", 'width': '70px',"orderable": false, },
{
"orderable": true,"data": "Ngay", "title": "Ngày tạo phiếu", 'width': '30px',
render: (data, type, full, meta) => {
return (data ? moment(data).format('DD/MM/YYYY hh:mm') : '');
}
} ]
});
$('#table-phieu-mo_wrapper #table-phieu-mo_filter').append($('<label><i class="fa fa-file-excel-o fa-lg col-red pointer" title="xuất excel" aria-hidden="true"></i></label>'));
}
}
|
import React, {useState, useEffect} from 'react'
import {Group} from '../../domain/group'
import { Timetable } from '../../domain/timetable';
import {Timetables} from './timetable'
import AddConditions from './addCondition'
import ConditionList from './conditionList'
const FindTimetable = ({grouplist, _seeDetails}) => {
const [conditions, setConditions] = useState([
"A교시 1개 이하",
"C교시 3개 이하",
"D교시 3개 이하",
"금요일 공강",
"3 연강 0개 이하",
"4 공강 0개 이하",
"운영체제 F032 선택"
]);
const [filteredTimetables, setFilteredTimetables] = useState();
const [allTimetables, setAllTimetables] = useState();
useEffect(()=>{
setAllTimetables(__getAllPossibleTimetables(grouplist));
}, [grouplist])
useEffect(()=>{
setFilteredTimetables(allTimetables)
console.log("useEffect called")
}, [allTimetables])
const __getAllPossibleTimetables = (grouplist) => {
let testTimetable = new Timetable();
let timetables = new Array()
const __cloneObject = (obj) =>{
return JSON.parse(JSON.stringify(obj));
}
const __getTimetables = (gIdx) =>{
if(grouplist==null) return;
if(gIdx == grouplist.length){
timetables.push(__cloneObject(testTimetable));
return;
}
else{
for(let rank = 0; rank < 3; rank ++){
const rankCourses = grouplist[gIdx].courses[rank]
for(let idx = 0; idx< rankCourses.length; idx++){
const course = rankCourses[idx]
if(testTimetable._canAddCourse(course)){
testTimetable._addCourse(course)
__getTimetables(gIdx+1);
testTimetable._removeCourse(course);
}
}
}
}
}
__getTimetables(0);
return timetables
}
const _filter = () =>{
console.log("filtering")
}
return(
<>
<div id= "showResults">
<Timetables timetables = {allTimetables} _seeDetails = {_seeDetails}/>
</div>
<ConditionList
conditions = {conditions}
_filter = {_filter}
/>
<AddConditions grouplist = {grouplist}/>
</>
)
}
export default FindTimetable;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require fancybox
//= require admin/ui.checkbox
//= require admin/jquery.bind
//= require admin/jquery.selectbox-0.5
//= require admin/jquery.filestyle
//= require admin/custom_jquery
//= require admin/jquery.tooltip
//= require admin/jquery.dimensions
//= require admin/jquery.pngFix.pack
$(function(){
$('input').checkBox( { replaceInput: true } );
$('#toggle-all').click(function(){
$('#toggle-all').toggleClass('toggle-checked');
$('#mainform input[type=checkbox]').checkBox('toggle');
return false;
});
$('.action-edit').click(function(){
$('#mainform input[type=checkbox]:checked').each(function(i,cb){
window.open( window.location.href+'/edit/'+cb.value );
});
$("#actions-box-slider").slideUp();
return false;
});
$('.action-delete').click(function(){
$('#mainform').submit();
return false;
});
$('.styledselect').selectbox({ inputClass: "selectbox_styled" });
$('.styledselect_form_1').selectbox({ inputClass: "styledselect_form_1", containerClass: "selectbox-wrapper2", hoverClass: "current2", selectedClass: "selected2" });
$('.styledselect_form_2').selectbox({ inputClass: "styledselect_form_2", containerClass: "selectbox-wrapper2", hoverClass: "current2", selectedClass: "selected2" });
$('.styledselect_pages').selectbox({ inputClass: "styledselect_pages", containerClass: "selectbox-wrapper2", hoverClass: "current2", selectedClass: "selected2" });
$("input.file_1").filestyle({
image: "/assets/forms/upload_file.gif",
imageheight : 29,
imagewidth : 78,
width : 200
});
$('a.info-tooltip ').tooltip({
track: true,
delay: 0,
fixPNG: true,
showURL: false,
showBody: " - ",
top: -35,
left: 5
});
$("a.fancybox").fancybox({
titlePosition: 'over'
});
$('#same_billing_btn').click(function(){
$('input[id^=dealer_billing_address],input[id^=wholesaler_billing_address]').each(function(key,el){
$(el).val( $('#'+el.id.replace('billing','shipping')).val() );
if( $(el).is(':checked') != $('#'+el.id.replace('billing','shipping')).is(':checked') )
$(el).checkBox('toggle');
});
$('#dealer_billing_address_country').val( $('#dealer_shipping_address_country').val() );
$('#wholesaler_billing_address_country').val( $('#wholesaler_shipping_address_country').val() );
});
$('a.icon-5,a.icon-6').on('ajax:success', function() {
if( $(this).hasClass( 'icon-5' ) )
$(this).removeClass( 'icon-5' ).addClass( 'icon-6' );
else
$(this).removeClass( 'icon-6' ).addClass( 'icon-5' );
});
$(document).pngFix( );
});
function switch_layouts( el ) {
var num = 1;
var m = $(el).val().match( /^(\d+)/ );
if( m )
num = parseInt( m[1] );
for( var i = 1; i <= 4; i++ ) {
if( i <= num )
$('#page_body_'+(i-1)).show();
else
$('#page_body_'+(i-1)).hide();
}
}
function add_another_image( cnt ) {
if( typeof add_another_image.counter == 'undefined' ) {
add_another_image.counter = cnt;
}
$('#product_images').append('<tr><th valign="top">Image:</th><td style="width: 300px"><input type="file" id="file_'+add_another_image.counter+'" name="product[images]['+add_another_image.counter+'][image]" class="file_1" /></td><td><div class="bubble-left"></div><div class="bubble-inner">JPEG, GIF or PNG</div><div class="bubble-right"></div></td></tr>');
$("#file_"+add_another_image.counter).filestyle({
image: "/assets/forms/upload_file.gif",
imageheight : 29,
imagewidth : 78,
width : 200
});
add_another_image.counter++;
}
function add_another_qty( cnt ) {
if( typeof add_another_qty.counter == 'undefined' ) {
add_another_qty.counter = cnt;
}
$('#deal_quantities').append('<tr><td><input type="text" value="" size="30" name="deal[deal_quantities_attributes]['+add_another_qty.counter+'][qty]" id="deal_deal_quantities_attributes_'+add_another_qty.counter+'_qty" class="inp-form"></td><td> </td><td><input type="text" value="" size="30" name="deal[deal_quantities_attributes]['+add_another_qty.counter+'][price_change]" id="deal_deal_quantities_attributes_'+add_another_qty.counter+'_price_change" class="inp-form"></td></tr>');
add_another_qty.counter++;
}
|
function callAnotherPage(){
// alert("aqui");
var req = new XMLHttpRequest();
req.open('GET', '/json', true);
xhttp.send();
};
|
var pushedButton="";
$(".button").on("click", function(){
pushedButton =$(this).attr("txt");
console.log("pushed button: " + pushedButton);
displayInfo(pushedButton);
});
function displayInfo(sentButton) {
var api_URL = "https://sv443.net/jokeapi/v2/joke/"+sentButton; //grabs a joke with the given category from the API.
$.ajax({
url: api_URL,
method: "GET"
}).then(function(response){
if(response.type==="single"){
$(".joke-display").text(response.joke);
}else{
var nextLine=$("<p>")
$(".joke-display").text(response.setup);
nextLine.text(response.delivery);
$(".joke-display").append(nextLine);
}
});
}
$(".gif-trigger").on("click", gif_grabber); //grabs a gif using random word sampling, if one of the main 4 buttons (marked "gif-trigger" class) is pressed
var jokeNumber=0;
//var i=0;
var id=[0];
function search() {
var api_URL = "https://sv443.net/jokeapi/v2/joke/Any";
$.ajax({
url: api_URL,
method: "GET"
}).then(function(response){
var flag;
if (stopSign===true){return}
if(response.type==="single"){
var strng = response.joke;
} else{
var strng = response.setup+response.delivery;
}
var incStr=false;
for (t=0;t<keyWords.length;t++){
incStr = strng.includes(keyWords[t]);
if (incStr) {
break;
}
}
//var incStr = strng.includes(keyWords[0],keyWords[1],keyWords[2]);
if (response.type==="single" & incStr===true){
flag=$.inArray( response.id, id );
if (flag===-1){
id.push(response.id);
//i++;
jokeNumber++;
var parag=$("<p>");
var lineExtra=$("<hr>")
$(".joke-display").append(lineExtra);
$(parag).text(response.joke);
$(parag).append(lineExtra);
$(".joke-display").append(parag);
if (jokeNumber<2) {
search();
}
} else{search()}
} else{ if(response.type==="twopart" & incStr===true){
flag=$.inArray( response.id, id );
if (flag===-1){
id.push(response.id);
//i++;
jokeNumber++;
var lineExtra=$("<hr>")
var parag=$("<p>");
var nextLine=$("<p>");
$(".joke-display").append(lineExtra);
$(parag).text(response.setup);
$(nextLine).text(response.delivery);
$(parag).append(nextLine);
// $(parag).append(lineExtra);
$(".joke-display").append(parag);
if (jokeNumber<2) {
search();
}
} else{search()}
} else { if (jokeNumber<2 ) {search()}}
}
});
}
var j=0;
var jd=[0];
function search2(){
var settings = {
"async": true,
"crossDomain": true,
"url": "https://joke3.p.rapidapi.com/v1/joke",
"method": "GET",
"headers": {
"x-rapidapi-host": "joke3.p.rapidapi.com",
"x-rapidapi-key": "3367949124msh172f5ef1dc35cf5p149ef8jsnb141a19d717e"
}
}
$.ajax(settings).done(function (response) {
var strng = response.content;
var incStr=false;
for (t=0;t<keyWords.length;t++){
incStr = strng.includes(keyWords[t]);
if (incStr) {
break;
}
}
var flag;
if (stopSign===true){return}
if (incStr===true){
flag=$.inArray( response.id, jd );
if (flag===-1){
jd.push(response.id);
//j++;
jokeNumber++
var parag=$("<p>");
var lineExtra=$("<hr>")
$(".joke-display").append(lineExtra);
$(parag).text(response.content);
//$(parag).append(lineExtra);
$(".joke-display").append(parag);
if (jokeNumber<1) {
search2();
}
}else{search2();}
} else{search2();}
});
}
//prepend
var k=0;
var kd=[0];
function search3() {
var api_URL = "http://api.icndb.com/jokes/random/";
if (stopSign===true){return}
$.ajax({
url: api_URL,
method: "GET"
}).then(function(response){
var strng = response.value.joke;
var incStr=false;
for (t=0;t<keyWords.length;t++){
incStr = strng.includes(keyWords[t]);
if (incStr) {
break;
}
}
var flag;
if (incStr===true){
flag=$.inArray( response.value.id, kd );
if (flag===-1){
kd.push(response.id);
//k++;
jokeNumber++
var lineExtra=$("<hr>")
var parag=$("<p>");
$(".joke-display").append(lineExtra);
$(parag).text(response.value.joke);
// $(parag).append(lineExtra);
$(".joke-display").append(parag);
if (jokeNumber<2) {
search3();
}
}else{search3();}
} else{search3();}
});
}
var nextJokes=$("<button>").text("next");
var stopSearching=$("<button>").text("stop");
var keyWords;
$("#search-btn").on("click", function(event){
event.preventDefault();
stopSign= false;
$("#nextORstop").empty();
$(".joke-display").empty();
$(".joke-display").text("Loading... ")
// var nextJokes=$("<button>").text("next");
// var stopSearching=$("<button>").text("stop");
$("#nextORstop").append(nextJokes,stopSearching);
keyWords=$("#search-box").val().split(" ");
search();
search2();
search3();
gif_searcher(keyWords[0]);
})
var stopSign= false;
$("#finish").on("click", function(event){
event.preventDefault();
stopSign= true;
})
$(nextJokes).on("click", function(){
jokeNumber=0;
$(".joke-display").empty();
$(".joke-display").text("Loading... ")
gif_searcher(keyWords[0]);
search();
search2();
search3();
})
$(stopSearching).on("click", function(){
jokeNumber=0;
stopSign= true;
})
function sample_word(joke){
//grabs a non-common word from a given joke (so no "the", "or", "are") and returns it
var blacklist = ["the", "of", "or", "are", "is", "to", "that", "for", "as", "test"];
var words = joke.split(" ");
var result = "";
while(result == ""){
var index = Math.floor(Math.random() * words.length); //selects a random index
var selected_word = words[index].toLowerCase(); //selects a random word and normalizes it to lowercase
if (blacklist.indexOf(selected_word) < 0){ //if word is not in our blacklist, return. Otherwise, reroll
result = selected_word;
return (result);
}
}
}
function gif_grabber(){
//samples a random word from the currently-displayed joke, and sends that word to the giphy API. Displays the resulting gif.
var sampled_word = sample_word($(".joke-display").text());
console.log(sampled_word);
var api_key = "XhXMrsEUUNOn44NMuFufbM8ji4bdOHdM"; //limit 42 requests per hour, 1000 requests per day
var queryURL = "https://api.giphy.com/v1/gifs/random?api_key=" + api_key +"&tag=" + sampled_word;
console.log(queryURL);
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
console.log(response);
$("#gif-display").attr("src", response.data.image_original_url);
});
}
function gif_searcher(searched_word){
//given a search word, searches the giphy API for a gif and displays the result
var api_key = "XhXMrsEUUNOn44NMuFufbM8ji4bdOHdM"; //limit 42 requests per hour, 1000 requests per day
var queryURL = "https://api.giphy.com/v1/gifs/random?api_key=" + api_key +"&tag=" + searched_word;
console.log(queryURL);
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
console.log(response);
$("#gif-display").attr("src", response.data.image_original_url);
});
}
function copyJoke(){
//copies the current joke to te clipboard
var joke_holder = document.createElement("textarea");
joke_holder.style.height = 0;
joke_holder.style.width = 0;
joke_holder.value = $(".joke-display").text().trim();
document.body.appendChild(joke_holder); //add element into the page that will hold the joke for copying
joke_holder.select();
joke_holder.setSelectionRange(11, 99999); /*For mobile devices*/ //we start at index 11 so that we don't copy the "Loading..." text
/* Copy the text inside the text field */
document.execCommand("copy");
}
$("#joke-copy-btn").on("click", copyJoke); //when the copy joke button is pressed, copies the current joke to the clipboard
function copyGif(){
//copies the giphy url of the currently displayed gif to the clipboard
var link_holder = document.createElement("textarea");
link_holder.style.height = 0;
link_holder.style.width = 0;
link_holder.value = $("#gif-display").attr("src");
document.body.appendChild(link_holder); //add element into the page that will hold the link for copying
//console.log(link_holder.value);
link_holder.select();
link_holder.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
}
$('#navbar a, .btn-scroll').on('click', function(event){
if (this.hash !== ' ') {
event.preventDefault();
const hash = this.hash;
$('html, body').animate(
{scrollTop: $(hash).offset().top- 100
},
800
);
}
});
$("#gif-copy-btn").on("click", copyGif); //when the copy gif button is pressed, copies the link of the current gif to the clipboard
|
import React, { useState, useEffect } from "react";
import SelectCategory from "../Fields/Select/SelectCategory";
import { getCategory, storeTestType } from "../Utils/Shared/apiCall";
const TestType = () => {
const [data, setData] = useState();
const [testType, setTestType] = useState("");
const [testCost, setTestCost] = useState("");
const [categoryId, setCategoryId] = useState("");
useEffect(() => {
let mounted = true;
const promiseCategory = getCategory();
promiseCategory
.then((res) => {
let serverData = res.data;
if (mounted) {
setData(serverData);
}
})
.catch((err) => {
console.log(err);
alert("Error Occured whilte Fetching Category");
});
return function cleanup() {
mounted = false;
};
}, []);
const handleSelectChange = (e) => {
setCategoryId(e.target.value);
};
const handleSaveClick = () => {
if (!isNaN(categoryId) && testType !== "" && !isNaN(testCost)) {
const promiseSave = storeTestType(categoryId, testType, testCost);
promiseSave
.then((res) => {
let serverData = res.data;
alert(serverData);
setTestType("");
setTestCost("");
})
.catch((err) => {
console.log(err);
alert("Error occured while store testtype");
});
} else {
alert("Please Enter Valid Data");
}
};
return (
<div className="testType-component">
<h4>Add Your TestType</h4>
<div className="form-group">
<label>Choose Category</label>
<SelectCategory data={data} onChange={handleSelectChange} />
</div>
<div className="form-group">
<label>TestTypeName</label>
<input
type="text"
className="form-control"
value={testType}
onChange={(e) => {
setTestType(e.target.value);
}}
/>
</div>
<div>
<label>Test Cost</label>
<input
type="text"
value={testCost}
onChange={(e) => setTestCost(e.target.value)}
/>
</div>
<div>
<input type="button" value="SAVE" onClick={handleSaveClick} />
</div>
</div>
);
};
export default TestType;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var MeetingSchema = new Schema({
patient: { type: ObjectId, ref: 'user' },
doctor: { type: ObjectId, ref: 'user' },
date: Date,
slot: Number,
patientNotRegister: {
phone: String,
name: {
first: String,
last: String
}
},
patientId: String,
doctorId: String,
approved: Boolean
});
module.exports = mongoose.model('meeting', MeetingSchema);
|
$(document).ready(function () {
var selectedCountry = localStorage.getItem("selected_country");
var rec_country = selectedCountry;
console.log("Random country " + rec_country + " successfully retrieved!");
var rec_city = "";
//creating switch case so the right city will be selected once the random Country has been determined
switch (rec_country) {
case "BRAZIL":
rec_city = "Rio de Janeiro";
console.log(rec_city);
break;
case "PERU":
rec_city = "Machu Picchu";
console.log(rec_city);
break;
case "FRANCE":
rec_city = "Paris";
console.log(rec_city);
break;
case "AUSTRAILA":
rec_city = "Sydney";
console.log(rec_city);
break;
case "ICELAND":
rec_city = "Reykjavik";
console.log(rec_city);
break;
}
// var rec_city = "Rio de Janeiro"; //recommended city - testing to make sure the rest of the code works properly
// "Brazil"; //recommended country - testing to make sure the rest of the code works properly
if (rec_city.includes(" ")) {
rec_city = rec_city.split(" ").join("+");
console.log(rec_city);
//adjusting name of the city so it will have the correct format for the ajax call in the event the city name contains more than one word
}
var destination = new Array(rec_city, rec_country);
var newDest = destination.join(",");
//joining the city name and country with "," so the ajax call can be performed with the correct syntax
console.log(newDest);
var weatherAPIKey = "98faab3250f1413496f172502182010";
// "f5f08ce79b534c1a907162145181310";
var queryURL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=" + weatherAPIKey + "&q=" + newDest + "&format=JSON";
// var location = ""
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
var currentInfo = response.data.current_condition[0];
var highLow = response.data.weather[0];
//calculating day of the week from date response....
// var days_of_the_week = [];
var currentDay = {
currentTemp: currentInfo.temp_F,
weatherDesc: currentInfo.weatherDesc[0].value,
weatherIconUrl: currentInfo.weatherIconUrl[0].value,
low: highLow.mintempF,
high: highLow.mintempF
}
// var template = document.getElementById("navIndexWeather").innerHTML;
// var renderWeather = Handlebars.compile(template);
// document.getElementById("weatherInfo").innerHTML = renderWeather(currentDay);
// console.log(response);
// console.log("It works... " + response.data.current_condition[0]);
console.log("Current Temperature: " + currentDay.currentTemp); //current temperature...
console.log("Current Weather Condition: " + currentDay.weatherDesc); //current weather description...
console.log("Weather Icon URL: " + currentDay.weatherIconUrl); //current weather icon image
console.log("Today's Low: " + currentDay.low); //lowest temperature for the current day
console.log("Today's High: " + currentDay.high); //highest temperature for the current day
console.log("/////////////////////");
//display weather image on webpage..
// document.getElementById("icon").setAttribute("src", currentDay.weatherIconUrl);
// var img = document.createElement("img");
// img.src = currentDay.weatherIconUrl;
// var src = document.getElementById("icon");
// src.appendChild(img);
var weatherToday = `<p>
<img src=${currentDay.weatherIconUrl}><br>
Weather Condition: ${currentDay.weatherDesc} <br>
Current Temp: ${currentDay.currentTemp}℉<br>
Low ${currentDay.low}℉/ High ${currentDay.high}℉
</p>`
$("#weatherInfo").append(weatherToday);
// ********** 5 Day Weather Forecast ***********
//DAY ONE response data...
var day1 = response.data.weather[2];
var dayOne = {
date: day1.date,
minTemp: day1.mintempF,
maxTemp: day1.maxtempF,
weatherDesc: day1.hourly[4].weatherDesc[0].value,
weatherIconUrl: day1.hourly[4].weatherIconUrl[0].value
}
console.log(dayOne.date); //date to convert to day-of-the-week
console.log("Day 1 Low: " + dayOne.minTemp); //lowest temperature for day 1
console.log("Day 1 High: " + dayOne.maxTemp); //highest temperature for day1
console.log("Day 1 Weather Condition: " + dayOne.weatherDesc); //weather description for day 1
console.log("Day 1 Weather Icon Url: " + dayOne.weatherIconUrl); //weather icon image for day 1
console.log("/////////////////////");
var weekday = new Date(dayOne.date);
console.log("Weekday number " + weekday);
var daysofWeek = new Array(7); //Sunday - Saturday : 0-6
daysofWeek[0] = "Sunday";
daysofWeek[1] = "Monday";
daysofWeek[2] = "Tuesday";
daysofWeek[3] = "Wednesday";
daysofWeek[4] = "Thursday";
daysofWeek[5] = "Friday";
daysofWeek[6] = "Saturday";
var new_weekday = daysofWeek[weekday.getDay()];
// days_of_the_week.push(new_weekday);
console.log(new_weekday);
// $("#weatherInfo").prepend(new_weekday)
;
// var img2 = document.createElement("img");
// img2.src = dayOne.weatherIconUrl;
// var src2 = document.getElementById("icon");
// src2.appendChild(img2);
var weatherDayOne = `<p>
<img src=${dayOne.weatherIconUrl}><br>
<strong>${new_weekday}</strong><br>
Weather Condition: ${dayOne.weatherDesc} <br>
Low Temp: ${dayOne.minTemp}℉<br>
High Temp: ${dayOne.maxTemp}℉
</p>`
$("#weatherInfo").append(weatherDayOne);
//DAY TWO response data...
// var weekday2 = new DataCue(dayTwo.date);
// var new_weekday2 = daysofWeek[weekday2.getDay()];
// days_of_the_week.push(new_weekday2);
var day2 = response.data.weather[3];
var dayTwo = {
date: day2.date,
minTemp: day2.mintempF,
maxTemp: day2.maxtempF,
weatherDesc: day2.hourly[4].weatherDesc[0].value,
weatherIconUrl: day2.hourly[4].weatherIconUrl[0].value
}
console.log(dayTwo.date) //date to convert to day-of-the-week
console.log("Day 2 Low: " + dayTwo.minTemp); //lowest temperature for day 2
console.log("Day 2 High: " + dayTwo.maxTemp); //highest temperature for day 2
console.log("Day 2 Weather Condition: " + dayTwo.weatherDesc); //weather description for day 2
console.log("Day 2 Weather Icon Url: " + dayTwo.weatherIconUrl); //weather icon image for day 2
console.log("/////////////////////");
var weekday2 = new Date(dayTwo.date);
var daysofWeek = new Array(7); //Sunday - Saturday : 0-6
daysofWeek[0] = "Sunday";
daysofWeek[1] = "Monday";
daysofWeek[2] = "Tuesday";
daysofWeek[3] = "Wednesday";
daysofWeek[4] = "Thursday";
daysofWeek[5] = "Friday";
daysofWeek[6] = "Saturday";
var new_weekday2 = daysofWeek[weekday2.getDay()];
var weatherDayTwo = `<p>
<img src=${dayTwo.weatherIconUrl}><br>
<strong>${new_weekday2}</strong><br>
Weather Condition: ${dayTwo.weatherDesc} <br>
Low Temp: ${dayTwo.minTemp}℉<br>
High Temp: ${dayTwo.maxTemp}℉
</p>`
$("#weatherInfo").append(weatherDayTwo);
//DAY THREE response data...
// var weekday3 = new DataCue(dayThree.date);
// var new_weekday3 = daysofWeek[weekday3.getDay()];
// days_of_the_week.push(new_weekday3);
var day3 = response.data.weather[4];
var dayThree = {
date: day3.date,
minTemp: day3.mintempF,
maxTemp: day3.maxtempF,
weatherDesc: day3.hourly[4].weatherDesc[0].value,
weatherIconUrl: day3.hourly[4].weatherIconUrl[0].value
}
console.log(dayThree.date) //date to convert to day-of-the-week
console.log("Day 3 Low: " + dayThree.minTemp); //lowest temperature for day 3
console.log("Day 3 High: " + dayThree.maxTemp); //highest temperature for day 3
console.log("Day 3 Weather Condition: " + dayThree.weatherDesc); //weather description for day 3
console.log("Day 3 Weather Icon Url: " + dayThree.weatherIconUrl); //weather icon image for day 3
console.log("/////////////////////");
var weekday3 = new Date(dayThree.date);
var daysofWeek = new Array(7); //Sunday - Saturday : 0-6
daysofWeek[0] = "Sunday";
daysofWeek[1] = "Monday";
daysofWeek[2] = "Tuesday";
daysofWeek[3] = "Wednesday";
daysofWeek[4] = "Thursday";
daysofWeek[5] = "Friday";
daysofWeek[6] = "Saturday";
var new_weekday3 = daysofWeek[weekday3.getDay()];
var weatherDayThree = `<p>
<img src=${dayThree.weatherIconUrl}><br>
<strong>${new_weekday3}</strong><br>
Weather Condition: ${dayThree.weatherDesc} <br>
Low Temp: ${dayThree.minTemp}℉<br>
High Temp: ${dayThree.maxTemp}℉
</p>`
$("#weatherInfo").append(weatherDayThree);
//DAY FOUR response data...
// var weekday4 = new DataCue(dayFour.date);
// var new_weekday4 = daysofWeek[weekday4.getDay()];
// days_of_the_week.push(new_weekday4);
var day4 = response.data.weather[5];
var dayFour = {
date: day4.date,
minTemp: day4.mintempF,
maxTemp: day4.maxtempF,
weatherDesc: day4.hourly[4].weatherDesc[0].value,
weatherIconUrl: day4.hourly[4].weatherIconUrl[0].value
}
console.log(dayFour.date) //date to convert to day-of-the-week
console.log("Day 4 Low: " + dayFour.minTemp); //lowest temperature for day 4
console.log("Day 4 High: " + dayFour.maxTemp); //highest temperature for day 4
console.log("Day 4 Weather Condition: " + dayFour.weatherDesc); //weather description for day 4
console.log("Day 4 Weather Icon Url: " + dayFour.weatherIconUrl); //weather icon image for day 4
console.log("/////////////////////");
var weekday4 = new Date(dayFour.date);
var daysofWeek = new Array(7); //Sunday - Saturday : 0-6
daysofWeek[0] = "Sunday";
daysofWeek[1] = "Monday";
daysofWeek[2] = "Tuesday";
daysofWeek[3] = "Wednesday";
daysofWeek[4] = "Thursday";
daysofWeek[5] = "Friday";
daysofWeek[6] = "Saturday";
var new_weekday4 = daysofWeek[weekday4.getDay()];
var weatherDayFour = `<p>
<img src=${dayFour.weatherIconUrl}><br>
<strong>${new_weekday4}</strong><br>
Weather Condition: ${dayFour.weatherDesc} <br>
Low Temp: ${dayFour.minTemp}℉<br>
High Temp: ${dayFour.maxTemp}℉
</p>`
$("#weatherInfo").append(weatherDayFour);
//DAY FIVE response data...
var day5 = response.data.weather[6];
var dayFive = {
date: day5.date,
minTemp: day5.mintempF,
maxTemp: day5.maxtempF,
weatherDesc: day5.hourly[4].weatherDesc[0].value,
weatherIconUrl: day5.hourly[4].weatherIconUrl[0].value
}
console.log(dayFive.date) //date to convert to day-of-the-week
console.log("Day 5 Low: " + dayFive.minTemp); //lowest tempertaure for day 5
console.log("Day 5 High: " + dayFive.maxTemp); //highest temperature for day 5
console.log("Day 5 Weather Condition: " + dayFive.weatherDesc); //weather description for day 5
console.log("Day 5 Weather Icon Url: " + dayFive.weatherIconUrl); //weather icon image for day 5
// ********** STEP FOR MAKING WEATHER API CALL **********
//1. Reference the destination object
//2. Slice the destination object/array so that only the county name and city are left and set equal to new_var_name
//.....nameOfArray.prototype.slice(-1) - use negative to slice off the end of the array
//...Check to see if city name includes space(s) i.e. more than one word, city.includes(" ");
//.....if city name is > 1 word, will need to separate each word and rejoin them with (+);
//3. need to join the new City name (if amended) and county using (,), arrayName.join(" ");
//......either combine 2 & 3 on the same variable or create a new variable for step 3
//4. Make ajax call using the variable where the city and country have been joined (city,country)
//Responses to include on page:
//1. City, Country (not needed since it will be at the top of page (handled by dest.handlebars)
//2. current temperature = response.data.current_condition[0].tempF..see code below to add degree symbol
// <p>I will display ℉</p> I will display ℉ - will need to add on handlebars page
// <p>I will display ℉</p> I will display ℉ - will need to add on handlebars page
//3. weather desription = response.data.current_condition[0].weatherDesc[0].value
//4. weather icon url = response.data.current_condition[0].weatherIconURL[0].value
// document.getElementById("icon").setAttribute("src", currentDay.weatherIconUrl);
//5. mintemp = response.data.weather[0].mintempF
//6 max temp = response.data.weather[0].maxtempF
//7. Min/Max Temp & weather descip, weather icon for next 5 days
});
});
// });
// });
// });
// module.exports = currLogic;
|
import { Dimensions } from 'react-native'
const { height } = Dimensions.get('window')
import theme from './theme'
export const getStyling = () => {
console.log(height);
switch (height) {
case 667:
return {
// topBar: 15,
input: 13,
titleHead: 19,
button: 17,
buttonPadding: theme.spacing.unit * 1.2,
titleHolderMarginTop: theme.spacing.unit * 6 + 2,
titleHolderMarginBottom: theme.spacing.unit * 3.5,
buttonMarginTop: 28.9 - 11.4,
inputsMarginTop: 144.1 + 1.5, //theme.spacing.unit * 1.2,
headerPaddingTop: 0,
titleCenterTop: 10,
inputPadding: 9, //theme.spacing.unit * 1.2,
titleHolderMarginLeft: -2,
titleLetterSpacing: 0.38,
titleLineHeigt: 22,
headerContainer: {
width: '100%',
height: 37.05,
position: 'relative'
},
headerItems: {
height: 22,
left: 12.1,
bottom: 7.7,
},
backIcon: {
width: 11,
height: 19.7
},
backText: {
marginLeft: 7.1,
fontSize: 15
},
title: {
fontSize: 15,
letterSpacing: 0.15,
lineHeight: 18,
marginLeft: 1,
marginBottom: .5,
fontFamily: 'sfPro-semi',
},
titleHolder: {
left: 0,
right: 0,
bottom: 9.9,
},
textInput: {
letterSpacing: 0.32,
lineHeight: 19,
fontSize: 13,
padding: theme.spacing.unit * 1.2,
height: 40.2,
borderColor: '#DBDBDB',
borderWidth: 1,
borderRadius: theme.shape.roundedInputBorderRadius / 1.5,
color: '#919191',
fontFamily: 'heebo-medium',
},
inputContainer: {
marginBottom: 11.4
},
inputs: {
marginTop: 48.6,
marginRight: -0.9
},
buttonText: {
letterSpacing: 0.08,
fontSize: 17,
fontFamily: 'heebo-medium',
marginTop: 'auto',
marginBottom: 'auto',
textAlign: 'center',
}
}
case 736:
return {
topBar: 17,
input: 15.5,
titleHead: 22,
button: 19,
buttonPadding: theme.spacing.unit * 1.4,
titleHolderMarginTop: theme.spacing.unit * 6.5,
titleHolderMarginBottom: theme.spacing.unit * 5,
buttonMarginTop: theme.spacing.unit * 4,
inputsMarginTop: 0,
headerPaddingTop: theme.spacing.unit,
titleCenterTop: 15,
inputPadding: theme.spacing.unit * 1.2,
titleHolderMarginLeft: -2,
titleLetterSpacing: 0.42,
titleLineSpacing: 24,
headerContainer: {
width: '100%',
height: 37.05,
position: 'relative'
},
headerItems: {
height: 22,
left: 12.1,
bottom: 7.7,
},
backIcon: {
width: 11,
height: 19.7
},
backText: {
marginLeft: 7.1,
fontSize: 17
},
title: {
fontSize: 15,
letterSpacing: 0.15,
lineHeight: 18,
marginLeft: 1,
marginBottom: .5,
fontFamily: 'sfPro-semi',
},
titleHolder: {
left: 0,
right: 0,
bottom: 9.9,
},
textInput: {
letterSpacing: 0.32,
lineHeight: 19,
fontSize: 15.5,
padding: theme.spacing.unit * 1.2,
height: 40.2,
borderColor: '#DBDBDB',
borderWidth: 1,
borderRadius: theme.shape.roundedInputBorderRadius / 1.5,
color: '#919191',
fontFamily: 'heebo-medium',
},
inputContainer: {
marginBottom: 11.4
},
inputs: {
marginTop: 48.6,
marginRight: -0.9
},
buttonText: {
letterSpacing: 0.08,
fontSize: 19,
fontFamily: 'heebo-medium',
marginTop: 'auto',
marginBottom: 'auto',
textAlign: 'center',
}
}
case 896:
return {
topBar: 16,
input: 13,
titleHead: 21,
button: 18,
buttonPadding: theme.spacing.unit * 1.4,
titleHolderMarginTop: theme.spacing.unit * 6.5,
titleHolderMarginBottom: theme.spacing.unit * 6.5,
buttonMarginTop: theme.spacing.unit * 4,
inputsMarginTop: 0,
headerPaddingTop: theme.spacing.unit * 1.7,
titleCenterTop: 10,
inputPadding: theme.spacing.unit * 1.5,
titleHolderMarginLeft: -2,
titleLetterSpacing: 0.42,
titleLineSpacing: 24,
headerContainer: {
width: '100%',
height: 37.05,
position: 'relative'
},
headerItems: {
height: 22,
left: 12.1,
bottom: 7.7,
},
backIcon: {
width: 11,
height: 19.7
},
backText: {
marginLeft: 7.1,
fontSize: 16
},
title: {
fontSize: 15,
letterSpacing: 0.15,
lineHeight: 18,
marginLeft: 1,
marginBottom: .5,
fontFamily: 'sfPro-semi',
},
titleHolder: {
left: 0,
right: 0,
bottom: 9.9,
},
textInput: {
letterSpacing: 0.32,
lineHeight: 19,
fontSize: 13,
padding: theme.spacing.unit * 1.5,
height: 40.2,
borderColor: '#DBDBDB',
borderWidth: 1,
borderRadius: theme.shape.roundedInputBorderRadius / 1.5,
color: '#919191',
fontFamily: 'heebo-medium',
},
inputContainer: {
marginBottom: 11.4
},
inputs: {
marginTop: 48.6,
marginRight: -0.9
},
buttonText: {
letterSpacing: 0.08,
fontSize: 18,
fontFamily: 'heebo-medium',
marginTop: 'auto',
marginBottom: 'auto',
textAlign: 'center',
}
}
case 812:
return {
topBar: 15,
input: 13,
titleHead: 19,
button: 17,
buttonPadding: theme.spacing.unit * 1.4,
titleHolderMarginTop: theme.spacing.unit * 6.5,
titleHolderMarginBottom: theme.spacing.unit * 5,
buttonMarginTop: theme.spacing.unit * 3.5,
inputsMarginTop: 0,
headerPaddingTop: theme.spacing.unit,
titleCenterTop: 15,
inputPadding: theme.spacing.unit * 1.2,
titleHolderMarginLeft: -2,
titleLetterSpacing: 0.42,
titleLineSpacing: 24,
headerContainer: {
width: '100%',
height: 37.05,
position: 'relative'
},
headerItems: {
height: 22,
left: 12.1,
bottom: 7.7,
},
backIcon: {
width: 11,
height: 19.7
},
backText: {
marginLeft: 7.1,
fontSize: 15
},
title: {
fontSize: 15,
letterSpacing: 0.15,
lineHeight: 18,
marginLeft: 1,
marginBottom: .5,
fontFamily: 'sfPro-semi',
},
titleHolder: {
left: 0,
right: 0,
bottom: 9.9,
},
textInput: {
letterSpacing: 0.32,
lineHeight: 19,
fontSize: 13,
padding: theme.spacing.unit * 1.2,
height: 40.2,
borderColor: '#DBDBDB',
borderWidth: 1,
borderRadius: theme.shape.roundedInputBorderRadius / 1.5,
color: '#919191',
fontFamily: 'heebo-medium',
},
inputContainer: {
marginBottom: 11.4
},
inputs: {
marginTop: 48.6,
marginRight: -0.9
},
buttonText: {
letterSpacing: 0.08,
fontSize: 17,
fontFamily: 'heebo-medium',
marginTop: 'auto',
marginBottom: 'auto',
textAlign: 'center',
}
}
default:
return {
topBar: 15,
input: 13,
titleHead: 19,
button: 17,
buttonPadding: theme.spacing.unit * 1.4,
titleHolderMarginTop: theme.spacing.unit * 6.5,
titleHolderMarginBottom: theme.spacing.unit * 5,
buttonMarginTop: theme.spacing.unit * 3.5,
inputsMarginTop: 0,
headerPaddingTop: theme.spacing.unit,
titleCenterTop: 15,
inputPadding: theme.spacing.unit * 1.2,
titleHolderMarginLeft: -2,
titleLetterSpacing: 0.42,
titleLineSpacing: 24,
headerContainer: {
width: '100%',
height: 37.05,
position: 'relative'
},
headerItems: {
height: 22,
left: 12.1,
bottom: 7.7,
},
backIcon: {
width: 11,
height: 19.7
},
backText: {
marginLeft: 7.1,
fontSize: 15
},
title: {
fontSize: 15,
letterSpacing: 0.15,
lineHeight: 18,
marginLeft: 1,
marginBottom: .5,
fontFamily: 'sfPro-semi',
},
titleHolder: {
left: 0,
right: 0,
bottom: 9.9,
},
textInput: {
letterSpacing: 0.32,
lineHeight: 19,
fontSize: 13,
padding: theme.spacing.unit * 1.2,
height: 40.2,
borderColor: '#DBDBDB',
borderWidth: 1,
borderRadius: theme.shape.roundedInputBorderRadius / 1.5,
color: '#919191',
fontFamily: 'heebo-medium',
},
inputContainer: {
marginBottom: 11.4
},
inputs: {
marginTop: 48.6,
marginRight: -0.9
},
buttonContainer: {
width: '100%',
height: 45.2,
},
buttonText: {
letterSpacing: 0.08,
fontSize: 17,
fontFamily: 'heebo-medium',
marginTop: 'auto',
marginBottom: 'auto',
textAlign: 'center',
},
}
}
}
|
import React from 'react'
export default function adapter(props) {
return (
<div style={{width: `${props.size}px`}} dangerouslySetInnerHTML={{__html: `${props.svg.data}`}}/>
);
};
|
// JavaScript Document
function indexInicializar() {
var crearWidgets = function () {
// Menú de opciones
$("#jqxMenu_Index").jqxMenu({
width: $("#jqxMenu_Index").parent.width,
height: $("#jqxMenu_Index").parent.height,
animationShowDuration: 300,
animationHideDuration: 100,
animationShowDelay: 300,
showTopLevelArrows: true,
autoOpen: true,
enableHover: true,
keyboardNavigation: true
});
};
var agregarEventos = function () {
$('.jqx-menu-item').click(function (event) {
indexMenuOpcionIr( $(this).attr('id') );
});
};
crearWidgets();
agregarEventos();
}
function indexMenuOpcionIr(psNombreArchivoVista, agregarBreadcrumb) {
if (typeof agregarBreadcrumb === 'undefined') {agregarBreadcrumb = true;}
var tituloActual = $('.wrapper > .container h1').html();
$("#divPrincipal").fadeIn().html("Cargando...");
$("#divInformacionEmpleado").fadeOut();
var vista = "vista/" + psNombreArchivoVista + ".php";
$.get(vista, function (data, status) {
if (status == 'success') {
var tituloVista = $(data).filter('h1').text(),
inicializar = psNombreArchivoVista.charAt(3).toLowerCase() + psNombreArchivoVista.substring(4) + 'Inicializar';
if (tituloActual != tituloVista){
// Agregar al breadcrumb
$('#breadcrumb ul').append('<li class="separador animated fadeInRight"> ≫ </li><li class="animated fadeInRight delay-5" onclick="indexMenuOpcionIr(\''+psNombreArchivoVista+'\',false);" rel="cargarVista" data-breadcrumb="'+psNombreArchivoVista+'">'+ tituloVista +'</li>')
}else{
$('[data-breadcrumb="'+psNombreArchivoVista+'"]').nextAll().remove();
}
$("#divPrincipal").html(data);
//Inicializar la vista
window[inicializar]();
}
});
}
|
$(document).on('mouseenter', '[data-toggle="tab"]', function () {
$(this).tab('show');
});
$(document).on('click', '[data-toggle="tab"]', function () {
window.location.href=$(this).attr("data-url");
});
|
const http = require('http')
const { PORT = 3000 } = process.env
const psi = require('psi');
http.createServer(async (req, res) => {
const searchParams = new URL(req.url, 'https://example.org').searchParams;
const targetURL = searchParams.get('url') || 'https://icing.space/';
const { data } = await psi(targetURL);
const jsonEncoded = JSON.stringify(data);
res.writeHead(200, {
'content-type': 'application/json',
'content-length': Buffer.byteLength(jsonEncoded)
});
res.end(jsonEncoded);
}).listen(PORT)
|
import React, { Component } from 'react'
import {useForm, userForm , useStep} from 'react-hooks-helper'
import Names from './StepForm/Names'
import Address from './StepForm/Address'
const defaultData = {
firstName : "",
lastName : "",
nickName : ""
}
const steps = [
{ id : "names" },
{ id : "address" },
{ id : "contact" },
{ id : "review" },
{ id : "submit" },
]
const MultiFormRegistraion = () => {
const [formData,setForm] = useForm(defaultData)
const {step , navigation} = useStep({
steps,
initialStep: 0
})
const props = {formData , setForm , navigation}
switch(step.id){
case "names":
return <Names {...props}/>;
case "address":
return <Address {...props} />;
}
return (
<>
</>
)
}
export default MultiFormRegistraion
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom';
class Navbar extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand navbar-dark bg-success">
<div className="nav navbar-nav">
<a className="nav-item nav-link active" href="#">Home <span className="sr-only">(current)</span></a>
<Link className="nav-item nav-link" to="/blog">Blog</Link>
<Link className="nav-item nav-link" to="/courses">list Courses</Link>
<Link className="nav-item nav-link" to="/users">Users</Link>
</div>
</nav>
</div>
)
}
}
export default Navbar
|
import Vue from "vue";
import VueRouter from "vue-router";
// 商城
import center from "@/pages/shop/center/index.vue";
import lists from "@/pages/shop/lists/index.vue";
import cart from "@/pages/shop/cart/index.vue";
import index from "@/pages/shop/index/index.vue";
import goodsDetail from "@/pages/shop/goods_detail/index.vue";
import order from "@/pages/shop/my_order/index.vue";
import collect from "@/pages/shop/collect/index.vue";
import track from "@/pages/shop/track/index.vue";
import address from "@/pages/shop/add_address/index.vue";
import my_comment from "@/pages/shop/my_comment/index.vue";
import comment from "@/pages/shop/comment/index.vue";
import confirm_order from "@/pages/shop/confirm_order/index.vue";
import done_pay from "@/pages/shop/done_pay/index.vue";
import order_detail from "@/pages/shop/order_detail/index.vue";
import logistics from "@/pages/shop/logistics/index.vue";
import refund from "@/pages/shop/refund/index.vue";
import msg from "@/pages/shop/msg/index.vue";
import service from "@/pages/shop/service/index.vue";
import shop_lists from "@/pages/shop/shop_list/index.vue";
// 要告诉 vue 使用 vueRouter
Vue.use(VueRouter);
const routes = [
{
path: '/lists',
name: 'lists',
component: lists
},
{
path: '/service',
name: 'service',
component: service
},
{
path: '/center',
name: 'center',
component: center
},
{
path: '/cart',
name: 'cart',
component: cart
},
{
path: '/',
name: 'index',
component: index,
meta: {keepAlive: true}
},
{
path: '/goods_detail/:id',
name: 'goods_detail',
component: goodsDetail,
},
{
path: '/order',
name: 'order',
component: order
},
{
path: '/collect',
name: 'collect',
component: collect
},
{
path: '/track',
name: 'track',
component: track
},
{
path: '/address',
name: 'address',
component: address
},
{
path: '/my_comment',
name: 'my_comment',
component: my_comment
},
{
path: '/comment',
name: 'comment',
component: comment
},
{
path: '/confirm_order/:id',
name: 'confirm_order',
component: confirm_order,
},
{
path: '/order_detail/:id',
name: 'order_detail',
component: order_detail
},
{
path: '/refund/:id',
name: 'refund',
component: refund
},
{
path: '/logistics/:id',
name: 'logistics',
component: logistics
},
{
path: '/msg',
name: 'msg',
component: msg
},
{
path: '/done_pay/:id',
name: 'done_pay',
component: done_pay
},
{
path: '/shop_lists/:id',
name: 'shop_lists',
component: shop_lists
}
]
var router = new VueRouter({
// mode: 'history',
routes
})
router.beforeEach((to, from, next) => {
console.log('从:', from)
console.log('到:', to)
next();
// 返回不刷新
if(from.name == "coupon_lists" || from.name == "confirm_order") {
to.meta.isBack = true
}
})
export default router;
|
import React from "react";
import { scrollById } from "../../utils/Tools";
import "./menu.css";
const Menu = () => {
return (
<div className="menu d-flex">
<p onClick={() => scrollById("aboutMe")}>About me</p>
<p onClick={() => scrollById("projects")}>My projects</p>
<p onClick={() => scrollById("contact")}>Contact</p>
</div>
);
};
export default Menu;
|
$(document).ready(function () {
$(".message-user").hide();
$(".message-recipient").hide();
$("form").hide();
$(".reloaded").show(); // if message was sent from inbox, show the thread
// get id of message thread that the user clicks on
$(".message-threads").click(function () {
$(".message-user").hide();
$(".message-recipient").hide();
let id = $(this).attr("id");
$("#message-container").removeAttr("hidden");
$(`.${id}`).show();
$(`form:not(.${id})`).hide();
});
// scroll to bottom of chat if reloaded
let messageDiv = $("#message-container");
messageDiv.scrollTop(messageDiv.get(0).scrollHeight);
});
|
import React, { Component } from "react";
import { Button } from "react-bootstrap"
import BubbleSort from "../Algorithms/BubbleSort.js";
import InsertionSort from "../Algorithms/InsertionSort.js";
import MergeSort from "../Algorithms/MergeSort.js";
import NavBar from "./NavBar.jsx";
import Slider from "./Slider.jsx"
import "./Board.css"
import SelectionSort from "../Algorithms/SelectionSort.js";
import InstructionsModal from './InstructionsModal'
const ANIMATION_SPEED = 2;
const DEFAULT_BAR_COLOR = "pink";
const ALTER_BAR_COLOR = "blue";
const DEFAULT_BAR_CLASS = "array-bar-pink"
const ALTER_BAR_CLASS = "array-bar-blue"
const CORRECT_PLACE_COMPARISION_BAR_COLOR = "green";
const INCORRECT_PLACE_COMPARISION_BAR_COLOR = "red";
let WIDTH = 980;
let MAX_HEIGHT = 700;
let BAR_WIDTH = 7;
class Bars extends Component {
constructor() {
super();
this.state = {
array: [],
barColor: DEFAULT_BAR_COLOR,
size: 0,
modalActive: false,
algoSelected: null,
barClass: DEFAULT_BAR_CLASS,
isSliderActive: true,
isGenerateArrayEnabled: true
};
this.changeBarColor = this.changeBarColor.bind(this)
this.resetArray = this.resetArray.bind(this)
this.mergeSort = this.mergeSort.bind(this)
this.insertionSort = this.insertionSort.bind(this)
this.bubbleSort = this.bubbleSort.bind(this)
this.selectionSort = this.selectionSort.bind(this)
this.showModal = this.showModal.bind(this)
this.selectAlgo = this.selectAlgo.bind(this)
this.deactivateSlider = this.deactivateSlider.bind(this)
}
componentDidMount() {
this.resetArray(0);
}
// method to set showModal to true so that it can be shown when We click on Instructions on the NavBar.
showModal() {
this.setState({modalActive: true});
}
selectAlgo(algorithm) {
this.setState({algoSelected : algorithm});
}
deactivateSlider() {
this.setState({isSliderActive : false , isGenerateArrayEnabled : false});
}
// used to toggle between the bar color pink and blue.
changeBarColor() {
if (this.state.barColor === DEFAULT_BAR_COLOR) {
const arrayBars = document.getElementsByClassName(
`${this.state.barClass}`
);
for (let i = 0; i < arrayBars.length; i++)
arrayBars[i].style.backgroundColor = ALTER_BAR_COLOR;
this.setState({barColor : ALTER_BAR_COLOR , barClass : ALTER_BAR_CLASS})
}
else {
const arrayBars = document.getElementsByClassName(
`${this.state.barClass}`
);
for (let i = 0; i < arrayBars.length; i++)
arrayBars[i].style.backgroundColor = DEFAULT_BAR_COLOR;
this.setState({barColor : DEFAULT_BAR_COLOR , barClass : DEFAULT_BAR_CLASS})
}
}
// Called everytime the generate array is called or when we use the slider.
resetArray(array_size) {
if (array_size !== -1)
this.setState({size : array_size})
BAR_WIDTH = WIDTH / this.state.size - 1;
const bars = [];
let max_height = 0;
for (let i = 0; i < this.state.size; i++) {
let number = generateRandomValue(5, 500);
if (max_height < number){
max_height = number;
}
bars.push(number);
}
MAX_HEIGHT = max_height;
this.setState({ array: bars });
}
bubbleSort() {
const { array } = this.state
const newArray = BubbleSort.bubbleSort(array);
const animations = [];
for (const animation of newArray) {
animations.push(animation.comparision);
animations.push(animation.swap);
animations.push(animation.comparision);
}
for (let i = 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName(`${this.state.barClass}`);
const [indexBar1, indexBar2] = animations[i];
if (i % 3 === 1) {
setTimeout(() => {
let height_bar1 = arrayBars[indexBar1].style.height;
let height_bar2 = arrayBars[indexBar2].style.height;
arrayBars[indexBar1].style.height = height_bar2;
arrayBars[indexBar2].style.height = height_bar1;
}, i * ANIMATION_SPEED);
} else {
setTimeout(() => {
let height_bar1 = arrayBars[indexBar1].style.height;
let height_bar2 = arrayBars[indexBar2].style.height;
if (height_bar1 - height_bar2 > 0) {
arrayBars[
indexBar1
].style.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
arrayBars[
indexBar2
].style.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
if (i % 3 === 2) {
arrayBars[indexBar1].style.backgroundColor = DEFAULT_BAR_COLOR;
arrayBars[indexBar2].style.backgroundColor = DEFAULT_BAR_COLOR;
}
} else {
arrayBars[
indexBar1
].style.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
arrayBars[
indexBar2
].style.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
if (i % 3 === 2) {
arrayBars[indexBar1].style.backgroundColor = DEFAULT_BAR_COLOR;
arrayBars[indexBar2].style.backgroundColor = DEFAULT_BAR_COLOR;
}
}
}, i * ANIMATION_SPEED);
}
}
setTimeout(() => {
this.setState({isSliderActive : true, algoSelected: null , isGenerateArrayEnabled : true});
} , animations.length * ANIMATION_SPEED);
}
insertionSort() {
const { array } = this.state
const animations = InsertionSort.insertionSort(array);
for (let i = 0; i < animations.length; i++) {
const arrayBar = document.getElementsByClassName(`${this.state.barClass}`);
const [index_1, index_2, operation] = animations[i];
setTimeout(() => {
if (operation === 1) {
let bar1_prop = arrayBar[index_1].style;
let bar2_prop = arrayBar[index_2].style;
if (bar1_prop.height < bar2_prop.height) {
bar1_prop.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
bar2_prop.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
} else {
bar1_prop.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
bar2_prop.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
}
} else if (operation === 2) {
let bar1_prop = arrayBar[index_1].style;
let bar2_prop = arrayBar[index_2].style;
bar1_prop.backgroundColor = `${this.state.barColor}`;
bar2_prop.backgroundColor = `${this.state.barColor}`;
} else {
let bar1_prop = arrayBar[index_1].style;
bar1_prop.height = `${index_2}px`;
}
}, i * ANIMATION_SPEED);
}
setTimeout(() => {
this.setState({isSliderActive : true, algoSelected: null , isGenerateArrayEnabled : true});
} , animations.length * ANIMATION_SPEED);
}
selectionSort() {
const { array } = this.state
const animations = SelectionSort.selectionSort(array);
for (let i = 0; i < animations.length; i++) {
const arrayBar = document.getElementsByClassName(`${this.state.barClass}`);
const [index_1, index_2, operation] = animations[i];
setTimeout(() => {
if (operation === 1) {
let bar1_prop = arrayBar[index_1].style;
let bar2_prop = arrayBar[index_2].style;
if (bar1_prop.height < bar2_prop.height) {
bar1_prop.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
bar2_prop.backgroundColor = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
} else {
bar1_prop.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
bar2_prop.backgroundColor = CORRECT_PLACE_COMPARISION_BAR_COLOR;
}
} else if (operation === 2) {
let bar1_prop = arrayBar[index_1].style;
let bar2_prop = arrayBar[index_2].style;
bar1_prop.backgroundColor = `${this.state.barColor}`;
bar2_prop.backgroundColor = `${this.state.barColor}`;
} else {
let bar1_prop = arrayBar[index_1].style;
bar1_prop.height = `${index_2}px`;
}
}, i * ANIMATION_SPEED);
}
setTimeout(() => {
this.setState({isSliderActive : true, algoSelected: null , isGenerateArrayEnabled : true});
} , animations.length * ANIMATION_SPEED);
}
mergeSort() {
const { array } = this.state
const animations = MergeSort.getAnimationsforMergeSort(array);
const arrayBars = document.getElementsByClassName(`${this.state.barClass}`);
let index = 0;
let size = arrayBars.length
for (let [index_1, index_2, operation] of animations) {
setTimeout(() => {
if (operation === 1) {
console.log(index_1);
arrayBars[
index_1
].style.height = INCORRECT_PLACE_COMPARISION_BAR_COLOR;
} else {
if (index_1 >= size) {
console.log(index_1);
} else arrayBars[index_1].style.height = `${index_2}px`;
}
}, index * ANIMATION_SPEED);
index++;
}
setTimeout(() => {
this.setState({isSliderActive : true, algoSelected: null , isGenerateArrayEnabled : true});
} , animations.length * ANIMATION_SPEED);
}
render() {
return (
<>
<Slider resetArray={this.resetArray}
isSliderActive={this.state.isSliderActive}/>
<NavBar resetArray={this.resetArray}
changeBarColor={this.changeBarColor}
selectAlgo={this.selectAlgo}
showModal={this.showModal}
deactivateSlider={this.deactivateSlider}
isGenerateArrayEnabled={this.state.isGenerateArrayEnabled}/>
<InstructionsModal
show={this.state.modalActive}
onHide={() => this.setState({modalActive: false})}
/>
<div style={{ backgroundColor: "black", width: "100%" , position: "relative" }}>
<div
style={{
marginTop: "70px",
backgroundColor: "black",
height: `${MAX_HEIGHT}px`,
margin: "3% 10%"
}}
className="array-container"
>
{this.state.array.map((value, idx) => (
<div
className={this.state.barClass}
key={idx}
style={{ height: `${value}px`, width: `${BAR_WIDTH}px`}}
></div>
))}
</div>
<Button variant="outline-warning" className="button-centre" onClick={ () => {
const currentAlgo = this.state.algoSelected;
if (currentAlgo == null) {
alert("Please select an algorithm to visualize");
return;
}
switch(currentAlgo) {
case "InsertionSort": this.insertionSort();
break;
case "MergeSort" : this.mergeSort();
break;
case "SelectionSort" : this.selectionSort();
break;
case "BubbleSort" : this.bubbleSort();
break;
default : alert("Algo not found");
}
} }>Visualize</Button>{' '}
</div>
</>
)
}
}
function generateRandomValue(lower_bound, upper_bound) {
return Math.floor(
Math.random() * (upper_bound - lower_bound + 1) + lower_bound
);
}
export default Bars;
|
import React, { useContext } from "react";
import Head from "next/head";
import { fetchAPI } from "../lib/api";
import { GlobalContext } from "../pages/_app";
import stylesheet from "styles/main.scss";
import Image from "../components/Image";
import format from "date-fns/format";
import NavBar from "../components/NavBar";
const Articles = ({ articles }) => {
const { siteName } = useContext(GlobalContext);
console.log(articles);
return (
<div>
<Head>
<title>{siteName}</title>
<link
href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600,600i"
rel="stylesheet"
/>
</Head>
<style dangerouslySetInnerHTML={{ __html: stylesheet }} />
<NavBar />
<div id="wrapper" className="articles-wrapper">
<div id="articles">
<div id="blog-page-title">
<h1>Miriam's Blog</h1>
</div>
{articles.map((article) => {
return (
<div
className="article-container"
key={`${article.id}-${article.slug}`}
title={article.title}
>
<div className="article-image-container">
<Image image={article.image} />
</div>
<div className="article-meta-container">
<h2 className="article-title-container">{article.title}</h2>
<div>
{format(new Date(article.publishedAt), "MMMM do, yyyy")}
</div>
<div>{article.author.name}</div>
<div>{article.category.name}</div>
</div>
</div>
);
})}
</div>
</div>
<div id="bg" />
</div>
);
};
export async function getStaticProps() {
const articles = await fetchAPI("/articles?status=published");
return {
props: { articles },
revalidate: 1,
};
}
export default Articles;
|
/**
* Created by cl-macmini-63 on 2/1/17.
*/
/**
* Created by cl-macmini-63 on 1/18/17.
*/
'use strict';
const responseFormatter = require('Utils/responseformatter.js');
let commonFunction=require('Utils/commonfunction.js');
var config=require('../config');
const cardSchema = require('schema/mongo/cardschema');
const log = require('Utils/logger.js');
const logger = log.getLogger();
var async=require('async')
var AWS = config.amazon.s3
module.exports = {};
module.exports.addCards = function(payload , callback){
let card = new cardSchema.Card();
card.card_id = card._id;
card.card_name = payload.card_name;
card.card_type = payload.card_type;
card.card_fields = payload.card_fields;
async.series([
function(cb){
if (payload.hasOwnProperty("icon") && payload.icon) {
let fileName = payload.icon.filename;
let tempPath = payload.icon.path;
if(typeof payload.icon !== 'undefined' && payload.icon.length){
fileName = payload.icon[1].filename;
tempPath = payload.icon[1].path;
}
console.log("tempPath",fileName)
commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) {
if (err) {
cb(err);
}
else {
let x = fileName;
let fileNameFirst = x.substr(0, x.lastIndexOf('.'));
let extension = x.split('.').pop();
card.icon = {
original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName,
thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension
};
console.log("file upload success");
console.log("teamPhoto",card.icon);
cb(null)
}
});
}
else {
cb(null);
}
},
function(cb){
card.save(function(err,card){
if (err){
responseFormatter.formatServiceResponse(err, cb);
}
else {
console.log("in success :card created successfully");
responseFormatter.formatServiceResponse(card, cb, 'card Saved successfully','success',200);
}
});
}
],function(err,data){
if(err){
callback(err)
}
else{
data=card
callback(null,data)
}
})
};
module.exports.getCards = function(callback){
cardSchema.Card.find({"is_active" : true}, function (err, cards) {
if (err){
logger.error("Find failed", err);
responseFormatter.formatServiceResponse(err, callback);
}
else {
if(cards && cards.length){
responseFormatter.formatServiceResponse(cards, callback ,'','success',200);
}
else{
responseFormatter.formatServiceResponse({}, callback, "No cards Found." , "error",404);
}
}
});
};
|
'use strict';
require('es6-promise').polyfill();
// Load required files that aren't auto-loaded by
// gulp-load-plugins (see below)
var argv = require('yargs').argv,
fs = require('fs'),
gulp = require('gulp'),
mainBowerFiles = require('main-bower-files'),
merge = require('merge-stream'),
minifyCss = require('gulp-minify-css'),
path = require('path'),
taskListing = require('gulp-task-listing');
// Browserify specific
var babelify = require('babelify'),
browserify = require('browserify'),
source = require('vinyl-source-stream');
// This will load any gulp plugins automatically that
// have this format ('gulp-pluginName' [can only have one dash])
// The plugin can used as $.pluginName
var $ = require('gulp-load-plugins')();
// Browser Sync
var browserSync = require('browser-sync'),
reload = browserSync.reload;
// Add a task to render the output
// Used for $-> gulp help
gulp.task('help', taskListing);
// Paths
var cssPath = 'static_dev/css',
javascriptsPath = 'static_dev/javascripts',
imagesPath = 'static_dev/images',
sassPath = 'static_dev/sass';
// Get Folder Function (from paths)
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
// Main serve task
// Watches coffee, js, and scss files for changes. Will restart
// apache and reload browser automatically
gulp.task('serve', function() {
gulp.watch([
'static_dev/javascripts/**/app.js',
'static_dev/javascripts/**/**/*.js'
], ['scripts-browserify', 'shell-apache']);
gulp.watch('static_dev/css/**/*.css', ['styles-css', 'shell-apache']);
gulp.watch('static_dev/sass/**/*.scss', ['styles-sass', 'shell-apache']);
});
/* Shell tasks */
// Quick ways of running python and client related tasks
gulp.task('shell-apache', $.shell.task(['sudo service httpd restart']))
/* Main bower tasks */
gulp.task('bower', ['bower-scripts', 'bower-styles']);
/* mainBowerFiles looks in an npm package's bower.json file
for the 'main' entry - http://bower.io/docs/creating-packages/#main
- and loops through the files listed there */
// Uglify's all bower/vendor scripts into single file
gulp.task('bower-scripts', function() {
return gulp.src(mainBowerFiles())
// Filter javascript files
.pipe($.filter('*.js'))
// Concat to single file
.pipe($.concat('vendor.js'))
// Remove whitespace and uglify
.pipe($.uglify())
// Rename the file
.pipe($.rename('vendor.min.js'))
// Copy to static folder
.pipe(gulp.dest('static/javascripts'))
});
// Concats all bower/vendor styles into single file
gulp.task('bower-styles', function() {
return gulp.src(mainBowerFiles())
// Filter CSS files
.pipe($.filter('*.css'))
// Concat to single file
.pipe($.concat('vendor.css'))
// Minify CSS
.pipe(minifyCss({ compatibility: 'ie9', rebase: false }))
// Post CSS processor
.pipe($.postcss([
require('autoprefixer')({ browsers: ['last 1 version'] })
]))
// Copy to static folder
.pipe(gulp.dest('static/stylesheets'))
});
/* Main scripts tasks */
gulp.task('scripts', ['scripts-browserify'])
// Browserify task
gulp.task('scripts-browserify', function() {
var folders = getFolders(javascriptsPath);
var tasks = folders.map(function(folder) {
return browserify({
entries: ['./static_dev/javascripts/' + folder + '/app.js'],
debug: true
})
.transform(babelify, { presets: ['es2015', 'react'] })
.bundle()
.pipe(source(folder + '.js'))
//.pipe($.uglify())
.pipe($.rename(folder + '.min.js'))
.pipe(gulp.dest('./static/javascripts/'));
});
return merge(tasks);
});
/* Main styles tasks */
gulp.task('styles', ['styles-sass']);
// CSS Task
// Concats and minifies css files
gulp.task('styles-css', function() {
var folders = getFolders(cssPath);
var tasks = folders.map(function(folder) {
return gulp.src('static_dev/css/' + folder + '/*.css',
{ base: 'static_dev/css/' + folder }
)
// Concat files
.pipe($.concat(folder + '.css'))
// Minify CSS
.pipe(minifyCss({ compatibility: 'ie9', rebase: false }))
// Post CSS processor
.pipe($.postcss([
require('autoprefixer')({ browsers: ['last 1 version'] })
]))
// Rename the file
.pipe($.rename(folder + '.min.css'))
// Copy it to static folder
.pipe(gulp.dest('static/stylesheets'))
});
return merge(tasks);
});
// SASS Task
// Compiles, concats, minifies, and versions scss files
gulp.task('styles-sass', function() {
var folders = getFolders(sassPath);
var tasks = folders.map(function(folder) {
return gulp.src(['static_dev/sass/' + folder + '/*.scss'],
{ base: 'static_dev/sass/' + folder }
)
// Compile to CSS
.pipe($.sass({
outputStyle: 'nested',
precision: 10,
includePaths: ['.'],
onError: console.error.bind(console, 'Sass error:')
}))
// Concat files
.pipe($.concat(folder + '.css'))
// Minify CSS
//.pipe(minifyCss({ compatibility: 'ie9', rebase: false }))
// Post CSS processor
.pipe($.postcss([
require('autoprefixer')({ browsers: ['last 1 version'] })
]))
// Rename the file
.pipe($.rename(folder + '.min.css'))
// Copy it to static folder
.pipe(gulp.dest('static/stylesheets'))
});
return merge(tasks);
});
/* Main image tasks */
gulp.task('media', ['images']);
/* Images Task
Optimizes images and places copies in static/app_name/*.{jpg|png}
This task needs to be run manually. It is not triggered by anything
other than 'build' */
gulp.task('images', function() {
var folders = getFolders(imagesPath);
var tasks = folders.map(function(folder) {
return gulp.src('static_dev/images/' + folder + '/*',
{ base: 'static_dev/images/' })
.pipe($.imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{cleanupIDs: false}]
}))
.pipe(gulp.dest('static/images'));
});
return merge(tasks);
});
gulp.task('build', ['bower', 'scripts', 'styles'])
|
(function () {
'use strict';
/**
* @ngdoc object
* @name posters.controller:PostersCtrl
*
* @description
*
*/
angular
.module('posters')
.controller('PostersCtrl', PostersCtrl);
function PostersCtrl($scope, $rootScope, $mdDialog,Posters) {
$scope.posters = [];
$scope.getAll = function() {
showLoader();
Posters.getAll().then(function(response) {
$scope.posters = response.data;
hideLoader();
});
}
$scope.deleteDialog = function(itemToDelete, index, ev) {
$scope.itemToDelete = itemToDelete;
$scope.itemToDelete.index = index;
$mdDialog.show({
targetEvent: ev,
templateUrl: 'deleteDialog.html',
scope: $scope,
preserveScope: true,
clickOutsideToClose: true
});
}
$scope.delete = function() {
showLoader();
Posters.delete($scope.itemToDelete.Id).then(function(response) {
if (response.data) {
$scope.posters.splice($scope.itemToDelete.index, 1);
$scope.itemToDelete = {};
$scope.hideDialog();
}
hideLoader();
});
}
$scope.getAll();
}
}());
|
var wordBank = ['Zeus', 'Cronos', 'Ares', 'Hermes', 'Apollo', 'Uranus', 'Helios','Atlas',
'Hephaestus','Prometheus','Kratos','Tyche','Athena','Poisedon','Aphrodite','Demeter','Hestia','Hera','Artemis','Hades'] ;
var random = Math.floor(Math.random() * wordBank.length);
var randomWord = wordBank[random];
module.exports = randomWord;
|
import React, { useState } from 'react';
import { Table, Input, Button, Space, Popconfirm } from 'antd';
import { SearchOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import Modal from "../Modal";
import EditPuestoForm from "./EditPuestoForm";
import { deletePuestoApi } from "../../Api/puestos";
export default function ListPuestos(props) {
const { puestos, setReloadPuesto } = props
const [viewPuestos, setviewPuestos] = useState(true);
const [isVisibleModal, setIsVisibleModal] = useState(false);
const [modalTitle, setModalTitle] = useState("");
const [modalContent, setModalContent] = useState(null);
return (
<>
<div>
{viewPuestos ? <Puestos puestos={puestos} setIsVisibleModal={setIsVisibleModal} setModalTitle={setModalTitle} setModalContent={setModalContent}
setReloadPuesto={setReloadPuesto} /> : <Puestos />}
</div>
<Modal
title={modalTitle}
isVisible={isVisibleModal}
setIsVisible={setIsVisibleModal}
>
{modalContent}
</Modal>
</>
)
}
function Puestos(props) {
const { puestos, setIsVisibleModal, setModalTitle, setModalContent, setReloadPuesto } = props;
const editPuesto = puesto => {
setIsVisibleModal(true);
setModalTitle(`Editar ${puesto.nombre}`);
setModalContent(<EditPuestoForm puesto={puesto} setIsVisibleModal={setIsVisibleModal} setReloadPuesto={setReloadPuesto} />);
}
return (
<div>
<br />
<PuestosListTable userData={puestos} editFunction={editPuesto} />
</div>
)
}
class PuestosListTable extends React.Component {
state = {
searchText: '',
searchedColumn: ''
};
getColumnSearchProps = dataIndex => ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
<div style={{ padding: 8 }}>
<Input
ref={node => {
this.searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
<Space>
<Button
type="primary"
onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
icon={<SearchOutlined />}
size="small"
style={{ width: 90 }}
>
Search
</Button>
<Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
Reset
</Button>
<Button
type="link"
size="small"
onClick={() => {
confirm({ closeDropdown: false });
this.setState({
searchText: selectedKeys[0],
searchedColumn: dataIndex,
});
}}
>
Filter
</Button>
</Space>
</div>
),
filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
onFilter: (value, record) =>
record[dataIndex]
? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
: '',
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => this.searchInput.select(), 100);
}
},
render: text =>
this.state.searchedColumn === dataIndex ? (
<Highlighter
highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
searchWords={[this.state.searchText]}
autoEscape
textToHighlight={text ? text.toString() : ''}
/>
) : (
text
),
});
handleSearch = (selectedKeys, confirm, dataIndex) => {
confirm();
this.setState({
searchText: selectedKeys[0],
searchedColumn: dataIndex,
});
};
handleReset = clearFilters => {
clearFilters();
this.setState({ searchText: '' });
};
handleDelete = (key) => {
const dataSource = [...this.props.userData];
this.setState(
deletePuestoApi(key)
);
window.location.reload()
}
render() {
const columns = [
{
title: 'Codigo',
dataIndex: 'codigo',
key: 'codigo',
width: '20%',
...this.getColumnSearchProps('codigo'),
},
{
title: 'Nombre',
dataIndex: 'nombre',
key: 'nombre',
width: '25%',
...this.getColumnSearchProps('nombre'),
},
{
title: 'Interno o Externo',
dataIndex: 'internoExterno',
key: 'internoExterno',
width: '25%',
...this.getColumnSearchProps('internoExterno'),
},
{
title: 'Rol',
dataIndex: 'roll',
key: 'roll',
width: '25%',
...this.getColumnSearchProps('roll'),
},
{
title: 'Editar',
key: 'action',
width: '12.5%',
render: (text, record) => (
<Space size="middle" onClick={() => this.props.editFunction(record)}>
<a style={{ color: "rgb(192, 0, 64" }}>Editar</a>
</Space>
)
},
{
title: 'Eliminar',
dataIndex: 'operation',
width: '20%',
render: (_, record) =>
this.props.userData.length >= 1 ? (
<Popconfirm title="¿Seguro que desea eliminarlo?" onConfirm={() => this.handleDelete(record._id)} icon={<QuestionCircleOutlined style={{ color: 'red' }} />}>
<a style={{ color: "rgb(192, 0, 64" }}>Delete</a>
</Popconfirm>
) : null,
}
];
return <Table columns={columns} dataSource={this.props.userData} bordered />;
}
}
|
import React from 'react';
import FA from 'react-fontawesome';
import Tile from 'components/tiles/tile.js'
export default class WebGL3D extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
var main = (
<Tile className="bg-warning col-xs-6 col-sm-4 col-md-3"
title="Prüfstation • 3D-Ansicht"
description="Modell der Drucker als WebGL-Plugin">
<a href="/webgl_unity_tp3" className="btn btn-warning">
<FA name="check-square" className="px-1" size="3x"/>
<FA name="cubes" className="px-1" size="2x"/>
</a>
</Tile>
)
return main;
}
}
|
/*
Implements the logic for editing the profile's bio and avatar.
*/
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// When page renders.
document.addEventListener('DOMContentLoaded', () => {
// if current user if the profile's owner, add ability to edit bio on click.
const btn = document.querySelector(`#bio-btn`)
if(btn) btn.onclick = editBio;
});
// Render profile's bio as a textarea.
function editBio(e) {
e.preventDefault();
const content_div = document.querySelector(`#profile-bio`);
// Transform bio into a textarea.
content_div.innerHTML = `<textarea class="form-control" rows="${ content_div.offsetHeight / 25 }"> ${ content_div.innerText } </textarea>`;
// render a button to save edited bio.
document.querySelector(`#btn-div`).style.display ='block';
};
// Save edited bio or avatar.
function save(edit_avatar) {
// Get avatar and bio div and profile's id.
const content_div = document.querySelector(`#profile-bio`),
avatar_div = document.querySelector(`#profile-avatar`),
id = document.querySelector(`#profile-id`).innerText;
// Request header
// url is profile/profile_id
const request = new Request(
`/profile/${id}`,
{headers: {'X-CSRFToken': csrftoken}}
),
// body is either the new avatar or the new bio
body = edit_avatar ?
{avatar: document.querySelector(`#avatar-url`).value}
: {bio: content_div.children[0].value}
;
// Put new bio or avatar in profile.
fetch(request, {
method: 'PUT',
mode: 'same-origin',
body: JSON.stringify(body)
}).then(response => response.json())
.then(result => {
if(!result.error) {
// if no error occurred, render update information without reloading
content_div.innerText = result.bio;
avatar_div.innerHTML = `<img id="profile-img" src="${result.avatar || '/static/calendarApp/profile.svg'}" alt="">`;
// Hide avatar modal in case avatar was edited
$('#modal').modal('hide');
}
else {
// if an error occurred, handle it.
handleError(result.error);
}
}
);
document.querySelector(`#btn-div`).style.display ='none';
};
// Handle possible errors on fetching data.
// Display error message in #error-alert element
function handleError(message) {
const tmp = document.querySelector('#error-alert')
tmp.innerText = message;
tmp.style.display = 'grid';
tmp.addEventListener('click', () => {
tmp.innerText = '';
tmp.style.display = 'none';
});
}
|
/**
* Created by xuwusheng on 15/12/12.
*/
define(['../../../app'], function (app) {
app.factory('platformDestroyDetail', ['$http','$q','HOST',function ($http,$q,HOST) {
return {
getThead: function () {
return [
{name:'序号',type:'pl4GridCount'},
{field:'taskId',name:'客户'},
{field:'fhtime',name:'仓库'},
{field:'chuHuoName',name:'日期'},
{field:'clientName',name:'损毁单号'},
{field:'orderTypeName',name:'供应商全称'},
{field:'inGoodsStateName',name:'赔偿主体名称'},
{field:'origGoodCount',name:'商品品类'},
{field:'origGoodCount',name:'商品品牌'},
{field:'origGoodCount',name:'商品编码'},
{field:'origGoodCount',name:'商品名称'},
{field:'origGoodCount',name:'规格型号'},
{field:'origGoodCount',name:'出厂编码'},
{field:'origGoodCount',name:'计量单位'},
{field:'origGoodCount',name:'损毁数量'}
]
},
getDataTable: function (data) {
//将parm转换成json字符串
data.param=$filter('json')(data.param);
var deferred=$q.defer();
$http.get(HOST+'/pl4/rest/pl4/ckTaskIn/ckTaskInList',{params:data})
.success(function (data) {
deferred.resolve(data);
})
.error(function (e) {
deferred.reject('error:'+e);
});
return deferred.promise;
}
}
}]);
});
|
function register(env) {
env.addGlobal("crm_object", handler);
}
function handler(object_type, query_or_object_instance_id, properties, formatting) {
return 'crm_object not implemented yet';
}
export {
handler,
register as default
};
|
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.app.FREnreport.report_stock', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('app.FREnreport.report_stock', {
url: '/report_stock',
templateUrl: 'app/pages/app/FREnreport/report_stock/report_stock.html',
controller: 'Report_StockCtrl',
title: 'report.report_stock',
sidebarMeta: {
icon: 'ion-android-home',
order: 1,
},
});
}
})();
|
import React from 'react';
import Omikuji from "./components/Omikuji";
const omikujiPossibilities = [
{
name: 'daikichi',
weight: 30,
},
{
name: 'kichi',
weight: 50,
},
{
name: 'daikyo',
weight: 20,
},
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
result: 0,
};
}
render() {
return (
<div className="App">
<Omikuji
omikujiPossibilities={omikujiPossibilities}
/>
</div>
);
}
}
export default App;
|
import log4js from 'log4js';
import fs from 'fs';
import path from 'path';
export default class Log {
constructor() {
var objConfig = JSON.parse(fs.readFileSync(path.join(config.configpath,'log4js.json'), "utf8"));
if (objConfig.appenders) {
var baseDir = path.join(config.rootpath, objConfig["customBaseDir"]);
var defaultAtt = objConfig["customDefaultAtt"];
for (var i = 0, j = objConfig.appenders.length; i < j; i++) {
var item = objConfig.appenders[i];
if (item["type"] == "console") {
continue;
}
if (defaultAtt != null) {
for ( var att in defaultAtt) {
if (item[att] == null)
item[att] = defaultAtt[att];
}
}
if (baseDir != null) {
if (item["filename"] == null) {
item["filename"] = baseDir;
} else {
item["filename"] = baseDir + item["filename"];
}
}
var fileName = item["filename"];
if (fileName == null) {
continue;
}
var pattern = item["pattern"];
if (pattern != null) {
fileName += pattern;
}
var dir = path.dirname(fileName);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
}
}
log4js.configure(objConfig);
this.console = log4js.getLogger('console');
this.logAll = log4js.getLogger('logAll');
this.logTrace = log4js.getLogger('logTrace');
this.logDebug = log4js.getLogger('logDebug');
this.logInfo = log4js.getLogger('logInfo');
this.logWarn = log4js.getLogger('logWarn');
this.logError = log4js.getLogger('logError');
this.logFatal = log4js.getLogger('logFatal');
this.use = function * (app){
app.use(log4js.connectLogger(this.console, {
level : config.loglevel,
format : ':method :url'
}));
}
}
trace = function(msg) {
if (msg == null) {
msg = "";
}
if(config.env === 1) {
this.console.trace(msg);
}
this.logAll.trace(msg);
this.logTrace.trace(msg);
}
debug = function(msg) {
if (msg == null) {
msg = "";
}
if(config.env === 1) {
this.console.debug(msg);
}
this.logAll.debug(msg);
this.logDebug.debug(msg);
}
info = function(msg) {
if (msg == null) {
msg = "";
}
if(config.env === 1) {
this.console.info(msg);
}
this.logAll.info(msg);
this.logInfo.info(msg);
}
warn = function(msg) {
if (msg == null) {
msg = "";
}
if(config.env === 1) {
this.console.warn(msg);
}
this.logAll.warn(msg);
this.logWarn.warn(msg);
}
error = function(msg, exp) {
if (msg == null) {
msg = "";
}
if (exp != null) {
msg += "\r\n" + exp;
}
if(config.env === 1) {
this.console.error(msg);
}
this.logAll.error(msg);
this.logError.error(msg);
}
fatal = function(msg, exp) {
if (msg == null) {
msg = "";
}
if (exp != null) {
msg += "\r\n" + exp;
}
if(config.env === 1) {
this.console.fatal(msg);
}
this.logAll.fatal(msg);
this.logFatal.fatal(msg);
}
}
|
Ext.define('Gvsu.modules.docs.model.DocTypesModel', {
extend: "Core.data.DataModel"
,collection: 'gvsu_docstypes'
,fields:[{
name: '_id',
type: 'ObjectID',
visable: true
},{
name: 'name',
type: 'string',
filterable: true,
editable: true,
visable: true
},{
name: 'duration',
type: 'int',
filterable: true,
editable: true,
visable: true
},{
name: 'descript',
type: 'text',
filterable: false,
editable: true,
visable: true
},{
name: 'required',
type: 'boolean',
filterable: true,
editable: true,
visable: true
},{
name: 'indx',
type: 'sortfield',
sort: 1,
filterable: true,
editable: true,
visable: true
}]
})
|
export default {
'': [
'rgba',
'hsl',
'hsla',
],
};
|
../../../../../shared/src/App/Pornstar/actions.js
|
var express = require('express');
const errors = require("../../../../../errors");
const models = require("../../../../../../models");
const ResponseTemplate = require("../../../../../ResponseTemplate");
const SimpleValidators = require("../../../../../../util/SimpleValidators");
const {hasValue} = SimpleValidators;
const JalaliDate = require("../../../../../../util/JalaliDate");
const TypeChecker = require("../../../../../../util/TypeChecker");
const {firstWithValue} = require("../../../../../../util/DatabaseNormalizer");
const {asyncFunctionWrapper} = require("../../../../util");
const {QueryTypes} = require("sequelize");
var router = express.Router();
router.get('', asyncFunctionWrapper(getAllVisits));
router.post('', asyncFunctionWrapper(addVisit));
router.get('/:visitId', asyncFunctionWrapper(getVisit));
async function getAllVisits(req, res, next) {
const patientUserId = req.patientInfo.userId;
let patient = await models.Patient.findOne({
where: {userId: patientUserId, physicianUserId: req.principal.userId},
include: ['visits', 'medicationHistory'],
});
if (patient == null) {
next(new errors.PatientNotFound());
return;
}
let visits = patient.visits
.map(visit => visit.getApiObject());
visits.forEach(visit => visit.medicationHistory = patient.medicationHistory);
const response = ResponseTemplate.create()
.withData({
visits,
});
res.json(response);
}
async function getVisit(req, res, next) {
const patientUserId = req.patientInfo.userId;
const visitId = req.params.visitId;
let patient = await models.Patient.findOne({
where: {userId: patientUserId, physicianUserId: req.principal.userId},
include: [{model: models.Visit, as: 'visits', where: {id: visitId}}, 'medicationHistory'],
});
if (patient == null) {
next(new errors.VisitNotFound());
return;
}
else if (patient.visits.length === 0) {
next(new errors.VisitNotFound());
return;
}
let visit = patient.visits[0].getApiObject();
visit.medicationHistory = patient.medicationHistory;
const response = ResponseTemplate.create()
.withData({
visit,
});
res.json(response);
}
async function addVisit(req, res, next) {
const patientUserId = req.patientInfo.userId;
const appointmentId = req.query.appointmentId;
const visitToAdd = req.body.visit;
if ((visitToAdd || null) == null) {
next(new errors.IncompleteRequest("Visit info was not provided."));
return;
}
if (!SimpleValidators.hasValue(appointmentId)) {
next(new errors.IncompleteRequest("Please provide appointmentId as a query string ."));
return;
}
let patient = await models.Patient.findOne({
where: {userId: patientUserId, physicianUserId: req.principal.userId},
include: [{model: models.VisitAppointment, as: 'appointments', where: {id: appointmentId}}, 'medicationHistory'],
});
if (patient == null) {
next(new errors.AppointmentNotFound());
return;
}
const attendedAppointment = patient.appointments[0];
if (attendedAppointment.hasVisitHappened) {
next(new errors.AlreadyExistsException("This appointment was attended before."));
return;
}
await models.Visit.sequelize.transaction(async (tr) => {
attendedAppointment.hasVisitHappened = true;
attendedAppointment.save({transaction: tr});
const medicationHistory = visitToAdd.medicationHistory;
if (SimpleValidators.hasValue(medicationHistory) && TypeChecker.isList(medicationHistory)) {
await models.PatientMedicationRecord.destroy({
where: {
patientUserId: patientUserId,
},
transaction: tr,
});
medicationHistory.forEach(record => record.patientUserId = patientUserId);
const insertedMedicationHistory = await models.PatientMedicationRecord.bulkCreate(
medicationHistory,
{returning: true, transaction: tr}
)
}
const insertedDosageRecords = await models.WarfarinDosageRecord.insertPrescriptionRecords(visitToAdd.recommendedDosage, patientUserId, new Date(), tr);
if (SimpleValidators.hasValue(visitToAdd.nextVisitDate || null)) {
const jDate = JalaliDate.create(visitToAdd.nextVisitDate);
if (jDate.isValidDate()) {
const appointmentToAdd = {
patientUserId: patientUserId,
approximateVisitDate: jDate.toJson().jalali.asString,
}
const insertedAppointment = await models.VisitAppointment.create(appointmentToAdd, {transaction: tr});
}
}
visitToAdd.patientUserId = patientUserId;
visitToAdd.visitDate = JalaliDate.now().toJson().jalali.asString;
visitToAdd.visitFlag = true;
const insertedVisit = await models.Visit.create(visitToAdd, {transaction: tr});
const response = ResponseTemplate.create()
.withData({
visit: insertedVisit.getApiObject(),
});
res.json(response);
});
}
module.exports = router;
|
import { window, document, setTimeout } from "./globals";
import equiv from "./equiv";
import dump from "./dump";
import module from "./module";
import Assert from "./assert";
import Logger from "./logger";
import Test, { test, pushFailure } from "./test";
import exportQUnit from "./export";
import reporters from "./reporters";
import config from "./core/config";
import { extend, objectType, is, now } from "./core/utilities";
import { registerLoggingCallbacks, runLoggingCallbacks } from "./core/logging";
import { sourceFromStacktrace } from "./core/stacktrace";
import ProcessingQueue from "./core/processing-queue";
import SuiteReport from "./reports/suite";
import { on, emit } from "./events";
import onWindowError from "./core/onerror";
import onUncaughtException from "./core/on-uncaught-exception";
const QUnit = {};
export const globalSuite = new SuiteReport();
// The initial "currentModule" represents the global (or top-level) module that
// is not explicitly defined by the user, therefore we add the "globalSuite" to
// it since each module has a suiteReport associated with it.
config.currentModule.suiteReport = globalSuite;
let globalStartCalled = false;
let runStarted = false;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = ( window && window.location && window.location.protocol === "file:" );
// Expose the current QUnit version
QUnit.version = "@VERSION";
extend( QUnit, {
config,
dump,
equiv,
reporters,
is,
objectType,
on,
onError: onWindowError,
onUncaughtException,
pushFailure,
assert: Assert.prototype,
module,
test,
// alias other test flavors for easy access
todo: test.todo,
skip: test.skip,
only: test.only,
start: function( count ) {
if ( config.current ) {
throw new Error( "QUnit.start cannot be called inside a test context." );
}
const globalStartAlreadyCalled = globalStartCalled;
globalStartCalled = true;
if ( runStarted ) {
throw new Error( "Called start() while test already started running" );
}
if ( globalStartAlreadyCalled || count > 1 ) {
throw new Error( "Called start() outside of a test context too many times" );
}
if ( config.autostart ) {
throw new Error( "Called start() outside of a test context when " +
"QUnit.config.autostart was true" );
}
if ( !config.pageLoaded ) {
// The page isn't completely loaded yet, so we set autostart and then
// load if we're in Node or wait for the browser's load event.
config.autostart = true;
// Starts from Node even if .load was not previously called. We still return
// early otherwise we'll wind up "beginning" twice.
if ( !document ) {
QUnit.load();
}
return;
}
scheduleBegin();
},
onUnhandledRejection: function( reason ) {
Logger.warn( "QUnit.onUnhandledRejection is deprecated and will be removed in QUnit 3.0." +
" Please use QUnit.onUncaughtException instead." );
onUncaughtException( reason );
},
extend: function( ...args ) {
Logger.warn( "QUnit.extend is deprecated and will be removed in QUnit 3.0." +
" Please use Object.assign instead." );
// delegate to utility implementation, which does not warn and can be used elsewhere internally
return extend.apply( this, args );
},
load: function() {
config.pageLoaded = true;
// Initialize the configuration options
extend( config, {
started: 0,
updateRate: 1000,
autostart: true,
filter: ""
}, true );
if ( !runStarted ) {
config.blocking = false;
if ( config.autostart ) {
scheduleBegin();
}
}
},
stack: function( offset ) {
offset = ( offset || 0 ) + 2;
return sourceFromStacktrace( offset );
}
} );
registerLoggingCallbacks( QUnit );
function scheduleBegin() {
runStarted = true;
// Add a slight delay to allow definition of more modules and tests.
if ( setTimeout ) {
setTimeout( function() {
begin();
} );
} else {
begin();
}
}
function unblockAndAdvanceQueue() {
config.blocking = false;
ProcessingQueue.advance();
}
export function begin() {
if ( config.started ) {
unblockAndAdvanceQueue();
return;
}
// The test run hasn't officially begun yet
// Record the time of the test run's beginning
config.started = now();
// Delete the loose unnamed module if unused.
if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) {
config.modules.shift();
}
// Avoid unnecessary information by not logging modules' test environments
const l = config.modules.length;
const modulesLog = [];
for ( let i = 0; i < l; i++ ) {
modulesLog.push( {
name: config.modules[ i ].name,
tests: config.modules[ i ].tests
} );
}
// The test run is officially beginning now
emit( "runStart", globalSuite.start( true ) );
runLoggingCallbacks( "begin", {
totalTests: Test.count,
modules: modulesLog
} ).then( unblockAndAdvanceQueue );
}
exportQUnit( QUnit );
export default QUnit;
|
/**
* 海底漂浮物
*/
class Dust {
constructor(){
this.x = [];
this.y = [];
this.amp = [];//振幅
this.pic = [];
this.NO = [];
this.num;
this.alpha = 0;
}
init(){
this.num = 30;
for(let i = 0; i < 7; i++){
this.pic[i] = new Image();
this.pic[i].src = './src/dust' + i + '.png';
}
for (let i = 0; i < this.num; i++) {
this.x[i] = Math.random() * canWidth;
this.y[i] = Math.random() * canHeight;
this.amp[i] = 20 + Math.random() * 15;
this.NO[i] = Math.floor(Math.random() * 7);//[0,7)
}
this.alpha = 0
}
draw(){
this.alpha += deltaTime * 0.0008;
let l = Math.sin(this.alpha);
for (let i = 0; i < this.num; i++) {
let NO = this.NO[i];
ctx1.drawImage(this.pic[NO], this.x[i] + this.amp[i] * l, this.y[i]);
}
}
}
|
export { default } from 'ember-print-this/services/print-this';
|
import * as React from "react";
function PmIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="5.262"
height="5.263"
viewBox="0 0 5.262 5.263"
{...props}
>
<path
id="Path_245"
data-name="Path 245"
d="M4.926,7.512c-.081,0-.162,0-.244-.011a2.636,2.636,0,0,1,0-5.25.2.2,0,0,1,.182.323A1.69,1.69,0,0,0,7.227,4.936a.2.2,0,0,1,.323.182A2.64,2.64,0,0,1,4.926,7.512ZM4.3,2.732A2.231,2.231,0,1,0,7.067,5.5,2.1,2.1,0,0,1,4.3,2.732Z"
transform="translate(-2.288 -2.249)"
fill="#685bc7"
/>
</svg>
);
}
export default PmIcon;
|
import React, { Component, PropTypes } from 'react';
import AddTodo from '../components/AddTodo.js';
import TodoList from '../components/TodoList.js';
import Footer from '../components/Footer.js';
import { connect } from 'react-redux';
import { addTodo, toggleTodo, setVisibilityFilter, VisibilityFilters } from '../action.js';
class App extends Component {
render() {
const {dispatch, visibleTodos, visibilityFilter} = this.props;
return (
<div>
<AddTodo onAddClick={ text => dispatch(addTodo(text)) } />
<TodoList todos={ visibleTodos } onTodoClick={ index => dispatch(toggleTodo(index)) } />
<Footer filter='SHOW_ALL' onFilterChange={ nextFilter => dispatch(setVisibilityFilter(nextFilter)) } />
</div>
)
}
}
function selectTodos(todos, filter) {
switch (filter) {
case VisibilityFilters.SHOW_ALL:
return todos;
case VisibilityFilters.SHOW_COMPLETED:
return todos.filter(todo => todo.completed);
case VisibilityFilters.SHOW_UNCOMPLETED:
return todos.filter(todo => !todo.completed);
default:
return todos;
}
}
function select(state) {
return {
visibleTodos: selectTodos(state.todos, state.visibilityFilter),
visibilityFilter: state.visibilityFilter
}
}
export default connect(select)(App);
|
'use strict';
// let fileInput = $('#fileToUpload');
// const uploadImage = function () {
// console.log(this.files[0]);
// }
// fileInput.on('change', uploadImage);
var ali = 'hgoli';
var axios = require('axios');
function uImage(e) {
console.log(e.target);
}
|
import React from 'react'
import { shallow, mount } from 'enzyme'
import CardContainer from '../CardContainer'
describe('CardContainer', () => {
let wrapper
let mockData
let mockCompare
beforeEach(() => {
mockData = []
wrapper = shallow(<CardContainer
data={mockData}
comparedArr={mockCompare}/>)
})
it('matches the snapshot', () => {
expect(wrapper).toMatchSnapshot()
})
it('should return information to the card', () => {
expect(wrapper.find('div').length).toEqual(1)
})
})
|
var markedLog = []
for(var i = 0 ; i< 29; i++ ) {
for(var j = 1 ; j< 1200; j++) {
var key = i + "_" + j
if (localStorage.getItem(key)) {
markedLog.push(key)
}
}
}
var eleLink = document.createElement('a');
eleLink.download = 'markers.json';
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([JSON.stringify(markedLog)]);
eleLink.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
|
const dbHelper = require("../utils/dbHelper");
const Response = require("../models/response");
const RESPONESE_CODE = require("../enum/responseCode");
class ContentsController {
read(req, res) {
dbHelper.query("SELECT * FROM my_contents", function(error, results, fields){
if (error) throw error;
res.status(200).json((new Response(RESPONESE_CODE.SUCCESS, "Success Read", results).value()));
});
};
update(req, res) {
if (!req.body.title || !req.body.contents || !req.body.writer){
res.status(400).json((new Response(RESPONESE_CODE.FAIL, "Update Failed", null).value()));
return;
};
dbHelper.query(`UPDATE my_contents SET Title='${req.body.title}', Contents='${req.body.contents}', Writer='${req.body.writer}', CreateDate=now(), ViewCount=0 WHERE ContentNo = '${req.body.contentNo}'`,
function(error, results, fields){
res.status(200).json((new Response(RESPONESE_CODE.SUCCESS, "Success Update", results).value()));
});
};
create(req, res) {
if (!req.body.title || !req.body.contents || !req.body.writer){
res.status(400).json((new Response(RESPONESE_CODE.FAIL, "Invalid Parameters", null).value()));
return;
};
dbHelper.query(`INSERT INTO my_contents VALUES ('${req.body.contentNo}', '${req.body.title}', '${req.body.contents}', '${req.body.writer}', now(), 0)`,
function(error, results, fields){
if(error) {
res.status(500).json((new Response(RESPONESE_CODE.FAIL, "DB Operation Failure", null).value()));
console.log(error);
return;
};
res.status(200).json((new Response(RESPONESE_CODE.SUCCESS, "Success Create", results).value()));
});
};
delete(req, res) {
if (!req.body.contentNo) {
res.status(400).json((new Response(RESPONESE_CODE.FAIL, "Delete Failed", null).value()));
return;
};
dbHelper.query(`DELETE FROM my_contents WHERE contentNo='${req.body.contentNo}'`, function(error, results, fields){
res.status(200).json((new Response(RESPONESE_CODE.SUCCESS, "Success Delete", results).value()));
});
};
};
module.exports = new ContentsController();
|
import React from 'react';
import { withPrefix } from 'gatsby'
import { AnchorLink } from 'gatsby-plugin-anchor-links';
import { useLaxElement } from 'use-lax';
import styled from 'styled-components'
import SEO from "../seo"
import Layout from '../layout'
import Section from '../sections'
import Header from '../headers'
import Navbar from '../navbar'
import Footer from '../content/footer-animated-vs1'
import Image from '../image'
import bgImage from '../../images/backgrounds/bettedaviseyes.png'
const ParallaxLayout = () => {
const menu = [
{ label: "Home", to: "/index-parallax/#PageTop" }, // default pagetop id
{ label: "About", to: "/index-parallax/#About" },
{ label: "Services", to: "/index-parallax/#Services" },
{ label: "Partners", to: "/index-parallax/#Partners" },
{ label: "Contact", to: "/index-parallax/#Footer" } // when contact form is in the footer
]
const refContent = useLaxElement();
return (
<Layout>
<SEO title="Landing Page" />
<Navbar menu={menu} />
<Header>
<div className="container">
<div className="row">
<div className="col-sm-12 col-md-6 mt-5 d-flex flex-column justify-content-center">
<h1 className="text-sm-center text-md-left">
Titulo da página
</h1>
<p className="text-center text-md-left">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolor iusto a libero labore vitae voluptatibus quod, sed sit doloribus aspernatur, ut impedit, adipisci ex autem?
</p>
<AnchorLink to={withPrefix("/#About")} className="m-auto m-md-0">
<p className='btn btn-primary'>More about us</p>
</AnchorLink>
</div>
<div className="col-sm-12 col-md-6 order-first order-md-last p-5 p-md-0">
<Image src="header-illustration.png" alt="illustrated woman holding phone" />
</div>
</div>
</div>
</Header>
<WithLocalStyles
servicesBg={bgImage}
>
<div ref={refContent}
data-lax-translate-y="0 0, vh -400"
className="parallaxContent"
>
<Section id="About">
<div className="py-5" id="about-scroll-target">
<h1 className="mb-5">About</h1>
<div className="row">
<div
data-lax-translate-y = "vh 50, (vh*0.5) -20"
data-lax-opacity_sm = "vh 0, (vh/2) 1"
data-lax-opacity = "vh 0, (vh*0.7) 1"
data-lax-anchor="#about-scroll-target"
className="col-sm-12 col-md-6 col-lg-3 lax">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aut neque in corrupti fugit molestiae deleniti minus iure alias laborum atque.
</div>
<div
data-lax-opacity = "vh 0, (vh*0.7) 1"
data-lax-opacity_sm = "vh 0, (vh/6) 1"
data-lax-translate-y = "vh 100, (vh*0.5) -20"
data-lax-anchor="#about-scroll-target"
className="col-sm-12 col-md-6 col-lg-3 lax">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore dolorem cum ducimus accusamus ea iusto ullam quaerat? Vero eaque unde dolorum, laboriosam quidem fugiat nemo recusandae! Architecto, odio?
</div>
<div
data-lax-opacity = "vh 0, (vh*0.7) 1"
data-lax-translate-y = "vh 150, (vh*0.5) -20"
data-lax-anchor="#about-scroll-target"
className="col-sm-12 col-md-6 col-lg-3 lax">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum, illo tempora repellendus blanditiis consequatur repudiandae!
</div>
<div
data-lax-opacity = "vh 0, (vh*0.7) 1"
data-lax-translate-y = "vh 200, (vh*0.5) -20"
data-lax-anchor="#about-scroll-target"
className="col-sm-12 col-md-6 col-lg-3 lax">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum, illo tempora repellendus blanditiis consequatur repudiandae!
</div>
</div>
</div>
</Section>
<div className="container-fluid p-0 m-0 moving-bg">
<div className="h-moving-bg lax"
data-lax-translate-x="vh 0, 0 -1500"
data-lax-anchor="self">
</div>
</div>
<div className="arrow-down lax"
data-lax-scale="vh 1.2, (vh/1.2) 1"
data-lax-opacity="vh 1, (vh/1.5) 1, 0 0"
data-lax-anchor="self"
>
<Image src="arrows/popart-arrowdown.png"/>
</div>
<div className="container-fluid m-0 p-0">
<div className="container lax"
data-lax-anchor="self"
data-lax-translate-y="vh 0"
>
<h1 className="text-center">Services</h1>
<div className="row">
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore delectus, assumenda expedita beatae quasi dolore esse magni explicabo reprehenderit consequatur. Deleniti, nulla sequi? Deserunt, optio?</p>
</div>
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Temporibus recusandae eligendi laborum accusantium quidem impedit et assumenda laboriosam aliquam at a eveniet dolore cum expedita, provident nesciunt, optio magni eius culpa ipsam. Ipsa inventore molestiae optio! Reprehenderit ad dolorum quae explicabo magnam sunt porro perferendis quas iure iusto! Quos, iste!</p>
</div>
</div>
<div className="row">
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore delectus, assumenda expedita beatae quasi dolore esse magni explicabo reprehenderit consequatur. Deleniti, nulla sequi? Deserunt, optio?</p>
</div>
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Temporibus recusandae eligendi laborum accusantium quidem impedit et assumenda laboriosam aliquam at a eveniet dolore cum expedita, provident nesciunt, optio magni eius culpa ipsam. Ipsa inventore molestiae optio! Reprehenderit ad dolorum quae explicabo magnam sunt porro perferendis quas iure iusto! Quos, iste!</p>
</div>
</div>
<div className="row">
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore delectus, assumenda expedita beatae quasi dolore esse magni explicabo reprehenderit consequatur. Deleniti, nulla sequi? Deserunt, optio?</p>
</div>
<div className="col-sm-12 col-md-6">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Temporibus recusandae eligendi laborum accusantium quidem impedit et assumenda laboriosam aliquam at a eveniet dolore cum expedita, provident nesciunt, optio magni eius culpa ipsam. Ipsa inventore molestiae optio! Reprehenderit ad dolorum quae explicabo magnam sunt porro perferendis quas iure iusto! Quos, iste!</p>
</div>
</div>
</div>
</div>
</div>
</WithLocalStyles>
<Footer/>
</Layout>
)}
export default ParallaxLayout;
// local CSS
const WithLocalStyles = styled.div`
.parallaxContent {
background-color: var(--page-background-hex);
}
.arrow-down {
width: 320px;
height: 320px;
margin: 0 auto;
}
.moving-bg {
--height: 30vh;
overflow: hidden;
position: relative;
box-shadow: inset 0 15px 35px black;
background-color: #6a9ef7;
height: var(--height);
.h-moving-bg {
position: absolute;
top: 0;
left: 0;
background-image: url(${props => props.servicesBg});
background-repeat: repeat;
background-size: auto var(--height);
height: 512px;
width: 400vw;
opacity: 0.5;
}
}
`
|
import DS from 'ember-data';
const {RESTSerializer} = DS;
export default RESTSerializer.extend({
normalizeQueryRecordResponse(store, primaryModelClass, payload, id, requestType) {
payload.room.id = payload.room.rates[0].rateToken;
return this._super(store, primaryModelClass, payload, id, requestType)
}
});
|
function knuthShuffle(numbers) {
var length = numbers.length;
for (var i = 0; i < length; i++) {
var r = Math.floor(Math.random() * (i + 1));
var temp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = temp;
}
}
exports.knuthShuffle = knuthShuffle;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.