text
stringlengths 7
3.69M
|
|---|
/* eslint-disable import/prefer-default-export */
import config from 'config';
export function getInfo(req, res, next) {
const wagerrFee = config.get('wagerr.withdrawalFee');
const bnbFee = config.get('binance.withdrawalFee');
const wagerrAmount = (parseFloat(wagerrFee) * 1e9).toFixed(0);
const bnbAmount = (parseFloat(bnbFee) * 1e9).toFixed(0);
const info = {
fees: { wagerr: wagerrAmount,bnb: bnbAmount },
minWagerrConfirmations: config.get('wagerr.minConfirmations'),
minBnbConfirmations: 1,
};
res.status(205);
res.body = {
status: 200,
success: true,
result: info,
};
return next(null, req, res, next);
}
|
var a;
function f() {
a=5;
};
function g() {
a=5;
f();
};
g();
|
'use strict'
const os = require('os')
const path = require('path')
const fs = require('fs-extra')
const merge = require('webpack-merge')
const webpack = require('webpack')
const MemoryFS = require('memory-fs')
const parse = require('parse-package-name')
const find = require('lodash.find')
const chalk = require('chalk')
const co = require('co')
const gzipSize = require('gzip-size')
const yarnGlobal = require('yarn-global')
const debug = require('debug')('package-size')
const cache = require('./cache')
const install = require('./install')
const statOptions = {
colors: true,
chunks: false,
children: false,
modules: false,
hash: false,
timings: false,
builtAt: false
}
const ensureCachePath = co.wrap(function*() {
const name = `package-size-${rs()}`
const dir = path.join(os.tmpdir(), name)
yield fs.ensureDir(dir)
const data = {
name,
private: true,
license: 'MIT'
}
yield fs.writeFile(
path.join(dir, 'package.json'),
JSON.stringify(data),
'utf8'
)
return dir
})
module.exports = co.wrap(function*(name, opts = {}) {
const outDir = yield ensureCachePath()
const parsed = name.split(',').map(parse)
// When you run `package-size ./dist/index.js,react`
// Or `package-size react-dom,react --cwd`
// All packages will be fetched from cwd.
const isFile = name.charAt(0) === '.'
const isCwd = opts.cwd || isFile
const registry = opts.registry
const config = {
devtool: false,
entry: parsed.map(pkg => {
if (pkg.name === '.' || pkg.path) {
return pkg.name + '/' + pkg.path
}
return pkg.name
}),
output: {
path: outDir
},
resolve: {
modules: [path.join(__dirname, '../node_modules')]
},
performance: {
hints: false
},
externals: [],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty',
dns: 'mock'
},
plugins: [
opts.debug && {
apply(compiler) {
compiler.hooks.done.tap('stats', stats => {
const res = stats.toString(statOptions)
console.log(`\n ${chalk.bold.blue.inverse(` Bundled ${name} `)}\n`)
console.log(res.replace(/^\s*/gm, ' ') + '\n')
})
}
}
].filter(Boolean)
}
const packageInfo = {} // {name:<contents of package.json>}
if (yarnGlobal.inDirectory(__dirname)) {
config.resolve.modules.push(path.join(yarnGlobal.getDirectory()))
}
if (opts.resolve) {
config.resolve.modules = config.resolve.modules.concat(opts.resolve)
}
if (isCwd) {
config.resolve.modules.unshift(path.join(process.cwd(), 'node_modules'))
const pkg = yield readPkg(process.cwd())
config.externals = config.externals.concat(
pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
)
packageInfo[pkg.name] = pkg // Save package info for caching
} else {
config.resolve.modules.unshift(path.join(outDir, 'node_modules'))
yield install(
parsed.map(
pkg => (pkg.version ? `${pkg.name}@${pkg.version}` : pkg.name)
),
registry,
{ cwd: outDir }
)
yield Promise.all(
parsed.map(p => {
return readPkg(path.join(outDir, 'node_modules', p.name)).then(pkg => {
packageInfo[pkg.name] = pkg // Save package info for caching
config.externals = config.externals.concat(
pkg.peerDependencies
? Object.keys(pkg.peerDependencies).filter(name => {
// Don't include packages in the `externals` if they are also in `entry`
return parsed.every(parsedPkg => parsedPkg.name !== name)
})
: []
)
})
})
)
}
// Create a deterministic cache key, by taking the version specifiers
// for each package and sorting them
const cacheKey = Object.keys(packageInfo)
.map(name => `${name}:${packageInfo[name].version}`)
.sort()
.join(',')
.replace(/\./g, '-')
// The cache key replaces the '.'s with '-' so DotProp in `conf` won't
// store the build sizes as nested objects.
// If the key is present in the cache, return the values without re-running
// the webpack build.
if (
!opts.analyze &&
!opts.debug &&
cache.has(cacheKey) &&
opts.cache !== false &&
process.env.NODE_ENV !== 'test'
) {
return cache.get(cacheKey)
}
if (opts.externals) {
const externals = Array.isArray(opts.externals)
? opts.externals
: [opts.externals]
config.externals = config.externals.concat(
externals.map(v => (typeof v === 'string' ? new RegExp(`^${v}$`) : v))
)
}
debug('webpack version', require('webpack/package').version)
const prodConfig = merge(config, {
mode: 'production',
output: {
filename: 'prod.js'
},
optimization: {
minimize: true,
minimizer: [
{
apply(compiler) {
// eslint-disable-next-line import/no-extraneous-dependencies
const Terser = require('terser-webpack-plugin')
new Terser({
cache: true,
parallel: true,
sourceMap: false,
terserOptions: {
output: {
comments: false
},
mangle: true
}
}).apply(compiler)
}
}
]
}
})
if (opts.analyze) {
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
prodConfig.plugins.push(
new BundleAnalyzerPlugin({ analyzerPort: opts.port })
)
console.log('Please wait..')
const stats = yield runWebpack(prodConfig)
console.log(stats.toString(statOptions))
}
const devConfig = merge(config, {
mode: 'development',
output: {
filename: 'dev.js'
}
})
const [devStats, prodStats] = yield Promise.all([
runWebpack(devConfig),
runWebpack(prodConfig)
])
if (devStats.hasErrors()) {
throw new Error(devStats.toString('errors-only'))
}
if (prodStats.hasErrors()) {
throw new Error(prodStats.toString('errors-only'))
}
yield fs.remove(outDir)
const devAssets = devStats.toJson().assets
const prodAssets = prodStats.toJson().assets
const asset = devAssets[0]
const { outputOptions } = prodStats.compilation
const { outputFileSystem } = prodStats.compilation.compiler
const prodOutputFilePath = path.join(
outputOptions.path,
outputOptions.filename
)
const prodGzipSize = yield promisify(gzipSize)(
outputFileSystem.readFileSync(prodOutputFilePath, 'utf8')
)
const info = {
name,
versionedName: parsed
.map(
pkg =>
`${pkg.name}${pkg.path ? `/${pkg.path}` : ''}${packageInfo[pkg.name] ? `@${packageInfo[pkg.name].version}` : ''}`
)
.join(','),
size: asset.size - 2753, // minus webpack runtime size
minified: find(prodAssets, v => {
return decodeURIComponent(v.name) === `prod.js`
}).size - 537,
gzipped: prodGzipSize - 297
}
// Cache the package size information.
cache.set(cacheKey, info)
return info
})
function rs() {
return Math.random().toString(36).substring(7)
}
function runWebpack(config) {
return new Promise((resolve, reject) => {
const compiler = webpack(config)
const mfs = new MemoryFS()
compiler.outputFileSystem = mfs
compiler.run((err, stats) => {
if (err) return reject(err)
resolve(stats)
})
})
}
function readPkg(dir) {
return fs
.readFile(path.join(dir, 'package.json'), 'utf8')
.then(JSON.parse)
.catch(() => ({})) // eslint-disable-line handle-callback-err
}
function promisify(fn) {
return (...args) =>
new Promise((resolve, reject) => {
fn(...args, (err, result) => {
if (err) return reject(err)
resolve(result)
})
})
}
|
import React from "react";
import "./tabListCommon.scss";
function TabListCommon (props) {
const itemLen = props.tabListItem.length;
const eachItemWidth = 100/itemLen;
return (
<div className="info-tab-list clickable" style={{width: `${props.width}`}}>
{
itemLen > 0 &&
props.tabListItem.map( (item, index) => {
return (
<div className={props.activeModuleIndex === index ? "active" : ""}
style={{width: `${eachItemWidth}%`}}
onClick={() => props.onClick(index)}
key={item.title}>
<img src={props.activeModuleIndex === index ? item.activeIcon : item.icon}
alt="" />
<span>{item.title}</span>
</div>
)
})
}
<div className="bar"
style={{left: `${eachItemWidth * props.activeModuleIndex}%`,
width: `${eachItemWidth}%`}}>
</div>
</div>
);
}
export default TabListCommon;
|
import React, { Component } from "react";
import { i18n, withTranslation } from "~/i18n";
class Step4Panel extends Component {
render() {
const { t } = this.props;
const {
stepOneProp,
stepTwoProp,
stepThreeProp,
stepFourProp,
onChangeVendorBranch,
vendorBranchList,
selectedVendorBranch,
isNotGetVendorBranchList
} = this.props;
return (
<div className="col-12 box d-flex flex-wrap vendorAndCompany">
{/* Vendor information - Start */}
<div className="col-6 d-flex-inline flex-wrap">
<h4 className="col-12 border-bottom border-1px pt-0 pb-2">
{t("Vendor")}
</h4>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Code")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.vendorNumber || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Name")} : </div>
<div className="col-7 text-left text-uppercase">
{stepOneProp.mainPO.vendorName || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Tax ID")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.vendorTaxNumber || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap vendor-branch">
<div className="col-5 text-right">{t("Branch")} : </div>
<div className="col-7 text-left">
<select
value={selectedVendorBranch}
name="branch"
onChange={e => onChangeVendorBranch(e)}
>
{console.log(
"---selectedVendorBranch---",
selectedVendorBranch
)}
{stepOneProp.settings &&
stepOneProp.settings.INVOICE_CONFIG.defaultVendorBranch !=
"PO" ? (
<option value={-1} key="0">
Select branch
</option>
) : (
""
)}
}
{vendorBranchList.map((item, i) => {
{
console.log("ITEM ID : ", item.id);
}
return (
<option value={item.id} key={i}>{`${item.branchCode ||
""} ${`(${item.name})` || ""} ${
item.def ? "(PO)" : ""
}`}</option>
);
})}
</select>
<p
className="mt-2 mb-0 ml-0 mr-0 p-0 remark small text-grey"
hidden={!isNotGetVendorBranchList}
>
Only Vendor Branch from PO is available.
</p>
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Address")} : </div>
<div className="col-7 text-left" id="vendorAddress">
{`${stepOneProp.mainPO.vendorAddress1 || ""} ${stepOneProp.mainPO
.vendorDistrict || ""} ${stepOneProp.mainPO.vendorCity ||
""} ${stepOneProp.mainPO.vendorPostalCode || ""}`}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Tel")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.vendorTelephone || "-"}
</div>
</div>
</div>
{/* Vendor information - End */}
{/* Company information - Start */}
<div className="col-6 d-flex-inline flex-wrap">
<h4 className="col-12 border-bottom border-1px pt-0 pb-2">
{t("Company")}
</h4>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Code")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.companyCode || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Name")} : </div>
<div className="col-7 text-left text-uppercase">
{stepOneProp.mainPO.companyName || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Tax ID")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.businessPlaceTaxNumber || "-"}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Branch")} : </div>
<div className="col-7 text-left">
{`${stepOneProp.mainPO.companyBranchCode ||
""} ${`(${stepOneProp.mainPO.companyBranchName})` || ""}`}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Address")} : </div>
<div className="col-7 text-left">
{`${stepOneProp.mainPO.businessPlaceAddress1 || ""} ${stepOneProp
.mainPO.businessPlaceDistrict || ""} ${stepOneProp.mainPO
.businessPlaceCity || ""} ${stepOneProp.mainPO
.businessPlacePostalCode || ""}`}
</div>
</div>
<div className="col-12 py-2 px-0 d-flex flex-wrap">
<div className="col-5 text-right">{t("Tel")} : </div>
<div className="col-7 text-left">
{stepOneProp.mainPO.businessPlaceTelephone || "-"}
</div>
</div>
</div>
{/* Company information - End */}
</div>
);
}
}
export default withTranslation(["detail"])(Step4Panel);
|
$(document).ready(function() {
const alert_val = $('.alert').text();
switch (true) {
case alert_val.indexOf('Name') !== -1 :
$('input[name="name"]').css({'border': '1px solid red', 'background-color' : '#f2dede', 'color': '#b94a48'});
break;
case alert_val.indexOf('email') !== -1 :
$('input[name="email"]').css({'border': '1px solid red', 'background-color' : '#f2dede', 'color': '#b94a48'});
break;
case alert_val.indexOf('password') !== -1 :
$('input[name="password"]').css({'border': '1px solid red', 'background-color' : '#f2dede', 'color': '#b94a48'});
break;
}
});
|
function dateFromSortDate(number) {
var y = Number(number.toString().slice(0,4));
var m = Number(number.toString().slice(4,6));
var d = Number(number.toString().slice(6,8));
return new Date(y,m-1,d);
}
function gleanType(propName, propValue) {
propValue = propValue.trim();
numberValue = Number(propValue.replace(/[,$]/gm,''));
if (!isNaN(numberValue)) { propValue = Number(numberValue); };
if (propName == 'date') { propValue = dateFromSortDate(propValue); };
return propValue;
}
function getPrimaryData(row) {
// hide details "expansion" link
row.cells[0].children[0].hidden = true;
var cellData = {};
for (const cell of row.cells) {
var propName = cell.headers;
var propValue;
if (cell.hasAttribute("sortvalue")) {
propValue = gleanType(propName, cell.getAttribute("sortvalue"));
} else {
propValue = gleanType(propName, cell.innerText);
}
Object.defineProperty(cellData, propName, {
value: propValue,
writable: false
});
}
return cellData;
}
function getTableData() {
var dataTable = document.querySelector("#sortable");
var ret = [];
var ti = -1;
for (const ch of dataTable.children) {
// INCREMENT ROW ITERATOR...
ti++;
// SKIP THEAD... ONLY PROCESS TBODY (GROUPINGS OF DATA)
if (ch.tagName == "TBODY") {
var rowCount= ch.rows.length;
// FIRST ROW IS PRIMARY DATA
var rowData = {};
rowData = getPrimaryData(ch.rows[0]);
rowData.index = ti;
rowData.sources = {};
// SKIP "sources" LABEL ROW... start on index 2. (zero-based)
for (var i = 2; i < rowCount; i++ ) {
const propNames = [];
propNames[1] = 'preTax';
propNames[3] = 'roth401k';
propNames[6] = 'employerMatch';
propNames[24] = 'profitShare';
var propName;
var code;
var description;
var amount;
var currency;
var shares;
// SPLIT TRANSACTION CODE/DESCRIPTION
[code, description] = ch.rows[i].cells[1].innerText.split(" - ");
code = Number(code);
if (propNames[code] != null) {
propName = propNames[code];
currency = "USD";
// DETAIL USD AMOUNT AND SHARE VOLUME
if (ch.rows[i].cells[2].hasAttribute("sortvalue")) {
amount = gleanType(propName, ch.rows[i].cells[2].getAttribute("sortvalue"));
} else {
amount = gleanType(propName, ch.rows[i].cells[2].innerText);
}
shares = gleanType(propName, ch.rows[i].cells[3].innerText);
Object.defineProperty( rowData.sources, propName, {
value: {
code: code,
description: description,
amount: amount,
currency: currency,
shares: shares
},
writable: false
});
} else {
console.log("getTableData: Unknown source " + ch.rows[i].cells[1].innerText + " in group_details for index " + ti + ".");
}
}
ret.push(rowData);
}
}
return ret;
}
function getData() {
// get data
var data = getTableData();
// HIDES DETAILS LINK
// dataTable.rows[1].cells[0].children[0].hidden = true;
return data;
}
function start() {
url.location = 'https://retiretxn.fidelity.com/nbretail/savings2/navigation/dc/History'
}
|
const helloWorld = 'Olá mundão NodeJs!'
console.log(helloWorld)
|
import React from 'react';
import Icon from 'react-native-vector-icons/FontAwesome'
import { createBottomTabNavigator, createAppContainer } from 'react-navigation';
import Map from "./components/Map"
import Home from "./components/Home"
import Chat from "./components/Chat"
import Perfil from "./components/Perfil"
import Friends from "./components/Friends"
const MenuConfig = {
initialRouteName: 'Home',
tabBarOptions: {
showLabel: false,
}
}
const TabNavigator = createBottomTabNavigator({
Home: {
name: 'Home',
screen: Home,
navigationOptions: {
title: 'Home',
tabBarIcon: ({tintColor}) =>
<Icon name= 'home' size= {30} />
}
},
Events: {
name: 'Events',
screen: Friends,
navigationOptions: {
title: 'Chat',
tabBarIcon: ({tintColor}) =>
<Icon name= 'users' size = {30} color= {tintColor} />
}
},
Search :{
name: 'Search',
screen: Map,
navigationOptions: {
title: 'InfoPerson',
tabBarIcon: ({tintColor}) =>
<Icon name= 'search' size = {30} color= {tintColor} />
},
},
Chat: {
name: 'Chat',
screen: Chat,
navigationOptions: {
title: 'Events',
tabBarIcon: ({tintColor}) =>
<Icon name= 'comments' size = {30} color= {tintColor} />
}
},
Perfil: {
name: 'Perfil',
screen: Perfil,
navigationOptions: {
title: 'Perfil',
tabBarIcon: ({tintColor}) =>
<Icon name= 'user' size= {30} color= {tintColor} />
}
}
},MenuConfig);
const App = createAppContainer(TabNavigator,);
export default App;
|
window.onload=function(){
var oBox = document.getElementById("box");
var oPrev = document.getElementsByTagName("span")[0];
var oNext = document.getElementsByTagName("span")[1];
var oUl = document.getElementsByTagName("ul")[0];
var aLi = document.getElementsByTagName("li");
var iHeight = aLi[0].offsetHeight;
var timer = null;
oPrev.onclick = function(){
oUl.insertBefore(aLi[aLi.length-1],aLi[0]);
oUl.style.top = -iHeight + "px";
doMove(0);
}
oNext.onclick = function(){
doMove(-iHeight, function(){
oUl.appendChild(aLi[0]);
oUl.style.top = 0;
})
}
function doMove(iTarget, callBack){
clearInterval(timer);
timer = setInterval(function(){
var iSpeed = (iTarget - oUl.offsetTop) / 5;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed):Math.floor(iSpeed);
oUl.offsetTop == iTarget ? (clearInterval(timer),callBack && callBack.apply(this)):oUl.style.top = iSpeed + oUl.offsetTop + "px";
},30)
}
}
|
// ********MODEL********
// maintains data
// creates doctor and patient objects and adds them to data storage
const model = (function () {
const appData = {
doctors: [],
patients: []
}
function handleAddItem(item) {
if (item instanceof Doctor) {
appData.doctors.push(item);
} else if (item instanceof Patient) {
appData.patients.push(item);
}
}
function handleChooseDoctor(patientIndex, chosenDoctor) {
appData.patients[patientIndex].chosenDoctor = chosenDoctor;
}
const Person = function (name) {
this.name = name;
}
const Doctor = function (name, specialty) {
Person.call(this, name);
this.specialty = specialty;
}
const Patient = function (name, idNumber, cardNumber) {
Person.call(this, name);
this.idNumber = idNumber;
this.cardNumber = cardNumber;
this.chosenDoctor = null;
}
return {
Doctor,
Patient,
handleAddItem,
appData,
handleChooseDoctor
}
})();
// *******VIEW*******
// takes user inputs, displays data
// makes sure UI is updated when data is changed
const view = (function () {
function handleTakeDoctorData(e) {
e.preventDefault();
const elements = e.target.elements;
return {
name: elements.doctorNameInput.value,
specialty: elements.doctorSpecialtyInput.value
}
}
function handleTakePatientData(e) {
e.preventDefault();
const elements = e.target.elements;
return {
name: elements.patientNameInput.value,
id: elements.patientIdInput.value,
cardNo: elements.patientCardNoInput.value
}
}
function handleDisplayDoctors(doctors) {
let output = "";
doctors.forEach((doctor) => {
output += `<li><p>${doctor.name}</p><p>${doctor.specialty}</p></li>`
});
document.getElementById("doctorList").innerHTML = output;
}
function handleDisplayPatients(patients, doctors) {
document.getElementById("patientList").innerHTML = "";
let doctorsListStr = "";
doctors.forEach((doctor) => {
doctorsListStr += `<option>${doctor.name}</option>`;
});
patients.forEach((patient, i) => {
const patientsContainerDiv = document.createElement("div");
patientsContainerDiv.id = i;
const patientElement = document.createElement("div");
patientElement.innerHTML = `<p>${patient.name}</p><p>${patient.idNumber}</p><p>${patient.cardNumber}</p>`;
patientsContainerDiv.appendChild(patientElement);
// create and append an element displaying data on chosen doctor
const chosenDoctorElement = document.createElement("p");
patientsContainerDiv.appendChild(chosenDoctorElement);
// if doctor has been chosen, display the data, else display "no doctor chosen"
// and create and append select element with doctor options
if (patient.chosenDoctor) {
chosenDoctorElement.innerHTML = `<p>${patient.chosenDoctor}</p>`;
} else {
chosenDoctorElement.innerHTML = "(no doctor chosen)";
const selectDoctorElement = document.createElement("select");
const defaultOption = document.createElement("option");
defaultOption.innerHTML = "Choose doctor";
selectDoctorElement.add(defaultOption);
selectDoctorElement.innerHTML += doctorsListStr;
patientsContainerDiv.appendChild(selectDoctorElement);
}
document.getElementById("patientList").appendChild(patientsContainerDiv);
});
}
function handleChooseDoctor(e) {
e.preventDefault();
return {
chosenDoctor: e.target.value,
patientIndex: e.target.parentNode.id
}
}
return {
handleTakeDoctorData,
handleTakePatientData,
handleDisplayDoctors,
handleDisplayPatients,
handleChooseDoctor
}
})();
// *****CONTROLLER*****
// holds event handlers, receives methods from other two modules and runs them
const controller = (function (model, view) {
const doctorForm = document.getElementById("doctorForm");
const patientForm = document.getElementById("patientForm");
const patientList = document.getElementById("patientList");
function handleAddDoctor(e) {
const doctorData = view.handleTakeDoctorData(e);
const doctor = new model.Doctor(doctorData.name, doctorData.specialty);
model.handleAddItem(doctor);
view.handleDisplayDoctors(model.appData.doctors);
}
function handleAddPatient(e) {
const patientData = view.handleTakePatientData(e);
const patient = new model.Patient(patientData.name, patientData.id, patientData.cardNo);
model.handleAddItem(patient);
view.handleDisplayPatients(model.appData.patients, model.appData.doctors);
}
function handleChooseDoctor(e) {
e.preventDefault();
const data = view.handleChooseDoctor(e);
model.handleChooseDoctor(data.patientIndex, data.chosenDoctor);
view.handleDisplayPatients(model.appData.patients, model.appData.doctors)
}
doctorForm.addEventListener("submit", handleAddDoctor);
patientForm.addEventListener("submit", handleAddPatient);
patientList.addEventListener("change", handleChooseDoctor);
})(model, view);
|
import React, { Fragment } from "react";
import classes from "./Footer.css";
const Footer = ({
// title = "Title",
// description = "Description",
className,
children,
}) => (
<footer className="bg-dark p-2 fixed-bottom">
<div className="container-fluid text-white">
<div className="row">
<div className="col-6">
<p className="mb-0 ">
Copyright © 2020 All Rights Reserved by Book Shop Web!
</p>
</div>
<div className="col-6 d-flex justify-content-center align-items-center">
<div className="mr-3">
<i className="fab fa-facebook "></i>
</div>
<div className="mr-3">
<i className="fab fa-linkedin"></i>
</div>
<div className="mr-3">
<i className="fab fa-dribbble"></i>
</div>
<div className="mr-3">
<i className="fab fa-instagram"></i>
</div>
</div>
</div>
</div>
</footer>
);
export default Footer;
|
import React, { Component, Fragment } from 'react';
import { Pagination, Table } from 'antd';
export default class PMTabA extends Component {
state = {
baseAdminId: '', //当前点击的用户baseAdminId pdaid
dataSourcePMTabA: {
list: [], //table 表格数据
total: 10, //当前页面总数据量
current: 1, //默认显示第几页
pageSize: 10, //每页显示多少数据
loading: true,
},
};
constructor(props) {
super(props);
}
componentWillReceiveProps(nextPros) {
if (this.props !== nextPros) {
this.state.dataSourcePMTabA = nextPros.dataSourcePMTabA;
this.state.baseAdminId = nextPros.baseAdminId;
}
}
render() {
return (
<Fragment>
<Table
pagination={false}
size="middle"
bordered
columns={this.props.columnsPMTabA}
dataSource={this.props.dataSourcePMTabA.list}
loading={this.props.dataSourcePMTabA.loading}
scroll={{ x: '100%', y: 210 }}
/>
<Pagination
size="small"
showSizeChanger
showQuickJumper
style={{ marginTop: '10px' }}
current={this.state.dataSourcePMTabA.current}
pageSize={this.state.dataSourcePMTabA.pageSize}
total={this.state.dataSourcePMTabA.total}
showTotal={total => `共${total}条数据`}
onChange={(page, pageSize) => {
this.state.dataSourcePMTabA.loading = true;
let parmas = {};
parmas.pageNum = page;
parmas.taskStatus = 3; //0待审核 1未分配 2抢单中 3未确定 4进行中 5任务完成状态 6任务异常 7已关闭任务
this.props.taskManageByPda(parmas);
}}
onShowSizeChange={(current, size) => {
this.state.dataSourcePMTabA.loading = true;
let parmas = {};
parmas.taskStatus = 3; //0待审核 1未分配 2抢单中 3未确定 4进行中 5任务完成状态 6任务异常 7已关闭任务
parmas.pageSize = size;
this.props.taskManageByPda(parmas);
}}
/>
</Fragment>
);
}
}
|
/*
PlotKit EasyPlot
================
User friendly wrapper around the common plotting functions.
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
try {
if (typeof(PlotKit.CanvasRenderer) == 'undefined')
{
throw ""
}
}
catch (e) {
throw "PlotKit.EasyPlot depends on all of PlotKit's components";
}
// --------------------------------------------------------------------
// Start of EasyPlot definition
// --------------------------------------------------------------------
PlotKit.EasyPlot = function(style, options, divElem, datasources) {
this.layout = new PlotKit.Layout(style, options);
this.divElem = divElem;
this.width = parseInt(divElem.getAttribute('width'));
this.height = parseInt(divElem.getAttribute('height'));
this.deferredCount = 0;
// make sure we have non-zero width
if (this.width < 1) {
this.width = this.divElem.width ? this.divElem.width : 300;
}
if (this.height < 1) {
this.height = this.divElem.height ? this.divElem.height : 300;
}
// load data sources
if (MochiKit.Base.isArrayLike(datasources)) {
for (var i = 0; i < datasources.length; i++) {
if (typeof(datasources[i]) == "string") {
this.deferredCount++;
// load CSV via ajax
var d = MochiKit.Async.doSimpleXMLHttpRequest(datasources[i]);
d.addCallback(MochiKit.Base.bind(PlotKit.EasyPlot.onDataLoaded, this));
}
else if (MochiKit.Base.isArrayLike(datasources[i])) {
this.layout.addDataset("data-" + i, datasources[i]);
}
}
}
else if (!MochiKit.Base.isUndefinedOrNull(datasources)) {
throw "Passed datasources are not Array like";
}
// setup canvas to render
if (CanvasRenderer.isSupported()) {
this.element = MochiKit.DOM.CANVAS({"id": this.divElem.getAttribute("id") + "-canvas",
"width": this.width,
"height": this.height}, "");
this.divElem.appendChild(this.element);
this.renderer = new SweetCanvasRenderer(this.element, this.layout, options);
}
else if (SVGRenderer.isSupported()) {
this.element = SVGRenderer.SVG({"id": this.divElem.getAttribute("id") + "-svg",
"width": this.width,
"height": this.height,
"version": "1.1",
"baseProfile": "full"}, "");
this.divElem.appendChild(this.element);
this.renderer = new SweetSVGRenderer(this.element, this.layout, options);
}
if ((this.deferredCount == 0) && (this.layout.datasetNames.length > 0)) {
this.layout.evaluate();
this.renderer.clear();
this.renderer.render();
}
};
PlotKit.EasyPlot.NAME = "PlotKit.EasyPlot";
PlotKit.EasyPlot.VERSION = PlotKit.VERSION;
PlotKit.EasyPlot.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.EasyPlot.toString = function() {
return this.__repr__();
}
PlotKit.EasyPlot.onDataLoaded = function(request) {
// very primitive CSV parser, should fix to make it more compliant.
var table = new Array();
var lines = request.responseText.split('\n');
for (var i = 0; i < lines.length; i++) {
var stripped = MochiKit.Format.strip(lines[i]);
if ((stripped.length > 1) && (stripped.charAt(0) != '#')) {
table.push(stripped.split(','));
}
}
this.layout.addDataset("data-ajax-" + this.deferredCount, table);
this.deferredCount--;
if ((this.deferredCount == 0) && (this.layout.datasetNames.length > 0)) {
this.layout.evaluate();
this.renderer.clear();
this.renderer.render();
}
};
PlotKit.EasyPlot.prototype.reload = function() {
this.layout.evaluate();
this.renderer.clear();
this.renderer.render();
};
// Namespace Iniitialisation
PlotKit.EasyPlotModule = {};
PlotKit.EasyPlotModule.EasyPlot = PlotKit.EasyPlot;
PlotKit.EasyPlotModule.EXPORT = [
"EasyPlot"
];
PlotKit.EasyPlotModule.EXPORT_OK = [];
PlotKit.EasyPlotModule.__new__ = function() {
var m = MochiKit.Base;
m.nameFunctions(this);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
};
PlotKit.EasyPlotModule.__new__();
MochiKit.Base._exportSymbols(this, PlotKit.EasyPlotModule);
|
/**
* @file Timer.js
* @description This file generates a timer for the game.
* @author Manyi Cheng
* @version Latest edition on April 10, 2021
*/
import React, { useState, useEffect } from 'react';
/**
* @function Timer
* @param {*} props
* @returns A timmer that counts down from 10 minutes on the upper right corner of the web page during the game
*/
const Timer = (props) => {
const { initialMinutes = 0, initialSeconds = 0 } = props;
const [minutes, setMinutes] = useState(initialMinutes);
const [seconds, setSeconds] = useState(initialSeconds);
useEffect(() => {
let myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval);
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000);
return () => {
clearInterval(myInterval);
};
}, [minutes, seconds]);
useEffect(() =>{
if(minutes === 0 && seconds === 0){
console.log("times up")
props.onTimer()
}
}, [minutes, seconds]);
return (
<div className = "timer-container" >
{minutes === 0 && seconds === 0 ? null: (
<div>
{' '}
{minutes}:{seconds < 10 ? `0${seconds}` : seconds}
</div>
)}
</div>
);
};
/**
* @exports Timer
*/
export default Timer;
|
import React from 'react'
const Legend = ({ searchColLength }) => {
const legend = __i18n('PROFILE.SEARCH.LEGEND').replace('${count}', searchColLength)
return (
<span className='legend' dangerouslySetInnerHTML={{ __html: legend }} />
)
}
export default Legend
|
module.exports={
name:'ping',
description: "Comprueba el ping del bot",
execute(message) {
message.channel.send(`🏓 | Latencia es: **${Date.now() - message.createdTimestamp}ms.**`);
},
};
|
import React, {Component} from 'react';
import logo from './assets/images/spotify-black.svg';
import './App.css';
import config from './config';
import hash from './hash';
import Routes from './routes';
import CoreLayout from './common/layouts/CoreLayout';
import './styles/_main.scss';
import { connect } from 'react-redux';
import { fetchUserInfo } from './actions/userActions';
import { ThemeProvider } from "styled-components";
import { GlobalStyles } from "./components/GlobalStyles";
import { lightTheme, darkTheme } from "./components/Themes";
class App extends Component {
constructor() {
super();
let tokenSaved = null;
this.state = {
token: tokenSaved || null
};
}
/**
* Se obtiene el token de acceso y se almancena para las peticiones posteriores
*/
componentDidMount() {
let _token = hash.access_token;
if (_token) {
this.setState({
token: _token
});
localStorage.setItem("token", _token);
}
this.props.fetchUserInfo();
}
render() {
let userInfo = this.props.userInfo ? this.props.userInfo : null;
let themeSelected = this.props.theme ? this.props.theme : 'dark';
return (
<ThemeProvider theme={themeSelected == 'light' ? lightTheme : darkTheme}>
<>
<GlobalStyles/>
<div className="main">
{!userInfo.logeado && (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<a
className="btn btn--loginApp-link"
href={`${config.api.authUrl}?client_id=${config.api.clientId}&redirect_uri=${config.api.redirectUri}&scope=${config.api.scopes.join(
"%20"
)}&response_type=token&show_dialog=true`}
>
Login Spotify
</a>
</header>
</div>
)}
{userInfo.logeado && (
<CoreLayout>
<Routes />
</CoreLayout>
)}
</div>
</>
</ThemeProvider>
);
}
}
//recuperar estado
const mapStateToProps = (state) => {
return {
userInfo: state.userReducer,
theme: state.appReducer.theme
}
}
//enviar acciones
const mapDispatchToProps = (dispatch) => {
return {
fetchUserInfo: () => dispatch(fetchUserInfo())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
/**
* Calculates the adjugate of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @return {mat4} out
*/
export function adjoint(out, a) {
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
var a30 = a[12];
var a31 = a[13];
var a32 = a[14];
var a33 = a[15];
out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
return out;
}
/**
* Creates a new matrix initialized with values from an existing matrix
* @param {mat4} a matrix to clone
* @return {mat4} a new matrix
*/
function clone(a) {
var out = new Float32Array(16);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
}
/**
* Copy the values from one matrix to another
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @return {mat4} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/**
* Creates a new identity mat4
* @return {mat4} a new 4x4 matrix
*/
function create() {
var out = new Float32Array(16);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Calculates the determinant of a matrix
*
* @param {mat4} a the source matrix
* @return {Number} determinant of a
*/
function determinant(a) {
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
var a30 = a[12];
var a31 = a[13];
var a32 = a[14];
var a33 = a[15];
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
var out = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
return out;
}
/**
* Creates a matrix from a quaternion rotation.
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @return {mat4} out
*/
function from_quaternion(out, q) {
var x = q[0];
var y = q[1];
var z = q[2];
var w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var yx = y * x2;
var yy = y * y2;
var zx = z * x2;
var zy = z * y2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
out[0] = 1 - yy - zz;
out[1] = yx + wz;
out[2] = zx - wy;
out[3] = 0;
out[4] = yx - wz;
out[5] = 1 - xx - zz;
out[6] = zy + wx;
out[7] = 0;
out[8] = zx + wy;
out[9] = zy - wx;
out[10] = 1 - xx - yy;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Creates a matrix from a quaternion rotation and vector translation.
* @param {mat4} out Matrix receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @return {mat4} out
*/
function from_rotation_translation(out, q, v) {
var x = q[0];
var y = q[1];
var z = q[2];
var w = q[3];
var x2 = x + x;
var y2 = y + y;
var z2 = z + z;
var xx = x * x2;
var xy = x * y2;
var xz = x * z2;
var yy = y * y2;
var yz = y * z2;
var zz = z * z2;
var wx = w * x2;
var wy = w * y2;
var wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
}
/**
* Generates a frustum matrix with the given bounds.
* @param {mat4} out Matrix frustum matrix will be written into
* @param {Number} left Left bound of the frustum
* @param {Number} right Right bound of the frustum
* @param {Number} bottom Bottom bound of the frustum
* @param {Number} top Top bound of the frustum
* @param {Number} near Near bound of the frustum
* @param {Number} far Far bound of the frustum
* @return {mat4} out
*/
function frustum(out, left, right, bottom, top, near, far) {
var rl = 1 / (right - left);
var tb = 1 / (top - bottom);
var nf = 1 / (near - far);
out[0] = (near * 2) * rl;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = (near * 2) * tb;
out[6] = 0;
out[7] = 0;
out[8] = (right + left) * rl;
out[9] = (top + bottom) * tb;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (far * near * 2) * nf;
out[15] = 0;
return out;
}
/**
* Set a mat4 to the identity matrix.
* @param {mat4} out the receiving matrix
* @return {mat4} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/**
* Inverts a matrix.
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @return {mat4} out
*/
function invert(out, a) {
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
var a30 = a[12];
var a31 = a[13];
var a32 = a[14];
var a33 = a[15];
var b00 = a00 * a11 - a01 * a10;
var b01 = a00 * a12 - a02 * a10;
var b02 = a00 * a13 - a03 * a10;
var b03 = a01 * a12 - a02 * a11;
var b04 = a01 * a13 - a03 * a11;
var b05 = a02 * a13 - a03 * a12;
var b06 = a20 * a31 - a21 * a30;
var b07 = a20 * a32 - a22 * a30;
var b08 = a20 * a33 - a23 * a30;
var b09 = a21 * a32 - a22 * a31;
var b10 = a21 * a33 - a23 * a31;
var b11 = a22 * a33 - a23 * a32;
var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return out;
}
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis.
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @return {mat4} out
*/
function look_at(out, eye, center, up) {
var x0;
var x1;
var x2;
var y0;
var y1;
var y2;
var z0;
var z1;
var z2;
var len;
var eyex = eye[0];
var eyey = eye[1];
var eyez = eye[2];
var upx = up[0];
var upy = up[1];
var upz = up[2];
var centerx = center[0];
var centery = center[1];
var centerz = center[2];
var epsilon = 0.000001;
if (Math.abs(eyex - centerx) < epsilon &&
Math.abs(eyey - centery) < epsilon &&
Math.abs(eyez - centerz) < epsilon) {
return identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
}
/**
* Multiplies two mat4's
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function multiply(out, a, b) {
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
var a30 = a[12];
var a31 = a[13];
var a32 = a[14];
var a33 = a[15];
var b0;
var b1;
var b2;
var b3;
b0 = b[0];
b1 = b[1];
b2 = b[2];
b3 = b[3];
out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[4];
b1 = b[5];
b2 = b[6];
b3 = b[7];
out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[8];
b1 = b[9];
b2 = b[10];
b3 = b[11];
out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[12];
b1 = b[13];
b2 = b[14];
b3 = b[15];
out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
return out;
};
/**
* Generates a orthogonal projection matrix with the given bounds.
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @return {mat4} out
*/
function ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right);
var bt = 1 / (bottom - top);
var nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
}
/**
* Generates a perspective projection matrix with the given bounds.
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspective(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2);
var nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
return out;
}
/**
* Generates a perspective projection matrix with the given field of view.
* This is primarily useful for generating projection matrices to be used
* with the still experiemental WebVR API.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} up Degrees
* @param {number} down Degrees
* @param {number} left Degrees
* @param {number} right Degrees
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspective_from_fov(out, up, down, left, right, near, far) {
var ratio = Math.PI/180.0;
var up_tan = Math.tan(up * ratio);
var down_tan = Math.tan(down * ratio);
var left_tan = Math.tan(left * ratio);
var right_tan = Math.tan(right * ratio);
var x_scale = 2.0 / (leftTan + rightTan);
var y_scale = 2.0 / (upTan + downTan);
out[0] = xScale;
out[1] = 0.0;
out[2] = 0.0;
out[3] = 0.0;
out[4] = 0.0;
out[5] = yScale;
out[6] = 0.0;
out[7] = 0.0;
out[8] = -((leftTan - rightTan) * xScale * 0.5);
out[9] = ((upTan - downTan) * yScale * 0.5);
out[10] = far / (near - far);
out[11] = -1.0;
out[12] = 0.0;
out[13] = 0.0;
out[14] = (far * near) / (near - far);
out[15] = 0.0;
return out;
}
/**
* Rotates a mat4 by the given angle
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function rotate(out, a, rad, axis) {
var x = axis[0];
var y = axis[1];
var z = axis[2];
var len = Math.sqrt(x*x + y*y + z*z);
var epsilon = 0.000001;
if (Math.abs(len) < epsilon) {
return null;
}
len = 1/len;
x *= len;
y *= len;
z *= len;
var s = Math.sin(rad);
var c = Math.cos(rad);
var t = 1 - c;
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
// Construct the elements of the rotation matrix
var b00 = x * x * t + c;
var b01 = y * x * t + z * s;
var b02 = z * x * t - y * s;
var b10 = x * y * t - z * s;
var b11 = y * y * t + c;
var b12 = z * y * t + x * s;
var b20 = x * z * t + y * s;
var b21 = y * z * t - x * s;
var b22 = z * z * t + c;
// Perform rotation-specific matrix multiplication
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
// If the source and destination differ, copy the unchanged last row
if (a !== out) {
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
};
/**
* Rotates a matrix by the given angle around the X axis
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotate_x(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
// If the source and destination differ, copy the unchanged rows
if (a !== out) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[4] = a10 * c + a20 * s;
out[5] = a11 * c + a21 * s;
out[6] = a12 * c + a22 * s;
out[7] = a13 * c + a23 * s;
out[8] = a20 * c - a10 * s;
out[9] = a21 * c - a11 * s;
out[10] = a22 * c - a12 * s;
out[11] = a23 * c - a13 * s;
return out;
}
/**
* Rotates a matrix by the given angle around the Y axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotate_y(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
// If the source and destination differ, copy the unchanged rows
if (a !== out) {
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c - a20 * s;
out[1] = a01 * c - a21 * s;
out[2] = a02 * c - a22 * s;
out[3] = a03 * c - a23 * s;
out[8] = a00 * s + a20 * c;
out[9] = a01 * s + a21 * c;
out[10] = a02 * s + a22 * c;
out[11] = a03 * s + a23 * c;
return out;
}
/**
* Rotates a matrix by the given angle around the Z axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotate_z(out, a, rad) {
var s = Math.sin(rad);
var c = Math.cos(rad);
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
// If the source and destination differ, copy the unchanged last row
if (a !== out) {
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c + a10 * s;
out[1] = a01 * c + a11 * s;
out[2] = a02 * c + a12 * s;
out[3] = a03 * c + a13 * s;
out[4] = a10 * c - a00 * s;
out[5] = a11 * c - a01 * s;
out[6] = a12 * c - a02 * s;
out[7] = a13 * c - a03 * s;
return out;
}
/**
* Scales the mat4 by the dimensions in the given vec3
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {vec3} v the vec3 to scale the matrix by
* @returns {mat4} out
**/
function scale(out, a, v) {
var x = v[0];
var y = v[1];
var z = v[2];
out[0] = a[0] * x;
out[1] = a[1] * x;
out[2] = a[2] * x;
out[3] = a[3] * x;
out[4] = a[4] * y;
out[5] = a[5] * y;
out[6] = a[6] * y;
out[7] = a[7] * y;
out[8] = a[8] * z;
out[9] = a[9] * z;
out[10] = a[10] * z;
out[11] = a[11] * z;
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
}
/**
* Returns a string representation of a matrix.
* @param {mat4} mat matrix to represent as a string
* @return {String} string representation of the matrix
*/
function to_string(a) {
var open = '['
var close = ']'
var space = space
var out = open +
a[0] + space + a[1] + space + a[2] + space + a[3] + space +
a[4] + space + a[5] + space + a[6] + space + a[7] + space +
a[8] + space + a[9] + space + a[10] + space + a[11] + space +
a[12] + space + a[13] + space + a[14] + space + a[15] + close;
return out;
}
/**
* Translate a mat4 by the given vector
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to translate
* @param {vec3} v vector to translate by
* @returns {mat4} out
*/
function translate(out, a, v) {
var x = v[0];
var y = v[1];
var z = v[2];
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
return out;
}
var a00 = a[0];
var a01 = a[1];
var a02 = a[2];
var a03 = a[3];
var a10 = a[4];
var a11 = a[5];
var a12 = a[6];
var a13 = a[7];
var a20 = a[8];
var a21 = a[9];
var a22 = a[10];
var a23 = a[11];
var a30 = a[12];
var a31 = a[13];
var a32 = a[14];
var a33 = a[15]
out[0] = a00;
out[1] = a01;
out[2] = a02;
out[3] = a03;
out[4] = a10;
out[5] = a11;
out[6] = a12;
out[7] = a13;
out[8] = a20;
out[9] = a21;
out[10] = a22;
out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a30;
out[13] = a01 * x + a11 * y + a21 * z + a31;
out[14] = a02 * x + a12 * y + a22 * z + a32;
out[15] = a03 * x + a13 * y + a23 * z + a33;
return out;
}
/**
* Transpose the values of a matrix
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function transpose(out, a) {
if (out === a) {
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
return out;
}
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
return out;
}
// export { adjoint, clone, copy, create, determinant, from_quaternion, from_rotation_translation, frustum, identity, invert, look_at, multiply, ortho, perspective, perspective_from_fov, rotate, rotate_x, rotate_y, rotate_z, scale, to_string, translate, transpose };
|
module.exports = {
// Define API type (feathers, default)
apiType: 'feathers',
// - Path to REST API, or feathers api
apiPath: 'https://example.com/',
// - Path to uploaded files, or feathers files api endpoint
filesUrl: 'https://example.com/files/',
// Define files call type, feathers-rest (https://docs.feathersjs.com/guides/file-uploading.html), direct (default)
filesType: 'feathers-rest',
// - Pagination
pageSize: 50,
// - Language (en/fr)
locale: 'en',
};
|
/* jshint node:true */
/**
* convert an absolute source import to a relative one
* expects filenames to start with <sourceRoot>
*
source: 'sourceRoot/file', filename: 'cke/index.js' -> './file'
source: 'sourceRoot/helpers/xyz', filename: 'cke/tests/t.js' -> '../helpers/xyz'
source: 'sourceRoot/helpers/../xyz', filename: 'cke/tests/t.js' -> '../xyz'
source 'sourceRoot/relative-file' filename 'content-kit-editor/index.js' -> './relative-file'
*/
function resolveSourceToRelative(source, filename, sourceRoot) {
var isRelative = source.indexOf('.') === 0;
if (isRelative) {
return source;
}
if (filename.indexOf(sourceRoot) !== 0) {
throw new Error('Expected filename "' + filename + '" to start with sourceRoot (' + sourceRoot + ')');
}
var path = require('path');
var sourceParts = source.split('/');
if (sourceParts[0] === sourceRoot) {
sourceParts.shift(); // remove sourceRoot
}
var fileParts = path.dirname(filename).split('/');
fileParts.shift(); // remove sourceRoot
var relativeParts = [];
for (var i=0; i<fileParts.length; i++) {
relativeParts.push('..');
}
relativeParts = relativeParts.concat(sourceParts);
var relativePath = path.normalize(relativeParts.join('/'));
if (relativePath.indexOf('..') === -1) {
relativePath = './' + relativePath;
}
return relativePath;
}
module.exports = resolveSourceToRelative;
|
import React, {useEffect} from 'react';
import TeamDetails from '../components/TeamDetails';
//REDUX
import {useDispatch, useSelector} from 'react-redux';
import { useLocation } from 'react-router';
import {loadTeams} from '../actions/teamsAction'
//Components
import Team from '../components/Team';
//Styling and Animation
import styled from 'styled-components';
import {motion, AnimatePresence, AnimateSharedLayout} from 'framer-motion';
import Topscorer from '../components/Topscorer';
const Home = () => {
//get current location
const location = useLocation();
const pathId = location.pathname.split("/")[2];
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadTeams());
}, [dispatch]);
//Get data back
const {eplTeams, laligaTeams, ligueOneTeams, bundesligaTeams, SerieATeams, topscorersEpl, topscorerLaliga, topscorerSerieA, topscorerLigueOne,topscorersBundesliga} = useSelector((state) => state.football);
const year = new Date().getFullYear() - 1
// console.log(topscorersEpl)
return(
<TeamList>
<AnimateSharedLayout type="">
<AnimatePresence>
{pathId && <TeamDetails pathId={pathId}/>}
</AnimatePresence>
<div>
<h2>Epl Teams</h2>
<Teams>
{eplTeams.map((team) => (
<Team name={team.name}
stadium={team.venue}
founded={team.founded}
phone={team.phone}
id={team.id}
image={team.crestUrl}
tla={team.tla}
website={team.website}
colours={team.clubColors}
email={team.email}
key={team.id}
/>
))}
</Teams>
</div>
<div>
<h2>LaLiga Teams</h2>
<Teams>
{laligaTeams.map((team) => (
<Team name={team.name}
stadium={team.venue}
founded={team.founded}
phone={team.phone}
id={team.id}
image={team.crestUrl}
tla={team.tla}
website={team.website}
colours={team.clubColors}
email={team.email}
key={team.id}
/>
))}
</Teams>
</div>
<div>
<h2>Ligue One Teams</h2>
<Teams>
{ligueOneTeams.map((team) => (
<Team name={team.name}
stadium={team.venue}
founded={team.founded}
phone={team.phone}
id={team.id}
image={team.crestUrl}
tla={team.tla}
website={team.website}
colours={team.clubColors}
email={team.email}
key={team.id}
/>
))}
</Teams>
</div>
<div>
<h2>Bundesliga Teams</h2>
<Teams>
{bundesligaTeams.map((team) => (
<Team name={team.name}
stadium={team.venue}
founded={team.founded}
phone={team.phone}
id={team.id}
image={team.crestUrl}
tla={team.tla}
website={team.website}
colours={team.clubColors}
email={team.email}
key={team.id}
/>
))}
</Teams>
</div>
<div>
<h2>SerieA Teams</h2>
<Teams>
{SerieATeams.map((team) => (
<Team name={team.name}
stadium={team.venue}
founded={team.founded}
phone={team.phone}
id={team.id}
image={team.crestUrl}
tla={team.tla}
website={team.website}
colours={team.clubColors}
email={team.email}
key={team.id}
/>
))}
</Teams>
</div>
<Topscorers>
<h2>Top Scorers {year}</h2>
<div className="cards">
<div>
<h3>EPL</h3>
<Teams>
<Topscorer
name={topscorersEpl.player.name}
image={topscorersEpl.player.photo}
age={topscorersEpl.player.age}
team={topscorersEpl.statistics[0].team.name}
goals={topscorersEpl.statistics[0].goals.total}
assist={topscorersEpl.statistics[0].goals.assists}
/>
</Teams>
</div>
<div>
<h3>Laliga</h3>
<Teams>
<Topscorer
name={topscorerLaliga.player.name}
image={topscorerLaliga.player.photo}
age={topscorerLaliga.player.age}
team={topscorerLaliga.statistics[0].team.name}
goals={topscorerLaliga.statistics[0].goals.total}
assist={topscorerLaliga.statistics[0].goals.assists}
/>
</Teams>
</div>
<div>
<h3>Seria A</h3>
<Teams>
<Topscorer
name={topscorerSerieA.player.name}
image={topscorerSerieA.player.photo}
age={topscorerSerieA.player.age}
team={topscorerSerieA.statistics[0].team.name}
goals={topscorerSerieA.statistics[0].goals.total}
assist={topscorerSerieA.statistics[0].goals.assists}
/>
</Teams>
</div>
<div>
<h3>Ligue One</h3>
<Teams>
<Topscorer
name={topscorerLigueOne.player.name}
image={topscorerLigueOne.player.photo}
age={topscorerLigueOne.player.age}
team={topscorerLigueOne.statistics[0].team.name}
goals={topscorerLigueOne.statistics[0].goals.total}
assist={topscorerLigueOne.statistics[0].goals.assists}
/>
</Teams>
</div>
<div>
<h3>Bundesliga</h3>
<Teams>
<Topscorer
name={topscorersBundesliga.player.name}
image={topscorersBundesliga.player.photo}
age={topscorersBundesliga.player.age}
team={topscorersBundesliga.statistics[0].team.name}
goals={topscorersBundesliga.statistics[0].goals.total}
assist={topscorersBundesliga.statistics[0].goals.assists}
/>
</Teams>
</div>
</div>
</Topscorers>
</AnimateSharedLayout>
</TeamList>
);
};
const TeamList = styled(motion.div)`
background-color: #25203a;
color: white;
padding: 0rem 5rem;
h2 {
padding: 1rem 1rem;
}
div{
}
`;
const Teams = styled(motion.div)`
min-height: 80vh;
display: flex;
min-height: 100px;
/* margin-right: 5rem; */
/* padding: 5rem; */
overflow-y: hidden;
overflow-x: scroll;
&::-webkit-scrollbar {
display: none;
}
padding: 3rem 1rem;
`;
const Topscorers = styled(motion.div)`
.cards {
min-height: 80vh;
display: flex;
min-height: 100px;
/* margin-right: 5rem; */
/* padding: 5rem; */
overflow-y: hidden;
overflow-x: scroll;
&::-webkit-scrollbar {
display: none;
}
padding: 3rem 1rem;
}
h3 {
padding: 0rem 1rem;
font-size: 2rem;
font-family: 'Abril Fatface', cursive;
font-weight: lighter;
color: white;
}
`
export default Home;
|
const axios = require('axios');
const qs = require('qs');
const has = require('lodash.has');
const isPlainObject = require('lodash.isplainobject');
const isEmpty = require('lodash.isempty');
const status = require('./utils/status');
const { version } = require('../package.json');
// Import the error utils.
const {
RequestError,
StatusCodeError,
isAxiosRequestError,
isAxiosResponseError
} = require('./utils/errors');
// Validation utils.
const {
uuidSchema,
uuidOrUniqueKeySchema,
tagsSchema,
flipsQuerySchema,
checkSchema,
performValidation
} = require('./utils/validation');
// Base URL for Healthchecks.io.
const BASE_URL = 'https://healthchecks.io';
// Client user agent string.
const USER_AGENT = `HealthChecks-IO-Client-JS/${version}`;
// Default API version.
const API_VERSION = 1;
/**
* A library for interacting with the Healthchecks.io Management
* REST API for listing, creating, updating, pausing and deleting
* health checks.
*
* @class HealthChecksApiClient
*/
class HealthChecksApiClient {
/**
* Creates an instance of HealthChecksApiClient.
*
* @param {Object} [options={}] Client options.
* @memberof HealthChecksApiClient
*/
constructor(options = {}) {
this._options = options;
this._apiKey = undefined;
// Check the options for the Api Key.
this._checkApiKey(this._options);
// Get the headers for the requests.
this._headers = this._getRequestHeaders();
this.timeout = this._options.timeout || 5000;
this.baseUrl = this._options.baseUrl || BASE_URL;
this.fullResponse = this._options.fullResponse || false;
this.maxContentLength = this._options.maxContentLength || 10000;
this.maxBodyLength = this._options.maxBodyLength || 2000;
this.apiVersion = this._options.apiVersion || API_VERSION;
// Create the Axios instance.
this._axiosInstance = this._getAxiosInstance();
}
/**
* Checks the provided options for the Api Key.
*
* @param {Object} options Provided options.
* @memberof HealthChecksApiClient
*/
_checkApiKey(options) {
// Check the 'apiKey'.
if ((!has(options, 'apiKey') && !has(process, 'env.HC_API_KEY')) &&
isEmpty(options.apiKey)
) {
throw new Error('A HealthChecks.io Api Key is a required option.');
}
this._apiKey = (process.env.HC_API_KEY || options.apiKey).trim();
// Make sure the API key is not empty.
if (!this._apiKey.length) {
this._apiKey = undefined;
throw new Error('A HealthChecks.io Api Key is a required option.');
}
}
/**
* Performs validation on a value using the provided Joi schema.
*
* @param {Array<*>} values The values to validate.
* @param {Array<Object>} schemas Joi schemas.
* @memberof HealthChecksApiClient
*/
_checkInput(values, schemas) {
values.forEach((value, index) => {
// Validate the value with the Joi schema.
const result = performValidation(value, schemas[index]);
if (result.errors) {
throw new Error(result.errors);
}
});
}
/**
* Gets the headers for a Healthchecks.io request.
*
* @returns {Object} Request headers.
* @memberof HealthChecksApiClient
*/
_getRequestHeaders() {
if (!this._apiKey) {
throw new Error('Missing the Api Key (apiKey).');
}
return {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json; charset=utf-8',
'X-Api-Key': this._apiKey,
'User-Agent': USER_AGENT,
};
}
/**
* Creates an Axios instance.
*
* @returns {Axios} Axios instance.
* @memberof HealthChecksApiClient
*/
_getAxiosInstance() {
return axios.create({
baseURL: this.baseUrl,
headers: this._headers,
timeout: this.timeout,
responseType: 'json',
responseEncoding: 'utf8',
maxContentLength: this.maxContentLength,
maxBodyLength: this.maxBodyLength,
paramsSerializer: (params) => {
return qs.stringify(params, { arrayFormat: 'repeat' });
},
});
}
/**
* Gets the request options for a Healthchecks.io API request.
*
* @param {String} method HTTP method.
* @param {String} path HTTP request path.
* @param {Object} [qs=null] Query parameters.
* @param {Object} [body=null] Request body.
* @returns {Object} Request options.
* @memberof HealthChecksApiClient
*/
_getRequestOptions(method, path, qs = null, body = null) {
// Set the request options.
const options = {
method,
url: path,
params: (qs && isPlainObject(qs)) ? qs : undefined,
};
// Add body value (if needed).
if (/put|post|patch|delete/i.test(method) &&
(body && isPlainObject(body))
) {
options.data = body;
}
return options;
}
/**
* Performs a Healthchecks.io API request.
*
* @param {Object} options Request options.
* @returns {Promise<Object|Array>} The response from the API request.
* @memberof HealthChecksApiClient
*/
async _performRequest(options) {
// Check the options.
if (!options || !isPlainObject(options) || isEmpty(options)) {
throw new Error('A request options object must be provided');
}
// Get the response.
const response = await this._axiosInstance.request(options);
// Should the full response be returned.
if (this.fullResponse) {
// Get the status message.
const statusMessage = response.statusText || status[response.status];
return {
statusCode: response.status,
statusMessage,
headers: response.headers,
data: response.data,
};
}
return response.data;
}
/**
* Creates a custom error from an Axios error.
*
* @param {Error} err The 'axios' Error.
* @returns {Error} The custom error.
* @memberof HealthChecksApiClient
*/
_handleError(err) {
// Check for Axios errors.
if (isAxiosRequestError(err)) {
return new RequestError(err);
} else if (isAxiosResponseError(err)) {
return new StatusCodeError(err);
}
return err;
}
/**
* Gets a list of health checks. If 'tags' are provided
* then a list of health checks matching the tags is
* returned.
*
* @param {Array<String>} [tags=[]] Health check tags.
* @returns {Promise<Object>} List of health checks.
* @memberof HealthChecksApiClient
*/
async getChecks(tags = []) {
// Check the tags.
this._checkInput([ tags ], [ tagsSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('GET',
`/api/v${this.apiVersion}/checks/`, { tag: tags });
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Gets the information for a health check.
*
* @param {String} uuid Health check identifier or unique key.
* @returns {Promise<Object>} The health check information.
* @memberof HealthChecksApiClient
*/
async getCheck(uuid) {
// Check the uuid/unique key.
this._checkInput([ uuid ], [ uuidOrUniqueKeySchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('GET',
`/api/v${this.apiVersion}/checks/${uuid}`);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Creates a new health check.
*
* @param {Object} [checkInfo={}] Check information.
* @returns {Promise<Object>} The created health check.
* @memberof HealthChecksApiClient
*/
async createCheck(checkInfo = {}) {
// Check the health check info.
this._checkInput([ checkInfo ], [ checkSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('POST',
`/api/v${this.apiVersion}/checks/`, null, checkInfo);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Updates an existing health check.
*
* @param {String} uuid Health check identifier.
* @param {Object} [checkInfo={}] Updated check information.
* @returns {Promise<Object>} The updated check.
* @memberof HealthChecksApiClient
*/
async updateCheck(uuid, checkInfo = {}) {
// Check the uuid and health check info.
this._checkInput([ uuid, checkInfo ], [ uuidSchema, checkSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('POST',
`/api/v${this.apiVersion}/checks/${uuid}`, null, checkInfo);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Disables monitoring for a check, without removing it.
*
* @param {String} uuid Health check identifier.
* @returns {Promise<Object>} The paused check information.
* @memberof HealthChecksApiClient
*/
async pauseCheck(uuid) {
// Check the uuid.
this._checkInput([ uuid ], [ uuidSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('POST',
`/api/v${this.apiVersion}/checks/${uuid}/pause`);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Permanently deletes the check from user's account.
*
* @param {String} uuid Health check identifier.
* @returns {Promise<Object>} The deleted check.
* @memberof HealthChecksApiClient
*/
async deleteCheck(uuid) {
// Check the uuid.
this._checkInput([ uuid ], [ uuidSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('DELETE',
`/api/v${this.apiVersion}/checks/${uuid}`);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Gets a list of pings a check has received.
*
* @param {String} uuid Health check identifier.
* @returns {Promise<Object>} The list of pings.
* @memberof HealthChecksApiClient
*/
async listPings(uuid) {
// Check the uuid.
this._checkInput([ uuid ], [ uuidSchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('GET',
`/api/v${this.apiVersion}/checks/${uuid}/pings`);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Gets a list of flips (status changes) a check has experienced.
*
* @param {String} uuid Health check identifier or unique key.
* @param {Object} [params={}] Query parameters.
* @returns {Promise<Object>} The list of flips (status changes).
* @memberof HealthChecksApiClient
*/
async listFlips(uuid, params = {}) {
// Check the uuid/unique key and query parameters.
this._checkInput([ uuid, params ],
[ uuidOrUniqueKeySchema, flipsQuerySchema ]);
try {
// Get the request options.
const options = this._getRequestOptions('GET',
`/api/v${this.apiVersion}/checks/${uuid}/flips`, params);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
/**
* Gets a list of integrations belonging to the user.
*
* @returns {Promise<Object>} List of integrations.
* @memberof HealthChecksApiClient
*/
async getIntegrations() {
try {
// Get the request options.
const options = this._getRequestOptions('GET',
`/api/v${this.apiVersion}/channels`);
// Peform the request.
return await this._performRequest(options);
} catch (err) {
throw this._handleError(err);
}
}
}
module.exports = HealthChecksApiClient;
|
import styled from "styled-components"
export const TemplateWrapper = styled.div`
min-height: 100vh;
display: flex;
flex-Direction: column;
`
|
import React, { Component } from "react";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlay } from '@fortawesome/free-solid-svg-icons';
class Welcome extends Component {
render() {
return (
<section className="welcome">
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-12 col-12">
<div className="welcome-title">
<h2>WELCOME TO <span>FIND HOUSES</span></h2>
<h4>THE BEST PLACE TO FIND THE HOUSE YOU WANT.</h4>
</div>
<div className="welcome-content">
<p> <span>FIND HOUSES</span> is the best place for elit, sed do eiusmod tempor dolor sit amet, conse ctetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et lorna aliquatd minimam, quis nostrud exercitation oris nisi ut aliquip ex ea.</p>
</div>
<div className="welcome-services">
<div className="row">
<div className="col-lg-6 col-md-6 col-xs-12 ">
<div className="w-single-services">
<div className="services-img img-1">
<img src={require('../../../images/1.png')} width="32" alt="" />
</div>
<div className="services-desc">
<h6>Buy Property</h6>
<p>We have the best properties
<br/> elit, sed do eiusmod tempe</p>
</div>
</div>
</div>
<div className="col-lg-6 col-md-6 col-xs-12 ">
<div className="w-single-services">
<div className="services-img img-2">
<img src={require('../../../images/2.png')} width="32" alt=""/>
</div>
<div className="services-desc">
<h6>Rent Property</h6>
<p>We have the best properties
<br/> elit, sed do eiusmod tempe</p>
</div>
</div>
</div>
<div className="col-lg-6 col-md-6 col-xs-12 ">
<div className="w-single-services no-mb mbx">
<div className="services-img img-3">
<img src={require('../../../images/3.png')} width="32" alt=""/>
</div>
<div className="services-desc">
<h6>Real Estate Kit</h6>
<p>We have the best properties
<br/> elit, sed do eiusmod tempe</p>
</div>
</div>
</div>
<div className="col-lg-6 col-md-6 col-xs-12 ">
<div className="w-single-services no-mb">
<div className="services-img img-4">
<img src={require('../../../images/4.png')} width="32" alt=""/>
</div>
<div className="services-desc">
<h6>Sell Property</h6>
<p>We have the best properties
<br/> elit, sed do eiusmod tempe</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="col-lg-6 col-md-12 col-xs-12">
<div className="wprt-image-video w50">
<img alt="image" src={require('../../../images/projects/welcome.jpg')}/>
<a className="icon-wrap popup-video popup-youtube" href="https://www.youtube.com/watch?v=2xHQqYRcrx4">
<i className="fa fa-play"><FontAwesomeIcon icon={faPlay} /></i>
</a>
<div className="iq-waves">
<div className="waves wave-1"></div>
<div className="waves wave-2"></div>
<div className="waves wave-3"></div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default Welcome;
|
import React, { Component } from 'react'
import axios from 'axios';
class DetailProduct extends Component {
constructor(props) {
super(props);
this.formatterIDR = new Intl.NumberFormat('id', {
style: 'currency',
currency: 'IDR',
minimumFractionDigits: 0
})
}
state = {
product: {}
}
componentDidMount() {
const idproduct = parseInt(this.props.match.params.asdfg)
axios.get('http://localhost:1997/products/' + idproduct)
.then(res => {
this.setState({ product: res.data })
})
}
render() {
const { product } = this.state
return (
<div className=" card" key={product.id}>
<div className="card-header">
{product.name}
</div>
<div className="card-body">
<img src={product.src} alt={product.name} />
<h3 className="card-title">Product: {product.name}</h3>
<p className="card-text">Description: {product.desc}</p>
<p className="card-text">Price : {this.formatterIDR.format(product.price)}</p>
<a href="/" className="btn btn-block btn-primary">Add to Cart</a>
</div>
</div>
)
}
}
export default DetailProduct;
|
;(function($, mini, window, document, undefined) {
"use strict";
var ServiceCalculator = mini.ServiceCalculator = mini.ServiceCalculator || (function() {
var DATA = [];
var PLUSDATA = [];
var selectedModel = '';
var familyCode = '';
var selectedYear = '';
var language = 'en';
var init = function ( lang ) {
// SET LANGUAGE AS STRING
language = lang;
// CREATE A DATA OBJECT
DATA = new MINI.ServiceCalculatorDataManager(setData);
// CLOSE MODAL WINDOW
$('#modal-close').on('click',function () {
$("#ServiceCalculator").modal('hide');
$("#ServiceCalculator #calculations-view").hide();
});
// OPEN MODAL WINDOW
$('.open-service-calculator').on('click',function () {
$("#ServiceCalculator").modal({ show: true, backdrop: 'static' });
$("#ServiceCalculator #calculations-view").hide();
});
};
// SET MAIN DATA OBJECT TO
// EQUALS PARSED DATA RETURN
var setData = function (d,p) {
if(d!=''){DATA = d;}
if(p!=''){PLUSDATA = p;}
if(DATA.length > 0 && PLUSDATA.length > 0 ){
buildVehicleView();
}
}
// BUILD MAIN THUMB VIEW
var buildVehicleView = function () {
$('select').prop('selectedIndex', 0);
$('select').on('change', function() {
var p = $(this).parent().attr('id');
var id = $(this).attr('id');
var val = $(this).val();
familyCode = p;
var optionVal = $(this).find("option:selected").text();
if( id == 'year'){ selectedYear = optionVal; }
if( id == 'model'){ selectedModel = val; }
// CLEAR ALL OTHER INPUT FIELDS
$('select').each(function() {
var p = $(this).parent().attr('id');
if( p != familyCode ){
$(this).prop('selectedIndex', 0);
$(this).find('option').show();
}
});
getAvailableSelections(p,id,val);
});
$('#calculate-btn').on('click',function () {
if( selectedYear != '' && selectedModel != '' ){
buildCalulatorView();
}else{
alert("PLEASE SELECT A YEAR AND MODEL");
}
});
$('.change-model-btn').on('click',function () {
$("#ServiceCalculator #calculations-view").fadeOut();
$('.change-model-btn').hide();
selectedModel = '';
familyCode = '';
selectedYear = '';
// CLEAR ALL SELECT FIELDS
$('select').each(function() {
$(this).prop('selectedIndex', 0);
});
$('option').show();
});
var domain = window.location.origin + '/'+language+'/';
$('.retailer-btn').on('click',function () {
window.location = domain+'find-retailer'
});
}
// REMOVE ANY ITEMS NOT FOUND IN THE DATA FEED
// THESE LSIT ITEMS ARE HIDDEN IF NOT FOUND
var getAvailableSelections = function (p,type,option) {
//$('option').show();
if( type == 'model'){
$('#'+p).find('#year option').each(function () {
if( isAvailableYear($(this).val()) == false ){ $(this).hide(); } else { $(this).show(); }
});
}
if( type == 'year'){
// check if year ( option ) is available
// in the selected model
$('#'+p).find('#model option').each(function () {
//console.log( $(this).val() );
if( isAvailableModel($(this).val()) == false ){ $(this).hide(); } else { $(this).show(); }
});
}
}
// IS YEAR AVAILABLE RETURNS TRUE
var isAvailableYear = function (year) {
var t = false;
for( var i = 0; i < DATA.length; i++ ){
if( DATA[i]['AG Code'] == selectedModel && DATA[i]['Year'] == year ){
t = true;
}
}
return t;
}
// IS MODEL AVAILABLE RETURNS TRUE
var isAvailableModel = function (model) {
var t = false;
for( var i = 0; i < DATA.length; i++ ){
if( DATA[i]['AG Code'] == model && DATA[i]['Year'] == selectedYear ){
t = true;
}
}
return t;
}
// BUILD CALCULATIONS VIEW
// THIS VIEW IS BUILT DYNAMICALLY
var buildCalulatorView = function () {
$("#ServiceCalculator #calculations-view").fadeIn();
$('.change-model-btn').show();
// REST VALUES
$('.view-copy h4').html('');
$('#inc-price #year3').html('');
$('#inc-price #year5').html('');
$('#inc-price #year6').html('');
$('#plus-price #year3').html('');
$('#plus-price #year5').html('');
$('#plus-price #year6').html('');
// SWITCH OUT THE IMAGE ::
var img = '<img src="/Public/img/nav/'+familyCode+'.jpg"/>';
$('.selected-calculator-thumb').html(img);
for( var i = 0; i < DATA.length; i++ ){
if( DATA[i].Year == selectedYear && DATA[i]['AG Code'] == selectedModel ){
var modelName = DATA[i]['Year'] +' '+ DATA[i]["Model Name (English)"];
$('.view-copy h4').html(modelName);
$('#inc-price #year3').html(buildPrice(DATA[i]["3 years/50,000 kms"]));
$('#inc-price #year5').html(buildPrice(DATA[i]["5 years/70,000 kms"]));
$('#inc-price #year6').html(buildPrice(DATA[i]["6 years/110,000 kms"]));
$('#plus-price #year3').html(buildPrice(PLUSDATA[i]["3 years/50,000 kms"]));
$('#plus-price #year5').html(buildPrice(PLUSDATA[i]["5 years/70,000 kms"]));
$('#plus-price #year6').html(buildPrice(PLUSDATA[i]["6 years/110,000 kms"]));
}
}
}
// COONVERT TO FR PRICE DISPLAY
var buildPrice = function (str) {
var tmp = str.split('$')[1];
var rtn = tmp.split(',')[0]+' $';
if(typeof tmp.split(',')[1] != 'undefined'){
rtn = tmp.split(',')[0] + " " + tmp.split(',')[1] + ' $';
}
var rt = rtn.split('.00')[0];
if(language == 'en'){
return str;
}else{
return rt + ',00 $';
}
}
return{ init : init }
})();
return { ServiceCalculator : ServiceCalculator };
}(jQuery, window._mini = window._mini || {}, window, document));
|
import React, {Component, Fragment} from 'react';
import {Button, Form, Input, InputNumber, Select, DatePicker} from "antd";
const Option = Select.Option;
const FormItem = Form.Item;
class RequisicionesForm extends Component{
render(){
let {getFieldDecorator} = this.props.form
return(
<Fragment>
<Form>
<FormItem label="Fecha de Entrega">
{getFieldDecorator('fecha_entrega', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<DatePicker />
)}
</FormItem>
<FormItem label="Fecha de Límite">
{getFieldDecorator('fecha_limite', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<DatePicker />
)}
</FormItem>
<FormItem label="Línea de Negocio">
{getFieldDecorator('bl', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Select>
<Option value={"1"}>1</Option>
</Select>
)}
</FormItem>
<FormItem label="Producto">
{getFieldDecorator('prducto', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Select>
<Option value={"1"}>1</Option>
</Select>
)}
</FormItem>
<FormItem label="Tipo de egreso">
{getFieldDecorator('prducto', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Select>
<Option value={"gasto"}>Gasto</Option>
<Option value={"costo"}>Costo</Option>
</Select>
)}
</FormItem>
<FormItem label="Solicitante">
{getFieldDecorator('solicitante', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem label="Último Precio">
{getFieldDecorator('ultimo_precio', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem label="Comentarios">
{getFieldDecorator('comentarios', {
rules: [{
required: true, message: 'Completa!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">Guardar</Button>
</FormItem>
</Form>
</Fragment>
)
}
}
const RequisicionesWForm = Form.create()(RequisicionesForm);
export default RequisicionesWForm;
|
'use strict';
import * as aws from 'aws-sdk';
import { debug } from '../../lib/index';
import { EmailQueue } from '../../lib/email_queue';
import { SendEmailService } from '../../lib/send_email_service';
import { parse } from 'aws-event-parser';
aws.config.update({region: process.env.SERVERLESS_REGION});
const sqs = new aws.SQS();
const lambda = new aws.Lambda();
module.exports.respond = (event, cb, context) => {
debug('= sender.sendEmails', JSON.stringify(event));
let emailQueue;
if (event.hasOwnProperty('QueueUrl')) {
debug('= sender.sendEmails', 'The queue url was provided', event);
emailQueue = new EmailQueue(sqs, {url: event.QueueUrl});
} else {
debug('= sender.sendEmails', 'Got an SNS event');
const snsMessage = parse(event)[0];
if (snsMessage.hasOwnProperty('QueueName')) {
debug('= sender.sendEmails', 'The queue name was provided', snsMessage);
emailQueue = new EmailQueue(sqs, {name: snsMessage.QueueName});
} else {
debug('= sender.sendEmails', 'Lambda was invoked by CW alarm');
const queueName = snsMessage.Trigger.Dimensions[0].value;
emailQueue = new EmailQueue(sqs, {name: queueName});
}
};
const senderService = new SendEmailService(emailQueue, lambda, context);
senderService.sendEnqueuedEmails()
.then((result) => cb(null, result))
.catch((err) => cb(err, null));
};
|
// Data Change with Mutation
var player = {score: 1, name: 'Jeff'};
player.score = 2;
// Now player is {score: 2, name: 'Jeff'}
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
function callable( fn, a, b) {
return fn(a, b);
}
callable(sum, 10, 20);
function sum(a,b) {
return a+b;
}
|
import React, { useState } from "react"
import { render } from "react-dom"
import { HashRouter } from "react-router-dom";
import { Main } from "./src/main";
function App() {
return <div>
<HashRouter>
<Main />
</HashRouter>
</div>
}
render(<App></App>, document.querySelector(`#app`))
|
var TEST = function(){
var self = this;
var boolToBin = function(x){ return (x? 1:0); };
// contains the data of our circuit. what devices and connections exist? what is the state of each device?
var data;
// if a labeled device has this type, we should set it when testing. otherwise the device is an output pin, and we
// should simply check it's value when testing
var inputPinTypes = ['SINGLEINPUT','CUSTOMBUSOUT'];
// the data object contains an array of devices. given a label, what is the index of the device?
var iOfLabelInData = function(label){
for(var i = 0;i<data.devices.length;i++){
if (data.devices[i]['label']===label)
return i;
}
return null;
};
//returns the simcir device with a given index (data.devices[id])
var getDevice = function(id){ return simcir.controller($('#circuitBox').find('.simcir-workspace')).data().deviceFuncts[id]; }
//returns the stored value of a given device.
var getState = function(label){
var i = iOfLabelInData(label);
let isBus = deviceIsBus(label);
let d = getDevice(i).deviceDef;
if( isBus ){
//2s compliment
if(d.value>32768 && ( d['numInputs']===16 || d['numOutputs']===16 ) ){
return d.value-Math.pow(2,15);
}
return d.value;
}
i = d.state['on']
return boolToBin(i);
};
// sets the device with label "CLOCK" to the specified value
var setClock = function(value){
return new Promise(function(resolve, reject) {
var i = iOfLabelInData('CLOCK');
getDevice(i).trigger(value);
setTimeout(() => {
resolve()}, 10); // (*)
});
};
//sets the device with the given label to a specified value
var setState = function(label,value){
return new Promise(function(resolve, reject) {
var i = iOfLabelInData(label);
getDevice(i).trigger(value);
//console.log('uploading new circuit data')
setTimeout(() => { //console.log(simcir.controller($('#circuitBox').find('.simcir-workspace')).data() );
resolve()}, 60); // (*)
});
};
// returns true if the device is a bus, false if otherwise. buses must have their outputs converted from an array of 1/null values
// into a decimal value
var deviceIsBus = function(label){
let i = iOfLabelInData(label);
if(i===null) throw('device with label '+label+' not found')
if( data.devices[i]['isBus'] ) {
return data.devices[i]['isBus'];
}
return false;
};
//returns the labels of all the devices which need to be set for this test
var getPinsToSet = function(testobj){
var labels = testobj[0];
var answer = [];
for(var i in labels){
var pinLabel = labels[i];
var pinIndex = iOfLabelInData( pinLabel )
if(inputPinTypes.includes( data.devices[pinIndex].type ) && labels[i]!=="CLOCK")
answer.push(labels[i])
}
return answer;
}
//returns the labels of all the pins we need to check for this test
var getPinsToCheck = function(testobj){
var labels = testobj[0];
var answer = [];
for(var i in labels){
var pinLabel = labels[i];
var pinIndex = iOfLabelInData( pinLabel )
if(!inputPinTypes.includes( data.devices[pinIndex].type ))
answer.push(labels[i])
}
return answer;
}
var tickTock = function(){
return new Promise(function(resolve,reject){
// If the time label has a '+', we are on clock-high, and should enable the clock so that
// clocked chips can have their outputs updated.
if( self.instructions[self.instructionIndex][0].includes('+') ){
setClock(1).then( ()=> {resolve();})
}else{
setClock(0).then( ()=> {resolve();})
}
});
}
var setAllDevices = function(){
return new Promise(function(resolve, reject) {
let promiseChain = Promise.resolve();
let j = self.instructionIndex;
//if we have a clocked test add the clocked time to our output line
if(self.isClockedTest){
let clockVal = self.instructions[ j ][0];
self.oneLine.push( clockVal );
}
for(let i = 0;i<self.devicesToSet.length;i++){
let valueToSet;
let devLabel = self.devicesToSet[i];
let z = self.indOfLabel[devLabel]; // the index in our instruction row of this device
let isBus = deviceIsBus( devLabel );
if( isBus ){
valueToSet = self.instructions[j][ z ];
}else{
valueToSet = self.instructions[j][ z ] === 1 ? true : false;
}
if(! isBus )
valueToSet = boolToBin(valueToSet);
self.oneLine.push( valueToSet );
promiseChain = promiseChain.then( () => {return setState( devLabel , valueToSet);} );
}
promiseChain = promiseChain.then( () => { resolve(); } );
promiseChain.catch( (err) => {console.log(err); reject(); } );
});
};
var getAllOutputs = function(){
// get all results from the test
return new Promise(function(resolve, reject) {
try{
let promiseChain = Promise.resolve();
//adding set pin to output
for(let i = 0;i<self.devicesToCheck.length;i++){
let devLabel = self.devicesToCheck[i];
let actualValue = getState(devLabel);
self.oneLine.push( actualValue );
}
self.outputs.push( self.oneLine );
resolve();
}catch(err) {console.log(err); reject();}
});
};
var checkActualAgainstExpectedOuts = function(){
return new Promise(function(resolve, reject) {
try{
let j = self.instructionIndex;
let actualLine = self.oneLine; //most recent output
let expectedLine = self.instructions[ j ]; // look at our array of tests. find the j'th test, element z is our output
for(let i = 0;i<self.devicesToCheck.length;i++){
let devLabel = self.devicesToCheck[i];
let z = self.indOfLabel[devLabel]; //index in our test row
let expectedValue = expectedLine[z]
let actualValue = actualLine[z]
if(actualValue !== expectedValue && expectedValue !=='*' ){ //'*' is wildcard, any value is acceptable
self.passed = false;
self.testOver = true;
}
}
if(!self.passed){
self.outputs.push( expectedLine );
}
resolve();
}catch(err) {console.log(err); reject();}
});
};
//returns the results of a single run of testing
//test are as follows [clock, in0, in1, in2, in_n, out1, out2, out_n]
this.runSingleTest =function(){
return new Promise(function(resolve, reject) {
if(self.testOver) resolve(null);
self.outputs = [];
self.oneLine = [];
let promiseChain = Promise.resolve();
// set all input devices
promiseChain = promiseChain.then( ()=> {return setAllDevices();} );
// get all output devices state
promiseChain = promiseChain.then( ()=> {return getAllOutputs();} );
// log the output of our circuit and check against expected values
promiseChain = promiseChain.then( () => {
return checkActualAgainstExpectedOuts();
});
// tick tock the clock if we have a clocked test
if(self.isClockedTest){
promiseChain = promiseChain.then( ()=>{
return tickTock();
});
}
// check for end of testing, then resolve
promiseChain = promiseChain.then( ()=>{
if(!self.passed){
self.testOver = true;
}
else{
if(self.instructionIndex<self.instructions.length-1){
self.instructionIndex+=1;
}else{
self.testOver = true;
}
}
resolve(self.outputs);
});
});
};
// a call to tester returns a results object as follows:
// passed:true/false if all tests ran correctly
// head: an array of strings which are the labels of the devices in our circuit
// test results[], where each element is a string which describes the expected and actual values, followed by a check or x for pass/fail
//testobj is formatted as follows:
// first line ['label0','label1','labeln']
// if the first device is labeled "clock", we must run a clocked test
// each subsequent line is the expected values for each label
// this works using a promise chain, evaluating each test. reject the chain on the first failed test.
this.startTest = function(testobj){
return new Promise(function(resolve,reject){
// get the current state of the board (devices and connections)
data = simcir.controller($('#circuitBox').find('.simcir-workspace')).data();
self.numTests = testobj.length-1;
self.devicesToSet = getPinsToSet(testobj);
self.devicesToCheck = getPinsToCheck(testobj);
self.outputs = [];
self.head = testobj[0];
self.results = [];
self.passed = true;
self.isClockedTest = testobj[0].includes("CLOCK");
self.instructions = testobj.slice(1);
self.instructionIndex = 0;
self.testOver = false;
//indOfLabel in our answer row
self.indOfLabel = {};
for(let i = 0;i<self.head.length;i++){
let devName = self.head[i];
self.indOfLabel[devName] = self.head.indexOf(devName);
}
let clockOn;
let clockOff;
self.chain = Promise.resolve();
let chain = self.chain;
// clear any input pins to 0;
for(let i in self.devicesToSet){
let devLabel = self.devicesToSet[i]
let zeroVal = deviceIsBus(devLabel) ? 0 : null;
chain=chain.then( ()=> {
return setState(devLabel,zeroVal);
} );
}
// if we have a clocked test, clean the clock to reset any lingering values
if(self.isClockedTest){
//clock on
chain = chain.then( ()=>{ return setClock(1); });
//clock off
chain = chain.then( ()=>{ return setClock(0); });
}
chain = chain.then( ()=>{ resolve(self.head); })
});
};
}
|
workbox.routing.registerRoute(
new RegExp('^https://blog.sa2taka.com/'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'page-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 14, // for 2 weeks
}),
],
})
);
workbox.routing.registerRoute(
new RegExp(
'^https://cdn.contentful.com/spaces/xw0ljpdch9v4/environments/master/'
),
workbox.strategies.staleWhileRevalidate({
cacheName: 'entry-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 14, // for 2 weeks
}),
],
})
);
workbox.routing.registerRoute(
new RegExp('^https?://images.ctfassets.net/xw0ljpdch9v4/.*.(png|jpg|webp)$'),
workbox.strategies.cacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 14, // for 2 weeks
}),
],
})
);
workbox.routing.registerRoute(
new RegExp('^https://fonts.googleapis.com/'),
workbox.strategies.cacheFirst({
cacheName: 'google-fonts-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 30, // for 1 month
}),
],
})
);
|
import React from "react";
import { Link } from "react-router-dom";
//import { Link } from 'react-router-dom';
import logo from "../images/hamburguesa.svg";
import "./styles/header.css";
class HeaderCocina extends React.Component {
render() {
return (
<div className="Navbar-c">
<div className="container-fluid">
<a className="Navbar__brand" href="/">
<img className="Navbar__brand-logo" src={logo} alt="Logo" />
<span className="font-weight-light">Burger</span>
<span className="font-weight-bold">Queen</span>
</a>
<Link className="Navbar-p" href="/cocina">cocina</Link>
</div>
</div>
);
}
}
export default HeaderCocina;
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
// import { Card, Callout, Tooltip } from '@blueprintjs/core';
import { Timeline } from 'antd';
class Study extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data,
year: this.props.routeProps.location.state.year,
desc: this.props.routeProps
};
}
render() {
return (
<div>
<h3 style={{ margin: '2%' }}>{this.state.year} R&D Tax Credit Study</h3>
<Timeline>
<Timeline.Item>step1 2015-09-01</Timeline.Item>
<Timeline.Item>step2 2015-09-01</Timeline.Item>
<Timeline.Item>step3 2015-09-01</Timeline.Item>
<Timeline.Item>step4 2015-09-01</Timeline.Item>
</Timeline>
</div>
);
}
}
export default Study;
|
WAF.onAfterInit = function onAfterInit() {// @lock
// @region namespaceDeclaration// @startlock
var documentEvent = {}; // @document
// @endregion// @endlock
// eventHandlers// @lock
documentEvent.onLoad = function documentEvent_onLoad (event)// @startlock
{// @endlock
var theme = getTheme();
var source = new Array();
for (i = 0; i < 3; i++) {
var movie = 'avatar.png';
var title = 'Avatar';
var year = 2009;
switch (i) {
case 1:
movie = 'endgame.png';
title = 'End Game';
year = 2006;
break;
case 2:
movie = 'priest.png';
title = 'Priest';
year = 2011;
break;
}; // end switch
var html = "<div style='padding: 0px; margin: 0px; height: 95px; float: left;'><img width='60' style='float: left; margin-top: 4px; margin-right: 15px;' src='../../images/" + movie + "'/><div style='margin-top: 10px; font-size: 13px;'>" + "<b>Title</b><div>" + title + "</div><div style='margin-top: 10px;'><b>Year</b><div>" + year.toString() + "</div></div></div>";
// source[i] = { html: html, title: title };
source[i] = title;
}; // end for
// Create a jqxComboBox
$("#jqxWidget").jqxComboBox({ source: source, selectedIndex: 0, width: '250', height: '25px', theme: theme });
};// @lock
// @region eventManager// @startlock
WAF.addListener("document", "onLoad", documentEvent.onLoad, "WAF");
// @endregion
};// @endlock
|
import {SIGN_IN} from './types';
const signIn = (userId) => {
return { type: SIGN_IN, payload: userId };
};
export default signIn;
|
import styled from "styled-components";
export const CardContainer = styled.div`
position: relative;
display: inline-block;
border-radius: 5px;
overflow: hidden;
width: 300px;
margin-left: 10px;
margin-bottom: 10px;
background: ${({ theme }) => theme.primaryWhite};
transition: ${({ theme }) => theme.boxShadow};
box-shadow: 0 0 11px rgba(83, 68, 68, 0.2);
:hover {
box-shadow: 0 0 11px rgba(33, 33, 33, 0.4);
}
@media (max-width: ${({ theme }) => theme.sm}) {
margin-left: 0;
}
`;
//POST CARD HEADER
export const HeaderContainer = styled.div`
display: flex;
z-index: 2;
width: 100%;
height: 32px;
padding: 5px;
background: ${({ theme }) => theme.primaryWhite};
:hover {
cursor: default;
}
`;
//POST CARD CONTENT
export const ContentContainer = styled.div`
z-index: 2;
height: 80px;
width: 100%;
padding: 10px;
overflow: hidden;
background: ${({ theme }) => theme.primaryWhite};
`;
export const ContentTitle = styled.div`
font-size: 18px;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
//POST CARD IMAGES
export const ImageContainer = styled.div`
position: relative;
text-align: center; /* needed to allow vertical centering */
width: 300px;
height: 288px;
line-height: 288px; /* overall post card height - post header height | used to center photo in white space*/
background-color: #f3f7f9;
overflow: hidden;
`;
export const ImageBackgroundWrapper = styled.div`
position: absolute;
left: 0;
top: 0;
filter: opacity(0.2);
-webkit-filter: opacity(0.2);
background-size: cover;
min-width: 100%;
min-height: 100%;
background-position: center;
`;
export const ImageWrapper = styled.img`
max-height: 100%; /* overall post card height - post header height | used to center photo in white space*/
max-width: 100%;
vertical-align: middle; /* center vertically */
margin: 0 auto; /* center horizontally */
position: relative;
border: 1px solid rgb(255, 255, 255);
margin-top: -3px; /* fix margin issue */
`;
//MANAGEMENT OPTIONS
export const ManagementContainer = styled.div`
margin: 0 10px 10px 10px;
display: flex;
`;
|
const DefaultCollections = [
'users',
];
export default DefaultCollections;
|
//Questão 3//
let lista = [25,10,15,2,90,3];
function Maior_menor(lista){
let maior = lista[0];
let menor = lista[0];
for (let k = 0; k < 6; k++) {
if (lista[k] > maior){
maior = lista[k];
}
else if (lista[k] < menor){
menor = lista[k];
}
}
let vet = [2];
vet[0] = maior;
vet[1] = menor;
return vet;
}
let num = Maior_menor(lista);
console.log('Maior número: ' + num[0] + ' e Menor Número: ' + num[1]);
|
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import TextField from 'material-ui/TextField';
import css from './GradeReview.css';
import Dialog from 'material-ui/Dialog';
// Material-UI
import Drawer from 'material-ui/Drawer';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
class Review extends Component {
constructor(props) {
super(props);
this.state = {
dialogOpen: false
};
}
handleCancel = () => {
this.setState({dialogOpen: false});
}
handleSubmit = () => {
this.setState({dialogOpen: true});
}
handleConfirm = (msg) => {
this.setState({dialogOpen: false});
this.props.postGradeReview(msg);
this.props.closeGradeReview();
}
render() {
const actions = [
<FlatButton
label="取消"
primary={true}
onTouchTap={this.handleCancel}
/>,
<FlatButton
label="提交"
primary={true}
onTouchTap={(msg) => this.handleConfirm(this.refs.review_reason.input.refs.input.value)}
/>,
];
return (
<div>
<Drawer
width={(document.body.clientWidth > 992) ? '50%' : '80%'}
docked={false}
open={this.props.reviewOpen}
onRequestChange={this.props.closeGradeReview}
openSecondary={true}
containerClassName={css.drawer}
>
<h1 className={css.title}>{"成绩复议"}</h1>
<table>
<tbody>
<tr className={css.line}>
<td className={css.label}>申请人</td>
<td className={css.content}>{this.props.studentName}</td>
</tr>
<tr className={css.line}>
<td className={css.label}>学号/工号</td>
<td className={css.content}>{this.props.studentID}</td>
</tr>
<tr className={css.line}>
<td className={css.label}>复议课程</td>
<td className={css.content}>{this.props.courseName}</td>
</tr>
</tbody>
</table>
<TextField
ref='review_reason'
hintText="成绩复议理由(不超过200字)"
multiLine={true}
fullWidth={true}
rows={17}
rowsMax={20}
/>
<div className={css.buttonGroup}>
<RaisedButton className={css.button} label="提交申请" onTouchTap={this.handleSubmit}/>
</div>
</Drawer>
<div className="review-dialog">
<Dialog
title="确定提交申请吗?"
actions={actions}
modal={true}
contentStyle={{width: '100%', maxWidth: 'none'}}
open={this.state.dialogOpen}
>
确定要提交课程{this.props.courseName}的成绩复议吗?
</Dialog>
</div>
</div>
);
}
}
module.exports = Review;
|
import convertRadiansToIndex from 'util/convertRadiansToIndex';
import { modulo, toRadianDirection} from '@danehansen/math';
import {STANDARD_SEMITONES} from 'util/music';
import {RADIANS_IN_CIRCLE, DEGREES_IN_CIRCLE} from './constants';
describe('convertRadiansToIndex', function() {
it('correctly identifies indexes of chromatic scale starting with A', function() {
const semitones = STANDARD_SEMITONES;
const RADIANS_IN_SLICE = RADIANS_IN_CIRCLE / semitones;
const pitchSkip = 1;
const rootPitch = 0;
const expectedResults = [
3,
2,
1,
0,
11,
10,
9,
8,
7,
6,
5,
4,
];
for (let i = 0; i < expectedResults.length; i++) {
const result = convertRadiansToIndex(i * RADIANS_IN_SLICE, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it('correctly idendifies indexes of chromatic scale starting with C', function() {
const semitones = STANDARD_SEMITONES;
const RADIANS_IN_SLICE = RADIANS_IN_CIRCLE / semitones;
const pitchSkip = 1;
const rootPitch = 3;
const expectedResults = [
6,
5,
4,
3,
2,
1,
0,
11,
10,
9,
8,
7,
];
for (let i = 0; i < expectedResults.length; i++) {
const result = convertRadiansToIndex(i * RADIANS_IN_SLICE, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it('correctly idendifies indexes of circle of fifths starting with A', function() {
const semitones = STANDARD_SEMITONES;
const RADIANS_IN_SLICE = RADIANS_IN_CIRCLE / semitones;
const pitchSkip = 7;
const rootPitch = 0;
const expectedResults = [
9,
2,
7,
0,
5,
10,
3,
8,
1,
6,
11,
4,
];
for (let i = 0; i < expectedResults.length; i++) {
const result = convertRadiansToIndex(i * RADIANS_IN_SLICE, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it('correctly idendifies indexes of circle of fifths starting with C', function() {
const semitones = STANDARD_SEMITONES;
const RADIANS_IN_SLICE = RADIANS_IN_CIRCLE / semitones;
const pitchSkip = 7;
const rootPitch = 3;
const expectedResults = [
0,
5,
10,
3,
8,
1,
6,
11,
4,
9,
2,
7,
];
for (let i = 0; i < expectedResults.length; i++) {
const result = convertRadiansToIndex(i * RADIANS_IN_SLICE, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it('correctly identifies indexes of 11 pitch scale starting with A', function() {
const semitones = 11;
const DEGREES_IN_SLICE = DEGREES_IN_CIRCLE / semitones;
const pitchSkip = 1;
const rootPitch = 0;
const expectedResults = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
];
for (let i = 0; i < expectedResults.length; i++) {
const degrees = DEGREES_IN_SLICE * i * pitchSkip;
const radians = toRadianDirection(degrees);
const result = convertRadiansToIndex(radians, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it('correctly identifies indexes of 11 pitch scale starting with D', function() {
const semitones = 11;
const DEGREES_IN_SLICE = DEGREES_IN_CIRCLE / semitones;
const pitchSkip = 1;
const rootPitch = 3;
const expectedResults = [
3,
4,
5,
6,
7,
8,
9,
10,
0,
1,
2,
];
for (let i = 0; i < expectedResults.length; i++) {
const degrees = DEGREES_IN_SLICE * i * pitchSkip;
const radians = toRadianDirection(degrees);
const result = convertRadiansToIndex(radians, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
it.skip('correctly identifies indexes of 11 pitch scale starting with D incrementing by 3', function() {
const semitones = 11;
const DEGREES_IN_SLICE = DEGREES_IN_CIRCLE / semitones;
const pitchSkip = 3;
const rootPitch = 3;
const expectedResults = [
3,
7,
0,
4,
8,
1,
5,
9,
2,
6,
10,
];
for (let i = 0; i < expectedResults.length; i++) {
const degrees = modulo(DEGREES_IN_SLICE * (i - rootPitch) * pitchSkip, DEGREES_IN_CIRCLE);
const radians = toRadianDirection(degrees);
const result = convertRadiansToIndex(radians, semitones, rootPitch, pitchSkip);
const expectedResult = expectedResults[i];
expect(result).toBe(expectedResult);
}
});
});
|
import { ApolloError, ForbiddenError } from 'apollo-server-micro';
import User from '../../../models/user';
import fieldsCannotBeEmpty from '../../../utils/user-input/fieldsCannotBeEmpty';
import getAccessTokenPayload from '../../../utils/auth/getAccessTokenPayload';
import validateAccessTokenPayload from '../../../utils/auth/validateAccessTokenPayload';
import getJWTSecret from '../../../utils/auth/getJWTSecret';
import { sign } from 'jsonwebtoken';
export default async (mutation, { accessToken }, { signedIn }) => {
if (signedIn) {
throw new ForbiddenError('You are already signed in.');
}
fieldsCannotBeEmpty({ accessToken });
const payload = await getAccessTokenPayload(accessToken);
validateAccessTokenPayload(payload);
const user = await User.findByEmail(payload.email);
if (!user) {
throw new ApolloError(
`You're not in the database. Send an email to it@stuysu.org and we'll sort this out.`,
'NOT_IN_DATABASE'
);
}
const anonymousId = await user.getAnonymousId(accessToken);
const { id, email, firstName, lastName } = user;
const tokenData = {
user: {
id,
email,
firstName,
lastName,
anonymousId,
},
};
const secret = await getJWTSecret();
return sign(tokenData, secret, { expiresIn: '30d' });
};
|
var passwords = require("sdk/passwords");
var self = require("sdk/self");
var passwordList = self.data.load("common-password-list.txt")
console.debug("Password list: " + passwordList.substring(0, 30));
function analyze(options, callback) {
console.debug("analyze called");
var results = {};
passwords.search({onComplete:
function (credentials) {
var dupes = {};
results.all = [];
credentials.forEach(function(cred) {
console.debug(cred.url);
console.debug(cred.username);
if (cred.password in dupes) {
dupes[cred.password].push(cred.url);
}
else {
dupes[cred.password] = [cred.url];
}
results.all.push(cred);
});
results.all.forEach(function(result) {
result.issues = [];
var numDupes = dupes[result.password].length.toString();
if (numDupes == "1") {
numDupes = 'None';
result.score = 0;
}
else {
console.debug("Found duplicates for " + result.url);
result.score = numDupes;
result.issues.push("Duplicate, used for " + numDupes + " other sites.");
}
result.numDupes = numDupes;
result.score += testCommon(result);
result.score += testEntropy(result);
console.debug("Score for " + result.url + " is " + result.score);
});
console.debug("Returning " + results.length + " results.");
results.all.sort(function(a, b) {
if (a.score > b.score) {
return -1;
}
else if (a.score < b.score) {
return 1;
}
return 0;
});
callback(results);
}
});
}
// names correspond to POSIX character classes
var digit = {re: /^\d+$/g, size: 10};
var lower = {re: /^[a-z]+$/g, size: 26};
var alpha = {re: /^[A-Za-z]+$/g, size: 52};
var alnum = {re: /^\w+$/g, size: 63};
var print = {re: /^[\x20-\x7E]+$/g, size: 94};
var charClasses = [digit, lower, alpha, alnum, print];
function entropy(str) {
var cls;
for (var i = 0; i < charClasses.length; i++) {
cls = charClasses[i];
if (str.match(cls.re)) {
break;
}
}
// log_2(alphabet_size^(str_length))
return Math.log(Math.pow(cls.size, str.length)) / Math.log(2);
}
/**
* The entropy of an 8-character string with a mix of upper and lower case, a
* digit, and a special character is just over 52 so that is used as the
* cutoff.
**/
function testEntropy(result) {
var pw = result.password;
var entr = entropy(pw);
console.debug("Entropy for " + result.username + "@" + result.url + " is " + entr);
if (entr < 52) {
result.lowEntropy = true;
result.issues.push("Simple");
return 1;
}
return 0;
}
/**
* Checks if password is in common password list
**/
function testCommon(result) {
if (passwordList.indexOf(result.password.toLowerCase()) != -1) {
result.isCommon = true;
result.issues.push("Common password");
return 1;
}
else {
result.isCommon = false;
return 0;
}
}
exports.analyze = analyze;
exports.entropy = entropy;
exports.testCommon = testCommon;
|
'use strict';
const pkg = require('../package.json');
const uuid = require('uuid');
const ua = require('universal-analytics');
const ci = require('ci-info');
const osName = require('os-name');
const Conf = require('conf');
const detectMocha = require('detect-mocha');
const os = osName();
const packageName = pkg.name;
const nodeVersion = process.version;
const appVersion = pkg.version;
const conf = new Conf({
configName: `ga-${packageName}`,
projectName: packageName,
defaults: {
cid: uuid.v4()
}
});
var fake = {
pageview: () => {
return {
send: () => { return 'fake'; }
};
},
event: () => {
return {
send: () => { return 'fake'; }
};
}
};
var fakeMocha = {
pageview: () => {
return {
send: () => { return 'fakeMocha'; }
};
},
event: () => {
return {
send: () => { return 'fakeMocha'; }
};
}
};
var real = ua('UA-148336517-1', conf.get('cid'));
real.set('cd1', os);
real.set('cd2', nodeVersion);
real.set('cd3', appVersion);
let visitor;
function getVisitor() {
if (!visitor) {
if (detectMocha()) {
return fakeMocha;
}
if (ci.isCI) {
return fake;
}
visitor = real;
}
return visitor;
}
function sendDownloaded() {
real.pageview('/downloaded').send();
if (ci.isCI) {
real.pageview(`/downloaded/ci/${ci.name}`).send();
}
}
function visitorWrap(category) {
const visitor = getVisitor();
return ((category) => {
return (action, func) => {
return async () => {
try {
visitor.pageview(`/${category}`).send();
const result = await func();
visitor.event({
ec: category,
ea: action,
el: 'success',
dp: `/${category}`
}).send();
return result;
} catch (e) {
visitor.event({
ec: category,
ea: action,
el: 'error',
dp: `/${category}`
}).send();
throw e;
}
};
};
})(category);
}
function hooksWrap(hooks, category) {
const wrap = visitorWrap(category);
const reducer = (acc, hookEvt) => {
acc[hookEvt] = wrap(hookEvt, hooks[hookEvt]);
return acc;
};
return Object.keys(hooks).reduce(reducer, {});
}
module.exports = { getVisitor, visitorWrap, hooksWrap, sendDownloaded };
|
function get_content() {
$.getScript(media_url+'js/aux/modals.js', function(){
$.getScript(media_url+'js/aux/journeys.js', function(){
$.getScript(media_url+'js/aux/date.js', function(){
$.getScript(media_url+'js/lib/jquery.keypad.min.js', function(){
$.getScript(media_url+'js/lib/jquery.keypad-es.js', function(){
$.post(base_url+'/partials/dashboard_digital_viewer', function(template, textStatus, xhr) {
$('#main').html(template);
loadRadio();
//loadGuard();
//startWakeup();
//startStatus();
});
});
});
});
});
});
}
var myradio=false;
//var guard=false;
//var firebase_url=false;
//var firebase_ref=false;
//var journeys_ref=false;
//var reservations_ref=false;
function show_radio_map() {
pulsador = window.open(base_url+'/radiomap/'+myradio.id, "RadioMap", "location=0,status=0,scrollbars=0,width=1024,height=680");
}
function loadRadio() {
$.getJSON(api_url+'radios/get?callback=?', {}, function(data){
if(data.status=='success'){
myradio = data.data;
//firebase_updating();
//checkhash();
startStats();
$('#radio_title').html(myradio.name);
if(myradio.digital){
$('#radio_map').fadeIn();
}
}
else super_error('Radio info failure');
});
}
function startStats() {
$.post(base_url+'/partials/stats_radio', function(template, textStatus, xhr) {
$('#submain').html(template);
loadStats();
});
}
function loadStats() {
$.getJSON(api_url+'radios/stats_foreign?callback=?', {id:myradio.id}, function(data){
if(data.status=='success'){
$('#stat_journeys').text(data.data.total_journeys);
$('#stat_completed').text(data.data.completed_journeys);
$('#stat_canceled').text(data.data.canceled_journeys);
$('#stat_credit_cards').text(parseInt(data.data.credit_card_percent)+'%');
$('#stat_enterprises').text(data.data.total_enterprises);
$('#stat_buttons').text(data.data.total_buttons);
$('#stat_licences').text(data.data.total_licences);
}
else{
if (data.response=='radio_analytics_not_found') launch_alert('<i class="fa fa-frown-o"></i> Aun sin datos','warning');
}
});
}
|
function Des({movies,match}){
const movie=movies.find((movie) =>movie.id==match.params.movieid)
return(
<div>
<iframe width="560" height="315" src={movie.trailer} title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<p>{movie.description}</p>
</div>
)
}
export default Des
|
exports.available = function (uri) {
return new Promise(function (resolve, reject) {
try {
try {
var pm = com.tns.NativeScriptApplication.getInstance().getPackageManager();
pm.getPackageInfo(uri, android.content.pm.PackageManager.GET_ACTIVITIES);
resolve(true);
} catch(e) {
resolve(false);
}
} catch (ex) {
console.log("Error in appavailability.available: " + ex);
reject(ex);
}
});
};
exports.availableSync = function (uri) {
try {
try {
var pm = com.tns.NativeScriptApplication.getInstance().getPackageManager();
pm.getPackageInfo(uri, android.content.pm.PackageManager.GET_ACTIVITIES);
return true;
} catch(e) {
return false;
}
} catch (ex) {
console.log("Error in appavailability.availableSync: " + ex);
return false;
}
};
|
const { DIRECTIONS,TABLE_SIZE } = require('./constants');
const { Robot } = require('./Robot');
const bot = new Robot();
const lineListener = (input) =>{
try{
const inputCommands = input.toUpperCase().trim();
if(inputCommands.includes('PLACE')){
const newPostion=validatePosition(inputCommands);
if(newPostion){
bot.setPosition(newPostion);
}else{
process.stdout.write("\nPLACING COMMAND ERROR\n");
}
}else{
if(!bot.position.f) throw "NO VALID POSITION SET,PLACE X,Y,F FIRST";
switch(inputCommands){
case "MOVE":
process.stdout.write("\nMOVE\n");
bot.move();
break;
case "REPORT":
bot.getReport();
break;
case "LEFT":
bot.faceOnChange("LEFT");
process.stdout.write("\nLEFT\n");
break;
case "RIGHT":
bot.faceOnChange("RIGHT");
process.stdout.write("\nRIGHT\n");
break;
default:
process.stdout.write("\nINPUT ERROR\n")
}
}
}catch (error) {
console.log("\nUNVALID INPUT",JSON.stringify(error));
}
}
const validatePosition = (input) => {
const inputForValidate = input.split(/[ ,]+/);
const directionArray = inputForValidate.filter(item=>DIRECTIONS.indexOf(item)!== -1);
const digitsArray = inputForValidate.filter(item=>/\d/.test(item));
if(directionArray.length===1 && digitsArray.length === 2 ){
const x = +digitsArray[0];
const y = +digitsArray[1];
if(x >= 0 && x <= TABLE_SIZE.x && y >= 0 && y <= TABLE_SIZE.y){
const newPosition = {
x: x,
y: y,
f: directionArray[0]
}
return newPosition;
}else { return false; }
}else{
return false;
}
}
module.exports = { lineListener,validatePosition };
|
const mongoose = require('mongoose');
const cardSchema = new mongoose.Schema({
category: String,
cardName: String,
description: String,
icon: String,
createdAt: {
type: Date,
default: new Date(),
},
});
module.exports = mongoose.model('Card', cardSchema);
|
import {FormTemplateRepository} from '../repository'
import {makeFindAllHandler, makeFindById, makeHandleArchive, makeHandlePost, makeHandlePut, makeHandleRestore} from './StandardController'
import {entityFromBody, parseFilters, parsePagination, requiresRole} from '../middlewares'
import {formSchema} from '../../modules/form-templates/validate'
import {boolean, Schema, string} from 'sapin'
import ROLES from '../../modules/accounts/roles'
const ACCEPTED_SORT_PARAMS = ['fullName']
const filtersSchema = new Schema({
contains: string,
isArchived: boolean,
includeArchived: boolean
})
export default (router) => {
const validateSchema = entityFromBody(formSchema)
router.use('/form-templates', requiresRole(ROLES.formsManager))
router.route('/form-templates')
.get([
parsePagination(ACCEPTED_SORT_PARAMS),
parseFilters(filtersSchema),
makeFindAllHandler(FormTemplateRepository)
])
.post([validateSchema, makeHandlePost(FormTemplateRepository)])
router.route('/form-templates/archive')
.post(makeHandleArchive(FormTemplateRepository))
router.route('/form-templates/restore')
.post(makeHandleRestore(FormTemplateRepository))
router.route('/form-templates/:id')
.get(makeFindById(FormTemplateRepository))
.put([validateSchema, makeHandlePut(FormTemplateRepository)])
}
|
var Promise = require('bluebird');
module.exports = function updateDatabase(server, cb) {
if (!server.get('standalone')) {
return cb();
}
var db = server.datasources.db;
var isActual = Promise.promisify(db.isActual, db);
var autoupdate = Promise.promisify(db.autoupdate, db);
var modelsToUpdate = require('../models-list');
db.setMaxListeners(40);
isActual(modelsToUpdate).then(function(actual) {
if (actual) {
console.log('Database models are up to date.');
return Promise.resolve();
} else {
return autoupdate(modelsToUpdate)
.then(function() {
console.log('Models: ' + modelsToUpdate + ' updated.');
}, function(err) {
console.log('Error: ' + err + ' when autoupdating models: ' + modelsToUpdate);
throw err;
});
}
})
.nodeify(cb);
};
|
const render = async (file, data = null) => {
const pageData = await file(data).replace(/\s{2,}|\n/g, '')
return pageData
}
module.exports = render
|
import styled from 'styled-components';
const BaseHeading = styled.h1`
font-size: 4.0rem; line-height: 1.2; letter-spacing: -.1rem;
text-transform: ${props => props.big ? 'uppercase' : ''};
margin: 2.0rem 0 1.0rem 0;
`;
/* Header components, from H1 through H6 */
export const H1 = BaseHeading.extend`
@media (min-width: 550px) { font-size: 5.0rem; } /* Larger than phablet */
`;
export const H2 = BaseHeading.extend`
font-size: 3.6rem; line-height: 1.25; letter-spacing: -.1rem;
@media (min-width: 550px) { font-size: 4.2rem; } /* Larger than phablet */
`;
export const H3 = BaseHeading.extend`
font-size: 3.0rem; line-height: 1.3; letter-spacing: -.1rem;
@media (min-width: 550px) { font-size: 3.6rem; } /* Larger than phablet */
`;
export const H4 = BaseHeading.extend`
font-size: 2.4rem; line-height: 1.35; letter-spacing: -.08rem;
@media (min-width: 550px) { font-size: 3.0rem; } /* Larger than phablet */
`;
export const H5 = BaseHeading.extend`
font-size: 1.8rem; line-height: 1.5; letter-spacing: -.05rem;
@media (min-width: 550px) { font-size: 2.4rem; } /* Larger than phablet */
`;
export const H6 = BaseHeading.extend`
font-size: 1.5rem; line-height: 1.6; letter-spacing: 0rem;
@media (min-width: 550px) { font-size: 1.5rem; } /* Larger than phablet */
`;
/* Bold text component */
export const Strong = styled.strong`
font-weight: 600;
`;
/* Anchor component for links outside of react router */
export const Anchor = styled.a`
color: #1EAEDB;
text-decoration: none;
:hover {
color: #0FA0CE;
text-decoration: none;
}
`;
|
module.exports = [
{
model: 'User',
data: {
email: 'test@abakus.no',
name: 'Test Bruker',
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
},
{
model: 'User',
data: {
email: 'backup@abakus.no',
name: 'Backup bruker',
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
}
];
|
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
//静态文件加载
app.use(express.static(__dirname+'/public'));
//路由
app.get('/login',(req,res)=>{
res.setHeader('Content-Type','text/html;charset=utf-8');
res.end(fs.readFileSync(__dirname+'/login.html'));
});
app.post('/login',(req,res,next)=>{
let data = req.body;
var json = readJsonSync(__dirname+'/public/data.json');
res.setHeader('Content-Type','text/plain;charset=utf-8');
if(json.users[0].username === data.username && json.users[0].password === data.password){
console.log('success!');
res.setHeader('Set-cookie',[`loginStatus=true`]);
res.redirect('/list');
}else{
console.log('failed!');
res.setHeader('Set-cookie',[`loginStatus=false`]);
res.end('用户名或密码错误');
}
});
app.get('/list',(req,res)=>{
//读取json文件
res.setHeader('Content-Type','text/html;charset=utf-8');
// console.log('json:',json);
//进行对比
var cookie = {};
cookie = cookieToObj(req.headers.cookie);
console.log('cookie:',cookie);
if(cookie.loginStatus === 'true'){
res.sendFile(__dirname + '/list.html');
}else{
res.send('用户名或密码错误');
}
});
app.get('/listData',(req,res)=>{
var json = readJsonSync(__dirname+'/public/data.json');
res.send(json.chapterList);
});
app.listen(8000);
//读取json
readJsonSync = (path)=>{
let data = fs.readFileSync(path,'utf8');
return JSON.parse(data);
}
//解析cookie
function cookieToObj(cookie){
let obj = {};
if(cookie.split !== undefined){
cookie.split(';').map(item=>{
// console.log(item);
item = item.trim();
let arr = item.split('=');
obj[arr[0]] = arr[1];
});
}
return obj;
}
|
/// <reference path="/Scripts/jquery-1.10.2-vsdoc.js"/>
/// <reference path="/Scripts/General.js"/>
/// <reference path="/Scripts/Servicios.js"/>
/// <reference path="/Scripts/InterfazGrafica.js"/>
/// <reference path="/Scripts/DOM.js"/>
/// <reference path="/Scripts/Conversiones.js" />
/// <reference path="/Scripts/ordenacion.js" />
/// <reference path="/Scripts/validaciones.js" />
$(document).ready(Inicializar);
function Inicializar()
{
LlenarCombo({ Combo: "cboPais", Resultado: window.parent.Paises, TextoNull: "Todos", ValorNull: "%%%", DivResultado: "lstPais" });
LlamarServicio(_Clientes_lst, "Clientes_lst");
}
function _Clientes_lst(msg)
{
Clientes = msg.d;
LlenarCombo({ Combo: "cboCliente", Resultado: Clientes, CampoId: "id", CampoValor: "Nombre" });
}
function Ejecutar()
{
var idCliente = Convert.ToInt32($("#cboCliente").val());
if (idCliente == 0) idCliente = null;
LlamarServicio(_ClienteCuentas_rpt, "ClienteCuentas_rpt", { idCliente: idCliente });
}
function _ClienteCuentas_rpt(msg)
{
Tabla({
Contenedor: "pnlResultados",
Resultado: msg.d,
Campos: [
{ Titulo: "Code", Campo: "Codigo", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Person", Campo: "Persona", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Country", Campo: "Pais", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Account", Campo: "Factura", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Type", Campo: "Producto", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "BL", Campo: "BL", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Buque", Campo: "Buque", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Date", Campo: "FechaDocumento", Clase: "grdFecha", Ordenacion: true, Filtro: true },
{ Titulo: "Currency", Campo: "Moneda", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Current", Campo: "MontoRestante", Clase: "grdDecimal", Ordenacion: true, Filtro: true },
{ Titulo: "Moneda(Local)", Campo: "MonedaLocal", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Restente(Local)", Campo: "MontoLocal", Clase: "grdDecimal", Ordenacion: true, Filtro: true },
{ Titulo: "Exchange", Campo: "CambioLocal", Clase: "grdDecimal", Ordenacion: true, Filtro: true },
{ Titulo: "Viaje", Campo: "Viaje", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "PuertoCarga", Campo: "PuertoCarga", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "PuertoDescarga", Campo: "PuertoDescarga", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "TipoPersona", Campo: "TipoPersona", Clase: "grdTexto", Ordenacion: true, Filtro: true },
{ Titulo: "Category", Campo: "Categoria", Clase: "grdTexto", Ordenacion: true, Filtro: true },
]
});
}
function Preparar()
{
$("#idCliente").val($("#cboCliente").val());
}
function FiltrarPorPais() {
var Pais = $("#cboPais").val();
var ListaClientes = Pais == "%%%" ? Clientes : Clientes.where(function (a) { return a.Nombre.indexOf("(" + Pais + ")") != -1 });
LlenarCombo({ Combo: "cboCliente", Resultado: ListaClientes, CampoId: "id", CampoValor: "Nombre"});
}
function SeleccionarPais() {
var paises = ObtenerLista("lstPais");
var CF = Clientes.where(function (a) { return paises.contains(a.idPais); });
LlenarCombo({ Combo: "cboCliente", Resultado: CF, CampoId: "id", CampoValor: "Nombre" });
}
|
import React, { Component } from 'react'
import { Modal, Button, Form, Select, Rate, Upload, Radio, Input, InputNumber, Icon, Switch } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
class Contact extends Component {
state = { visible: false }
showModal = () => {
this.setState({
visible: true,
});
}
handleOk = (e) => {
console.log(e);
this.setState({
visible: false,
});
}
handleCancel = (e) => {
console.log(e);
this.setState({
visible: false,
});
}
render() {
return (
<div>
<Button type="primary" onClick={this.showModal}>
Open Modal
</Button>
<Modal
title="Insira novo contato"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<Form>
<FormItem
label="Nome"
labelCol={{ span: 5 }}
wrapperCol={{ span: 12 }}
>
<Input/>
</FormItem>
<FormItem
label="Idade"
labelCol={{ span: 5 }}
wrapperCol={{ span: 12 }}
>
<InputNumber/>
</FormItem>
<FormItem
label="Cidade"
labelCol={{ span: 5 }}
wrapperCol={{ span: 8 }}
>
<Input/>
</FormItem>
<FormItem
style={{ display: 'inline-block', width: '100%', textAlign: 'center' }}
label="UF"
labelCol={{ span: 5 }}
wrapperCol={{ span: 3 }}
>
<Input/>
</FormItem>
<FormItem
label="Gênero"
labelCol={{ span: 5 }}
wrapperCol={{ span: 8 }}
>
<Select>
<Option value="M">Homem</Option>
<Option value="F">Mulher</Option>
<Option value="O">Outro</Option>
</Select>
</FormItem>
<FormItem
label="Ano"
labelCol={{ span: 5 }}
wrapperCol={{ span: 8 }}
>
<Input/>
</FormItem>
<FormItem
label="Fotos"
extra="Insira algumas fotos"
labelCol={{ span: 5 }}
wrapperCol={{ span: 8 }}
>
<Upload name="logo" action="/upload.do" listType="picture">
<Button>
<Icon type="upload" /> Inserir
</Button>
</Upload>
</FormItem>
<FormItem
label="Conexão"
labelCol={{ span: 5 }}
wrapperCol={{ span: 8 }}
>
<Switch></Switch>
</FormItem>
</Form>
</Modal>
</div>
);
}
}
export default Contact
|
const webSocket = new WebSocket("ws://127.0.0.1:3000");
// When the other client sends their offer and their ice candidates to us
// we have to accept that and give it to the peer connection so that the connection is established.
// Whenever there is a message fro the server to the websocket, below function is called
webSocket.onmessage = (event) => {
// event.data represents all the signalling data getting off the candidate
handleSignallingData(JSON.parse(event.data))
}
function handleSignallingData(data) {
switch (data.type) {
case "answer":
peerConn.setRemoteDescription(data.answer)
break
case "candidate":
peerConn.addIceCandidate(data.candidate)
}
}
let username;
function sendUsername() {
username = document.getElementById("username-input").value;
sendData({
type: "store_user"
})
}
function sendData(data) {
data.username = username
webSocket.send(JSON.stringify(data))
}
let localStream;
let peerConn;
function startCall() {
document.getElementById("video-call-div").style.display = "inline"
// Get video stream from device and show that video stream in the local video element
navigator.getUserMedia({
video: {
frameRate: 24,
width: {
min: 480, ideal: 720, max: 1280
},
aspectRatio: 1.33333
},
audio: true
}, (stream) => {
localStream = stream;
document.getElementById("local-video").srcObject = localStream;
// Configuration to be used to generate the icecandidates and to connect to the peer.
let configuration = {
// Check for functional stun servers at https://gist.github.com/sagivo/3a4b2f2c7ac6e1b5267c2f1f59ac6c6b
// or google webRTC stun / turn server list
// copy and paste url of stun server to Trace ICE page at https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/
// to confirm server is working. On the Trace ICE page, first remove existing server by selecting it and clicking remove server.
//Then paste new server on the STUN or TURN URI field. add stun: at the beginning of the link to look like stun:stun.l.google.com:19302
// Click on add server then click on gather candidates. If the type of the candidxate returned has srflx, then the server can be used.
iceServers: [
{
"urls": ["stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302"]
}
]
}
// Establish a peer connection to attach local stream. When a peer connects to our peer, the stream will be available to
// that person through a simple function that is available in the WebRTC API.
peerConn = new RTCPeerConnection(configuration)
// Attach stream to peer connection
peerConn.addStream(localStream)
//After peer connection is establisehd, this function is called
peerConn.onaddStream = (e) => {
// Show remote stream in remote video element
document.getElementById("remote-video").srcObject = e.stream;
}
// As soon as offer is created(see below), the peer connection starts gathering
// the ice candidates which need to be sent to the server. The server will send
// the candidates to the person trying to connect to us. With the candidates, we
// can make the connection happen. We send the icecandidate to the server using
// the onicecandidate function call
peerConn.onicecandidate = (e) => {
if(e.candidate == null)
return;
sendData({
type: "store_candidate",
candidate: e.candidate
})
}
createAndSendOffer()
}, (error) => {
console.log(error);
})
}
// Create and send offer which is stored in socket server. When someone connects with us,
// the server sends the offer to that person and get that person`s answer and returns the
// answer to us for storage in the peer connection.
function createAndSendOffer() {
peerConn.createOffer((offer) => {
// Send offer to the server
sendData({
type: "store_offer",
offer: offer
})
// Set description of remote peer connection
peerConn.setLocalDescription(offer)
}, (error) => {
console.log(error);
})
}
let isAudio = true;
function muteAudio() {
isAudio = !isAudio;
localStream.getAudioTracks()[0].enabled = isAudio;
}
let isVideo = true;
function muteVideo() {
isVideo = !isVideo;
localStream.getVideoTracks()[0].enabled = isVideo;
}
|
var Gearman = require("gearman").Gearman;
var shell = require("execSync");
var config = require("./config");
var fs = require("fs");
var worker = new Gearman('localhost', 4730);
worker.on("JOB_ASSIGN", function(job){
var payload = JSON.parse(job.payload);
var repo = config.configuration["buildWorker"][payload.appname].repo;
var projectPath = config.configuration["buildWorker"][payload.appname].projectPath;
var projectDirName = config.configuration["buildWorker"][payload.appname].projectDirName;
shell.run("mkdir -p " + projectPath);
if (!fs.existsSync(projectPath+"/"+projectDirName)) {
console.log("creating project");
shell.run("cd " + projectPath + " && git clone " + repo);
shell.run("cd "+projectPath+"/"+projectDirName+"/BashScripts && source ./create.sh");
console.log("create finished");
} else {
console.log("updating project");
shell.run("cd "+projectPath+"/"+projectDirName+"/BashScripts && source ./update.sh");
console.log("update finsihed")
}
var result = shell.run("cd "+projectPath+"/"+projectDirName+"/BashScripts && source ./build.sh");
console.log("build result is " + result);
worker.sendWorkComplete(job.handle, "");
worker.preSleep();
});
worker.on('NOOP', function(){
worker.grabJob();
});
worker.connect(function(){
worker.addFunction("build");
worker.preSleep();
});
|
import React from "react";
import { Card,Button,Container,CardDeck } from "react-bootstrap";
import San from './../images/wonders/san.jpg';
import Syd from './../images/wonders/sydney.jpg';
import Par from './../images/wonders/paris.jpg';
import Scotland from './../images/wonders/scotland.jpg';
import Japan from './../images/wonders/japan.jpg';
import Hawaii from './../images/wonders/hawaii.jpg';
import Rio from './../images/wonders/rio.jpg';
import Turkey from './../images/wonders/turkey.jpg';
import Ireland from './../images/wonders/ireland.jpg';
import './../CSS/home.css';
import About from './About Us';
import Footer from './Contact Us';
class Cities extends React.Component {
render() {
return (
<>
<Container>
<CardDeck>
<Card border='info' className = 'cards'>
<Card.Img variant="top" src={San} />
<Card.Header>California</Card.Header>
<Card.Body>
<Card.Title>Golden Gate Bridge</Card.Title>
<Card.Text>
The Golden Gate Bridge is a suspension bridge spanning the Golden Gate,
the one-mile-wide strait connecting San Francisco Bay and the Pacific Ocean.
</Card.Text>
<a href='https://en.wikipedia.org/wiki/Golden_Gate_Bridge' target='blank'>
<Button variant="primary" style={{position: 'relative', marginTop:'24px'}}>Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className = 'cards'>
<Card.Img variant="top" src={Syd} />
<Card.Header>Australia</Card.Header>
<Card.Body>
<Card.Title>Sydney Opera House</Card.Title>
<Card.Text>
The Sydney Opera House is a multi-venue performing arts centre at Sydney Harbour in Sydney, New South Wales, Australia.
</Card.Text>
<a href='https://www.sydneyoperahouse.com/' target='blank'>
<Button variant="primary" style={{position: 'relative', marginTop:'48px'}}>Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className = 'cards'>
<Card.Img variant="top" src={Par} />
<Card.Header>France</Card.Header>
<Card.Body>
<Card.Title>Eiffel Tower</Card.Title>
<Card.Text>
The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower.
</Card.Text>
<a href='https://www.toureiffel.paris/en' target='blank'>
<Button variant="primary">Know More</Button></a>
</Card.Body>
</Card>
</CardDeck><br /><br />
<CardDeck>
<Card border='info' className='cards'>
<Card.Img variant="top" src={Rio} />
<Card.Header>Rio de Janeiro</Card.Header>
<Card.Body>
<Card.Title>Sugarloaf Mountain</Card.Title>
<Card.Text>
Sugarloaf Mountain is a peak situated in Rio de Janeiro, Brazil,
at the mouth of Guanabara Bay on a peninsula that juts out into the Atlantic Ocean.
</Card.Text>
<a href='https://en.wikipedia.org/wiki/Sugarloaf_Mountain' target='blank'>
<Button variant="primary" style={{ position: 'relative', marginTop: '48px' }}>Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className='cards'>
<Card.Img variant="top" src={Japan} />
<Card.Header>JAPAN</Card.Header>
<Card.Body>
<Card.Title>MOUNT FUJI</Card.Title>
<Card.Text>
It's hard to pick the single most stunning place in Japan, but 12,388ft Mount Fuji might just take the prize. Visit Lake Kawaguchiko in the spring for some of the best views of the mountain and postcard-worthy cherry-blossom trees.
</Card.Text>
<a href='https://www.japan-guide.com/e/e2172.html' target='blank'>
<Button variant="primary" >Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className='cards'>
<Card.Img variant="top" src={Turkey} />
<Card.Header> TURKEY</Card.Header>
<Card.Body>
<Card.Title>CAPPADOCIA</Card.Title>
<Card.Text>
This Turkish region, where entire cities have been carved into rock, is incredible on its own. But whenever hot-air balloons pepper the sky, its awe-inspiring level skyrockets.
</Card.Text>
<a href='https://www.lonelyplanet.com/turkey/cappadocia-kapadokya' target='blank'>
<Button variant="primary" style={{ position: 'relative', marginTop: '48px' }}>Know More</Button></a>
</Card.Body>
</Card>
</CardDeck><br /><br />
<CardDeck>
<Card border='info' className='cards'>
<Card.Img variant="top" src={Hawaii} />
<Card.Header>HAWAII</Card.Header>
<Card.Body>
<Card.Title>NA PALI COAST</Card.Title>
<Card.Text>
Kauai has one of the world's most gorgeous coastlines, with towering waterfalls and isolated crescent beaches. Just be prepared to put in a little effort to soak up its wonders: Na Pali can only be seen from a helicopter, catamaran or on rather gruelling hike.
</Card.Text>
<a href='https://www.gohawaii.com/islands/kauai/regions/north-shore/napali-coast' target='blank'>
<Button variant="primary" style={{ position: 'relative', marginTop: '24px' }}>Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className='cards'>
<Card.Img variant="top" src={Ireland} />
<Card.Header>IRELAND</Card.Header>
<Card.Body>
<Card.Title>CLIFFS OF MOHER</Card.Title>
<Card.Text>
Few places exemplify the raw, untamed appeal of Ireland's west coast as this natural wonder, which tops 702ft at the highest point. And, while some might know them better as the Cliffs of Insanity from The Princess Bride, in reality, the cliffs are located just south of Galway.
</Card.Text>
<a href='https://www.cliffsofmoher.ie/' target='blank'>
<Button variant="primary" style={{ position: 'relative', marginTop: '24px' }}>Know More</Button></a>
</Card.Body>
</Card>
<Card border="info" className='cards'>
<Card.Img variant="top" src={Scotland} />
<Card.Header>SCOTLAND</Card.Header>
<Card.Body>
<Card.Title>ISLE OF SKYE</Card.Title>
<Card.Text>
With fairy pools and endless, undulating hills, the magical Isle of Skye is the stuff dreams are made of (regardless of whether you've binge-watched Outlander or not). While the nature here is timeless, the island has a food scene that's totally modern - we can't think of a better place to sample Michelin-starred dishes.
</Card.Text>
<a href='https://www.isleofskye.com/' target='blank'>
<Button variant="primary">Know More</Button></a>
</Card.Body>
</Card>
</CardDeck>
</Container><br /><br />
<About />
<Footer />
</>
);
}
}
export default Cities;
|
import { search } from './search'
import { layers } from './layers'
import { buildings } from './buildings'
export { search, layers, buildings }
|
import todosList from "./todos.json";
import {
TOGGLE_TODO,
ADD_TODO,
DELETE_TODO,
CLEAR_COMPLETED_TODOS
} from "./actions";
const initialState = {
todos: todosList
};
function todoApp(state = initialState, action) {
switch (action.type) {
case TOGGLE_TODO: {
const newTodos = state.todos.map(todo => {
if (todo.id === action.payload) todo.completed = !todo.completed;
return todo;
});
return { todos: newTodos };
}
case ADD_TODO: {
// action = { type: ADD_TODO, payload: newTodo }
// update component state with new todo
// create copy of data
const newTodos = state.todos.slice();
// modify and overwrite original
newTodos.push(action.payload);
return { todos: newTodos };
}
case DELETE_TODO: {
const newTodos = state.todos.filter(todo => todo.id !== action.payload);
return { todos: newTodos };
}
case CLEAR_COMPLETED_TODOS: {
const newTodos = state.todos.filter(todo => !todo.completed);
return { todos: newTodos };
}
default:
return state;
}
}
export default todoApp;
|
import React from 'react'
import { Link } from "@reach/router"
import Voter from '../general/Voter'
export default function ArticleCard(props) {
const { article_id, author, comment_count, created_at, title, topic, votes } = props.article
return (
<li className="articleCard">
<div className="cardTop">
<p className="articleTitle"><Link to={`/articles/${article_id}`} className="title">{`< ${title} />`}</Link></p>
<p className="author">By <Link to={`/users/${author}`}>{author}</Link></p>
<p className="date">{created_at} </p>
<p className="comments">{comment_count} comments</p>
<p className="topic">Topic: {topic}</p>
</div>
<Voter votes={votes} article_id={article_id} className="voterVotes"/>
</li>
)
}
|
angular.module('designer').requires.push('sfSelectors');
angular.module('designer')
.controller('SmartCtrl', ['$scope', '$http', 'propertyService', function ($scope, $http, propertyService) {
$scope.feedback.showLoadingIndicator = true;
// Get widget properies and load them in the controller's scope
propertyService.get()
.then(function (data) {
if (data) {
$scope.properties = propertyService.toAssociativeArray(data.Items);
}
}, function (data) {
$scope.feedback.showError = true;
if (data) {
$scope.feedback.errorMessage = data.Detail;
}
})
.finally(function () {
$scope.feedback.showLoadingIndicator = false;
});
$http.get('/api/default/newsitems?$filter=Tags/any(x:x eq 0dd81bd9-ac86-6d22-b705-ff0000413cd5)').then(function (response) {
$scope.newsItems = response.data.value;
});
$scope.$watch('properties.SelectedNewsItem.PropertyValue', function (newValue, oldValue) {
if (newValue) {
$scope.SelectedNewsItem = JSON.parse(newValue);
}
});
$scope.$watch('selectedItem', function (newValue, oldValue) {
if (newValue) {
$scope.properties.SelectedItem.PropertyValue = JSON.stringify(newValue);
}
});
// Build breaking news message form Date and Message widget properties
$scope.buildBreakingNewsMessage = function () {
$scope.properties.BreakingNewsMessage.PropertyValue = $scope.properties.Title.PropertyValue;
};
}]);
|
// @flow
import { action, observable, computed, decorate } from "mobx";
import remotedev from "mobx-remotedev";
import axios from "axios";
const _defaultInitialState = {
brand: null,
brands: [],
model: null,
models: [],
year: null,
years: [],
carInfo: null
};
const url = "https://parallelum.com.br/fipe/api/v1/carros";
class VehicleStore {
constructor() {
this.setInitialState(_defaultInitialState);
this.getBrands();
}
setInitialState = initialState => {
const {
brands,
brand,
models,
model,
years,
year,
carInfo
} = initialState;
this.brands = brands;
this.brand = brand;
this.models = models;
this.model = model;
this.years = years;
this.year = year;
this.carInfo = carInfo;
};
brandRequest = response => {
this.brands = response;
};
modelRequest = response => {
this.models = response;
};
yearsRequest = response => {
this.years = response;
};
infoRequest = responseFromRequest => {
this.carInfo = responseFromRequest;
};
getBrands = async () => {
const loadedBrands = await axios.get( url + "/marcas");
const loadedBrandsData = await loadedBrands.data;
this.brandRequest(loadedBrandsData);
};
getModels = async brandId => {
const loadedModels = await axios.get(url + `/marcas/${brandId}/modelos`);
const loadedModelsData = await loadedModels.data;
this.modelRequest(loadedModelsData.modelos);
};
getYears = async (brandId, modelId) => {
const loadedYears = await axios.get( url + `/marcas/${brandId}/modelos/${modelId}/anos`);
const loadedYearsData = await loadedYears.data;
this.yearsRequest(loadedYearsData);
};
getInfo = async (
brandId,
modelId,
year
) => {
const loadedInfo = await axios.get( url + `/marcas/${brandId}/modelos/${modelId}/anos/${year}`);
const loadedInfoData = await loadedInfo.data;
this.infoRequest(loadedInfoData);
};
setBrand = brand => {
this.brand = brand;
this.year = null;
this.model = null;
this.carInfo = null;
this.models = [];
this.carYears = [];
this.getModels(brand.code);
};
setModel = model => {
this.model = model;
this.year = null;
this.carInfo = null;
this.years = [];
this.getYears(this.brand.code, this.model.code);
};
setYear = year => {
this.year = year;
this.getInfo(
this.brand.code,
this.model.code,
this.year.code
);
};
}
export default remotedev(
decorate(VehicleStore, {
brands: observable,
brand: observable,
models: observable,
model:observable,
years:observable,
year: observable,
carInfo: observable,
getBrands: action,
getModels: action,
getYears: action,
setModel: action,
setBrand: action,
setYear: action,
getInfo: action,
brandRequest: action,
modelRequest: action,
yearsRequest : action,
infoRequest: action,
setInitialState: action
})
);
|
const attr = typeof console !== 'undefined' && 'info' in console ? 'info' : 'log'
const pad = num => ('0' + num).slice(-2)
const identity = obj => obj
export default function createLogger({ name, filter }) {
filter = typeof filter === 'function' ? filter : identity
const logInfo = data => {
data = filter(data)
const {
actionType,
actionPayload,
previousState,
currentState,
start = new Date(),
end = new Date(),
isAsync
} = data
const formattedTime = `${ start.getHours() }:${ pad(start.getMinutes()) }:${ pad(start.getSeconds()) }`
const takeTime = end.getTime() - start.getTime()
const message = `${ name || 'ROOT' }: action-type [${ actionType }] @ ${ formattedTime } in ${ takeTime }ms, ${isAsync ? 'async' : 'sync'}`
try {
console.groupCollapsed(message)
} catch (e) {
try {
console.group(message)
} catch (e) {
console.log(message)
}
}
if (attr === 'log') {
console[attr](actionPayload)
console[attr](previousState)
console[attr](currentState)
} else {
console[attr](`%c action-payload`, `color: #03A9F4; font-weight: bold`, actionPayload)
console[attr](`%c prev-state`, `color: #9E9E9E; font-weight: bold`, previousState)
console[attr](`%c next-state`, `color: #4CAF50; font-weight: bold`, currentState)
}
try {
console.groupEnd()
} catch (e) {
console.log('-- log end --')
}
}
return logInfo
}
|
var rhit = rhit || {};
rhit.ChatPageController = class {
constructor(sender, receiever, receieverName) {
console.log('i am the chat controller page');
rhit.fbUserManager.beginListening(rhit.fbAuthManager.uid, this.updateView.bind(this));
this._sender = sender;
this._receiver = receiever;
this._receiverName = receieverName;
this._currChatIndex = -1;
const messageInput = document.querySelector("#messageInput");
messageInput.addEventListener("keypress", (event) => {
if (event.key === 'Enter') {
if (this._currChatIndex > -1 && (messageInput.value != '' || messageInput.value != ' ')) {
let chat = rhit.fbChatsManager.getItemAtIndex(this._currChatIndex);
chat.messages.push({
message: messageInput.value,
sender: this._sender
});
rhit.fbChatsManager.update(chat);
messageInput.value = "";
} else {
rhit.fbChatsManager.addNewChatString([{"username": this._sender, "name": rhit.fbUserManager.name}, {"username": this._receiver, "name": this._receiverName}], [{message: messageInput.value, sender: this._sender}]);
messageInput.value = "";
}
}
});
document.querySelector("#enterBtn").addEventListener('click', (event) => {
if (this._currChatIndex > -1 && messageInput.value != "") {
let chat = rhit.fbChatsManager.getItemAtIndex(this._currChatIndex);
chat.messages.push({
message: messageInput.value,
sender: this._sender
});
rhit.fbChatsManager.update(chat);
messageInput.value = "";
} else {
messageInput.value = "";
rhit.fbChatsManager.addNewChatString([{"username": this._sender, "name": rhit.fbUserManager.name}, {"username": this._receiver, "name": this._receiverName}], [{message: messageInput.value, sender: this._sender}]);
}
});
document.querySelector("#submitDeleteChat").addEventListener('click', (event) => {
if (this._currChatIndex > -1) {
let chat = rhit.fbChatsManager.getItemAtIndex(this._currChatIndex);
console.log('chat id ', chat.id);
rhit.fbChatsManager.delete(chat.id);
}
});
rhit.fbChatsManager.beginListening(this.updateView.bind(this));
}
search(nameKey, myArray){
for (let i = 0; i < myArray.length; i++) {
if (myArray[i].username === nameKey) {
return i;
}
}
return -1;
}
updateView() {
const newList = htmlToElement('<div id="chats-list"></div>');
for (let i = 0; i < rhit.fbChatsManager.length; i++) {
let chat = rhit.fbChatsManager.getItemAtIndex(i);
if (((this.search(this._sender, chat.people) > -1) && (this.search(this._receiver, chat.people) > -1)) == true) {
this._currChatIndex = i;
for (let message of chat.messages) {
let messageCard = null;
if (message.sender == this._sender) {
messageCard = this._createSenderCard(message.message)
} else {
messageCard = this._createReceiverCard(message.message);
}
newList.appendChild(messageCard);
}
let emptyChild = this._createPlaceHolderDiv();
newList.appendChild(emptyChild);
}
}
const oldList = document.querySelector("#chats-list");
oldList.removeAttribute("id");
oldList.hidden = true;
// put in new quoteListContainer
oldList.parentElement.appendChild(newList);
if (this._currChatIndex < 0) {
$("#deleteIcon").attr('hidden', false);
}
}
_createPlaceHolderDiv(){
return htmlToElement(
`
<div id = "emptyPlaceHolder">
</div>
`
);
}
_createSenderCard(message) {
return htmlToElement(
`
<div class="chat-container">
<p>${message}</p>
</div>
`
);
}
_createReceiverCard(message) {
return htmlToElement(
`
<div class="chat-container darker">
<p>${message}</p>
</div>
`
);
}
}
|
#!/usr/bin/env node
'use strict';
var c = require("skilstak-colors");
function print(message){
//console.log(message);
process.stdout.write(message + "\n");
}
print(c.clear + c.blue + "Welcome to the Magic Eightball!");
print(c.red + "Enter your weird question. Go on. DO IT NOW!");
|
export default {
baseURL: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_API_URL
}
|
/**
* Created by rgautam on 1/13/17.
*/
import React from 'react';
import { Link } from 'react-router';
import Header from './Header';
export default class ErrorPage extends React.Component {
render() {
return (
<div>
<Header />
<div className = 'col-md-4 col-md-offset-4 col-xs-12'>
<img src="../styles/assets/images/404.gif" style={{width:'100%', margin:'20px 0'}} alt=''/>
<Link to = '/'>
<button className = 'col-xs-6 col-xs-offset-3 col-md-4 col-md-offset-4'>Back to home page</button>
</ Link>
</div>
</div>
)
}
}
|
'use strict';
import AWS from 'aws-sdk';
import { debug } from './index';
import Baby from 'babyparse';
import { Recipient, List } from 'moonmail-models';
import base64url from 'base64-url';
import querystring from 'querystring';
import moment from 'moment';
class ImportRecipientsService {
constructor({s3Event, importOffset = 0 }, s3Client, snsClient, lambdaClient, context) {
this.s3Event = s3Event;
this.importOffset = importOffset;
this.bucket = s3Event.bucket.name;
this.fileKey = querystring.unescape(s3Event.object.key);
const file = this.fileKey.split('.');
this.userId = file[0];
this.listId = file[1];
this.fileExt = file[file.length - 1];
this.s3 = s3Client;
this.corruptedEmails = [];
this.recipients = [];
this.totalRecipientsCount = 0;
this.lambdaClient = lambdaClient;
this.lambdaName = context.functionName;
this.context = context;
this.headerMapping = null;
this.sns = snsClient;
this.updateImportStatusTopicArn = process.env.UPDATE_IMPORT_STATUS_TOPIC_ARN;
}
get executionThreshold() {
return 60000;
}
get maxBatchSize() {
return 25;
}
// @deprecated
get s3Client() {
debug('= ImportRecipientsService.s3Client', 'Getting S3 client');
if (!this.s3) {
this.s3 = new AWS.S3({ region: process.env.SERVERLESS_REGION || 'us-east-1' });
}
return this.s3;
}
timeEnough() {
return (this.context.getRemainingTimeInMillis() > this.executionThreshold);
}
importAll() {
const importStatus = {
listId: this.listId,
userId: this.userId,
fileName: this.fileKey,
totalRecipientsCount: this.totalRecipientsCount,
corruptedEmailsCount: this.corruptedEmails.length,
corruptedEmails: this.corruptedEmails,
importedCount: this.importOffset,
importStatus: 'importing',
createdAt: moment().unix()
};
return this._publishToSns(importStatus)
.then(() => this.parseFile())
.then(recipients => {
this.totalRecipientsCount = recipients.length || 0;
this.recipients = recipients.filter(this.filterByEmail.bind(this));
return this.saveRecipients();
});
}
saveRecipients() {
if (this.importOffset < this.recipients.length) {
const recipientsBatch = this.recipients.slice(this.importOffset, this.importOffset + this.maxBatchSize);
return Recipient.saveAll(recipientsBatch)
.then(data => {
if (this.timeEnough()) {
if (data.UnprocessedItems && data.UnprocessedItems instanceof Array) {
this.importOffset += (this.maxBatchSize - data.UnprocessedItems.length);
} else {
this.importOffset += Math.min(this.maxBatchSize, recipientsBatch.length);
}
return this.saveRecipients();
} else {
if (data.UnprocessedItems && data.UnprocessedItems instanceof Array) {
this.importOffset += (this.maxBatchSize - data.UnprocessedItems.length);
} else {
this.importOffset += Math.min(this.maxBatchSize, recipientsBatch.length);
}
debug('= ImportRecipientsService.saveRecipients', 'Not enough time left. Invoking lambda');
return this.invokeLambda();
}
}).catch(err => {
return new Promise((resolve, reject) => {
debug('= ImportRecipientsService.saveRecipients', 'Error while saving recipients', err, err.stack);
const importStatus = {
listId: this.listId,
userId: this.userId,
fileName: this.fileKey,
totalRecipientsCount: this.totalRecipientsCount,
corruptedEmailsCount: this.corruptedEmails.length,
corruptedEmails: this.corruptedEmails,
importedCount: this.importOffset,
importStatus: 'failed',
finishedAt: moment().unix(),
message: err.message,
stackTrace: err.stack
};
this._publishToSns(importStatus)
.then(() => reject(importStatus))
.catch((e) => reject(importStatus));
});
});
} else {
return new Promise((resolve, reject) => {
const importStatus = {
listId: this.listId,
userId: this.userId,
fileName: this.fileKey,
totalRecipientsCount: this.totalRecipientsCount,
importedCount: this.importOffset,
corruptedEmailsCount: this.corruptedEmails.length,
corruptedEmails: this.corruptedEmails,
importStatus: 'success',
finishedAt: moment().unix()
};
debug('= ImportRecipientsService.saveRecipients', 'Saved recipients successfully', importStatus);
this._saveMetadataAttributes()
.then(() => this._publishToSns(importStatus))
.then(() => resolve(importStatus))
.catch((error) => reject(error));
});
}
}
invokeLambda() {
return new Promise((resolve, reject) => {
debug('= ImportRecipientsService.invokeLambda', 'Invoking function again', this.lambdaName);
const payload = { Records: [{ s3: this.s3Event }], importOffset: this.importOffset };
const params = {
FunctionName: this.lambdaName,
InvocationType: 'Event',
Payload: JSON.stringify(payload)
};
this.lambdaClient.invoke(params, (err, data) => {
if (err) {
debug('= ImportRecipientsService.invokeLambda', 'Error invoking lambda', err, err.stack);
reject(err);
} else {
debug('= ImportRecipientsService.invokeLambda', 'Invoked successfully');
resolve(data);
}
});
});
}
parseFile() {
return new Promise((resolve, reject) => {
const params = { Bucket: this.bucket, Key: this.fileKey };
debug('= ImportRecipientsService.parseFile', 'File', this.fileKey);
this.s3.getObject(params, (err, data) => {
if (err) {
debug('= ImportRecipientsService.parseFile', 'Error while loading an S3 file', err, err.stack);
reject(err);
} else {
debug('= ImportRecipientsService.parseFile', 'File metadata', data.Metadata);
if (this.fileExt === 'csv') {
this.headerMapping = JSON.parse(data.Metadata.headers);
return this.parseCSV(data.Body.toString('utf8')).then((recipients) => resolve(recipients)).catch((error) => reject(error));
} else {
debug('= ImportRecipientsService.parseFile', `${this.fileExt} is not supported`);
return reject(`${this.fileExt} is not supported`);
}
}
});
});
}
parseCSV(csvString) {
return new Promise((resolve, reject) => {
const headerMapping = this.headerMapping;
const userId = this.userId;
const listId = this.listId;
const recipients = [];
Baby.parse(csvString, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
step: (results, parser) => {
if (results.errors.length > 0) {
debug('= ImportRecipientsService.parseCSV', 'Error parsing line', JSON.stringify(results.errors));
} else {
debug('= ImportRecipientsService.parseCSV', 'Parsing recipient', JSON.stringify(item), headerMapping);
const item = results.data[0];
const emailKey = Object.keys(item)[0];
let newRecp = {
id: base64url.encode(item[emailKey]),
userId,
listId,
metadata: {},
status: Recipient.statuses.subscribed,
isConfirmed: true,
createdAt: moment().unix()
};
for (const key in headerMapping) {
const newKey = headerMapping[key];
if (newKey && newKey !== 'false') {
newRecp.metadata[newKey] = item[key];
}
}
newRecp.email = newRecp.metadata.email;
delete newRecp.metadata.email;
recipients.push(newRecp);
}
},
complete: (results, parser) => {
return resolve(recipients);
}
});
});
}
filterByEmail(recipient) {
const email = recipient.email;
if (/\S+@\S+\.\S+/.test(email)) {
return true;
} else {
this.corruptedEmails.push(email);
return false;
}
}
_saveMetadataAttributes() {
const metadataAttributes = Object.keys(this.recipients[0].metadata);
return List.update({ metadataAttributes }, this.userId, this.listId);
}
_publishToSns(message) {
const topic = this.updateImportStatusTopicArn;
return new Promise((resolve, reject) => {
debug('= ImportRecipientsService._publishToSns', 'Sending message', topic, JSON.stringify(message));
const params = {
Message: JSON.stringify(message),
TopicArn: topic
};
this.sns.publish(params, (err, data) => {
if (err) {
debug('= ImportRecipientsService._publishToSns', 'Error sending message', err);
reject(err);
} else {
debug('= ImportRecipientsService._publishToSns', 'Message sent');
resolve(data);
}
});
});
}
}
module.exports.ImportRecipientsService = ImportRecipientsService;
|
$(document).ready(function () {
$('.ee-login-auth-block form').submit(function (e) {
$(this).find('.-error').removeClass('-error');
var isErr = false;
$(this).find('.form-text.-required, .form-select.-required').each(function () {
if (!$(this).val().trim()) {
$(this).addClass('-error');
isErr = true;
}
});
$(this).find('input[type=checkbox]').each(function () {
if (!$(this).is(':checked')) {
$(this).parent().addClass('-error');
isErr = true;
}
});
if (isErr) {
e.preventDefault();
return false;
}
});
});
|
import React, { useState, useEffect, useRef } from 'react'
import './index.css'
const BottomMenu = () => {
// Valor da altura da tela em pixels
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
// O valor inicial é de 90% da altura total da tela
const [ y, setY ] = useState(viewHeight * 0.9)
const menu = useRef(null)
// Ao tocar no menu
const handleTouchStart = event => {
setY(event.touches[0].clientY - y)
} // handleTouchStart
// Ao arrastar
const handleTouchMove = event => {
if (
(event.touches[0].clientY - y) < (viewHeight - (viewHeight * 0.1)) &&
(event.touches[0].clientY - y) > (viewHeight - (viewHeight * 0.9))
) {
menu.current.style.top = `${(event.touches[0].clientY - y)}px`
} // if
} // handleTouchMove
// Soltar o toque
const handleTouchEnd = event => {
const change = event.changedTouches[0].clientY - y
if (change > (viewHeight * 0.7)) {
menu.current.style.top = '90%'
setY(viewHeight * 0.9)
} else {
menu.current.style.top = '10%'
setY(viewHeight * 0.1)
} // else
} // handleTouchEnd
return (
<div className="bottom-menu"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
ref={menu}
>
<div className="gesture-button"/>
</div>
) // return
} // BottomMenu
export default BottomMenu
|
import { call, put, takeLatest, all } from 'redux-saga/effects';
import * as types from '../types';
import _api from '../../services/api';
import URLS from '../../services/urls';
import * as onBoardActions from '../actions/onBoardActions';
// Workers
function* onBoardWorker(params) {
try {
const data = yield call(_api, URLS.onBoard, params.payload, 'POST');
if (!data.status) {
throw data;
}
// save auth token to local storage
localStorage.setItem('authToken', data.data.authToken);
yield put(onBoardActions.onBoardSuccess(data));
} catch (e) {
yield put(onBoardActions.onBoardError(e));
}
}
// Watchers
function* onBoardWatcher() {
yield takeLatest(types.ONBOARD_REQUEST, onBoardWorker);
}
export default function* onBoardSaga() {
yield all([onBoardWatcher()]);
}
|
var x = Number(prompt("please enter the number"));
function multiples(x){
if (x % 2 || 0 && x % 5 == 0)
{
return true;
}
else {
return false;
}
}
(x % 2 == 0 || x % 5 == 0)? alert("you win "): alert("your loose!");
console.log(x);
|
import CONSTANTS from '@/utils/interfaces/constants';
const REDUCER_KEY = 'CompetitiveAnxiety';
const API_PATH = 'getTestCompAnxiety';
const API_TYPE = 1;
const GRAPHQL_BACK_TYPE = 1;
export const RESULT_KEY = {
KOG: 'cognitive',
SOM: 'somatic',
SURANCE: 'selfConfidence',
RAW: 'raw'
};
export const GRAPHQL_KEYS = [
RESULT_KEY.KOG,
RESULT_KEY.SOM,
RESULT_KEY.SURANCE,
RESULT_KEY.RAW
]
export const LABELS = {
[RESULT_KEY.KOG]: 'Когнитивная',
[RESULT_KEY.SOM]: 'Соматическая',
[RESULT_KEY.SURANCE]: 'Уверенность в себе'
};
export default CONSTANTS(REDUCER_KEY, API_PATH, API_TYPE, undefined, GRAPHQL_BACK_TYPE, GRAPHQL_KEYS);
|
// Let's venture into JavaScript strings in this exercise.
// Hold onto your hats: we will be using functions with parameters here too.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 1) Create a function "helloWorld"
// 2) Return the string "Hello, world!"
function helloWorld() {
return 'Hello, world!';
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 1) Create a function "helloName" that accepts 1 parameter (arity of 1)
// 2) Use the symbol "name" for the parameter name
// 3) Return the string "Hello, <name>!" where <name> is the value passed to the function
function helloName (name) {
return 'Hello, ' + name + '!'
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Return the length of the string "tarPitAbstract" defined below.
// HINT: use the .length method
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
function abstractLength () {
const tarPitAbstract = 'Complexity is the single major difficulty in the successful development of large-scale software systems. ' +
'Following Brooks we distinguish accidental from essential difficulty, but disagree with his premise that most complexity remaining in contemporary systems is essential. ' +
'We identify common causes of complexity and discuss general approaches which can be taken to eliminate them where they are accidental in nature. ' +
'To make things more concrete we then give an outline for a potential complexity-minimizing approach based on functional programming and Codd’s relational model of data.'
let lengthOfAbstract = tarPitAbstract.length;
return lengthOfAbstract;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Return the string "chorus" in all capital letters.
// HINT: use the .toUpperCase method
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
function makeLoud () {
const chorus = 'Who let the dogs out?'
return chorus.toUpperCase();
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Assume that a string is passed to the parameter "str" in the function below.
// Return the value of "str" in all lower case letters.
// HINT: use the .toLowerCase method
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
function makeQuiet (str) {
return str.toLowerCase();
}
|
import {TimelineSequence} from './functions/TimelineSequence'; // Import the Timeline function
import {Timeline} from './Timeline'; // import Timeline sequence Array
TimelineSequence(Timeline, ['repeat', 3], function(){
console.log('finished');
});
|
const main = () => {
const form = document.getElementById('the-form');
const onSubmit = (e) => {
e.preventDefault();
const fields = Array.from(e.target.elements);
console.log({fields});
const name = fields.find(e => e.name === 'name').value;
const email = fields.find(e => e.name === 'email').value;
console.log({name, email});
fetch(`./api/to_google_doc?name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`)
e.target.reset();
};
form.addEventListener('submit', onSubmit);
}
main()
|
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var board = canvas.getContext('2d');
for(var i=0; i < 1; i++){
var x = Math.random()*window.innerWidth;
var y = Math.random()*window.innerHeight;
board.beginPath();
board.arc(x,y,30,0,Math.PI*2,false);
board.strokeStyle = "#333";
board.stroke();
}
|
var express = require('express');
var app = express.Router();
var { authenticate } = require('./..//middleware/authenticate');
const _ = require('lodash');
app.get('/',(req, res, next)=>{
res.send('Hello World!');
});
module.exports = app;
|
const Koa = require('koa2')
var mysql = require('mysql2/promise')
const app = new Koa()
// данные для подключения к БД
let dbKey = {
host: "127.0.0.1",
user: "root",
password: "root",
database: "mydb"
}
// используем один глобальный роутер
app.use(async (ctx, next) => {
console.log(ctx)
// Предусматриваем четырехуровневый URL
let method
let resource
let alias
let resourceId
let urlArr = await ctx.originalUrl.split('/')
if (urlArr[1]) method = urlArr[1]
if (urlArr[2]) resource = urlArr[2]
if (urlArr[3]) alias = urlArr[3]
if (urlArr[4]) resourceId = urlArr[4]
// переменные для обработки ответа БД
let answer
let gh
let connection
let statusCode
let sqlRq
/*
http://localhost:8080/GET/date/lim=1000/za
Отдает возможность сортировки, возможность порционного получения с оффсетом
http://localhost:8080/GET/resource/alias/resourceID
resource название колонки по которой будем фильтровать
принимает значения title date author
alias порционное получение 'lim=нужное количество строк' 'lim=1000'
или 'lim=5,100' то есть с паятой по сотую
resourceID в порядке возрастани или убывания
по умолчанию в порядке возростания для установки порядка убывания '/za/
*/
if (method == 'GET') {
//так как всего одна таблица пишем сразу единый запрос
sqlRq = 'SELECT * FROM customers'
try {
//если resourceId == 'za' сортируем список в порядке убывания
//в противном случае сортировка по возростанию
if (resourceId == 'za') sort = ' DESC'
else sort = ' ASC'
if (resource == 'title' || resource == 'date' || resource == 'author') {
sqlRq += ' ORDER BY ' + resource + sort
if (alias != undefined) {
alias = alias.split('=')
//если первая часть алиаса = lim а вторая введена
if (alias[0] == 'lim' && alias[1]) {
//для возможности получения строк с alias[1][0] по alias[1][1]
alias[1] = alias[1].split('&')
if (alias[1][1]) {
sqlRq += ` LIMIT ${alias[1][0]} , ${alias[1][1]} `
} else {
sqlRq += ` LIMIT ${alias[1]} `
}
}
}
statusCode = 201
} else
statusCode = 200
console.log(sqlRq)
connection = await mysql.createConnection(dbKey);
[answer, gh] = await connection.execute(sqlRq)
} catch (e) {
statusCode = 404
answer = e
}
ctx.body = {
code: statusCode,
data: answer
}
}
/*
Добавляет записи в БД
http://localhost:8080/POST/resource
все пишется в ресурс
//http://localhost:8080/POST/titleOne&authorOne&descriptionOne&2020&imageOne
согласно запроса INSERT INTO customers (title, author, description, date, image)
*/
else if (method == 'POST') {
try {
if (resource) {
resourceArr = resource.split('&')
console.log(resourceArr)
sqlRq = `INSERT INTO customers (title, author, description, date, image)
VALUES (
'${resourceArr[0]}',
'${resourceArr[1]}',
'${resourceArr[2]}',
'${resourceArr[3]}',
'${resourceArr[4]}')`
console.log(sqlRq)
statusCode = 201
connection = await mysql.createConnection(dbKey);
[answer, gh] = await connection.execute(sqlRq)
console.log(answer)
}
} catch (e) {
statusCode = 404
answer = e
}
ctx.body = {
code: statusCode,
data: answer
}
}
/*
http://localhost:8080/PUT/title/title0/aaa
Изменяет записи по принципу localhost:8080/PUT/имя столбца/старое значение/новое значение
*/
else if (method == 'PUT') {
try {
sqlRq = `UPDATE customers SET ${resource} = '${resourceId}'
WHERE ${resource} = '${alias}';`
console.log(sqlRq)
connection = await mysql.createConnection(dbKey);
//включаем разрешение изменения записей
[answ, gh] = await connection.execute('SET SQL_SAFE_UPDATES=0;');
[answer, gh] = await connection.execute(sqlRq);
//отключаем разрешение изменения записей
[answ, gh] = await connection.execute('SET SQL_SAFE_UPDATES=1;')
statusCode = 201
} catch (e) {
statusCode = 400
answer = e
}
ctx.body = {
code: statusCode,
data: answer
}
}
/**
Удаляет записи по принципу http://localhost:8080/DELETE/имя столбца/значение
*/
else if (method == 'DELETE') {
try {
let sqlRq = `DELETE FROM customers WHERE ${resource} = '${alias}'`
console.log(sqlRq)
connection = await mysql.createConnection(dbKey);
[answer, gh] = await connection.execute(sqlRq);
if (answer.affectedRows > 0) statusCode = 304
else statusCode = 301
console.log(answer, gh)
} catch (e) {
statusCode = 404
answer = e
} ctx.body = {
code: statusCode,
data: answer
}
}
//если ни один из запросов не совпал даем ссылку на доки
else{
ctx.body = {
code:400,
data: 'https://github.com/nick6996war/test'
}
}
})
app.listen(8080)
|
var express = require("express");
var router = express.Router();
const userModel = require("../models/userModel");
router.get("/", function(req, res, next) {
userModel.create(
[
{ name: "test1", age: 8, phone: 18991840822 },
{ name: "test2", age: 18, phone: 18991840823 },
{ name: "test3", age: 28, phone: 18991840824 }
],
function(error, docs) {
if (error) {
res.json({
errorCode: 400,
message: "添加失败"
});
} else {
res.json({
errorCode: 0,
message: "添加成功"
});
}
}
);
});
router.post("/saveUser", function(req, res, next) {
// 创建一个 userModel 模型的实例
let user_instance = new userModel({
name: req.body.name,
age: req.body.age,
email: req.body.email,
phone: req.body.phone
});
// 传递回调以保存这个新建的模型实例
user_instance.save(function(err, docs) {
if (err) {
res.json({
errorCode: 400,
message: "添加失败"
});
} else {
res.json({
errorCode: 0,
message: "添加成功"
});
}
});
});
router.post("/getUser", function(req, res, next) {
userModel.find({ phone: req.body.phone }, function(err, user) {
if (err) {
return handleError(err);
} else {
res.json(user);
}
});
});
router.post("/updateUser", function(req, res, next) {
userModel.update(
{
phone: req.body.phone
},
{
age: req.body.age,
email: req.body.email
},
function(err, docs) {
if (err) {
res.json({
errorCode: 400,
message: "修改失败"
});
} else {
res.json({
errorCode: 0,
message: "修改成功"
});
}
}
);
});
router.post("/delUser", function(req, res, next) {
userModel.remove({ phone: req.body.phone }, function(err, docs) {
if (err) {
res.json({
errorCode: 400,
message: "删除失败"
});
} else {
res.json({
errorCode: 0,
message: "删除成功"
});
}
});
});
module.exports = router;
|
import React, { useRef, useEffect } from "react";
import { searchProducts } from "../actions/productsActions";
import { useDispatch } from "react-redux";
const ProductSearch = () => {
const text = useRef("");
const dispatch = useDispatch();
const searching = (e) => {
if (e !== "") {
dispatch(searchProducts(e.target.value));
}
};
useEffect(() => {
text.current.focus();
}, []);
return (
<div>
<div style={{ textAlign: "center", padding: "10px", marginTop: "15px" }}>
<input
type='search'
placeholder='Search here...'
style={{
fontSize: "14px",
marginBottom: "10px",
borderRadius: "9px",
border: "1px solid #ccc",
padding: "7px",
width: "75%",
}}
ref={text}
onChange={searching}
/>
</div>
</div>
);
};
export default ProductSearch;
|
// 첫번째 파트
// 1. 이벤트 핸들러를 추가한다.
// 2. 입력한 데이터(ex. 자산)를 가져온다.
// 3. 새로운 자산을 우리의 데이터 스트럭쳐에 담는다.
// 4. 담은 데이터를 기반으로 자산을 화면에 더한다.
// 5. 자산을 계산하고 비지니스 로직에 연관된 작업을 한다.
// 6. 계산된 값을 기반으로 화면에 또 담는다.
// 두번째 파트
// 1. 이벤트 핸들러를 추가한다.
// 2. 클릭하면 model에 있는 데이터 스트럭쳐에서 데이터를 지운다.
// 3. 삭제 되면 UI에서도 지운다.
// 4. 새롭게 가계부를 계산한다.
// 5. UI도 새롭게 업데이트 한다.
// 세번째 파트
// 1. 아이템 각각의 퍼센테이지를 계산한다.
// 2. 퍼센테이지의 UI를 업데이트 한다.
// 3. 현재 날짜를 뷰에 그린다.
// 4. 넘버 포멧팅을 한다.
// 5. 인풋 필드의 UX를 향상시킨다.
// 어플리케이션이 커질 수록 모듈화 하는 작업은 중요하다.
// 깨끗하게 분리가 가능하고 잘 조직되어지게 구조를 잡아야한다.
// 데이터를 캡슐화시키고 필요한 것만 노출한다.
// 그러기 위해선 3개의 모듈로 나눈다.
// UI MODULE, DATA MODULE, CONTROLLER MODULE
// DATA(model) 모듈: 3, 5
// UI(view) 모듈: 2, 4, 6
// CONTROLLER(controller) 모듈: 1
// 이렇게 mvc 아키텍쳐를 구현한다.
// es5에서는 java script module 패턴 IIFE를 사용
// es6로 넘어가서는 class를 사용하면 된다.
// BUDGET CONTROLLER(model)
var budgetController = (function () {
// 데이터를 저장하기에는 오브젝트가 좋아서 오브젝트를 생성한다.
// 가계부에 저장할 많은 아이템(오브젝트)를 생성하기 위해서는 어떻게 해야하나? 펑션 컨스트럭터로 생성한다.
var Expense = function (id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
}
Expense.prototype.calcPercentage = function (totalIncome) {
if (totalIncome > 0) {
this.percentage = Math.round((this.value / totalIncome) * 100);
} else {
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function () {
return this.percentage;
};
var Income = function (id, description, value) {
this.id = id;
this.description = description;
this.value = value;
}
var calculateTotal = function (type) {
var sum = 0;
data.allItems[type].forEach(function (cur) {
sum += cur.value;
});
data.totals[type] = sum;
}
// var allExpenses = [];
// var allIncomes = [];
// var totalExpenses = 0;
// 위의 방식 보다 밑에 방식이 훨씬 깔끔하다.
// 만약 10개의 수입이 들어오면 데이터 오브젝트에 저장한다.
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function (type, des, val) {
var newItem, ID;
// [1 2 3 4 5] 다음 아이디는 6
// [1 2 4 6 8] 다음 아이디는 9
// ID = last ID + 1
// 새로운 아이디를 만든다.
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// inc 또는 exp를 기반으로 새로운 아이템을 생성한다.
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function (type, id) {
var ids, index;
// id = 6;
// data.allItems[type][id];
// ids = [1 2 4 6 8];
// index = 3;
ids = data.allItems[type].map(function (current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function () {
// 모든 수입과 지출을 각각 계산한다. 반복하지 않기 위해 프라이빗 함수로 만든다.
calculateTotal('inc');
calculateTotal('exp');
// 가계부를 계산한다. 모든 수입 - 모든 지출.
data.budget = data.totals.inc - data.totals.exp;
// 가계부의 퍼센테이지도 계산한다. 모든 지출 / 모든 수입 * 100에 반올림
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
calculatePercentages: function () {
// 모든 지출 오브젝트 개인적으로 필요 한 것이다. 이것은 메소드가 되어야 한다.
/*
a=20
b=20
c=40
income=100
a=20/100=20%
b=10/100=10%
c=40/100=40%
*/
data.allItems.exp.forEach(function (cur) {
cur.calcPercentage(data.totals.inc);
});
},
getPercentages: function () {
var allPerc = data.allItems.exp.map(function (cur) {
return cur.getPercentage();
});
return allPerc;
},
getBudget: function () {
return {
budget: data.budget,
percentage: data.percentage,
totalInc: data.totals.inc,
totalExp: data.totals.exp
}
},
tesing: function () {
console.log(data);
}
}
})();
// UI CONTROLLER(view)
// view안에서 만든 함수는 다른 view, model에서 사용해야 하므로 프라이빗 함수로 만들면 안됨
var UIController = (function () {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
percentageLabel: '.budget__expenses--percentage',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
container: '.container',
expensesPercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
var formatNumber = function (num, type) {
/*
+ or - 를 숫자 앞에 붙인다.
정확히 소수점 2개를 붙인다.
1000단위로 콤마를 넣는다.
2310.4567 -> + 2,310.46
2000 -> + 2,000.00
*/
var numSplit, int, dec, type;
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
// input 2310, output 2,310
// input 23100, output 23,100
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, int.length);
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
}
var nodeListForEach = function (list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
getInput: function () {
return {
type: document.querySelector(DOMstrings.inputType).value, // type: inc | exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},
addListItem: function (obj, type) {
var html, newHtml, element;
// DOM에 추가할 템플릿을 만든다.
if (type === 'inc') {
element = DOMstrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}
// 템플릿에 실제 데이터를 넣는다.
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value));
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function (selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
clearFields: function () {
var fields, fieldsArr;
fields = document.querySelectorAll(DOMstrings.inputDescription + ',' + DOMstrings.inputValue)
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function (current, index, array) {
current.value = ""
});
fieldsArr[0].focus();
},
displayBudget: function (obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');
if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentageLabel).textContent = '---';
}
},
displayPercentages: function (percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
nodeListForEach(fields, function (current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
}
});
},
displayMonth: function () {
var now, months, month, year;
now = new Date();
// var christmas = new Date(2020, 11, 25);
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = now.getMonth();
year = now.getFullYear();
document.querySelector(DOMstrings.dateLabel).textContent = months[month] + ' ' + year;
},
changedType: function () {
var fields = document.querySelectorAll(
DOMstrings.inputType + ',' +
DOMstrings.inputDescription + ',' +
DOMstrings.inputValue);
nodeListForEach(fields, function(cur) {
cur.classList.toggle('red-focus');
});
document.querySelector(DOMstrings.inputBtn).classList.toggle('red');
},
getDOMstrings: function () {
return DOMstrings;
}
}
})();
// GLOBAL APP CONTROLLER(controller)
// 여기서는 각각 이벤트에서 무슨일이 일어날지를 등록하고 다른 컨트롤러에게 던진다.
var controller = (function (budgetCtrl, UICtrl) {
var setupEventListeners = function () {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function (event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
// 이벤트 위임
// 1. 우리가 관심있는 수 많은 엘리먼트에 이벤트를 하나하나 다는 것이 힘들 때
// 2. 페이지 로드가 되기전에는 돔에 없다가 이벤트에 의해 생긴 엘리먼트에 이벤트가 필요할 경우
// 지금 같은 경우가(2) 돔이 로드 된 이후에 우리가 만든 가계부 자산의 아이템 하나하나에 삭제이벤트를 달기 위해서 컨테이너에 이벤트를 단다.
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
document.querySelector(DOM.inputType).addEventListener('change', UICtrl.changedType);
};
var updateBudget = function () {
// 1. 바뀌어야 하는 가계부 금액 계산을 하고(model)
budgetCtrl.calculateBudget();
// 2. 가계부 금액을 리턴한다.
var budget = budgetCtrl.getBudget();
// 3. 계신된 값을 UI에 그린다.
UICtrl.displayBudget(budget);
};
var updatePercentages = function () {
// 1. 퍼센테이지를 계산한다. (모델)
budgetCtrl.calculatePercentages();
// 2. 모델에서 퍼센테이지를 읽는다.
var percentages = budgetCtrl.getPercentages();
// 3. 새로운 퍼센테이지를 가지고 UI를 업데이트 한다.
UICtrl.displayPercentages(percentages);
};
// keypress, click 이벤트와 같이 여러가지 이벤트에서 같은 작업을 반복하지 않으려고(dry) 만든 변수
var ctrlAddItem = function () {
var input, newItem;
// 1. 필드의 인풋 데이터를 가져온다.
input = UICtrl.getInput();
// 인풋데이터의 유효성 검증을 해준다
if (input.description.trim() !== "" && !isNaN(input.value) && input.value > 0) {
// 2. budget controller(model)에 아이템을 넣는다.
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. UI controller(view)에 아이템을 넣는다.
UICtrl.addListItem(newItem, input.type);
// 4. 필드의 인풋 데이터를 초기화 하고 포커스를 다시 처음으로 준다.
UICtrl.clearFields();
// 밑에 두 부분은 updateBudget이라는 함수를 만든다. 반복하지 않기 위하여
// 5. 바뀌어야 하는 가계부 금액 계산을 하고(model)
// 6. 계산된 값을 UI에 그린다.(view)
updateBudget();
// 7. 각 지출 아이템의 소비 퍼센테이지를 계산한다.
updatePercentages();
}
};
var ctrlDeleteItem = function (event) {
var itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
// inc-1
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// 1. 모델에 있는 데이터 스트럭쳐에서 아이템을 지운다.
budgetCtrl.deleteItem(type, ID);
// 2. 뷰에 있는 아이템을 제거 한다.
UICtrl.deleteListItem(itemID);
// 3. 뷰에 있는 가계부 가격을 업데이트 한다.
updateBudget();
// 4. 각 지출 아이템의 소비 퍼센테이지를 계산한다.
updatePercentages();
}
};
return {
// 처음에 하고 싶은 것을 하는 것인데 실행하기 위해 필요한 최소한의 설정을 한다.
init: function () {
console.log('Application has started.');
UICtrl.displayMonth();
UICtrl.displayBudget({
budget: 0,
percentage: -1,
totalInc: 0,
totalExp: 0
});
setupEventListeners();
}
}
})(budgetController, UIController);
controller.init();
|
const debug = require("debug")("mongo:model-chat");
const mongo = require("mongoose");
module.exports = db => {
let schema = new mongo.Schema({
id: {
type: String,
required: true,
unique: true,
index: true
},
owner: String,
participates: [String],
isActive: Boolean,
messages: [{
text: String,
sender: String,
date: Date,
imgPath: String,
likes: [String],
unlikes: [String],
isImage: Boolean,
contentImgPath: String,
created_at: Date,
updated_at: Date
}],
autoIndex: false
});
// set user not active
schema.methods.setNotActive = function () {
this.isActive = false;
return !this.isActive;
};
// set user active
schema.methods.setActive = function () {
this.isActive = true;
return this.isActive;
};
// on every save, add the date
schema.pre('save', function (next) {
// get the current date
let currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
db.model('Chat', schema);
debug("Chat model created");
}
|
console.log('Script lib3 loaded!');
|
define(['ko', 'underscore', 'TaskBoard', 'KanbanApi'], function (ko, _, TaskBoard, KanbanApi) {
return function (todoArray, inProgressArray, completeArray, onChange) {
this.todoBoard = new TaskBoard('To Do', todoArray);
this.inProgressBoard = new TaskBoard('In Progress', inProgressArray);
this.completeBoard = new TaskBoard('Complete', completeArray);
this.newTaskName = ko.observable('');
this.addNewTask = function () {
var taskName = this.newTaskName();
if (taskName) {
this.todoBoard.addTask({ Description: taskName });
this.newTaskName('');
}
};
this.totalTasks = ko.computed(function () {
return this.todoBoard.numTasks() + this.inProgressBoard.numTasks() + this.completeBoard.numTasks();
}, this);
this.percentComplete = ko.computed(function () {
if (this.totalTasks() === 0) {
return 0;
}
return Math.floor(this.completeBoard.numTasks() / this.totalTasks() * 100);
}, this);
var onChangeEventInitialized = false;
ko.computed(function () {
this.todoBoard.tasks();
this.inProgressBoard.tasks();
this.completeBoard.tasks();
if (onChangeEventInitialized && typeof onChange === 'function') {
onChange();
}
onChangeEventInitialized = true;
}, this).extend({rateLimit: 0});
};
});
|
const getAllData = async url => {
const response = await fetch(url);
const data = await response.json();
return data;
};
const postData = async (url, dataToSend) => {
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: 'POST',
body: JSON.stringify(dataToSend)
});
const data = await response.json();
return data;
};
const updateData = async (url, id, dataToSend) => {
const response = await fetch(`${url}/${id}`, {
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: 'PUT',
body: JSON.stringify(dataToSend)
});
const data = await response.json();
return data;
};
const deleteData = async (url, id) => {
const response = await fetch(`${url}/${id}`, {
method: 'DELETE'
});
const data = await response.json();
return data;
};
const createNewTeamDom = () => {
document.querySelector('.addTeamButton').style.display = 'none';
document.querySelector('.saveTeamButton').style.display = 'block';
document.querySelector('.backChevron').style.display = 'block';
const table = document.querySelector('.myTable');
let tr = `
<tr class='rowToAdd'>
<th scope="row"></th>
<td>
<input required class="form-control form-control-sm" type="text" placeholder="Team's Name">
</td>
<td>
<input required class="form-control form-control-sm" type="text" placeholder="Coach Name">
</td>
<td>
<input required class="form-control form-control-sm" type="text" placeholder="Team Admin">
</td>
<td>
<input required class="form-control form-control-sm" type="number" placeholder="# Of Players">
</td>
<td class="actions">
<div class="editRow">
<i class="fal fa-edit" aria-hidden="true"></i>
</div>
<div class="deleteRow">
<i class="fal fa-trash" aria-hidden="true"></i>
</div>
</td>
</tr>
`;
table.innerHTML = table.innerHTML + tr;
$('.editRow').click(false);
$('.deleteRow').click(false);
};
$(document).ready(() => {
const api = 'https://zhilov93c6.execute-api.us-east-1.amazonaws.com/dev/team';
// populate table
getAllData(api).then(res => {
const table = document.querySelector('.myTable');
const teams = res.data;
teams.forEach(team => {
let tr = `
<tr>
<th scope="row">${team.id}</th>
<td>${team.teamName}</td>
<td>${team.coachName}</td>
<td>${team.teamAdmin}</td>
<td>${team.rosterSize}</td>
<td class="actions">
<div class="editRow">
<i class="fal fa-edit" aria-hidden="true"></i>
</div>
<div class="deleteRow">
<i class="fal fa-trash" aria-hidden="true"></i>
</div>
</td>
</tr>
`;
table.innerHTML = table.innerHTML + tr;
});
});
//Create New Team
$('.addTeamButton').click(() => {
createNewTeamDom();
});
$('.saveTeamButton').click(() => {
const dataNodes = document.querySelectorAll('.rowToAdd td input');
let teamToAddData = {};
dataNodes.forEach((node, i) => {
if (node.value) {
if (i === 0) teamToAddData.teamName = node.value;
if (i === 1) teamToAddData.coachName = node.value;
if (i === 2) teamToAddData.teamAdmin = node.value;
if (i === 3) teamToAddData.rosterSize = node.value;
}
});
if (Object.keys(teamToAddData).length === 4) {
document.querySelector('.snackbarFillInputs').style.display = 'none';
postData(api, teamToAddData).then(res => {
const snackbarSuccess = document.querySelector('.snackbarSuccess');
snackbarSuccess.style.display = 'block';
snackbarSuccess.innerHTML = res.message;
const rowToAdd = document.querySelector('.rowToAdd');
console.log(rowToAdd);
rowToAdd.parentNode.removeChild(rowToAdd);
const team = res.data;
const table = document.querySelector('.myTable');
let tr = `
<tr>
<th scope="row">${team.id}</th>
<td>${team.teamName}</td>
<td>${team.coachName}</td>
<td>${team.teamAdmin}</td>
<td>${team.rosterSize}</td>
<td class="actions">
<div class="editRow">
<i class="fal fa-edit" aria-hidden="true"></i>
</div>
<div class="deleteRow">
<i class="fal fa-trash" aria-hidden="true"></i>
</div>
</td>
</tr>
`;
table.innerHTML = table.innerHTML + tr;
setTimeout(() => {
snackbarSuccess.style.display = 'none';
}, 3000);
document.querySelector('.saveTeamButton').style.display = 'none';
document.querySelector('.addTeamButton').style.display = 'block';
});
} else {
document.querySelector('.snackbarFillInputs').style.display = 'block';
}
});
$('.backChevron').click(() => {
const rowToAdd = document.querySelector('.rowToAdd');
rowToAdd.parentNode.removeChild(rowToAdd);
document.querySelector('.addTeamButton').style.display = 'block';
document.querySelector('.saveTeamButton').style.display = 'none';
document.querySelector('.backChevron').style.display = 'none';
});
// Delete Team
$(document).on('click', '.deleteRow', e => {
const teamRow = e.target.parentNode.parentNode.parentNode;
const teamId = teamRow.children[0].innerHTML;
deleteData(api, teamId).then(res => {
teamRow.parentNode.removeChild(teamRow);
const snackbarSuccess = document.querySelector('.snackbarSuccess');
snackbarSuccess.style.display = 'block';
snackbarSuccess.innerHTML = res.message;
setTimeout(() => {
snackbarSuccess.style.display = 'none';
}, 3000);
});
});
// Update Team
$(document).on('click', '.editRow', e => {
document.querySelector('.addTeamButton').style.display = 'none';
document.querySelector('.saveEditedTeamButton').style.display = 'block';
$('.editRow').click(false);
$('.deleteRow').click(false);
const teamRow = e.target.parentNode.parentNode.parentNode;
teamRow.classList.add('rowToBeEdited');
const tdInput = Array.from(teamRow.children).slice(1, 5);
tdInput.forEach((td, i) => {
if (i === 0)
td.innerHTML = `<input required class="form-control form-control-sm" type="text" placeholder="Team's Name" value="${
td.innerHTML
}"></input>`;
if (i === 1)
td.innerHTML = `<input required class="form-control form-control-sm" type="text" placeholder="Coach Name" value="${
td.innerHTML
}"></input>`;
if (i === 2)
td.innerHTML = `<input required class="form-control form-control-sm" type="text" placeholder="Team Admin" value="${
td.innerHTML
}"></input>`;
if (i === 3)
td.innerHTML = `<input required class="form-control form-control-sm" type="number" placeholder="# of players" value="${
td.innerHTML
}"></input>`;
});
});
$('.saveEditedTeamButton').click(() => {
const rowsToBeEdited = document.querySelectorAll('.rowToBeEdited');
rowsToBeEdited.forEach(row => {
const dataNodes = row.querySelectorAll('td input');
const teamId = row.children[0].innerHTML;
let teamToAddData = {};
dataNodes.forEach((node, i) => {
if (node.value) {
if (i === 0) teamToAddData.teamName = node.value;
if (i === 1) teamToAddData.coachName = node.value;
if (i === 2) teamToAddData.teamAdmin = node.value;
if (i === 3) teamToAddData.rosterSize = node.value;
}
});
if (Object.keys(teamToAddData).length === 4) {
document.querySelector('.snackbarFillInputs').style.display = 'none';
updateData(api, teamId, teamToAddData).then(res => {
const snackbarSuccess = document.querySelector('.snackbarSuccess');
snackbarSuccess.style.display = 'block';
snackbarSuccess.innerHTML = res.message;
const team = res.data;
rowsToBeEdited.forEach((node, i) => {
node.innerHTML = `
<th scope="row">${team.id}</th>
<td>${team.teamName}</td>
<td>${team.coachName}</td>
<td>${team.teamAdmin}</td>
<td>${team.rosterSize}</td>
<td class="actions">
<div class="editRow">
<i class="fal fa-edit" aria-hidden="true"></i>
</div>
<div class="deleteRow">
<i class="fal fa-trash" aria-hidden="true"></i>
</div>
</td>
`;
});
setTimeout(() => {
snackbarSuccess.style.display = 'none';
}, 3000);
document.querySelector('.saveEditedTeamButton').style.display = 'none';
document.querySelector('.addTeamButton').style.display = 'block';
});
} else {
document.querySelector('.snackbarFillInputs').style.display = 'block';
}
});
});
});
|
export const FMS_SAVE_FORM = `athleteTests/FMS_InputForm/FMS_SAVE_FORM`;
export const FMS_SAVE_FORM_ERROR = `athleteTests/FMS_InputForm/FMS_SAVE_FORM_ERROR`;
export const FMS_SAVE_FORM_SUCCESS = `athleteTests/FMS_InputForm/FMS_SAVE_FORM_SUCCESS`;
export const STATUS = {};
|
function NavLinksUtil() {
return (
<ul>
<li><a href='#'>Features</a></li>
<li><a href='#'>Pricing</a></li>
<li><a href='#'>Contact</a></li>
<li><a href='#'>Login</a></li>
</ul>
)
}
export default NavLinksUtil;
|
//ボタンの実装急げよ
function table_change(obj){
var url=[];
var url_split = window.location.href.split("=");
url = url_split[0];
url += "="+obj.value;
window.location.href =url;
}
$(document).on("change","[name=word_first]:checked",function(){
if($(this).val() != "exist"){
$(".word_disabled").hide();
}else{
$(".word_disabled").show();
}
});
//その他ボタン設置
$(document).on("click","#word button",function(){
if(this.value=="add"){
$(this).parent().prev().clone(true).insertBefore($(this).parent());
}else{
if($("#word").find("[value='other']").length<2){
alert("一つだけの要素は削除できません");
}else{
$(this).parent().prev().remove();
}
}
});
$(document).on("change","[name=habitat_first]:checked",function(){
if($(this).val() != "other"){
$(".habitat_disabled").hide();
}else{
$(".habitat_disabled").show();
}
});
$(document).on("click","#habitat button",function(){
if(this.value=="add"){
$(this).parent().prev().clone(true).insertBefore($(this).parent());
}else{
if($("#habitat").find("[value='other']").length<3){
alert("一つだけの要素は削除できません");
}else{
$(this).parent().prev().remove();
}
}
});
$(document).on("change","#move input",function(){
if(this.value=="fly"){
if($(this).prop("checked")){
$(this).next().prop("disabled",true);
$(this).next().next().prop("disabled",false);
}else{
$(this).next().prop("disabled",false);
$(this).next().next().prop("disabled",true);
}
}
if(this.value=="swim"){
if($(this).prop("checked")){
$(this).prev().prop("disabled",true);
$(this).next().prop("disabled",false);
}else{
$(this).prev().prop("disabled",false);
$(this).next().prop("disabled",true);
}
}
});
function region_make(obj){
var val = obj.value;
//追加要件・コア部位、部位、スキル部位(この部分だけ最初1枠)
//hideクラスを持つ者はOnload時に隠す
if(val>1){
$(".hide").show();
}else{
$(".hide").hide();
}
var status=$("#status_0").html();
$("#status_0").parent().html("<div id='status_0'>"+status+"</div>");
var reg_name = $("#region_name").find("p:first-child").html();
$("#region_name").find("p:first-child").parent().html("<p>"+reg_name+"</p>");
for(var i=0; i<val-1; i++){
$("#status_"+i).clone(true).attr("id","status_"+parseInt(i+1)).insertAfter($("#status_"+i));
$("#region_name").find("p:last-child").clone(true).insertAfter($("#region_name").find("p:last-child"));
}
}
function skill_region(obj){
console.log($(obj.closest("tr")).find("p:last").clone(true));
if(obj.value=="add"){
var num = $(obj.closest("tr")).find("p:last").attr("class");
num = parseInt(num)+parseInt(1);
$(obj.closest("tr")).find("p:last").clone(true).attr("class",num).insertAfter($(obj.closest("tr")).find("p:last"));
}else{
if($(obj.closest("tr")).find("input").length<2){
alert("一つだけの要素は削除できません");
}else{
$(obj.closest("tr")).find("p:last-child").remove();
}
}
}
$(document).ready(function(){
$(".hide").hide();
var table = $($("form")[0]).attr("id");
$($("table select:first-child")[0]).val(table);
load_make();
});
$(function(){
$("#skill").on("change",".skill input",function(){
special_make(this);
});
$("#skill").on("click","button",function(){
special_make(this);
});
});
function special_make(obj){
var number = $("#skill_"+obj.className).attr("class");
//obj.classNameは部位のナンバリングです
if(obj.value == "skill_delete"){
var id_num = obj.className+"_"+number;
// 内容が入っていたら警告するように作り直す?できなくはないがめんどくさいぞ
if(number == 0){
alert("項目が一つしかない場合は削除できません");
return;
}
if(!window.confirm("項目を削除しますか?")){
return;
}
$("#first_select_"+id_num).remove();
$("#skill_insert_"+id_num).remove();
// 中身を全部消す
number--;
$("#skill_"+obj.className).attr("class",number);
// クラスデータを書き換える
return;
// 終了
}
if(obj.value == "skill_append"){
number++;
$("#skill_"+obj.className).attr("class",number);
var p = document.createElement("p");
p.id="first_select_"+obj.className+"_"+number;
p.className="skill";
$("#skill_inner_"+obj.className).append(p);
var div = document.createElement("div");
div.id="skill_insert_"+obj.className+"_"+number;
$("#skill_inner_"+obj.className).append(div);
var first_select_array = {
"resistance":"○○無効",
"magic" : "魔法",
"enhancer" : "練技",
"song" : "呪歌",
"commodity" : "汎用",
"other" : "その他"
};
$("#first_select_"+obj.className+"_"+number).empty();
jQuery.each(first_select_array,function(key,val){
var input = document.createElement("input");
if(key == "resistance"){
input.checked="checked";
}
input.type = "radio";
input.name = "first_select_"+number;
input.value = key;
input.className= obj.className;
//jqueryのonイベントで取得してもいい。うまく動かなければそちらで
$("#first_select_"+obj.className+"_"+number).append(input);
$("#first_select_"+obj.className+"_"+number).append(val);
});
var first_select = "resistance";
var id_num = $("#skill_insert_"+obj.className+"_"+number);
}else{
var first_select=obj.value;
id_num = $("#skill_insert_"+obj.className+"_"+number);
}
id_num.empty();
var select_ex="<option></option>";
var p_ex="<p></p>";
var span_ex="<span></span>";
switch(first_select){
/**
* なし、無効/耐性、魔法、戦闘特技、練技、汎用、その他・ラジオ
*/
case "none":
// 何もしない、というかここが呼ばれることはないはずなんだが
case "resistance":
var resistance_list = {
fire_invalid : "炎無効",
ice_invalid : "水・氷無効",
thunder_invalid : "雷無効",
wind_invalid : "風無効",
ground_invalid : "土無効",
pure_invalid : "純エネルギー無効",
impact_invalid : "衝撃・斬撃属性無効",
normal_invalid : "通常武器無効",
disease_invalid : "病気属性無効",
poison_invalid : "毒属性無効",
pow_weak_invalid : "精神効果属性(弱)無効",
pow_invalid : "精神効果属性無効",
curse_invalid : "呪い属性無効",
magic_invalid : "魔法無効",
magic_registance : "魔法耐性",
bones : "骨の身体",
iron : "機械の身体",
machine : "機械の身体",
machine : "機械の身体",
rock : "岩の身体"
};
//メモ:書いてある部分はすべて出力時spanタグでくくる
id_num.append(p_ex);
var i=0,j=0;
var temp=0;
// まずはPで段落生成
jQuery.each(resistance_list,function(key,val){
var input = document.createElement("input");
input.type ="checkbox";
input.name=first_select;
input.value=key;
$(id_num.find("p")[i]).append("<label>");
$(id_num.find("label")[j]).append(input);
$(id_num.find("label")[j]).append(val);
//こんな感じ 修正
temp += parseInt(val.length);
if(temp>20){
id_num.append(p_ex);
temp=0;
i++;
}
j++;
//20オーバーで段落変更
});
break;
case "magic":
var magic_list = {
sorcerer : "真語魔法",
conjurer : "操霊魔法",
priest : "神聖魔法",
magitec : "魔動機術",
fairy : "妖精魔法",
fairy_limit :"妖精魔法限定",
other : "その他",
};
//つまりリミット系は選択式イベントで表示する必要がある(チェックしたら作成するやつ)
// その他は特殊系統なので、選択したら別に表示させる
var i=0;
jQuery.each(magic_list,function(key,val){
id_num.append(p_ex);
var input = document.createElement("input");
input.name=first_select;
input.value=key;
input.className=key+"_"+obj.className;
input.type="checkbox";
$(id_num.find("p")[i]).append("<label>");
$(id_num.find("label")[i]).append(input);
$(id_num.find("label")[i]).append(val);
$(id_num.find("p")[i]).append(span_ex);
if(key=="other"){
var input = document.createElement("input");
input.name=first_select;
input.value=key;
$(id_num.find("span")[i]).append(" 名称");
var input = document.createElement("input");
input.type ="text";
$(id_num.find("span")[i]).append(input); // p内に生成
}
var select = document.createElement("select");
select.className=key+"_"+obj.className;
select.disabled=true;
select.id=key+"_level";
$(id_num.find("span")[i]).append(select);
for(l=1; l<=15; l++){
var option = document.createElement("option");
option.value=l;
option.innerHTML=l;
$(id_num.find("#"+key+"_level")).append(option);
}
$(id_num.find("span")[i]).append("レベル/魔力");
var select = document.createElement("select");
select.className=key+"_"+obj.className;
select.disabled=true;
select.id=key+"_power";
$(id_num.find("span")[i]).append(select);
for(l=1; l<=30; l++){
var option = document.createElement("option");
option.value=l;
option.innerHTML=l;
$(id_num.find("#"+key+"_power")).append(option);
}
if(key=="other"){
var input = document.createElement("input");
input.name=first_select;
input.value=key;
$(id_num.find("span")[i]).append("説明");
var input = document.createElement("input");
input.type ="text";
$(id_num.find("span")[i]).append(input); // p内に生成
}
i++;
});
break;
case "enhancer":
var enhancer = {
// ここはスキル順に
anti_body : "アンチボディ",
owl_vision : "オウルビジョン",
gazzel_hoot : "ガゼルフット",
cats_eye : "キャッツアイ",
scale_leggings : "スケイルレギンス",
strong_blood: "ストロングブラッド",
tick_tick : "チックチック",
dragon_tale : "ドラゴンテイル",
beatle_skin : "ビートルスキン",
muscle_bear : "マッスルベアー",
medi_tation : "メディテーション",
rabbit_ear : "ラビットイヤー",
centaur_leg : "ケンタウロスレッグ",
shape_animal : "シェイプアニマル",
giant_arm : "ジャイアントアーム",
sphinx_knowledge : "スフィンクスノレッジ",
deamon_finger : "デーモンフィンガー",
fire_bress : "ファイアブレス",
ricovery : "リカバリィ",
//回復量?
wide_wing : "ワイドウィング",
chameleon_camouflage : "カメレオンカムフラージュ",
kraken_stability : "クラーケンスタビリティ",
gie_prophecy : "ジィプロフェシー",
strider_walk : "ストライダーウォーク",
spider_web : "スパイダーウェブ",
titan_foot : "タイタンフット",
troll_vital : "トロールバイタル",
balloon_seed_shot : "バルーンシードショット",
fenrir_bite : "フェンリルバイト",
healthy_body : "ヘルシーボディ"
};
id_num.append(p_ex);
var input = document.createElement("input");
input.name=first_select;
input.className="secrets";
input.type="checkbox";
$(id_num.find("p")[0]).append(input);
$(id_num.find("p")[0]).append("練体の極意");
var input = document.createElement("input");
input.type="radio";
input.name=first_select;
input.value="exist";
$(id_num.find("p")[0]).append(input);
$(id_num.find("p")[0]).append("あり");
var input = document.createElement("input");
input.type="radio";
input.name=first_select;
input.value="none";
input.checked="checked";
$(id_num.find("p")[0]).append(input);
$(id_num.find("p")[0]).append("なし");
id_num.append(p_ex);
var j=0,temp=0;
var i=1;
jQuery.each(enhancer,function(key,val){
if(key=="ricovery"){
var input=document.createElement("input");
input.name=first_select;
input.type="checkbox";
input.value=key;
input.className=key+"_"+obj.className;
$(id_num.find("p")[i]).append("<label>");
$(id_num.find("label")[j]).append(input);
$(id_num.find("label")[j]).append(val);
var select = document.createElement("select");
select.className=key+"_"+obj.className;
select.disabled=true;
$(id_num.find("label")[j]).append(select);
for(var k=1; k<=20; k++){
var option = document.createElement("option");
option.value=k;
option.innerHTML=k;
$(id_num.find("select")[0]).append(option);
}
temp += parseInt(val.length)+3;
j++;
return true;
}
var input = document.createElement("input");
input.name=first_select;
input.type="checkbox";
input.value=key;
input.innerHTML=val;
$(id_num.find("p")[i]).append("<label>");
$(id_num.find("label")[j]).append(input);
$(id_num.find("label")[j]).append(val);
temp += parseInt(val.length);
if(temp>21){
temp =0;
id_num.append(p_ex);
i++;
}
j++;
});
break;
case "song":
var song = {
early_bird :"アーリーバード",
summon_small_animl :"サモン・スモールアニマル",
summon_fish :"サモン・フィッシュ",
ambient:"アンビエント",
noise:"ノイズ",
ballade:"バラード",
healing:"ヒーリング",
vivid:"ビビッド",
morals:"モラル",
lullaby:"ララバイ",
requiem :"レクイエム",
resistance:"レジスタンス",
atribute:"アトリビュート",
curiosity:"キュアリオスティ",
charming:"チャーミング",
choke:"チョーク",
noody:"ヌーディ",
nostalgy:"ノスタルジィ",
bitter:"ビター",
love_song:"ラブソング",
amasing:"アメージング",
crap:"クラップ",
chorus:"コーラス",
sonic_voice:"ソニックヴォイス",
dull:"ダル",
dance:"ダンス",
fall:"フォール",
march:"マーチ",
reduction:"リダクション",
lazy:"レイジィ"
};
var j=0,i=0,temp=0;
id_num.append(p_ex);
jQuery.each(song,function(key,val){
var input = document.createElement("input");
input.name=first_select;
input.type="checkbox";
input.value=key;
$(id_num.find("p")[i]).append("<label>");
$(id_num.find("label")[j]).append(input);
$(id_num.find("label")[j]).append(val);
temp += parseInt(val.length);
if(temp>20){
temp =0;
id_num.append(p_ex);
i++;
}
j++;
});
id_num.append(p_ex);
var select=document.createElement("select");
select.name=first_select;
id_num.find("p:last").append("範囲:");
id_num.find("p:last").append(select);
for(var i=10; i<50; i+=10){
var option=document.createElement("option");
option.value=i;
option.innerHTML=i;
id_num.find("select").append(option);
}
id_num.find("p:last").append("m");
break;
case "commodity":
// 別に戦闘特技じゃなくていいね。汎用特技に入れてしまおう
var commodity = {
// ここはスキル順に
full_power : "☑全力攻撃",
full_power2 : "☑全力攻撃Ⅱ",
provocation : "☑挑発攻撃",
tail_sweep : "☑テイルスイープ",
cleave :"〆薙ぎ払い",
magic_hit : "☑魔力撃",
advanced_magic_hit : "☑強化魔力撃",
shot : "〆銃撃",
bow : "〆弓",
pinpoint_shot : "○精密射撃",
pinpoint_eagle : "○精密射撃&鷹の目",
rush : "▽連続攻撃",
rush2 : "▽連続攻撃Ⅱ",
double_atack_twin : "〆2回攻撃&双撃",
double_action: "○2回行動",
triple_action: "○3回行動",
double_declaration: "○複数宣言 = 2回",
triple_declaration: "○複数宣言 = 3回",
counter : "▼カウンター",
fly : "○飛行",
warter_aptitude : "○水中適正",
warter_specialize : "○水中特化",
warter_only : "○水中専用",
fly_region : "○飛翔", // 部位もちの場合のみ
fly_region2 : "○飛翔Ⅱ",
obstruction : "○攻撃障害",
stand : "▽棒立ち",
magic_aptitude : "魔法適正",
// 魔法適正の取得時、それぞれ1ずつ足して頭につける記号を選ぶ
//魔法適正時はonchange
magic_incarnation : "魔法の化身"
// これは全部乗せ
};
id_num.append(p_ex);
var select = document.createElement("select");
select.name=first_select;
select.className="skill_insert_"+obj.className+"_"+number;
$(id_num.find("p")[0]).append(select); // p内に生成
jQuery.each(commodity,function(key,val){
var option = document.createElement("option");
option.value=key;
option.innerHTML=val;
$(id_num.find("select")[0]).append(option);
});
break;
case "other":
//抵抗がある?ない?
var other={
resist_able:"抵抗可能",
resist_unable:"抵抗不可能"
}
id_num.append(p_ex);
var i=0;
jQuery.each(other,function(key,val){
var input = document.createElement("input");
input.name=first_select;
input.type="radio";
input.value=key;
input.className="skill_insert_"+obj.className+"_"+number;
if(key=="resist_unable"){
input.checked="checked";
}
$(id_num.find("p")[0]).append("<label>");
$(id_num.find("label")[i]).append(input);
$(id_num.find("label")[i++]).append(val);
});
id_num.append(p_ex);
var select=document.createElement("select");
select.name="resist_unable";
$(id_num.find("p")[1]).append(select);
$(id_num.find("select")[0]).append("<option>〆</option>");
$(id_num.find("select")[0]).append("<option>○</option>");
$(id_num.find("select")[0]).append("<option>☑</option>");
$(id_num.find("select")[0]).append("<option>▽</option>");
$(id_num.find("select")[0]).append("<option>▼</option>");
var input = document.createElement("input");
input.name="resist_unable";
input.type="text";
$(id_num.find("p")[1]).append("能力名:");
$(id_num.find("p")[1]).append(input);
id_num.append("<p>説明</p>");
id_num.append(p_ex);
var textarea = document.createElement("textarea");
textarea.name="resist_unable";
$(id_num.find("p")[3]).append(textarea);
break;
}
}
function load_make(){
var p_ex="<p></p>";
var len=$("#region").find("select")[0].value;
for (var i=0; i<len; i++){
//iは部位ナンバー
//0がコア、1が上半身・・・みたいな
$("#skill td:nth-child(2)").empty();
var div = document.createElement("div");
div.id="skill_"+i;
div.className=-1;
$("#skill td:nth-child(2)").append(div);
// 部位ごとにidをわけてdivを作成
$("#skill_"+i).append(p_ex);
var input = document.createElement("input");
input.type="checkbox";
input.className=i;
input.name="no_skill";
input.value="none";
$("#skill_"+i).find("p").append(input);
$("#skill_"+i).find("p").append("なし");
var div = document.createElement("div");
div.id="skill_inner_"+i;
$("#skill_"+i).find("p").append(div);
// pタグの中にinputを作成(なし用)
var button = document.createElement("button");
button.type="button";
button.className=i;
button.value="skill_append";
button.innerHTML="追加";
$("#skill_"+i).append(button);
var button = document.createElement("button");
button.type="button";
button.className=i;
button.value="skill_delete";
button.innerHTML="削除";
$("#skill_"+i).append(button);
special_make($("#skill_"+i).find("button")[0]);
// 中身の作成
}
}
function booty_make(obj){
//製作に変更
if(obj.value=="booty_append"){
var number = $("#booty").attr("class");
// クローニング
var clone = $("#booty_"+number).clone(true).attr("id","booty_"+(parseInt(number)+1)).attr("class","booty");
$("#booty_"+number).after(clone);
$("#booty").attr("class",(parseInt(number)+parseInt(1)));
}else if(obj.value=="booty_edit"){
var number = $("#booty").attr("class");
if(number == 0){
return;
// 一つ目は削除できない
}
// ここで値が入っている場合アラートを表示?
if(!window.confirm("項目を削除しますか?")){
return;
}
$("#booty"+number).remove();
number--;
$("#booty").attr("class",number);
}
}
|
export const movieList = {
Search: [
{
Title: "Jurassic Park",
Year: "1993",
imdbID: "tt0107290",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BMjM2MDgxMDg0Nl5BMl5BanBnXkFtZTgwNTM2OTM5NDE@._V1_SX300.jpg",
},
{
Title: "Jurassic World",
Year: "2015",
imdbID: "tt0369610",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BNzQ3OTY4NjAtNzM5OS00N2ZhLWJlOWUtYzYwZjNmOWRiMzcyXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg",
},
{
Title: "The Lost World: Jurassic Park",
Year: "1997",
imdbID: "tt0119567",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BMDFlMmM4Y2QtNDg1ZS00MWVlLTlmODgtZDdhYjY5YjdhN2M0XkEyXkFqcGdeQXVyNTI4MjkwNjA@._V1_SX300.jpg",
},
{
Title: "Jurassic Park III",
Year: "2001",
imdbID: "tt0163025",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BZDMyZGJjOGItYjJkZC00MDVlLWE0Y2YtZGIwMDExYWE3MGQ3XkEyXkFqcGdeQXVyNDYyMDk5MTU@._V1_SX300.jpg",
},
{
Title: "Jurassic World: Fallen Kingdom",
Year: "2018",
imdbID: "tt4881806",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BNzIxMjYwNDEwN15BMl5BanBnXkFtZTgwMzk5MDI3NTM@._V1_SX300.jpg",
},
{
Title: "Jurassic Shark",
Year: "2012",
imdbID: "tt2071491",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BODI1ODAyODgtZDYzZS00ZTM2LTg5MzMtZjNjMDFjMzlkZGQ2XkEyXkFqcGdeQXVyMTg0MTI3Mg@@._V1_SX300.jpg",
},
{
Title: "Jurassic World: Camp Cretaceous",
Year: "2020–",
imdbID: "tt10436228",
Type: "series",
Poster:
"https://m.media-amazon.com/images/M/MV5BYTlmOWM4YzUtNDE5Yy00ZmI3LTkzOTQtMGNlMjNkMDM5MDk3XkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
},
{
Title: "The Jurassic Games",
Year: "2018",
imdbID: "tt6710826",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BZWJkMzE4ZTAtOTY1ZS00YmZjLWI2MzQtZTg4MzdiN2U4NmUyXkEyXkFqcGdeQXVyMTUwMzY1MDM@._V1_SX300.jpg",
},
{
Title: "Jurassic City",
Year: "2015",
imdbID: "tt2905674",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BMjM1MzUyMTk5MV5BMl5BanBnXkFtZTgwOTc2NzA0NDE@._V1_SX300.jpg",
},
{
Title: "Jurassic Island",
Year: "2014",
imdbID: "tt3033080",
Type: "movie",
Poster:
"https://m.media-amazon.com/images/M/MV5BMzAzOTA3NDUxNl5BMl5BanBnXkFtZTgwMTA2NjM4MzE@._V1_SX300.jpg",
},
],
totalResults: "153",
Response: "True",
};
|
var confige = require("confige");
var gameData = require("gameData");
cc.Class({
extends: cc.Component,
properties: {
// foo: {
// default: null, // The default value will be used only when the component attaching
// to a node for the first time
// url: cc.Texture2D, // optional, default is typeof default
// serializable: true, // optional, default is true
// visible: true, // optional, default is true
// displayName: 'Foo', // optional
// readonly: false, // optional, default is false
// },
// ...
overData_perfab:{
default:null,
type:cc.Prefab
},
isInit:false,
shareTitle:"",
shareDes:"",
},
// use this for initialization
onLoad: function () {
},
onInit:function(){
this.oriPosx = -525;
this.oriPosy = 190;
this.posxOffset = 210;
this.overDataCount = 0;
this.shareBtn = this.node.getChildByName("btn_other").getComponent("cc.Button");
confige.curOverLayer = this;
if(cc.sys.platform == cc.sys.MOBILE_BROWSER)
{
this.node.height = 790;
this.bgNode = this.node.getChildByName("gameOverBg");
this.bgNode.height = 790;
this.h5ShareNode = this.node.getChildByName("h5Share");
this.h5ShareNode.opacity = 0;
this.h5ShareNode.active = false;
// this.shareBtnNode = this.node.getChildByName("btn_other");
// this.shareBtnNode.active = false;
}
this.isInit = true;
this.itemNode = this.node.getChildByName("itemNode");
},
addOneOverData:function(playerData,master,cardHistory){
//console.log(playerData);
var newOverData = cc.instantiate(this.overData_perfab);
this.itemNode.addChild(newOverData);
var newOverDataS = newOverData.getComponent("overDataOnce");
newOverDataS.onInit();
var newName = "nick";
var niuTypeCount1=0,niuTypeCount2=0,niuTypeCount3=0,niuTypeCount4=0,niuTypeCount5=0,niuTypeCount6=0;
if(gameData.gameMainScene.isSanKung){
for(var i in cardHistory)
{
var newType = cardHistory[i].type;
if(newType == 9)
niuTypeCount1 = niuTypeCount1 + 1;
else if(newType == 10)
niuTypeCount2 = niuTypeCount2 + 1;
else if(newType == 11)
niuTypeCount3 = niuTypeCount3 + 1;
else if(newType == 12)
niuTypeCount4 = niuTypeCount4 + 1;
}
newOverDataS.node.getChildByName("sanKungNode").getChildByName("num0").getComponent("cc.Label").string = playerData.bankerCount;
newOverDataS.node.getChildByName("sanKungNode").getChildByName("num1").getComponent("cc.Label").string = niuTypeCount1;
newOverDataS.node.getChildByName("sanKungNode").getChildByName("num2").getComponent("cc.Label").string = niuTypeCount2;
newOverDataS.node.getChildByName("sanKungNode").getChildByName("num3").getComponent("cc.Label").string = niuTypeCount3;
newOverDataS.node.getChildByName("sanKungNode").getChildByName("num4").getComponent("cc.Label").string = niuTypeCount4;
newOverDataS.node.getChildByName("sanKungNode").active = true;
}
else if(gameData.gameMainScene.isJinHua){
for(var i in cardHistory)
{
var newType = cardHistory[i].type;
if(newType == 0)
niuTypeCount1 = niuTypeCount1 + 1;
else if(newType == 1)
niuTypeCount2 = niuTypeCount2 + 1;
else if(newType == 2)
niuTypeCount3 = niuTypeCount3 + 1;
else if(newType == 3)
niuTypeCount4 = niuTypeCount4 + 1;
else if(newType == 4)
niuTypeCount5 = niuTypeCount5 + 1;
else if(newType == 5)
niuTypeCount6 = niuTypeCount6 + 1;
}
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num1").getComponent("cc.Label").string = niuTypeCount1;
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num2").getComponent("cc.Label").string = niuTypeCount2;
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num3").getComponent("cc.Label").string = niuTypeCount3;
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num4").getComponent("cc.Label").string = niuTypeCount4;
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num5").getComponent("cc.Label").string = niuTypeCount5;
newOverDataS.node.getChildByName("jinHuaNode").getChildByName("num6").getComponent("cc.Label").string = niuTypeCount6;
newOverDataS.node.getChildByName("jinHuaNode").active = true;
}
else{
for(var i in cardHistory)
{
var newType = cardHistory[i].type;
if(newType === 0)//无牛
{
niuTypeCount6 = niuTypeCount6 + 1;
}else{//有牛
niuTypeCount5 = niuTypeCount5 + 1;
if(newType == 14)//小
niuTypeCount1 = niuTypeCount1 + 1;
else if(newType == 11 || newType == 12)//花
niuTypeCount2 = niuTypeCount2 + 1;
else if(newType == 13)//炸弹
niuTypeCount3 = niuTypeCount3 + 1;
else if(newType == 10)//牛牛
niuTypeCount4 = niuTypeCount4 + 1;
}
}
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num0").getComponent("cc.Label").string = playerData.bankerCount;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num1").getComponent("cc.Label").string = niuTypeCount1;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num2").getComponent("cc.Label").string = niuTypeCount2;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num3").getComponent("cc.Label").string = niuTypeCount3;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num4").getComponent("cc.Label").string = niuTypeCount4;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num5").getComponent("cc.Label").string = niuTypeCount5;
newOverDataS.node.getChildByName("niuTypeNode").getChildByName("num6").getComponent("cc.Label").string = niuTypeCount6;
newOverDataS.node.getChildByName("niuTypeNode").active = true;
}
var oriChair = confige.getCurChair(playerData.chair);
if(confige.WXHeadFrameList[oriChair+1])
newOverDataS.head.spriteFrame = confige.WXHeadFrameList[oriChair+1];
newOverDataS.nameL.string = playerData.playerInfo.nickname;
newOverDataS.IDL.string = playerData.uid;
newOverDataS.setScore(playerData.score);
if(master == true)
newOverDataS.showMaster();
this.newOverDataList[playerData.chair] = newOverDataS;
// if(playerData.score < 0)
// newOverDataS.loseIco.active = true;
// else
// newOverDataS.winIco.active = true;
newOverData.setPosition(this.oriPosx + this.posxOffset*this.overDataCount,this.oriPosy);
this.overDataCount = this.overDataCount + 1;
},
showOverWithData:function(overData){
console.log("overData@@@@@====");
console.log(overData);
this.newOverDataList = {};
this.maxScore = 0;
this.maxChair = -1;
for(var i in overData.player)
{
this.newOverDataList[i] = {};
var newPlayerData = overData.player[i];
var newCardHistory = overData.cardHistory[i];
if(newPlayerData.isActive == true)
{
var master = false;
if(i === 0)
master = true;
this.addOneOverData(newPlayerData,master,newCardHistory);
if(newPlayerData.score > this.maxScore)
{
this.maxScore = newPlayerData.score;
this.maxChair = newPlayerData.chair;
}
}
}
for(var i in overData.player)
{
var newPlayerData = overData.player[i];
if(newPlayerData.isActive == true && newPlayerData.chair != this.maxChair)
{
this.shareDes += "【"+newPlayerData.playerInfo.nickname+"】:"+newPlayerData.score+";";
}
}
if(this.maxChair != -1)
{
this.newOverDataList[this.maxChair].winIco.active = true;
this.shareTitle = "★大赢家【"+overData.player[this.maxChair].playerInfo.nickname+"】 : "+overData.player[this.maxChair].score;
}
if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
var self = this;
console.log("H5分享给好友");
var curShareURL = confige.h5ShareUrlNew.replace('ROOMNUM', '0');
if(confige.h5InviteCode != "0")
{
curShareURL += "&invite_code=" + confige.h5InviteCode;
}
wx.onMenuShareAppMessage({
title: self.shareTitle,
desc: self.shareDes,
link: curShareURL,
imgUrl: confige.h5ShareIco,
trigger: function(res) {},
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
console.log("H5分享到朋友圈2222222");
wx.onMenuShareTimeline({
title: self.shareTitle,
desc: self.shareDes,
link: curShareURL,
imgUrl: confige.h5ShareIco,
trigger: function(res) {},
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
}
},
onBtnStartGameClick:function(){
confige.curOverLayer = -1;
cc.loader.onProgress = function(completedCount, totalCount, item) {
// cc.log('step 1----------');
var progress = (completedCount / totalCount).toFixed(2);
// cc.log(progress + '%' + completedCount + "///" + totalCount);
var numString = "" + completedCount + "/" + totalCount;
if(totalCount > 10){
confige.loadNode.showNode();
confige.loadNode.setProgress(progress,numString);
}
};
cc.director.loadScene('NewHallScene');
if(confige.curGameScene.yuyinTimeOut != -1)
clearTimeout(confige.curGameScene.yuyinTimeOut);
confige.curGameScene.destroy();
confige.resetGameData();
if(confige.curUsePlatform == 1)
{
confige.GVoiceCall.quitRoom(confige.GVoiceRoomID);
confige.GVoiceCall.closeListen();
}
},
onBtnOtherClick:function(){
if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
var self = this;
console.log("H5分享给好友");
var curShareURL = confige.h5ShareUrlNew.replace('ROOMNUM', '0');
if(confige.h5InviteCode != "0")
{
curShareURL += "&invite_code=" + confige.h5InviteCode;
}
wx.onMenuShareAppMessage({
title: self.shareTitle,
desc: self.shareDes,
link: curShareURL,
imgUrl: confige.h5ShareIco,
trigger: function(res) {},
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
console.log("H5分享到朋友圈2222222");
wx.onMenuShareTimeline({
title: self.shareTitle,
desc: self.shareDes,
link: curShareURL,
imgUrl: confige.h5ShareIco,
trigger: function(res) {},
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
this.h5ShareNode.active = true;
this.h5ShareNode.stopAllActions();
this.h5ShareNode.opacity = 255;
var deactiveCall = cc.callFunc(function () {
this.h5ShareNode.active = false;
},this);
this.h5ShareNode.runAction(cc.sequence(cc.delayTime(2),cc.fadeOut(1),deactiveCall));
}
if (!cc.sys.isNative) return;
let dirpath = jsb.fileUtils.getWritablePath() + 'ScreenShoot/';
if (!jsb.fileUtils.isDirectoryExist(dirpath)) {
jsb.fileUtils.createDirectory(dirpath);
}
let name = 'ScreenShoot-' + (new Date()).valueOf() + '.png';
let filepath = dirpath + name;
let size = cc.winSize;
let rt = cc.RenderTexture.create(size.width, size.height);
cc.director.getScene()._sgNode.addChild(rt);
rt.setVisible(false);
rt.begin();
cc.director.getScene()._sgNode.visit();
rt.end();
rt.saveToFile('ScreenShoot/' + name, cc.ImageFormat.PNG, true, function() {
cc.log('save succ');
rt.removeFromParent();
if(confige.curUsePlatform == 1)
{
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "filepath222==="+filepath);
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "WXShareScreenPath", "(Ljava/lang/String;)V", filepath);
}else if(confige.curUsePlatform == 2){
jsb.reflection.callStaticMethod("JSCallOC","WXShareScreenWithPath:",filepath);
}
});
this.shareBtn.interactable = false;
},
openShare:function(){
this.shareBtn.interactable = true;
},
showLayer:function(){
if(this.isInit == false)
this.onInit();
this.node.active = true;
},
hideLayer:function(){
this.node.active = false;
this.selectHead = -1;
},
hideH5ShareNode:function(){
this.h5ShareNode.stopAllActions();
this.h5ShareNode.opacity = 0;
this.h5ShareNode.active = false;
},
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
});
|
//@ts-check
'use strict'
exports.missingParans = (res) => {
return res.status(200).json({ success: false, message: 'Missing params'})
}
exports.resourceAlreadyExists = (res, message) => {
return res.status(400).json({ success: false, message })
}
exports.handleResponse = (res, statusCode, message, data=null) => {
console.log(statusCode)
switch(statusCode) {
case 200:
return res.status(statusCode).json({ success: true, message, data })
break
case 201:
return res.status(statusCode).json({ success: true, message, data })
break
case 400:
return res.status(statusCode).json({ success: false, message, data })
case 404:
return res.status(statusCode).json({ success: false, message, data })
break
case 401:
return res.status(statusCode).json({ success: false, message, data })
break
default:
return res.status(404).json({ success: false, message: 'No response found'})
}
}
|
const mongoose = require("mongoose");
const { Schema } = mongoose;
const package = new Schema(
{
sender: {
type: Schema.Types.ObjectId,
ref: "senders",
},
packageName: {
type: String,
required: true,
},
destination: {
country: {
type: String,
required: true,
},
state: {
type: String,
required: true,
},
city: {
type: String,
required: true,
},
receiverName: {
type: String,
required: true,
},
receiverAddress: {
type: String,
required: true,
},
},
receiverContact: {
phone: String,
email: String
},
size: String,
agent: {
type: Schema.Types.ObjectId,
ref: "agents",
},
description: String,
},
{
timestamps: true,
}
);
module.exports = mongoose.model("packages", package);
|
var markers ;
$( document ).ready( function()
{
markers = new Markers() ;
} ) ;
function Markers()
{
this.all = new Array() ;
}
Markers.prototype.add = function ( index , map , title , latitude , longitude , info , callback )
{
var pos = { lat:Number( latitude ) , lng:Number( longitude ) } ;
var marker = new google.maps.Marker(
{
position:pos ,
map: map,
title: title,
label:
{
text: ( 1 + index ).toString() ,
color: 'white',
fontSize: '16px',
fontWeight: 'bold'
}
} ) ;
marker.info = info ;
marker.addListener( 'click' , function()
{
if( callback )
{
callback( index ) ;
}
markers.center( map , marker ) ;
} ) ;
this.all.push( marker ) ;
return pos ;
}
Markers.prototype.clear = function ()
{
var i ;
for( i = 0 ; i < this.all.length ; i++ )
{
this.all[i].setMap( null ) ;
}
this.all = new Array() ;
}
Markers.prototype.centerByIndex = function ( map , index )
{
this.center( map , this.all[ index ] ) ;
}
Markers.prototype.center = function ( map , marker )
{
if( this.infoWindow )
{
this.infoWindow.close() ;
}
this.infoWindow = new google.maps.InfoWindow(
{
content: marker.info
} ) ;
this.infoWindow.open( map , marker ) ;
}
|
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin'); //installed via npm
let pathsToClean = [
'build-firefox'
]
module.exports = {
entry: {
'bundle.js': [
path.resolve(__dirname, 'firefox/index.js')
]
},
output: {
filename: 'background.js',
path: path.resolve(__dirname,'build-firefox'),
},
plugins: [
new CleanWebpackPlugin(pathsToClean),
new CopyWebpackPlugin([
{from: path.resolve(__dirname, 'firefox/manifest.json'), to: path.resolve(__dirname, 'build-firefox')},
{from: path.resolve(__dirname, 'firefox/content-script.js'), to: path.resolve(__dirname, 'build-firefox')},
{from: path.resolve(__dirname, 'images/'), to: path.resolve(__dirname, 'build-firefox/images')}
])
],
//devtool: 'source-map'
};
|
import React from 'react';
import User from '../User';
import AlarmsService from '../common/AlarmsService';
export default class Options extends React.Component {
constructor(props) {
super(props);
this._handleUsernameChange = this._handleUsernameChange.bind(this);
this._handleTokenChange = this._handleTokenChange.bind(this);
this._handleIntervalChange = this._handleIntervalChange.bind(this);
this._handleSave = this._handleSave.bind(this);
this.user = new User();
this.state = Object.assign({}, this.user.getLoginInfo(), {
interval: AlarmsService.getInterval(),
});
}
_handleUsernameChange(event) {
this.setState({
username: event.target.value,
});
}
_handleTokenChange(event) {
this.setState({
token: event.target.value,
});
}
_handleIntervalChange(event) {
this.setState({
interval: parseInt(event.target.value, 10),
});
}
_handleSave(event) {
this.user.login({
username: this.state.username,
token: this.state.token,
});
AlarmsService.setInterval(this.state.interval);
this.props.onSave();
}
render() {
const { username, token, interval } = this.state;
return (
<div>
<label labelFor="username">Username:</label>
<input
id="username"
type="text"
value={username}
onChange={this._handleUsernameChange}
/>
<label labelFor="token"> token:</label>
<input
id="token"
type="text"
value={token}
onChange={this._handleTokenChange}
/>
<label labelFor="interval"> interval:</label>
<input
id="interval"
type="number"
value={interval}
onChange={this._handleIntervalChange}
/>
<button onClick={this._handleSave}>Save</button>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.