text stringlengths 7 3.69M |
|---|
import React, { Component } from 'react'
import Moment from 'react-moment'
class Card extends Component {
render() {
return (
<div className="card mb-3 mt-3" onClick={this.props.delete}>
<div className="card-header d-flex justify-content-between">
<h5>{this.props.title}</h5>
<Moment date={this.props.date} fromNow></Moment>
</div>
<div className="card-body">
<div className="card-text d-block ">{this.props.description}</div>
<div className="d-flex justify-content-between">
<footer className="blockquote-footer">{this.props.author}</footer>
<a href='https://google.com' className="btn btn-primary">Read More</a>
</div>
</div>
</div>
);
}
}
export default Card; |
import React from 'react';
import './GifTile.scss'
import {getUrlByEndpoint} from '../ApiHelper';
import { connect } from "react-redux";
import {UPDATE_TILE, TOGGLE_LOCK_TILE} from './../store/constants/action-types';
function GifTile(props) {
React.useEffect(() => {
setNewGif();
}, [props.refreshTiles])
function setNewGif() {
if (props.gifElementModel.isLocked) {
return;
}
const url = getUrlByEndpoint('random');
fetch(url)
.then(res => res.json())
.then(result => {
const gifUrl = result.data.images.downsized_medium.url
const newCurrentTile = {...props.gifElementModel, url: gifUrl}
props.dispatch({type: UPDATE_TILE, payload: newCurrentTile});
})
}
function toggleLockGif() {
props.dispatch({
type: TOGGLE_LOCK_TILE,
payload: props.gifElementModel
})
}
return (
<div className="gif-tile" onClick={toggleLockGif}>
{props.gifElementModel &&
<img src={props.gifElementModel.url}
alt="Gif image"
className={"gif-image " + (props.gifElementModel.isLocked && 'locked')} />
}
</div>
);
}
const mapDispatchToProps = dispatch => {
return {
dispatch
}
}
const mapStateToProps = state => {
return {gridElements: state.gifTiles,
refreshTiles: state.refreshTiles}
}
export default connect(mapStateToProps, mapDispatchToProps)(GifTile);
|
var Max7219 = require('node-max7219');
var moment = require("moment");
var options = {
device: 'matrix',
cascaded: 8,
vertical: true,
brightness: 4
};
var max7219 = Max7219(options);
/**
* fast teset
*/
// max7219.drawText('The repl module exports the repl.REPLServer class. While running, instances of repl.REPLServer');
// max7219.drawText('The');
process.on('exit', function(){
child_process.kill();
});
loop = function(time, callback){
var handler = function(){
callback(function(){
clearInterval(interval);
});
};
var interval = setInterval(handler, time);
};
setInterval(function(){
var time = moment().format("hh.mm.ss");
max7219.drawText(time);
}, 1000);
|
/**
* Abstract representation of navs components.
* @abstract
* @name Navs
* @class Navs
* @standalone
* @augments ch.Uiobject
* @memberOf ch
* @param {object} conf Object with configuration properties
* @returns itself
* @see ch.Dropdown
* @see ch.Expando
*/
ch.navs = function () {
/**
* Reference to a internal component instance, saves all the information and configuration properties.
* @private
* @name ch.Navs#that
* @type object
*/
var that = this,
conf = that.conf;
conf.icon = ch.utils.hasOwn(conf, "icon") ? conf.icon : true;
conf.open = conf.open || false;
conf.fx = conf.fx || false;
/**
* Inheritance
*/
that = ch.uiobject.call(that);
that.parent = ch.clon(that);
/**
* Protected Members
*/
/**
* Status of component
* @protected
* @name ch.Navs#active
* @returns boolean
*/
that.active = false;
/**
* Shows component's content.
* @protected
* @name ch.Navs#show
* @returns itself
*/
that.show = function (event) {
that.prevent(event);
if (that.active) {
return that.hide(event);
}
that.active = true;
that.$trigger.addClass("ch-" + that.type + "-trigger-on");
/**
* onShow callback function
* @name ch.Navs#onShow
* @event
*/
// Animation
if (conf.fx) {
that.$content.slideDown("fast", function () {
//that.$content.removeClass("ch-hide");
// new callbacks
that.trigger("show");
// old callback system
that.callbacks("onShow");
});
} else {
that.$content.removeClass("ch-hide");
// new callbacks
that.trigger("show");
// old callback system
that.callbacks("onShow");
}
return that;
};
/**
* Hides component's content.
* @protected
* @name ch.Navs#hide
* @returns itself
*/
that.hide = function (event) {
that.prevent(event);
if (!that.active) { return; }
that.active = false;
that.$trigger.removeClass("ch-" + that.type + "-trigger-on");
/**
* onHide callback function
* @name ch.Navs#onHide
* @event
*/
// Animation
if (conf.fx) {
that.$content.slideUp("fast", function () {
//that.$content.addClass("ch-hide");
that.callbacks("onHide");
});
} else {
that.$content.addClass("ch-hide");
// new callbacks
that.trigger("hide");
// old callback system
that.callbacks("onHide");
}
return that;
};
/**
* Create component's layout
* @protected
* @name ch.Navs#createLayout
*/
that.configBehavior = function () {
that.$trigger
.addClass("ch-" + that.type + "-trigger")
.bind("click", function (event) { that.show(event); });
that.$content.addClass("ch-" + that.type + "-content ch-hide");
// Visual configuration
if (conf.icon) { $("<span class=\"ch-" + that.type + "-ico\">Drop</span>").appendTo(that.$trigger); }
if (conf.open) { that.show(); }
};
/**
* Default event delegation
*/
that.$element.addClass("ch-" + that.type);
/**
* Triggers when component is visible.
* @name ch.Navs#show
* @event
* @public
* @example
* me.on("show",function () {
* this.content("Some new content");
* });
* @see ch.Floats#event:show
*/
/**
* Triggers when component is not longer visible.
* @name ch.Navs#hide
* @event
* @public
* @example
* me.on("hide",function () {
* otherComponent.show();
* });
* @see ch.Floats#event:hide
*/
return that;
}
|
import { takeLatest, call, put, all } from 'redux-saga/effects';
import {clearCart} from './cart.actions';
import * as UserActionTypes from '../user/user.type';
export function* clearCartOnSignOut() {
yield put(clearCart());
}
export function* onSignOutSuccess() {
yield takeLatest(UserActionTypes.SIGN_OUT_SUCCESS, clearCartOnSignOut)
}
export function* cartSagas() {
yield(all([call(onSignOutSuccess)]))
} |
import React from "react";
import { TouchableOpacity, Image, StyleSheet } from "react-native";
function Profile(props) {
return (
<TouchableOpacity>
<Image source={require("../assets/profile.jpeg")} style={styles.image} />
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
image: {
width: 50,
height: 50,
borderRadius: 100,
alignSelf: "center",
margin: 10,
},
});
export default Profile;
|
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
$model = arguments[0] ? arguments[0].$model : null;
var $ = this, exports = {}, __defers = {};
$.__views.resultWin = A$(Ti.UI.createWindow({
backgroundColor: "white",
exitOnClose: "false",
navBarHidden: !1,
id: "resultWin"
}), "Window", null);
$.addTopLevelView($.__views.resultWin);
$.__views.resultTable = A$(Ti.UI.createTableView({
top: "30px",
id: "resultTable"
}), "TableView", $.__views.resultWin);
$.__views.resultWin.add($.__views.resultTable);
$.__views.header = A$(Ti.UI.createView({
top: "0",
height: "30px",
backgroundColor: "gray",
id: "header"
}), "View", $.__views.resultWin);
$.__views.resultWin.add($.__views.header);
$.__views.nome = A$(Ti.UI.createLabel({
font: {
fontSize: "12dp",
"undefined": undefined
},
width: "25%",
left: "1%",
color: "black",
text: "Papel",
id: "nome"
}), "Label", $.__views.header);
$.__views.header.add($.__views.nome);
$.__views.precoSobreLucro = A$(Ti.UI.createLabel({
font: {
fontSize: "12dp",
"undefined": undefined
},
width: "15%",
left: "25%",
color: "black",
text: "P/L",
id: "precoSobreLucro"
}), "Label", $.__views.header);
$.__views.header.add($.__views.precoSobreLucro);
$.__views.retornoSobrePatrimonio = A$(Ti.UI.createLabel({
font: {
fontSize: "12dp",
"undefined": undefined
},
width: "20%",
left: "40%",
color: "black",
text: "ROE",
id: "retornoSobrePatrimonio"
}), "Label", $.__views.header);
$.__views.header.add($.__views.retornoSobrePatrimonio);
$.__views.dividaBrutaSobrePatrimonio = A$(Ti.UI.createLabel({
font: {
fontSize: "12dp",
"undefined": undefined
},
width: "15%",
left: "60%",
color: "black",
text: "Div/Ptr",
id: "dividaBrutaSobrePatrimonio"
}), "Label", $.__views.header);
$.__views.header.add($.__views.dividaBrutaSobrePatrimonio);
$.__views.patrimonioLiquido = A$(Ti.UI.createLabel({
font: {
fontSize: "12dp",
"undefined": undefined
},
width: "24%",
left: "75%",
color: "black",
textAlign: Ti.UI.TEXT_ALIGNMENT_RIGHT,
text: "Patr.",
id: "patrimonioLiquido"
}), "Label", $.__views.header);
$.__views.header.add($.__views.patrimonioLiquido);
exports.destroy = function() {};
_.extend($, $.__views);
var data = arguments[0];
$.resultTable.setData(data);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._, A$ = Alloy.A, $model;
module.exports = Controller; |
export const dailyGraphsStore = {
description:
'',
allSliceData: [],
graphs: [
{
name: 'DailyAlt',
id: 1,
sectionName: 'Daily Cases',
description:
'5 day average is average of current days new confirmed cases and 4 previous days.',
xAxisLabel: '# cases',
xAxisAttribute: 'Date',
selectedAttributeNames: ['ConfirmedCovidCases'],
selectedDate: '',
selectedDateData: [],
all: [],
avail: [
{
name: 'New Cases',
fieldName: 'ConfirmedCovidCases',
xAxisDescription: 'Number of Confirmed Cases',
xAxisAttribute: 'Date',
selected: true,
color: 'var(--covidPurple)',
attrData: [],
},
{
name: 'New Cases (5 day avg)',
fieldName: 'AverageConfirmedCases',
xAxisAttribute: 'Date',
xAxisDescription: 'AverageConfirmedCases',
selected: false,
color: 'var(--covidOrange)',
attrData: [],
},
{
name: 'Total Cases',
fieldName: 'TotalConfirmedCovidCases',
xAxisDescription: 'Total Number of Confirmed Cases',
xAxisAttribute: 'Date',
selected: false,
color: 'var(--white)',
attrData: [],
},
],
},
{
name: 'DailyAlt',
id: 2,
sectionName: 'Daily Cases (Percentage Change)',
description:
'Percentage Change calculated as (V2 - V1) x 100 / V1. 5 day average is average of current day and 4 previous days. ',
xAxisLabel: '% change',
xAxisAttribute: 'Date',
selectedAttributeNames: ['percentageDailyChange'],
selectedDate: '',
selectedDateData: [],
all: [],
avail: [
{
name: 'New Cases (% change)',
fieldName: 'percentageDailyChange',
xAxisAttribute: 'Date',
xAxisDescription: '% Daily Change (newCases)',
selected: true,
color: 'var(--covidBlue)',
attrData: [],
},
{
name: 'New Cases (% change) 5 day avg',
fieldName: 'percentageDailyChange5DayAverage',
xAxisDescription: 'percentageDailyChange5DayAverage',
xAxisAttribute: 'Date',
selected: false,
color: 'var(--covidPurple)',
attrData: [],
},
],
},
{
name: 'DailyAlt',
id: 3,
sectionName: 'Deaths',
description: '',
xAxisLabel: '# deaths',
xAxisAttribute: 'Date',
selectedAttributeNames: ['ConfirmedCovidDeaths'],
selectedDate: '',
selectedDateData: [],
all: [],
avail: [
{
name: 'New Deaths',
fieldName: 'ConfirmedCovidDeaths',
xAxisDescription: 'Number of Deaths',
xAxisAttribute: 'Date',
selected: true,
color: 'var(--white)',
attrData: [],
},
{
name: 'Total Deaths',
fieldName: 'TotalCovidDeaths',
xAxisDescription: 'Total Number of Deaths',
xAxisAttribute: 'Date',
selected: false,
color: 'var(--covidOrange)',
attrData: [],
},
],
},
],
} |
const chai = require("chai");
const expect = chai.expect;
const { v4: uuid4 } = require('uuid');
const {save, getAllPurchases, getHighestSalesProducts, getCustomerPurchase, getRegularCustomers } = require("../app/services/purchase.service");
describe("User Controller", function() {
describe("Error response for customer and product creation", function () {
const customerId = uuid4();
const purchase = {id: uuid4(), customerId: customerId, productId: "test", quantity: 1};
it("Should not be able to create new customer record with invalid email", async function () {
const customer = {id: customerId, firstName: "test", lastName: "test", email: "test"};
const product = {id: "test", name: "test"};
try {
await save(customer, product, purchase);
} catch(err) {
expect(err.statusCode).to.equal(400);
expect(err.message).to.equal(`Error: Invalid email format for customer: ${customer.firstName.concat(' ', customer.lastName)}`);
}
});
it("Should not be able to create new product record without product ID", async function () {
const customer = {id: customerId, firstName: "test", lastName: "test", email: "test@example.com"};
const product = {id: null, name: "test"};
try {
await save(customer, product, purchase);
} catch(err) {
expect(err.statusCode).to.equal(400);
expect(err.message).to.equal(`Error: Product ID cannot be empty for creation: ${product.name}`);
}
});
})
describe("Success response for creation and selection", function () {
it("Should be able to create new customer and product with correct input", async function () {
const customerId = uuid4();
const customer = {id: customerId, firstName: "test", lastName: "test", email: "test@example.com"};
const product = {id: "test", name: "test"};
const purchase = {id: uuid4(), customerId: customerId, productId: "test", quantity: 1};
await save(customer, product, purchase);
let result = await getCustomerPurchase(customerId);
result = result[0];
expect(result.customer_id).to.equal(customer.id);
expect(result.product_id).to.equal(product.id);
expect(result.quantity).to.equal(purchase.quantity);
});
it("Should be able to retrieve all purchases", async function () {
const purchases = await getAllPurchases();
expect(purchases.length).to.equal(12);
});
it("Should be able to retrieve individual customer purchase", async function () {
let purchase = await getCustomerPurchase("13e4f1a7-7c53-413d-a948-417bf10a8485");
purchase = purchase[0];
expect(purchase.customer_email).to.equal("marcelene.heaney@kirlinroob.com");
expect(purchase.product_id).to.equal("793");
expect(purchase.quantity).to.equal(10);
});
it("Should be able to retrieve highest sales products", async function () {
const products = await getHighestSalesProducts();
// only check the first highest sales product
expect(products[0].product_id).to.equal("510");
expect(products[0].product_name).to.equal("product_510");
expect(products[0].quantity).to.equal("13");
});
it("Should be able to retrieve regular customers with frequent purchase", async function () {
const customers = await getRegularCustomers();
// only check the most frequent purchase
expect(customers[0].customer_name).to.equal("Darby Dooley");
expect(customers[0].customer_email).to.equal("sharan_yundt@prosacco.us");
expect(customers[0].count).to.equal(1);
});
})
})
|
$(document).ready(function() {
$("#volunteergrid").kendoGrid({
height: 390,
scrollable: true,
sortable: true,
reorderable: true,
filterable: true,
// columnMenu: true,
// selectable: "row",
resizable: true,
columns: [
{field: "actions", width: 140, filterable: false },
{field: "id", width: 50 },
{field: "title", width: 60 },
{field: "first_name", width: 100 },
{field: "last_name", width: 100 },
{field: "address_1", width: 100 },
{field: "address_2", width: 100 },
{field: "city", width: 80 },
{field: "county", width: 80 },
{field: "state", width: 70 },
{field: "country", width: 100 },
{field: "zip_code", width: 80 },
{field: "date_of_birth", width: 100 },
{field: "phone_number_1", width: 120 },
{field: "phone_type_1", width: 100 },
{field: "phone_number_2", width: 120 },
{field: "phone_type_2", width: 100 },
{field: "email", width: 180 },
{field: "emergency_contact_name", width: 180 },
{field: "emergency_contact_relationship", width: 210 },
{field: "emergency_contact_phone_number", width: 220 },
{field: "occupation", width: 100 },
{field: "occupation_main_duties", width: 170 },
{field: "application_notes_talents", width: 180 },
{field: "application_notes_languages", width: 200 },
{field: "application_notes_passion", width: 180 },
{field: "application_notes_gain", width: 180 },
{field: "love_outreach", width: 120 },
{field: "official_volunteer", width: 150 },
{field: "interest_email_answered", width: 180 },
{field: "orientation_date", width: 130 },
{field: "orientation_location", width: 150 },
{field: "orientation_presenter", width: 180 },
{field: "application_form_received", width: 180 },
{field: "background_check", width: 180 },
{field: "letters_of_recommendation", width: 200 },
{field: "waiver", width: 100 },
{field: "notes", width: 100 },
{field: "created_at", width: 100 }
]
});
});
|
$(document).delegate('#review-form', 'submit', function(e) {
$(this).attr('disabled', 'disabled');
$('#review-form .alert').remove();
$.post(reviewUrl, $('#review-form').serialize(), function(json) {
if(json.operation == 'success')
{
location = location;
/*var html = '<div class="alert alert-warning">';
html += json.message;
html += '</div>';
$('#review-form').fadeOut();
$('#review-form').after(html);*/
}
if(json.operation == 'error')
{
var html = '<div class="alert alert-warning"><ul>';
$.each(json.message, function(index, value) {
$.each(value, function(key, err) {
html += '<li>' + err + '</li>';
});
});
html += '</ul></div>';
$('#review-form').append(html);
}
$(this).removeAttr('disabled');
});
e.preventDefault();
});
$(document).delegate('.rating .fa', 'click', function() {
//remove active class
$('.rating li').removeClass('active');
//add active class
$(this).parents('li').addClass('active');
$(this).parents('li').prevAll().addClass('active');
//set value
$('#vendorreview-rating').val($(this).parents('li').attr('data-value'));
});
$(document).delegate('.category_listing_nav a', 'click', function(e) {
$('.left-main-cat').val($(this).attr('data-slug')).change();
$('html, body').animate({ scrollTop: $('.listing_right').offset().top }, 'slow');
e.preventDefault();
});
jQuery(function()
{
//open return policy tab
if(location.hash == '#collapse2')
{
$('a[href=\"#collapse2\"]').trigger('click');
$('html, body').animate({ scrollTop: $('.vendor-profile-detail').offset().top }, 'slow');
}
});
|
const authRoutes = require('express').Router();
const passport = require('passport');
authRoutes.get('/twitter', passport.authenticate('twitter'));
authRoutes.get('/twitter-callback', passport.authenticate('twitter', {
failureRedirect: '/',
}), (req, res) => {
console.log(req);
res.redirect('/create');
});
authRoutes.get('/facebook', passport.authenticate('facebook'));
authRoutes.get('/facebook-callback', passport.authenticate('facebook', {
failureRedirect: '/',
}), (req, res) => {
res.redirect('/create');
});
module.exports = authRoutes;
|
import { parser } from './index.js';
(async() => {
const env = {};
await parser(
env,
'test.env',
true
);
console.log(env);
console.log(env.TEST1);
console.log(env.TEST2);
console.log(env.TEST3);
console.log(env.TEST4);
console.log(env.TEST5);
console.log(env.TEST6);
})(); |
'use strict';
var Opt = require('./opt');
var lib = require('./lib');
var Command = require('./command');
var hlp = require('./help');
var parse = require('./parse');
var Program = function(cmd, shortDesc, usage, longDesc) {
this.cmd = cmd;
this.shortDesc = shortDesc;
this.usage = usage;
this.longDesc = longDesc;
this.opts = [];
this.cmds = [];
}
Program.prototype.addOpt = function(short, long, description, conf) {
return lib.addOpt(this, short, long, description, conf);
}
Program.prototype.addCmd = function(cmd, shortDesc, usage, longDesc, conf) {
var cmd = new Command(cmd, shortDesc, usage, longDesc, conf);
this.cmds.push(cmd);
return cmd;
}
const helpDesc = 'output usage information.';
Program.prototype.addHelpOpt = function(description) {
if(!description) {
description = helpDesc;
}
return this.addOpt('h', 'help', description, {noMandatoryOptCheck: true});
}
Program.prototype.addHelpCmd = function(description) {
if(!description) {
description = helpDesc;
}
return this.addCmd('help', description, null, null, {noMandatoryOptCheck: true});
}
Program.prototype.addHelp = function(description) {
this.addHelpOpt(description);
this.addHelpCmd(description);
}
Program.prototype.getOpt = function(str) {
return lib.getOpt(this.opts, str);
}
Program.prototype.getCmd = function(str) {
for(let c of this.cmds) {
if(c.name === str) {
return c;
}
}
return null;
}
Program.prototype.printHelp = function(res, out) {
hlp.renderHelp(this, res, out);
}
Program.prototype.parse = function(arr) {
if(!arr) {
arr = process.argv.slice(2);
}
return parse(this, arr);
}
Program.prototype.parseCb = function(arr, cb) {
try {
var res = this.parse(arr);
cb(res);
}
catch(err) {
cb(null, err);
}
}
module.exports = Program;
|
import userRoutes from './userRoutes.js';
import footBallDataRoutes from './footBallDataRoutes.js';
import express from 'express';
const router = express.Router();
router.use('/user', userRoutes);
router.use('/football-data', footBallDataRoutes);
export default router; |
var MarkChart;
(function (MarkChart_1) {
var MarkChart = (function () {
function MarkChart(elementId, chartType, data, colors) {
this.data = [];
this.colors = [];
this.canvasElementId = elementId;
this.chartType = chartType;
this.data = data;
this.colors = colors;
}
// draw Chart
MarkChart.prototype.drawChart = function () {
var BorderWidth = 2.0;
var Total = null;
var canvas = document.getElementById(this.canvasElementId);
var context = canvas.getContext('2d');
context.lineCap = 'round';
var width = context.canvas.width;
var height = context.canvas.height;
var marginTop = 10;
var marginBottom = 10;
var marginLeft = 10;
var marginRight = 10;
var labelMargin = 10;
var dataValueMargin = 2;
var StrokeStyle = '#fff';
var Start = 150;
context.lineWidth = BorderWidth;
var dataSum = 0, dataSumForStartAngle = 0, dataLen = this.data.length;
for (var i = 0; i < dataLen; i++) {
dataSumForStartAngle += this.data[i];
if (this.data[i] < 0) {
return;
}
}
if (Total == null) {
dataSum = dataSumForStartAngle;
}
else {
dataSum = Total;
}
var AreaWidth = width - marginLeft - marginRight;
var AreaHeight = height - marginTop - marginBottom;
var centerX = width / 2;
var centerY = marginTop + (AreaHeight / 2);
var doublePI = 2 * Math.PI;
var radius = (Math.min(AreaWidth, AreaHeight) / 2);
var maxLabelWidth = 0;
radius = radius - maxLabelWidth - labelMargin;
var startAngle = Start * doublePI / dataSumForStartAngle;
var currentAngle = startAngle;
var endAngle = 0;
var incAngleBy = 0;
// draw chart in canvas
for (var i = 0; i < dataLen; i++) {
context.beginPath();
incAngleBy = this.data[i] * doublePI / dataSum;
endAngle = currentAngle + incAngleBy;
context.moveTo(centerX, centerY);
context.arc(centerX, centerY, radius, currentAngle, endAngle, false);
context.lineTo(centerX, centerY);
currentAngle = endAngle;
if (this.colors[i]) {
context.fillStyle = this.colors[i];
}
else {
context.fillStyle = '#0FFF2B';
}
context.fill();
context.strokeStyle = StrokeStyle;
context.stroke();
}
var ringCenterRadius = radius / 2;
// "cut" the central part from chart
context.save();
context.beginPath();
context.moveTo(centerX + ringCenterRadius, centerY);
context.arc(centerX, centerY, ringCenterRadius, 0, doublePI, false);
context.globalCompositeOperation = 'destination-out';
context.fillStyle = '#000';
context.fill();
context.restore();
};
return MarkChart;
}());
MarkChart_1.MarkChart = MarkChart;
})(MarkChart || (MarkChart = {}));
|
//Banner carousel
$('#car-banner').owlCarousel({
loop: true,
nav: false,
items: 2,
mouseDrag: false,
autoplay: true,
dots: true,
responsive : {
0 : {
items:1,
nav:false,
mouseDrag: true,
},
560 : {
items:2,
nav:false,
mouseDrag: true,
}
}
})
//mobile menu
$(".navbar-toggle-menu").click(function () {
$("#top-menu").slideToggle();
$("body").toggleClass("backshadow");
});
|
var room= require('../route/room.js');
exports= module.exports = function(io){
io.sockets.on('connection', (socket)=>{
console.log("New");
socket.on('webChange', (data)=>{
room.updateChange(data, (err, doc)=>{
if (err) {
throw err ;
console.log("err");
}
});
console.log(data);
io.emit('equipLoad',data);
});
socket.on('equipChange', function(data) {
console.log('equipChange');
console.log(data);
room.updateChange(data, (err, doc)=>{
if (err) {
throw err ;
console.log("err");
}
});
io.emit('webLoad', data);
});
socket.on('uploadSensor', function(data) {
console.log(data);
room.updateSensor(data,(err, doc)=>{
if(err){
throw err;
console.log("err when update value sensor");
}
});
io.emit('webLoadSensor', data)
});
});
}
|
(function() {
'use strict';
angular
.module('app', [])
.factory('skillManagerFactory', skillManagerFactory);
function skillManagerFactory() {}
})();
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const fs = require("fs");
const restify = require('restify');
const path = require('path');
const axios = require('axios');
axios.interceptors.request.use(function(config) {
config.headers['x-api-key'] = process.env.xapikey;
return config;
}, function(err) {
return Promise.reject(err);
});
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter, ChannelServiceRoutes, ConversationState, MemoryStorage, UserState, SkillHandler, SkillHttpClient } = require('botbuilder');
const { AuthenticationConfiguration, SimpleCredentialProvider, CertificateAppCredentials } = require('botframework-connector');
const { SkillDialog } = require('botbuilder-dialogs');
// Import our custom bot class that provides a turn handling function.
const { DialogBot } = require('./bots/dialogBot');
const { MainDialog } = require('./dialogs/mainDialog');
// Read environment variables from .env file
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const { allowedSkillsClaimsValidator } = require('./authentication/allowedSkillsClaimsValidator');
const { SkillsConfiguration } = require('./skillsConfiguration');
const { SkillConversationIdFactory } = require('./skillConversationIdFactory');
const url = require('url');
const msrest = require('@azure/ms-rest-js');
// Create the adapter. See https://aka.ms/about-bot-adapter to learn more about using information from
// the .bot file when configuring your adapter.
const keyPemFile = "./private-key.pem";
const pkFromFile = fs.readFileSync(
path.resolve(__dirname, keyPemFile),
{ encoding: 'utf8'}
);
const adapterSettings = {
appId: process.env.MicrosoftAppId,
// appPassword: process.env.MicrosoftAppPassword,
certificatePrivateKey: pkFromFile,
certificateThumbprint: process.env.CertificateThumbprint,
authConfig: new AuthenticationConfiguration([], allowedSkillsClaimsValidator)
}
class SignRequestAppCredentials extends CertificateAppCredentials {
async signRequest(webResource) {
//if(AppCredentials.isTrustedServiceUrl(webResource.url)){
webResource.headers.set('x-api-key', process.env.xapikey);
const token = await this.getToken();
return new msrest.TokenCredentials(token).signRequest(webResource);
//}
//return webResource;
}
}
class CustomCredentialsBotFrameworkAdapter extends BotFrameworkAdapter {
async buildCredentials(appId, oAuthScope) {
return new SignRequestAppCredentials(appId, adapterSettings.certificateThumbprint, adapterSettings.certificatePrivateKey, undefined, oAuthScope);
}
}
const adapter = new CustomCredentialsBotFrameworkAdapter(adapterSettings);
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Define the state store for your bot.
// See https://aka.ms/about-bot-state to learn more about using MemoryStorage.
// A bot requires a state storage system to persist the dialog and user state between messages.
const memoryStorage = new MemoryStorage();
// Create conversation state with in-memory storage provider.
const conversationState = new ConversationState(memoryStorage);
const userState = new UserState(memoryStorage);
class BuildCredentialsSkillHttpClient extends SkillHttpClient {
async buildCredentials(appId, oAuthScope) {
return new SignRequestAppCredentials(appId, adapterSettings.certificateThumbprint, adapterSettings.certificatePrivateKey, undefined, oAuthScope);
}
}
const credentialProvider = new SimpleCredentialProvider(process.env.MicrosoftAppId, '');
const conversationIdFactory = new SkillConversationIdFactory();
const skillClient = new BuildCredentialsSkillHttpClient(credentialProvider, conversationIdFactory);
// Load skills configuration
const skillsConfig = new SkillsConfiguration();
const skillDialog = new SkillDialog({
botId: process.env.MicrosoftAppId,
conversationIdFactory,
conversationState,
skill: {
id: process.env.SkillId,
appId: process.env.SkillAppId,
skillEndpoint: process.env.SkillEndpoint
},
skillHostEndpoint: process.env.SkillHostEndpoint,
skillClient
}, 'skillDialog');
// Create the main dialog.
const dialog = new MainDialog(userState, skillDialog);
const bot = new DialogBot(conversationState, userState, dialog, skillsConfig, skillClient);
// Create HTTP server.
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to ${ server.url }.`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route the message to the bot's main handler.
await bot.run(context);
});
});
// Create and initialize the skill classes
const authConfig = new AuthenticationConfiguration([], allowedSkillsClaimsValidator);
const handler = new SkillHandler(adapter, bot, conversationIdFactory, credentialProvider, authConfig);
const skillEndpoint = new ChannelServiceRoutes(handler);
skillEndpoint.register(server, '/api/skills');
// Listen for GET requests to the same route to accept Upgrade requests for Streaming.
server.on('upgrade', async (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new CustomCredentialsBotFrameworkAdapter(adapterSettings);
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
await adapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await bot.run(context);
});
});
|
const playerHelpPageData = [{
title: 'Bli med i turnering',
texts: [
'For å bli med i en turnering velger du "spill turnering" på hjemmesiden. Der etter fyller du ut skjemaet.',
' Game pin får du av turnerings verten. Spillernavn kan vær hvilket som helst navn du ønsker å bruke under ' +
'turneringen, så lenge det ikke allerede er i bruk av andre.'
],
images: [
require('@/assets/help-page/player/play_home.jpg'),
require('@/assets/help-page/player/enter_tournament.jpg')
],
altTags: [
'Hjemmesiden',
'Skjema for å bli med i turnering'
]
},
{
title: 'Forlat turnering',
texts: [
'Det er to måter du kan forlate turneringen på. Det første er å benytte "Forlat turnering" knappen. Den andre måten' +
' er å navigere bort fra siden.',
'Når du prøver å forlate turneringen vil du få en dialog for å være sikker på at det er dette du ønsker. Husk' +
' at å forlate turneringen er en ikke-reversibel handling! Trykker du forlat kan du ikke angre.'
],
images: [
require('@/assets/help-page/player/leave_tournament.jpg'),
require('@/assets/help-page/player/leave_tournament_box.jpg')
],
altTags: [
'Knapp for å forlate turnering',
'Dialog box for å varsle om at det ikke er en reversibel funksjon'
]
},
{
title: 'Se tidligere spillte partier',
texts: [
'For å se en oversikt over dine tidligere spillte parti i turneringen benytter du deg av "Tidligere parti" knappen.' +
' Denne vil åpne en tabell under som inneholder alle partiene. Benytt tilsvarende knapp for å fjerne listen.',
'Om du ikke har spilt noen partier enda, så vil en tabell med teksten "Du har jo ikke spilt enda!" vises.'
],
images: [
require('@/assets/help-page/player/show_past_results.jpg'),
require('@/assets/help-page/player/past_results.jpg')
],
altTags: [
'Spiller side med pil som viser knappen for å sette turnering på pasue',
'Spiller side med pil som viser knappen for fortsette turneringen'
]
},
{
title: 'Sjakkur',
texts: [
'Om det er ønskelig finnes det også ett sjakkur i applikasjonen. Denne finner man tilgjengelig i hjemmesiden & i' +
' turneringssiden til spillerne etter at parti er tildelt.',
'Sjakkuret startes ved å trykke på sorts knapp. Når tiden' +
' går ut er det spillerne selv som har ansvaret for å registrere resultatet.',
'Spillerne har selv ansvar for å konfigurere klokken ved å sette antall minutter, sekunder pr spiller og hvor' +
' mye ekstra tid hver spiller får pr trekk.'
],
images: [
require('@/assets/help-page/player/show_chess_clock.jpg'),
require('@/assets/help-page/player/chess_clock.jpg'),
require('@/assets/help-page/player/chess_clock_config.jpg')
],
altTags: [
'Spiller side med pil som viser sjakkur',
'Sjakkuret',
'Dialog box for konfigurasjon av sjakkur'
]
},
{
title: 'Pause',
texts: [
'Spillere kan selv velge å ta pause fra turneringen, dette gjøres enkelt ved å benytte "pause" knappen. Dette kan' +
' kun gjøres mens spilleren venter på at applikasjonen skal tildele ett nytt parti.',
' Når spilleren har tatt pause blir de ikke tildelt nytt parti før de velger å fortsette turneringen igjen.' +
' For å fortsette turneringen benytter spilleren knappen som ligger i den samme posisjonen. "fortsett spill".'
],
images: [
require('@/assets/help-page/player/take_break.jpg'),
require('@/assets/help-page/player/continue_tournament.jpg')
],
altTags: [
'Spiller side med pil som viser knappen for å sette turnering på pasue',
'Spiller side med pil som viser knappen for fortsette turneringen'
]
},
{
title: 'Registrering av resultat',
texts: [
'Når ett spill er ferdig skal resultatet registreres. Benytt "registrer resultat" knappen. Det er ikke nødvendig' +
' at begge spillerne legger inn resultat.',
'Resultat valgene er "Hvit seier", "remi (uavgjort)" eller "sort seier". Når du registrere resultatet kan ett' +
' bilde bli lastet opp, dette vil bli brukt til hjelp for turneringsvert dersom dere skulle være uenige om resultatet.' +
' Når bildet blir lagt inn så vil du få se en liten versjon av bildet slik du kan være sikker på at det er riktig.',
'Når ene spilleren har lagt inn resultat, så vil motstanderen få en dialog boks der man skal godkjenne eller ikke' +
' godkjenne resultatet. Velger man å ikke godkjenne, kan de prøve på nytt eller kontakte turneringsverten for' +
' å få oppklaring i uneighetene. Turneringsverten kan også selv velge å overstyre og sette resultatet.'
],
images: [
require('@/assets/help-page/player/register_result.jpg'),
require('@/assets/help-page/player/register_result_box.jpg'),
require('@/assets/help-page/player/validate_result.jpg')
],
altTags: [
'Spiller side med pil som viser knappen for å registrere resultat',
'Dialog box for å registrere resultat',
'Dialog box for å validere resultat'
]
}
]
export default playerHelpPageData
|
define([
"dcl",
"napp/Command"
], function (
dcl,
Command) {
return dcl([Command], {
constructor: dcl.advise({
after: function() {
this.canExecute = !!this.model.greeting;
this.model.observe(function () {
this.canExecute = !!this.model.greeting;
}.bind(this));
}
}),
execute: function() {
alert(this.model.greeting);
}
});
}); |
import React from 'react';
class PatternSection extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='pattern-item-section'>
<h5 className='pattern-item-section-label'>
{this.props.label}
</h5>
{this.props.children}
</div>
)
}
}
export default PatternSection; |
// TODO: lumbar prefix won't show up in font urls
// but will in all other urls
$(function() {
var css = '@font-face {font-family: MyriadPro; src: url("' + lumbarLoadPrefix + 'fonts/MyriadPro-Regular.otf"); format("opentype")} ';
css += '@font-face {font-family: MyriadPro; font-weight: bold; src: url("' + lumbarLoadPrefix + 'fonts/MyriadPro-Bold.otf"); format("opentype")}';
$('head').append('<style>' + css + '</style>')
});
|
!function () {
'use strict';
function UserListController($scope, dataService, info, model) {
$scope.results = [];
$scope.statuses = info.UserStatus;
$scope.search = function (filter) {
return $scope.results = dataService.user.query(filter);
};
};
function UserNewController($scope, dataService, $location, model) {
$scope.roles = model.role;
$scope.create = function (user) {
return dataService.user.save(user).$promise
.then(function () {
$location.path('/user/list');
});
};
};
function UserEditController($scope, dataService, $location, model) {
$scope.user = model.user;
$scope.roles = model.role;
$scope.update = function (user) {
return wrapPromise(dataService.user.update(user)
.then(function () {
$location.path('/user/list');
}));
};
};
angular.module('DNNT')
.controller('user.list', UserListController)
.controller('user.new', UserNewController)
.controller('user.edit', UserEditController);
}(); |
import React, { Component } from 'react';
import { AnimatedRoute, AnimatedSwitch, spring } from 'react-router-transition';
import { BrowserRouter, Route } from 'react-router-dom'
import About from './Components/About';
import Navbar from './Components/Navbar';
import Testimonials from './Components/Testimonials';
import FreeVideos from './Components/FreeVideos';
import Schedule from './Components/Schedule';
import Contact from './Components/Contact';
import './App.css';
class App extends Component {
render() {
function mapStyles(styles) {
return {
opacity: styles.opacity,
transform: `scale(${styles.scale})`,
};
}
// wrap the `spring` helper to use a bouncy config
function bounce(val) {
return spring(val, {
stiffness: 330,
damping: 22,
});
}
// child matches will...
const bounceTransition = {
// start in a transparent, upscaled state
atEnter: {
opacity: 0,
scale: 1.2,
},
// leave in a transparent, downscaled state
atLeave: {
opacity: bounce(0),
scale: bounce(0.8),
},
// and rest at an opaque, normally-scaled state
atActive: {
opacity: bounce(1),
scale: bounce(1),
},
};
return (
<div className="row appRow">
<BrowserRouter>
<div>
<Navbar />
<AnimatedSwitch
atEnter={{ offset: -100 }}
atLeave={{ offset: 100 }}
atActive={{ offset: 0 }}
mapStyles={(styles) => ({
transform: `translateX(${styles.offset}%)`,
})}
>
<Route exact path="/" component={About} />
<Route exact path="/testimonials" component={Testimonials}/>
<Route exact path="/videos" component={FreeVideos}/>
<Route exact path="/schedule" component={Schedule}/>
<Route exact path="/contact" component={Contact}/>
</AnimatedSwitch>
</div>
</BrowserRouter>
</div>
);
}
}
export default App;
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import omit from 'lodash/omit'
import { connect } from 'react-redux'
import { fromImpression } from 'store/selectors'
import { impressionDetailReadRequest } from 'store/actions'
import Chart from 'components/Chart'
class ChartContainer extends Component {
static propTypes = {
readImpressionDetail: PropTypes.func.isRequired,
}
componentDidMount() {
this.props.readImpressionDetail()
}
render() {
return <Chart {...this.props} />
}
}
const mapStateToProps = state => ({
impressions: omit(fromImpression.getDetail(state), 'title'),
})
const mapDispatchToProps = dispatch => ({
readImpressionDetail: () => dispatch(impressionDetailReadRequest(2)),
})
export default connect(mapStateToProps, mapDispatchToProps)(ChartContainer)
|
$(document).ready(function(){
// your jQuery codes will go here
$("img").hover(
function(){
var temp = $(this).attr("alt-img-src");
$(this).attr("alt-img-src", $(this).attr("src"));
$(this).attr("src", temp);
},
function(){
var temp = $(this).attr("alt-img-src");
$(this).attr("alt-img-src", $(this).attr("src"));
$(this).attr("src", temp);
}
);
}); |
function solve(arr, magicNumber){
let result = '';
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === magicNumber) {
result += arr[i] + ' ' + arr[j] + '\n';
}
}
}
console.log(result);
}
solve([14, 20, 60, 13, 7, 19, 8], 27); |
import React from 'react'
import './Dialog.scss'
function Dialog ({ children }) {
return (
<div className="dialog">
<div className="dialog__box">{children}</div>
</div>
)
}
export default Dialog
|
'use-strict'
/* base libs */
import express from 'express'
/* libs/modules */
/* utils/constants */
import { ClassController } from '../controllers'
const centreClass = express.Router()
/**
* ##############################################
* # CRUD
* ##############################################
*/
centreClass.get('/', (req, res, next) => { // eslint-disable-line no-unused-vars
})
/**
* ##############################################
* # AUTH
* ##############################################
*/
/**
* ##############################################
* # DOMAIN LOGIC
* ##############################################
*/
centreClass.get('/attendance/:id', (req, res, next) => { // eslint-disable-line no-unused-vars
ClassController.fetch(req, res)
})
export default centreClass |
import Board from "./board.js";
import BoardSolver from "./../solver/board_solver.js";
import SudokuSolver from "./../solver/sudoku_solver.js";
// purpose of this class:
// 1) Get one board
// 2) Get the solution of the board
// 3) save the inputsVal to display the hint (ex: {1: 3, 2:0, 3: 2})
class Sudoku {
constructor(difficulty = 15){
this.board = new Board(difficulty);
this.inputsVal = this.board.inputsVal;
const boardSolver = new BoardSolver(this.board);
this.solution = new SudokuSolver(boardSolver).solve();
}
}
export default Sudoku;
|
import {
checkEmailFormat,
checkUsernameFormat,
checkFullnameFormat,
checkEmptyField
} from '../../../api/signUpService';
/* eslint-disable no-unused-vars */
/* eslint-disable func-names */
/* eslint-disable object-shorthand */
const validations = {
fullnameEmpty: function(value, attributes, attributeName, options, constraints) {
const emptyField = checkEmptyField(attributes.fullname);
if (!emptyField) return null;
return {
presence: {
message: '^Para continuar debe completar el campo nombre completo.'
}
};
},
fullnameFormat: function(value, attributes, attributeName, options, constraints) {
const correctFullnameFormat = checkFullnameFormat(attributes.fullname);
if (correctFullnameFormat) return null;
return {
presence: {
message:
'^El nombre completo no puede contener símbolos y debe contener su nombre y apellido.'
}
};
},
usernameEmpty: function(value, attributes, attributeName, options, constraints) {
const emptyField = checkEmptyField(attributes.username);
if (!emptyField) return null;
return {
presence: {
message: '^Para continuar debe completar el campo usuario.'
}
};
},
usernameFormat: function(value, attributes, attributeName, options, constraints) {
const correctUsernameFormat = checkUsernameFormat(attributes.username);
if (correctUsernameFormat) return null;
return {
presence: {
message:
'^El nombre de usuario no puede contener espacios ni símbolos y al menos debe contener 4 caracteres.'
}
};
},
emailEmpty: function(value, attributes, attributeName, options, constraints) {
const emptyField = checkEmptyField(attributes.email);
if (!emptyField) return null;
return {
presence: {
message: '^Para continuar debe completar el campo email.'
}
};
},
emailFormat: function(value, attributes, attributeName, options, constraints) {
const correctEmailFormat = checkEmailFormat(attributes.email);
if (correctEmailFormat) return null;
return {
presence: {
message: '^La dirección de email que ha ingresado es inválida.'
}
};
},
passwordEmpty: function(value, attributes, attributeName, options, constraints) {
const emptyField = checkEmptyField(attributes.password);
if (!emptyField) return null;
return {
presence: {
message: '^Para continuar debe completar el campo contraseña.'
}
};
},
passwordSpaces: function(value, attributes, attributeName, options, constraints) {
if (attributes.password.indexOf(' ') === -1) return null;
return {
presence: {
message: '^La contraseña no puede contener espacios.'
}
};
},
passwordFormat: function(value, attributes, attributeName, options, constraints) {
if (attributes.password.length >= 6) return null;
return {
presence: {
message: '^La contraseña no es lo suficientemente fuerte.'
}
};
},
emptyUserType: function(value, attributes, attributeName, options, constraints) {
const emptyField = checkEmptyField(attributes.usertype);
if (!emptyField) return null;
return {
presence: {
message: '^Para continuar debe seleccionar el tipo de usuario.'
}
};
}
};
export default validations;
|
import React, {
createContext,
useState,
useEffect,
useContext,
useMemo,
} from "react";
import { auth } from "../firebase-config";
import { db } from "../firebase-config";
import firebase from "firebase/app";
const AuthContext = createContext();
export const useAuth = () => useContext(AuthContext);
export const AuthProvider = (props) => {
const [currentUser, setCurrentUser] = useState({});
const [userData, setUserData] = useState({});
let uData;
const signup = (email, password) => {
return auth.createUserWithEmailAndPassword(email, password);
};
const login = (email, password) => {
return auth.signInWithEmailAndPassword(email, password);
};
const logout = () => auth.signOut();
const getUserData = async () => {
let data;
const evt = [];
let userData;
if (currentUser) {
let email = String(currentUser.email);
try {
data = await db.collection("users").where("email", "==", email).get();
const snapshot = await data;
let temp;
snapshot.forEach((element) => {
temp = element.data();
temp.id = element.id;
evt.push(temp);
});
evt.map((element) => {
userData = element;
});
} catch (error) {
console.log("Where error here: ", error);
}
} else userData = null;
return userData;
};
const updateUserData = async (newUser) => {
try {
await setUserData(newUser);
await db.collection("users").doc(currentUser.uid).update(newUser);
console.log("updateUserData success");
} catch (error) {
console.log("error updatedUSerData", error);
}
};
const updateUserEmail = async (newEmail) => {
try {
await firebase.auth().currentUser.updateEmail(newEmail);
await console.log("update success");
} catch (error) {
console.log("We have problems: ", error);
}
};
const updateUserPassword = async (newPassword) => {
try {
await firebase.auth().currentUser.updatePassword(newPassword);
await console.log("Password update success");
} catch (error) {
console.log("error updating password", error)
}
};
useEffect(async () => {
console.log("userEffect AuthContext");
auth.onAuthStateChanged((user) => {
setCurrentUser(user);
});
uData = await getUserData();
await setUserData(uData);
console.log(await userData);
}, [currentUser]);
// const value = {
// signup,
// login,
// logout,
// currentUser,
// userData,
// updateUserEmail,
// updateUserData,
// };
const value = useMemo(() => {
return {
signup,
login,
logout,
currentUser,
userData,
updateUserEmail,
updateUserData,
updateUserPassword
};
}, [currentUser, userData]);
return (
<AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>
);
};
|
class ElasticSearchCases{
getCAseeTemplate(){
return {
id: 1551731054913653,
jurisdiction: "IA",
state: "respondentReview",
version: null,
case_type_id: "Asylum",
created_date: "2019-03-04T20:24:14.948",
last_modified: "2023-01-09T13:16:47.86",
last_state_modified_date: "2019-03-04T20:40:00.88",
security_classification: "PUBLIC",
case_data: {
caseManagementLocation: {
baseLocation: "765324",
region: "1",
},
hmctsCaseNameInternal: "Tim Burton",
caseNameHmctsInternal: "Tim Burton",
SearchCriteria: {
OtherCaseReferences: [
{
id: "456a9242-04cf-4852-a473-546b1e74c1ec",
value: "PA/50032/2019",
},
],
SearchParties: [
{
id: "c1ce1d74-e016-415c-b4e0-9a9c4b392180",
value: {
DateOfBirth: "1980-12-24",
AddressLine1: "2-3",
PostCode: "TW14 0LS",
Name: "Mr Tim Burton",
},
},
],
},
},
data_classification: {
staffLocation: "PUBLIC",
currentCaseStateVisibleToHomeOfficeAll: "PUBLIC",
uploadAddendumEvidenceLegalRepActionAvailable: "PUBLIC",
appealGroundsHumanRights: {
classification: "PUBLIC",
value: {
values: "PUBLIC",
},
},
newMatters: "PUBLIC",
appellantAddress: {
classification: "PUBLIC",
value: {
AddressLine3: "PUBLIC",
AddressLine2: "PUBLIC",
AddressLine1: "PUBLIC",
Country: "PUBLIC",
PostTown: "PUBLIC",
PostCode: "PUBLIC",
County: "PUBLIC",
},
},
haveHearingAttendeesAndDurationBeenRecorded: "PUBLIC",
uploadAddendumEvidenceActionAvailable: "PUBLIC",
appellantGivenNames: "PUBLIC",
appellantFamilyName: "PUBLIC",
hearingCentre: "PUBLIC",
uploadAddendumEvidenceHomeOfficeActionAvailable: "PUBLIC",
markAddendumEvidenceAsReviewedActionAvailable: "PUBLIC",
currentCaseStateVisibleToHomeOfficeGeneric: "PUBLIC",
caseArgumentEvidence: {
classification: "PUBLIC",
value: [
{
id: "fe2ead2d-dc8a-42e5-b401-701828774eaa",
value: {
document: "PUBLIC",
description: "PUBLIC",
},
},
],
},
currentCaseStateVisibleToHomeOfficePou: "PUBLIC",
directions: {
classification: "PUBLIC",
value: [
{
id: "3",
value: {
dateDue: "PUBLIC",
parties: "PUBLIC",
tag: "PUBLIC",
dateSent: "PUBLIC",
explanation: "PUBLIC",
},
},
{
id: "2",
value: {
dateDue: "PUBLIC",
parties: "PUBLIC",
tag: "PUBLIC",
dateSent: "PUBLIC",
explanation: "PUBLIC",
},
},
{
id: "1",
value: {
dateDue: "PUBLIC",
parties: "PUBLIC",
tag: "PUBLIC",
dateSent: "PUBLIC",
explanation: "PUBLIC",
},
},
],
},
hmctsCaseNameInternal: "PUBLIC",
currentCaseStateVisibleToAdminOfficer: "PUBLIC",
hmctsCaseCategory: "PUBLIC",
appellantTitle: "PUBLIC",
sendDirectionActionAvailable: "PUBLIC",
homeOfficeReferenceNumber: "PUBLIC",
appellantHasFixedAddress: "PUBLIC",
legalRepReferenceNumber: "PUBLIC",
uploadAddendumEvidenceAdminOfficerActionAvailable: "PUBLIC",
currentCaseStateVisibleToLegalRepresentative: "PUBLIC",
caseManagementLocation: {
classification: "PUBLIC",
value: {
baseLocation: "PUBLIC",
region: "PUBLIC",
},
},
appealGroundsForDisplay: "PUBLIC",
ccdReferenceNumberForDisplay: "PUBLIC",
legalRepresentativeEmailAddress: "PUBLIC",
legalRepresentativeName: "PUBLIC",
legalRepresentativeDocuments: {
classification: "PUBLIC",
value: [
{
id: "2",
value: {
document: "PUBLIC",
dateUploaded: "PUBLIC",
description: "PUBLIC",
tag: "PUBLIC",
},
},
{
id: "1",
value: {
document: "PUBLIC",
dateUploaded: "PUBLIC",
description: "PUBLIC",
tag: "PUBLIC",
},
},
],
},
hasOtherAppeals: "PUBLIC",
currentCaseStateVisibleToHomeOfficeLart: "PUBLIC",
caseArgumentAvailable: "PUBLIC",
caseArgumentDescription: "PUBLIC",
appealReferenceNumber: "PUBLIC",
appealType: "PUBLIC",
uploadAdditionalEvidenceActionAvailable: "PUBLIC",
markEvidenceAsReviewedActionAvailable: "PUBLIC",
appellantNationalities: {
classification: "PUBLIC",
value: [
{
id: "a148830d-48ee-4636-8a10-f4e46be00f48",
value: {
code: "PUBLIC",
},
},
],
},
homeOfficeDecisionDate: "PUBLIC",
changeDirectionDueDateActionAvailable: "PUBLIC",
currentCaseStateVisibleToJudge: "PUBLIC",
respondentDocuments: {
classification: "PUBLIC",
value: [
{
id: "1",
value: {
document: "PUBLIC",
dateUploaded: "PUBLIC",
description: "PUBLIC",
tag: "PUBLIC",
},
},
],
},
uploadAdditionalEvidenceHomeOfficeActionAvailable: "PUBLIC",
appealGroundsProtection: {
classification: "PUBLIC",
value: {
values: "PUBLIC",
},
},
appellantDateOfBirth: "PUBLIC",
caseNameHmctsInternal: "PUBLIC",
SearchCriteria: {
classification: "PUBLIC",
value: {
OtherCaseReferences: {
classification: "PUBLIC",
value: [
{
id: "456a9242-04cf-4852-a473-546b1e74c1ec",
classification: "PUBLIC",
},
],
},
SearchParties: {
classification: "PUBLIC",
value: [
{
id: "c1ce1d74-e016-415c-b4e0-9a9c4b392180",
value: {
DateOfBirth: "PUBLIC",
AddressLine1: "PUBLIC",
PostCode: "PUBLIC",
Name: "PUBLIC",
},
},
],
},
},
},
currentCaseStateVisibleToHomeOfficeApc: "PUBLIC",
currentCaseStateVisibleToCaseOfficer: "PUBLIC",
appellantNameForDisplay: "PUBLIC",
notificationsSent: {
classification: "PUBLIC",
value: [
{
id: "1551731054913653_APPEAL_SUBMITTED_CASE_OFFICER",
classification: "PUBLIC",
},
{
id: "1551731054913653_BUILD_CASE_DIRECTION",
classification: "PUBLIC",
},
],
},
respondentReviewAppealResponseAdded: "PUBLIC",
searchPostcode: "PUBLIC",
caseArgumentDocument: "PUBLIC",
hasNewMatters: "PUBLIC",
caseNotes: {
classification: "PUBLIC",
value: [
{
id: "1",
value: {
caseNoteSubject: "PUBLIC",
caseNoteDescription: "PUBLIC",
user: "PUBLIC",
dateAdded: "PUBLIC",
},
},
],
},
},
supplementary_data: null,
after_submit_callback_response: null,
callback_response_status_code: null,
callback_response_status: null,
delete_draft_response_status_code: null,
delete_draft_response_status: null,
}
}
}
module.exports = new ElasticSearchCases();
|
import React from 'react';
import './style.css';
import Card from '../UI/Card';
/**
* @author
* @function sidebar
**/
const sidebar = (props) => {
return(
<div className='sidebarcontainer'>
<Card style={{marginBotton:'20px', padding:'20px',boxSizing:'border-box'}}>
<div className="cardHeader">
<span>About us</span>
</div>
<div className="aboutusimagecontainer">
<img src="https://www.globalbollywood.com/wp-content/uploads/2020/06/dwwd.jpeg" alt ="aboutimage"/>
</div>
<div className="aboutusbody">
<p>
The FoodXp is online food delivery app ,order food from restaurants near, to make it simple for the customer in reaching the food on time to the customer, from nearest restaurants, hotels, cafes, bakeries etc.
</p>
</div>
</Card>
<Card>
<div className="cardHeader">
<span>Contact us</span>
</div>
</Card>
</div>
)
}
export default sidebar |
// Problem 7
var listSize = function(head) {
let n = 0;
while (head !== null) {
n++;
head = head.next;
}
return n;
}
var isPalindrome = function(head) {
if (head === null || head.next === null) return true;
let num = listSize(head);
let half = Math.floor(num / 2);
let remainder = num % 2 ? 1: 0;
let prev = null;
for (let i = 0; i < half; i++) {
let temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
if (remainder) {
head = head.next;
}
for (let j = 0; j < half; j++) {
if (prev.val !== head.val) {
return false;
}
prev = prev.next;
head = head.next;
}
return true;
} |
import {
ADD_NEW_MOBILE_IN_REDUX,
DELETE_EXISTING_MOBILE_BY_ID_FROM_REDUX,
SET_EXISTING_MOBILE_IN_REDUX_FOR_UPDATING,
UPDATE_EXISTING_MOBILE_IN_REDUX
} from "./actionTypes";
import * as URLPathConstant from "../URLPathConstant";
export const addNewMobileInRedux = (newMobile, history) => dispatch => {
dispatch({
type: ADD_NEW_MOBILE_IN_REDUX,
payload: newMobile
});
history.push(URLPathConstant.SHOW_ALL_MOBILES_URL_PATH);
};
export const setExistingMobileInReduxForUpdating = (
existingMobile,
history
) => dispatch => {
dispatch({
type: SET_EXISTING_MOBILE_IN_REDUX_FOR_UPDATING,
payload: existingMobile
});
history.push(URLPathConstant.UPDATE_MOBILE_URL_PATH);
};
export const updateExistingMobileInRedux = (
updatedExistingMobile,
history
) => dispatch => {
dispatch({
type: UPDATE_EXISTING_MOBILE_IN_REDUX,
payload: updatedExistingMobile
});
history.push(URLPathConstant.SHOW_ALL_MOBILES_URL_PATH);
};
export const deleteExistingMobileByIdFromRedux = mobileId => dispatch => {
dispatch({
type: DELETE_EXISTING_MOBILE_BY_ID_FROM_REDUX,
payload: mobileId
});
};
|
var util = require('util');
var name = 'Tony';
// formats code
var greeting = util.format('Hello, %s', name);
// prints with time stamp
util.log(greeting); |
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import AuthService from "./AuthService";
//Vue.config.productionTip = false
import MyModal from './components/Modal.vue'
import BoardTitle from './components/BoardTitle'
import ClickEdit from './components/ClickEdit'
import Collaborators from './components/Collaborators'
import Collaborator from './components/Collaborator'
import UserIcon from './components/UserIcon'
import LoggedInUser from './components/LoggedInUser'
Vue.component('board-title', BoardTitle)
Vue.component('click-edit', ClickEdit)
Vue.component('collaborators', Collaborators);
Vue.component('collaborator', Collaborator);
Vue.component('logged-in-user', LoggedInUser)
Vue.component('my-modal', MyModal);
Vue.component('user-icon', UserIcon)
// document.getElementById('').getElementsByClassName()
Vue.mixin({
methods: {
userId() {
return this.$store.state.Auth.user._id;
},
isAllowed(creatorId) {
let uid = this.$store.state.Auth.user._id;
let boardId = this.$store.state.Boards.activeBoard._id
let collaborators = this.$store.state.Collaborators.collaborators[boardId] || []
let collaboratorIds = new Set(
collaborators.map(c => {
return c.user_id;
})
);
let result = uid === creatorId || collaboratorIds.has(uid);
return result;
}
}
});
async function init() {
let user = await AuthService.Authenticate();
if (user) {
store.dispatch('getUsers')
store.commit("setUser", user);
} else {
router.push({ name: "login" });
}
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
}
init();
|
import React from "react";
const HomePackageCardSC = props => {
return (
<div className="cardMain">
<div className="cardMain_side cardMain_side--front">
<div className="cardMain_picture cardMain_picture">
<img
className="cardMain_picture cardMain_picture"
src={props.image}
alt="product"
/>
</div>
<h4 className="cardMain_heading">
<span className="cardMain_heading-span cardMain_heading-span">
{props.homePakHead}
</span>
</h4>
<div className="cardMain_details">
<p>{props.homePakList}</p>
</div>
</div>
<div className="cardMain_side cardMain_side--back cardMain_side--back">
<div className="cardMain_cta">
<div className="card_price-box">
<p className="class cardMain_price-only">
{props.homePakPriceBoxOnly} + {props.homePakPriceBoxValue}
</p>
</div>
<a
href="https://robertsspaceindustries.com/enlist?referral=STAR-LM2V-XX7D"
target="_blank"
className="btn btn-white">
{props.homePakButton}
</a>
</div>
</div>
</div>
);
};
export default HomePackageCardSC;
|
import React from "react";
import { Animated } from "react-animated-css";
import style from "./Conversion.css";
import fetch from "node-fetch";
import ProfileHolder from "../Images/spotifylogo.png";
import Dropdown from "react-bootstrap/Dropdown";
import Tracks from "./Tracks";
class Successful extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "User",
profileUrl: false,
profileImage: <ProfileHolder />,
token: this.props.token,
items: [],
clicked: false,
value: "Select Playlist",
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
document.title = "Convert | SpotiFibe";
fetch("https://api.spotify.com/v1/me", {
headers: {
Authorization: "Bearer " + this.state.token,
},
})
.then((res) => res.json())
.then((data) => {
this.setState({
name: data.display_name,
profileUrl: data.external_urls.spotify,
profileImage: data.images[0].url,
});
})
.catch((err) => console.error(err));
fetch("https://api.spotify.com/v1/me/playlists?limit=50", {
headers: {
Authorization: "Bearer " + this.state.token,
},
})
.then((res) => res.json())
.then((data) => {
this.setState({
items: data.items,
});
})
.catch((err) => console.error(err));
}
handleChange(event) {
this.setState({ value: event.target.name });
}
render() {
return (
<div className="successful" style={style}>
{this.state.value === "Select Playlist" ? (
<div>
<Animated
isVisible={true}
animationInDelay="1000"
animationIn="fadeIn"
>
<div className="fetched-header">
<h1>Welcome {this.state.name}.</h1>
</div>
</Animated>
<Animated
isVisible={true}
animationInDelay="2000"
animationIn="fadeIn"
>
<div className="profile">
<a
href={this.state.profileUrl}
target="_blank"
rel="noreferrer"
>
<img
className="profile-image"
src={this.state.profileImage}
alt="profile"
></img>
</a>
</div>
<hr></hr>
</Animated>
<Animated
isVisible={true}
animationInDelay="3000"
animationIn="fadeIn"
>
<h2>Playlists</h2>
<div className="playlists">
{this.state.items.map((item) => {
return (
<div>
<img src={item.images[0].url} alt={item.name}></img>
<p className="playlists-text">{item.name}</p>
</div>
);
})}
</div>
</Animated>
<Animated
isVisible={true}
animationInDelay="3000"
animationIn="fadeIn"
>
<div className="playlists-check">
<Dropdown
style={style}
className="dropdown"
id="dropdown-button-drop-down"
title="Dropdown button"
>
<Dropdown.Toggle
variant="success"
id="dropdown-basic"
className="dropdown-toggle"
>
{this.state.value}
</Dropdown.Toggle>
<Dropdown.Menu className="dropdown-menu">
{this.state.items.map((item) => {
return (
<Dropdown.Item
name={item.name}
eventKey={item.id}
className="dropdown-item"
onClick={this.handleChange}
>
{item.name}
</Dropdown.Item>
);
})}
</Dropdown.Menu>
</Dropdown>
<br></br>
<br></br>
</div>
</Animated>
</div>
) : (
<Tracks
value={this.state.value}
items={this.state.items}
token={this.state.token}
/>
)}
</div>
);
}
}
export default Successful;
|
const path = require('path'),
glob = require('glob'),
CleanWebpackPlugin = require('clean-webpack-plugin'),
UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin'),
CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin')
const dir = {
build : (...files) => path.join(__dirname, './.build', ...files),
src : (...files) => path.join(__dirname, './src', ...files),
test : (...files) => path.join(__dirname, './test', ...files),
node : (...files) => path.join(__dirname, './node_modules', ...files)
}
module.exports = {
bail: true,
devtool: 'inline-source-map',
entry: {
suite: dir.test('suite.js'),
source: glob.sync(dir.src('**/*.@(ts|js)'), { ignore: '**/*.@(spec|d).*' })
},
output: {
path: dir.build(),
filename: '[name].js',
// devtoolModuleFilenameTemplate: '[absolute-resource-path]',
// devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]',
},
externals: {
mocha: 'Mocha'
},
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|ts)$/,
loader: 'tslint-loader',
include: [dir.src()]
},
{
test: /\.(js|ts)$/,
loader: 'ts-loader?' + JSON.stringify({ entryFileIsJs: true }),
include: [dir.src()],
}
]
},
plugins: [
// failPlugin,
new CleanWebpackPlugin([dir.build()], { verbose: true, dry: false }),
// new UglifyJsPlugin({ sourceMap: true }),
new CommonsChunkPlugin({ name: 'vendor', minChunks: ({resource}) => !resource || resource.startsWith(dir.node()) }),
new CommonsChunkPlugin({ name: 'source', chunks: ['source', 'suite'] })
],
resolve: {
modules: ['node_modules', dir.src()],
extensions: ['.js', '.ts']
},
// tslint: {
// // tslint errors are displayed by default as warnings
// // set emitErrors to true to display them as errors
// emitErrors: false
// }
}
|
import { pushRelations } from "@/helpers/pushRelations";
export const restructureData = arr => {
return arr[0].reduce((acc, cur) => {
//Check if location matches another entries' location, return the index
const itemIndex = acc.findIndex(item => console.log(item.people));
// Check if index exists
if(itemIndex === -1) {
// Add capacity/chargingpointcapacity to this object
acc['people'] = [];
acc['departments'] = [];
acc['addresses'] = [];
}
cur[0].forEach(entry => {
let collection;
let correctType= null;
if(entry.AttributeCollection) {
collection = entry.AttributeCollection;
// Change structure of object when theres only one or no item.
if(!collection.length || collection.length === 1) {
collection = []
collection.push(entry.AttributeCollection.Attribute)
}
}
collection.forEach(attribute => {
if(attribute.AttributeClassReference === "iCOV_node_type"){
if (attribute.Value === "PEOPLE") {
correctType = {
id: null, // = [anb.xml] _ID
node_id: null, // = [anb.xml] iCOV_node_id
name: null, // = [anb.xml] _LABEL
sex: null, // = [anb.xml] _SEX
date_of_birth: null, // = [anb.xml] _DATE_OF_BIRTH
date_of_death: null, // = [anb.xml] _DATE_OF_DEATH, if null = not dead.
position: null, // = [anb.xml] iCOV_node_subtype
department_id: null, // = [anb.xml] _DEPARTMENT_ID
school_history: [],
relations: []
};
} else if (attribute.Value === "DEPARTMENT") {
correctType = {
id: null, // = [anb.xml] _DEPARTMENT_ID
node_id: null, // = [anb.xml] iCOV_node_id
name: null, // = [anb.xml] _DEPARTMENT_NAME
managerID: null, // = [anb.xml] _MANAGER_ID
locationID: null,
relations: []
};
} else if (attribute.Value === "ADDRESS") {
correctType = {
node_id: null, // = [anb.xml] iCOV_node_id
country: null, // = [anb.xml] _COUNTRY
city: null, // = [anb.xml] _CITY
street_address: null, // = [anb.xml] _STREET_ADDRESS
postal_code: null, // = [anb.xml] _POSTAL_CODE
from_date: null, // = [anb.xml] _FROM_DATE
to_date: null, // = [anb.xml] _TO_DATE
relations: []
};
}
}
})
// Check if there is an address, person or company
if (correctType) {
// check for unique property position from a person to check if its a person.
if (correctType.position === null) {
let collection = entry.AttributeCollection;
collection.forEach(attribute => {
// Assign the values to the object. Turn string numbers into real numbers.
switch (attribute.AttributeClassReference) {
case '_ID': correctType.id = parseInt(attribute.Value)
break;
case '_DATE_OF_BIRTH': correctType.date_of_birth = attribute.Value
break;
case '_DATE_OF_DEATH': correctType.date_of_death = attribute.Value
break;
case 'iCOV_node_id': correctType.node_id = parseInt(attribute.Value)
break;
case 'iCOV_node_subtype': correctType.position = attribute.Value
break;
case '_LABEL': correctType.name = attribute.Value
break;
case '_DEPARTMENT_ID': correctType.department_id = parseInt(attribute.Value)
break;
case '_SEX': correctType.sex = attribute.Value
break
}
})
// Add new person to people array
acc.people.push(correctType);
// Clear the type so a new entry can use it.
correctType = null;
}
// check for unique property managerID from a department to check if its a department.
else if (correctType.managerID === null) {
let collection = entry.AttributeCollection;
collection.forEach(attribute => {
// Assign the values to the object. Turn string numbers into real numbers.
switch (attribute.AttributeClassReference) {
case '_DEPARTMENT_ID': correctType.id = parseInt(attribute.Value)
break;
case 'iCOV_node_id': correctType.node_id = parseInt(attribute.Value)
break;
case '_MANAGER_ID': correctType.managerID = parseInt(attribute.Value)
break;
case '_DEPARTMENT_NAME': correctType.name = attribute.Value
break;
case '_LOCATION_ID': correctType.locationID = parseInt(attribute.Value)
break;
}
})
// Add the department to the departments array.
acc.departments.push(correctType);
// Clear the type so a new entry can use it.
correctType = null;
}
// check for unique property city from a address to check if its a address.
else if (correctType.city === null) {
let collection = entry.AttributeCollection;
collection.forEach(attribute => {
// Assign the values to the object. Turn string numbers into real numbers.
switch (attribute.AttributeClassReference) {
case '_DEPARTMENT_ID': correctType.id = parseInt(attribute.Value)
break;
case 'iCOV_node_id': correctType.node_id = parseInt(attribute.Value)
break;
case '_COUNTRY': correctType.country = attribute.Value
break;
case '_CITY': correctType.city = attribute.Value
break;
case '_STREET_ADDRESS': correctType.street_address = attribute.Value
break;
case '_POSTAL_CODE': correctType.postal_code = attribute.Value
break;
case '_TO_DATE': correctType.to_date = attribute.Value
break;
case '_FROM_DATE': correctType.from_date = attribute.Value
break;
}
})
// Add the address to the addresses array.
acc.addresses.push(correctType);
// Clear the type so a new entry can use it.
correctType = null;
}
}
})
// Add relations to each type
arr[1][0][0].forEach(relation => {
let relationEdges = relation.EdgesInSet[0]
// If theres only one relationship, change the path
if(!relationEdges) {
relationEdges = relation.EdgesInSet.Edge;
}
pushRelations(acc.people, parseInt(relationEdges.FromNodeSID), parseInt(relationEdges.ToNodeSID), relationEdges.EdgeCategory);
pushRelations(acc.departments, parseInt(relationEdges.FromNodeSID), parseInt(relationEdges.ToNodeSID), relationEdges.EdgeCategory);
pushRelations(acc.addresses, parseInt(relationEdges.FromNodeSID), parseInt(relationEdges.ToNodeSID), relationEdges.EdgeCategory);
});
return acc;
}, []);
};
|
"use strict";
angular.module('environment', [])
.constant('ENV', {name:'production',apiEndPoint:'https://diinner.herokuapp.com/ionic',stripePublishableKey:'pk_test_aVle0kDCMX2iyIfuEvHoYcfq',auth0ClientID:'BBLhUOEcSMo60RljToZKPWzNClPnAOPl',auth0Domain:'app35743745.eu.auth0.com'})
; |
import {createStore, applyMiddleware , compose} from "redux"
import rootReducer from "../reducers/index"
import {forbiddenWordsMiddleware} from "../middleware/index"
import thunk from "redux-thunk"
const storeEnhancers=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store=createStore(rootReducer,storeEnhancers(applyMiddleware(forbiddenWordsMiddleware,thunk)))
export default store
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* @OriginAccordion
* @author Mark Cotton
* @version 0.1
*/
'use strict';
/**
* @
* Origin Accordion
*
* @class
* @param {object} An object containing the element to bind the accordion to
* @param {Options}
*
* TODO
* Revise so there can be multiple accordions on a page
* Split into functions
* Callback
*/
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Accordion = function () {
/**
* Constructor
*
* TODO
* Allow options to be passed
*/
function Accordion(accordionInstance) {
var openSingle = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
_classCallCheck(this, Accordion);
// Accordion elements
this.accordionInstance = accordionInstance;
this.accordionControls = accordionInstance.querySelectorAll('[data-control]');
this.accordionContents = accordionInstance.querySelectorAll('[data-content]');
// Options
this.openSingle = openSingle;
// Init function - Check if this is the correct approach
this.setup();
this.toggle();
}
/**
* Adds the relevant classes to set up accordion
*
* @param
*/
_createClass(Accordion, [{
key: 'setup',
value: function setup() {
// Add classes
this.accordionInstance.classList.add('origin__accordion');
this.accordionControls.addClass('origin__accordion__section');
this.accordionContents.addClass('origin__accordion__content');
// Open first panel
this.accordionControls[0].classList.add('origin__accordion__section--active');
this.accordionContents[0].classList.add('origin__accordion__content--active');
}
/**
* Toggles sections open / close state
*
* TODO:
*/
// Methods
}, {
key: 'toggle',
value: function toggle() {
var _this = this;
// Set current tab
var currentTab = this.accordionControls[0];
console.dir(this.accordionControls);
console.dir(this.accordionControls);
console.dir(this.accordionContents);
Array.prototype.forEach.call(this.accordionControls, function (el, i) {
el.addEventListener('click', function (event) {
// Check if tab is currently open
var selectedTab = event.target.getAttribute('data-control');
// Close any currently open tabs
Array.prototype.forEach.call(_this.accordionControls, function (el, i) {
el.classList.remove('origin__accordion__section--active');
});
Array.prototype.forEach.call(_this.accordionContents, function (el, i) {
el.classList.remove('origin__accordion__content--active');
});
if (selectedTab != currentTab) {
// Open new tab
_this.accordionInstance.querySelectorAll('[data-control="' + selectedTab + '"]')[0].classList.add('origin__accordion__section--active');
_this.accordionInstance.querySelectorAll('[data-content="' + selectedTab + '"]')[0].classList.add('origin__accordion__content--active');
currentTab = selectedTab;
} else {
currentTab = '';
}
});
});
}
/**
* Destorys the instance of the accordion
*
* TODO:
* Write the function
*/
}, {
key: 'destroy',
value: function destroy() {
console.log('Destoryed');
}
}]);
return Accordion;
}();
exports.default = Accordion;
},{}],2:[function(require,module,exports){
'use strict';
var _originAccordion = require('./origin-accordion.js');
var _originAccordion2 = _interopRequireDefault(_originAccordion);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
document.addEventListener('DOMContentLoaded', function () {
var accordionFaqSelector = document.querySelectorAll('[data-accordion="faq"]')[0];
var accordionFaq = new _originAccordion2.default(accordionFaqSelector);
var accordionNotFaqSelector = document.querySelectorAll('[data-accordion="notfaq"]')[0];
var accodionNotFaq = new _originAccordion2.default(accordionNotFaqSelector);
});
},{"./origin-accordion.js":1}]},{},[2]);
|
export default function ContentSectionRowItem({ rowItem }) {
const { image, title, description } = rowItem;
return (
<div className="item team">
<img alt="" className="image" src={image} />
{title && <div className="component-title title">{title}</div>}
<div className="description">{description}</div>
</div>
);
}
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// 引入 redux
import { Provider } from 'react-redux';
import store from './store'
import { BrowserRouter } from 'react-router-dom'
import Search from './components/Search';
import Nav from './components/Nav';
import Main from './components/Main';
class App extends Component {
render() {
return (
<Provider store={store}>
<BrowserRouter>
<div className="App">
{/* <div class="loading" v-if="isLoading">
<div class="looping-rhombuses-spinner">
<div class="rhombus"></div>
<div class="rhombus"></div>
<div class="rhombus"></div>
</div>
</div> */}
<header class="header">
<div class="container">
<div class="logo"><a href="./">Travel Fun</a></div>
<Search />
<Nav />
</div>
</header>
<Main />
<footer class="footer">
<p class="footer-text">React Practice by Tiffany </p><a class="footer-link" href="" target="_blank"><i class="icon ion-logo-github"></i></a><a class="footer-link" href="" target="_blank"><i class="icon ion-logo-codepen"></i></a>
</footer>
</div>
</BrowserRouter>
</Provider>
)}
}
export default App;
|
export default class Job {
constructor(data) {
console.log('job formed')
this._id = data._id
this.company = data.company
this.jobTitle = data.jobTitle
this.hours = data.hours
this.rate = data.rate
this.description = data.description
}
get Template() {
return `
<div class="col-4 card">
<div class="card-body">
<h1 class"card-title">${this.jobTitle}</h1>
<h3 class="card-text">Company:${this.company}</h3>
<h3 class="card-text">Hours:${this.hours}</h3>
<h3 class="card-text">Rate:${this.rate}</h3>
<h3 class="card-text">Description:${this.description}</h3>
<button class="btn btn-danger" onclick = "app.controllers.jobCtrl.deleteJob('${this._id}')"> Delete Job</button >
</div >
</div >
</div >
`
}
}
|
import styled from '@emotion/styled/macro'
const Container = styled.div`
border: 2px solid white;
border-radius: 10px;
margin: 1rem;
width: 100%;
`
export default Container
|
var config = require('./config.json');// configuración de Postgres
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('client-sessions');
var app = express(); //Express
var massive = require("massive");// PostgreSQL
var connectionString = "postgres://"+config.postgres.user+":"+config.postgres.password+"@"+config.postgres.host+"/"+config.postgres.db;
var massiveInstance = massive.connectSync({connectionString : connectionString}); //Conexión con postgresSql
var db; // variable que servira para almacenar un objeto de la base de datos
var empleadoModel = require('./models/empleado');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
cookieName: 'session',
secret: 'shhhhhh',
duration: 30 * 60 * 1000*10,
activeDuration: 5 * 60 * 1000*10,
}));
app.get('/', function(req, res, next) {
res.render('index');
});
app.post('/login', function(req,res){
empleadoModel.buscarEmpleado(req.body.RFC, function(empleado){
if(empleado[0]){
req.session.user = empleado[0];
res.render('dashboard',{user: req.session.user});
}
else{
res.render('index', {mensaje:"Lo siento, el RFC ingresado no existe"});
}
});
});
app.get('/logout', function(req, res){
// Destruye la sesión del usuario y redirige al inicio de sesion
req.session.reset();
res.redirect('/');
});
//Rutas
var users = require('./routes/users');
var empleados = require('./routes/empleado');
var productos = require('./routes/productos');
var proveedor = require('./routes/proveedor');
var admin = require('./routes/admin');
var empleadosAngular = require('./angular-resources/empleados');
var productosAngular = require('./angular-resources/productos');
var proveedoresAngular = require('./angular-resources/proveedores');
var adminAngular = require('./angular-resources/admin');
app.use('/users', users);
app.use('/empleado', empleados);
app.use('/producto', productos);
app.use('/proveedor', proveedor);
app.use('/admin', admin);
app.use('/angular/admin', adminAngular);
app.use('/angular/empleado', empleadosAngular);
app.use('/angular/producto', productosAngular);
app.use('/angular/proveedor', proveedoresAngular);
/**
* 404 Error Handler
*/
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use( function(req, res, next) {
var err = req.session.error;
var msg = req.session.success;
delete req.session.error;
delete req.session.success;
res.locals.message = '';
if (err)
res.locals.message = '<p class="msg error">' + err + '</p>';
if (msg)
res.locals.message = '<p class="msg success">' + msg + '</p>';
next();
});
//Función para restringir el acceso
function restrict(req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/');
}
}
/**
* Dev Error Handler
* will Print StackTrace
*/
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
/**
* Prod Error Handler
* no StackTrace
*/
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// 500 Error handler
/*var handleError = function(res) {
return function(err){
console.log(err)
res.send(500,{error: err.message});
}
}*/
app.set('db', massiveInstance);
module.exports = app;
|
let nodemailer = require("nodemailer");
let htmlToText = require("html-to-text");
let {
welcomeTemplate,
passwordResetTemplate,
} = require("../utils/emailTemplates");
module.exports = class Email {
constructor(user, url) {
(this.to = user.email), (this.firstName = user.name.split(" ")[0]);
this.url = url;
this.from = "Natours <hello@natours.io>";
}
createTransport() {
if (process.env.NODE_ENV === "production") {
return nodemailer.createTransport({
host: process.env.EMAIL_HOST_PROD,
port: process.env.EMAIL_PORT_PROD,
auth: {
user: process.env.EMAIL_USERNAME_PROD,
pass: process.env.EMAIL_PASSWORD_PROD,
},
});
}
return nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: process.env.EMAIL_PORT,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
}
async send(template, subject) {
let emailOptions = {
from: this.from,
to: this.to,
subject: subject,
html: template,
text: htmlToText.htmlToText(template),
};
await this.createTransport().sendMail(emailOptions);
}
async sendWelcome() {
await this.send(
welcomeTemplate(this.firstName, this.url),
"welcome to the Natours family"
);
}
async sendPasswordResetEmail() {
await this.send(
passwordResetTemplate(this.firstName, this.url),
"Password Reset"
);
}
};
|
var eventInputBinding = new Shiny.InputBinding();
$.extend(eventInputBinding, {
find: function(scope) {
return $(scope).find(".shinysky-eventinput");
},
getValue: function(el) {
var elem = $(el)
console.log(elem)
return {
event: elem.data("shinysky-last-event"),
event_count: elem.data("shinysky-event-count")
//,tot_event_count: elem.data("shinysky-tot-event-count")
}
},
subscribe: function(el, callback) {
//figure out the events being monitored
var elem = $(el)
var events = elem.data("shinysky-monitored-events").split(" ") //e.g. ["click", "dblclick", "hover"]
events.map(function(x) {
elem.on(x + ".shinysky-eventinput", function(e) {
// some code here to change the tags
elem.data("shinysky-last-event", x)
elem.data("shinysky-event-count", parseInt(elem.data("shinysky-event-count")) + 1)
callback();
});
})
},
unsubscribe: function(el) {
$(el).off(".shinysky-eventinput");
}
});
Shiny.inputBindings.register(eventInputBinding); |
const LRU = require("lru-cache");
let cachePage = new LRU({
max: 100, // 缓存队列长度
maxAge: 1000 * 60, // 缓存1分钟
});
export default function (req, res, next) {
let url = req._parsedOriginalUrl;
let pathname = url.pathname;
console.log("%c huan", "color:green;font-weight:bold");
console.log(JSON.stringify());
// 通过路由判断,只有首页才进行缓存
if (["/home"].indexOf(pathname) > -1) {
const existsHtml = cachePage.get("homeData");
if (existsHtml) {
console.log("%c 缓存生效", "color:green;font-weight:bold");
return res.end(existsHtml.html, "utf-8");
} else {
res.original_end = res.end;
// 重写res.end
res.end = function (data) {
if (res.statusCode === 200) {
// 设置缓存
cachePage.set("homeData", { html: data });
}
// 最终返回结果
res.original_end(data, "utf-8");
};
}
}
next();
}
|
const pagarme = require('pagarme')
var fs = require('fs')
function createSubscription(subscriptionData,customerData,addressData){
return new Promise(function (resolve,reject){
var credentials = JSON.parse(fs.readFileSync('./storage/env.json','utf8'));
var data = {};
console.log(subscriptionData.plan_id)
pagarme.client.connect({ api_key: credentials.api_key })
.then(client => client.subscriptions.create({
payment_method: subscriptionData.payment_method,
card_hash: subscriptionData.card_hash,
customer: customerData,
plan_id: subscriptionData.plan_id,
address: addressData
}))
.then(subscription => {
console.log(JSON.stringify(subscription));
data = {
statusCode: 200,
msg: 'Sua assinatura foi criada com sucesso',
payment_method: subscription.payment_method
}
console.log(data);
resolve(data);
})
.catch(error => {
console.log(JSON.stringify(error))
data = {
statusCode: 400,
msg: error.response.errors
}
resolve(data);
})
});
}
module.exports = {
createSubscription
} |
export {ErrorMessage} from './error.message'
export {PendingMessage} from './pending.messages' |
import React, { useState } from 'react';
import { SafeAreaView, Text, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import {Input} from 'react-native-elements';
import firestore from '@react-native-firebase/firestore';
const InputBuku = ({navigation}) => {
const inputTitle = React.createRef();
const inputDesc = React.createRef();
const inputAuthor = React.createRef();
const [judul, setJudul] = useState();
const [penulis, setPenulis] = useState();
const [deskripsi, setDeskripsi] = useState();
const onChangeJudul = (judul) => {
setJudul(judul);
};
const onChangePenulis = (penulis) => {
setPenulis(penulis);
};
const onChangeDeskripsi = (deskripsi) => {
setDeskripsi(deskripsi);
};
const handleAddBook = () => {
firestore()
.collection('books')
.add({
title: judul,
author: penulis,
description: deskripsi,
})
.then(function (docRef) {
console.log('Document written with ID: ', docRef.id);
inputTitle.current.clear();
inputDesc.current.clear();
inputAuthor.current.clear();
alert('Book successfully added');
navigation.navigate('ListBuku');
})
.catch(function (error) {
console.error('Error adding document: ', error);
alert(error);
});
// console.log(`judulnya adalah ${boardTitle} | Description : ${boardDesc} | Author : ${boardAuthor}`);
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.createTitle}>Input Data Buku</Text>
<Input
placeholder="Judul"
ref={inputTitle}
onChangeText={(judul) => onChangeJudul(judul)}
rightIcon={
<Icon
name='adn'
size={24}
color='black'
/>
}
/>
<Input
placeholder="Penulis"
ref={inputAuthor}
onChangeText={(penulis) => onChangePenulis(penulis)}
rightIcon={
<Icon
name='user-circle'
size={24}
color='black'
/>
}
// onChangeText={(email) => onChangeEmail(email)}
/>
<Input
placeholder="Deskripsi"
ref={inputDesc}
onChangeText={(deskripsi) => onChangeDeskripsi(deskripsi)}
rightIcon={
<Icon
name='book'
size={24}
color='black'
/>
}
// onChangeText={(email) => onChangeEmail(email)}
/>
<TouchableOpacity style={styles.button} onPress={handleAddBook}>
<Text>
<Icon
name='save'
size={24}
color='black'
/> Simpan</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
display: 'flex',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
alignItems: 'center',
backgroundColor: '#00a4e4',
width: '50%',
padding: 10,
},
createTitle: {
alignItems: 'center',
marginBottom : 10,
fontWeight: "bold",
padding: 10,
},
});
export default InputBuku; |
//take action whenever a quantity input changes
var numInputs = $(".mid_col input[type=number]");
numInputs.change(handleQuantityUpdate);
numInputs.keyup(handleQuantityUpdate);
function handleQuantityUpdate() {
if (this.value == "" || this.value.indexOf('.') > -1)
this.value = ""; //Chrome/FF have "" if the field contains nonnumerics
var i = 0;
while (i < this.value.length && this.value[i] == '0')
i++;
//trim leading zeros, except if the whole thing is zeros
if (i > 0 && i != this.value.length)
this.value = this.value.substring(i, this.value.length);
//tells the cart manager to update a specific item by its ID and type
var quantityInput = this;
var newQuantity = $(quantityInput).closest('input').val();
$.ajax({
url: "/assets/php/ajax/cartManager.php",
type: "post",
data: {
action: "changeQuantity",
table: $(quantityInput).closest("table").attr('id'), //determine if supply or bees
element: $(quantityInput).attr('name'), //get supply item ID, or bee item string
newQuantity: newQuantity
}
})
.done(function(retVal) {
if (retVal == "Success") {
if (newQuantity == 0)
removeItem(quantityInput); //visually remove the item)
updateTotal(); //refresh the total calculation via AJAX
updateSidebarCartPreview(); //update the sidebar cart preview
}
else if (retVal == "Failure") {
console.log(retVal);
}
else {
console.log(retVal);
}
})
.fail(function(info, status) {
alert("Sorry, an issue was encountered, specifically, " + info.statusText);
});
}
//handles the clicking of the trash icon
$("input.trash").click(function() {
var button = this;
//tells the cart manager to delete a specific item by its ID and type
$.ajax({
url: "/assets/php/ajax/cartManager.php",
type: "post",
data: {
action: "deleteItem",
table: $(button).closest("table").attr('id'), //determine if supply or bees
element: $(button).attr('name') //get supply item ID, or bee item string
}
})
.done(function(retVal) {
if (retVal == "Success") {
removeItem(button); //visually remove the item
updateTotal(); //refresh the total calculation via AJAX
updateSidebarCartPreview(); //update the sidebar cart preview
}
else if (retVal == "Failure") {
console.log(retVal);
}
else {
console.log(retVal);
}
})
.fail(function(info, status) {
alert("Sorry, an issue was encountered, specifically, " + info.statusText);
});
});
function removeItem(source) {
table = $(source).closest("table");
row = $(source).closest("tr");
//remove item's row
row.hide(300, function() {
row.remove();
//remove table if it has no elements besides header
if (table.find('tr').length == 1) {
table.hide(500, function() {
table.remove();
});
}
});
}
function updateTotal() { //updates the cart editor's cart total
$.ajax({
url: "/assets/php/ajax/cartEditorView.php",
type: "get",
data: {
action: "getTotal"
}
})
.done(function(retVal) {
if (retVal.indexOf("$0.00") > -1) //if total is zero
window.location = "/stevesbees_home.php"; //go back
else
$("#cartEditorView .total").prop('outerHTML', retVal); //update total
})
.fail(function(info, status) {
alert("Sorry, an issue was encountered, specifically, " + info.statusText);
});
}
|
'use strict';
var Knex = require('knex');
var knexnest = require('../knexnest');
// to use postgres, the pg npm module must be installed
var knex = Knex({
client: 'postgres',
connection: process.env.DATABASE_URL
});
var testData = ''
+ 'CREATE TEMPORARY TABLE temp_user ('
+ ' id INTEGER PRIMARY KEY,'
+ ' name VARCHAR(100) NOT NULL'
+ ');'
+ 'CREATE TEMPORARY TABLE temp_product ('
+ ' id INTEGER PRIMARY KEY,'
+ ' title VARCHAR(100) NOT NULL'
+ ');'
+ 'CREATE TEMPORARY TABLE temp_user_product ('
+ ' id INTEGER PRIMARY KEY,'
+ ' user_id INTEGER NOT NULL,'
+ ' product_id INTEGER NOT NULL'
+ ');'
+ 'INSERT INTO temp_user (id, name) VALUES'
+ ' (1, \'Olga Chavez\'),'
+ ' (2, \'Carol Pierce\')'
+ ';'
+ 'INSERT INTO temp_product (id, title) VALUES'
+ ' (1, \'Orange Fresh Wrap\'),'
+ ' (2, \'Water Wetner\'),'
+ ' (3, \'Mug Mitten\')'
+ ';'
+ 'INSERT INTO temp_user_product (id, user_id, product_id) VALUES'
+ ' (1, 1, 1),'
+ ' (2, 1, 2),'
+ ' (3, 1, 3),'
+ ' (4, 2, 2),'
+ ' (5, 2, 3)'
+ ';'
;
knex.raw(testData)
// NOTHING COMPLICATED, SHOULD WORK ACROSS EVERYTHING
.then(function () {
var sql = knex
.select(
'u.id AS _id',
'u.name AS _name',
'p.id AS _has__id',
'p.title AS _has__title'
)
.from('temp_user AS u')
.innerJoin('temp_user_product AS up', 'u.id', 'up.user_id')
.innerJoin('temp_product AS p', 'p.id', 'up.product_id')
;
return knexnest(sql);
})
.then(function (data) {
var expected = [
{
id: 1,
name: 'Olga Chavez',
has: [
{id: 1, title: 'Orange Fresh Wrap'},
{id: 2, title: 'Water Wetner'},
{id: 3, title: 'Mug Mitten'}
]
},
{
id: 2,
name: 'Carol Pierce',
has: [
{id: 2, title: 'Water Wetner'},
{id: 3, title: 'Mug Mitten'}
]
}
];
var strExpected = JSON.stringify(expected, null, ' ');
var strData = JSON.stringify(data, null, ' ');
if (strData !== strExpected) {
throw Error('Expected\n' + strExpected + '\n to equal result of\n' + strData);
}
})
// LONG NAMES THAT WOULD GIVE POSTGRES PROBLEMS IF NOT CORRECTED BY KNEXNEST
.then(function () {
var sql = knex
.select(
'u.id AS _id',
'u.name AS _aReallyReallyReallyReallyReallyReallyReallyReallyReallyLongProperty',
'p.id AS _has__id',
'p.title AS _has__aReallyReallyReallyReallyReallyReallyReallyReallyLongProperty',
knex.raw('p.title AS "_has__aReallyReallyReallyReallyReallyReallyReallyLongQuotedProperty"'),
knex.raw('p.title AS "_has__aReallyReallyReallyReallyReallyReallyReallyLongUnquotedProperty"')
)
.from('temp_user AS u')
.innerJoin('temp_user_product AS up', 'u.id', 'up.user_id')
.innerJoin('temp_product AS p', 'p.id', 'up.product_id')
.where('u.id', 1)
.andWhere('p.id', 1)
;
return knexnest(sql);
})
.then(function (data) {
var expected = [
{
id: 1,
aReallyReallyReallyReallyReallyReallyReallyReallyReallyLongProperty: 'Olga Chavez',
has: [
{
id: 1,
aReallyReallyReallyReallyReallyReallyReallyReallyLongProperty: 'Orange Fresh Wrap',
aReallyReallyReallyReallyReallyReallyReallyLongQuotedProperty: 'Orange Fresh Wrap',
aReallyReallyReallyReallyReallyReallyReallyLongUnquotedProperty: 'Orange Fresh Wrap'
},
]
}
];
var strExpected = JSON.stringify(expected, null, ' ');
var strData = JSON.stringify(data, null, ' ');
if (strData !== strExpected) {
throw Error('Expected\n' + strExpected + '\n to equal result of\n' + strData);
}
})
.then(function () {
console.log('Success');
})
// ERROR OUTPUT AND CLEAN UP
.catch(function (error) {
console.error(error);
})
.then(function () {
knex.destroy();
})
;
|
const axios = require('axios');
const Portfolio = require('../model/portfolio.js');
const { APIKEY } = require('../../fmp-config.js');
const createPortfolio = (req, res) => {
const holdingsArray = req.body.holdings.map((holding) => ({
symbol: holding.symbol,
name: holding.name,
exchange: holding.exchange,
basisPrice: holding.price,
costBasis: holding.marketValue,
numberOfShares: holding.numberOfShares,
}));
const newPortfolio = new Portfolio({
name: req.body.name,
username: req.body.username,
risk: req.body.risk,
thesis: req.body.thesis,
totalCost: req.body.totalValue,
holdings: holdingsArray,
});
newPortfolio.save()
.then(() => {
res.status(201);
res.send('success');
})
.catch((err) => {
res.status(404);
res.send(err);
});
};
const requestQuote = (symbol) => new Promise((resolve, reject) => {
axios.get(`https://financialmodelingprep.com/api/v3/quote/${symbol}?apikey=${APIKEY}`)
.then((quote) => {
const quoteObj = {
price: quote.data[0].price,
dayChange: quote.data[0].change,
dayChangePct: quote.data[0].changesPercentage,
};
resolve(quoteObj);
})
.catch((err) => {
reject(err);
});
});
const formatHoldings = (holdingsArray) => {
const holdingsRequests = holdingsArray.map((holding) => new Promise((resolve, reject) => {
requestQuote(holding.symbol)
.then((quote) => {
let holdingObj = {
_id: holding._id,
symbol: holding.symbol,
name: holding.name,
exchange: holding.exchange,
basisPrice: holding.basisPrice,
costBasis: holding.costBasis,
numberOfShares: holding.numberOfShares,
quote,
};
resolve(holdingObj);
})
.catch((err) => {
reject(err);
});
}));
return holdingsRequests;
};
const formatPortfolios = (portfoliosArray) => {
const requestedPortfolios = portfoliosArray.map((portfolio) => new Promise((resolve, reject) => {
let portfolioObj = {
_id: portfolio._id,
name: portfolio.name,
username: portfolio.username,
risk: portfolio.risk,
thesis: portfolio.thesis,
totalCost: portfolio.totalCost,
createdAt: portfolio.createdAt,
};
Promise.all(formatHoldings(portfolio.holdings))
.then((formattedHoldings) => {
portfolioObj.holdings = formattedHoldings;
resolve(portfolioObj);
})
.catch((err) => {
reject(err);
});
}));
return requestedPortfolios;
};
const getPortfolios = (req, res) => {
Portfolio.find({})
.then((portfolios) => {
Promise.all(formatPortfolios(portfolios))
.then((formattedPortfolios) => {
res.status(200);
res.send(formattedPortfolios);
})
.catch((err) => {
res.status(404);
res.send(err);
});
})
.catch((err) => {
res.status(404);
res.send(err);
});
};
module.exports = {
createPortfolio,
getPortfolios,
};
|
import { useStory } from '../../dataHooks/storyHooks'
import withRouter from 'next/dist/client/with-router'
import {useState} from 'react'
import Link from 'next/link'
import {getCookie, isAuthenticated} from '../../actions/authAction'
import {removePart} from '../../actions/partAction'
import {mutate} from 'swr'
import StoryPartClassic from '../story/StoryPartClassic'
import StoryPartFoldingStory from '../story/StoryPartFoldingStory'
import StoryPartWritingPrompt from '../story/StoryPartWritingPrompt'
const PartsList = ({router}) => {
const {story, isLoading, error} = useStory(router.query.slug)
const username = story && story.postedBy.username
const [values, setValues] = useState({
removed: false
})
const {removed} = values
const token = getCookie('token')
const deleteConfirm = slug => {
let answer = window.confirm('Are you sure you want to delete this Part?')
if (answer) {
deletePart(slug)
}
}
const deletePart = slug => {
removePart(slug, token).then(data => {
if (data.error) {
console.log(data.error)
} else {
mutate(`${story.slug}`).then(r => console.log(r))
setValues({...values, removed: !removed})
}
})
}
const deletePartButton = (part) => (
isAuthenticated() && isAuthenticated().role === 1 && (
<button onClick={() => deleteConfirm(part.slug)} className="btn-small btn-danger">
Delete
</button>
)
)
const showParts = () => {
if (story) {
if (story.game_mode === 0 || (story.is_finished === true && story.game_mode === 1)) {
return story.parts.map((part, i) => {
return (
<StoryPartClassic part={part} deletePartButton={deletePartButton} iterator={i} key={i} />
)
})
} if (story.game_mode === 1) {
let partsLength = story.parts.length
return story.parts.map((part, i) => {
if (i === partsLength-1) {
return (
<StoryPartFoldingStory
part={part}
deletePartButton={deletePartButton}
iterator={i}
partsLength={partsLength}
key={i} />
)
}
})
} else if (story.game_mode === 2) {
return story.parts.map((part, i) => {
return (
<StoryPartWritingPrompt part={part} deletePartButton={deletePartButton} key={i} />
)
})
}
}
if (isLoading) {
return <p>is Loading...</p>
} else if (error) {
return <p>there is an error</p>
} else {
return <p>nope</p>
}
}
const showRemoved = () => {
if(removed) {
return <div className="alert alert-danger">Part is removed</div>
}
}
const mouseMoveHandler = (event) => {
setValues({...values, error: false, success: false, removed: ''})
}
const showUpdateButton = () => {
if (isAuthenticated() && isAuthenticated().username === username) {
return (
<div className="row flex-right">
<div className="margin-right">
<Link href={`/user/crud/${story.slug}`}>
<button className="btn btn-warning-outline">
edit Story
</button>
</Link>
</div>
</div>
)
}
}
return (
<React.Fragment>
<div onMouseMove={mouseMoveHandler} className="row">
<div className="col sm-12 padding-left-none padding-right-none">
{showParts()}
</div>
</div>
{showRemoved()}
{showUpdateButton()}
</React.Fragment>
)
}
export default withRouter(PartsList) |
/* Details
Remove all exclamation marks from the end of sentence.
Examples
remove("Hi!") === "Hi"
remove("Hi!!!") === "Hi"
remove("!Hi") === "!Hi"
remove("!Hi!") === "!Hi"
remove("Hi! Hi!") === "Hi! Hi"
remove("Hi") === "Hi"
Note
Please don't post issue about difficulty or duplicate.
End Details */
/* --- Solution --- */
function remove(s){
return s.replace(/!+$/gm,"");
}
|
module.exports = UserModel => {
const withReferences = references => {
const User = UserModel.query()
if (references) {
const extractedReferences = references.split(',')
extractedReferences.forEach(reference => User.with(reference))
}
return User
}
return {
createNewDevice: ({ response, auth, role, u_id, uuidv4 }) => {
const uuid = uuidv4()
if (role !== 'user') {
return response.status(403).send({
status: 'failed',
message: 'Access denied. only user can add devices.'
})
}
return UserModel.create({
u_id: uuid,
role: 'device',
auth_id: uuid,
owner: u_id
}).then(device => [device, auth.authenticator('api').generate(device)])
}
}
}
|
function Character(name, profession, gender, age) {
this.name = name;
this.profession = profession;
this.gender = gender;
this.age = age;
this.strength = Math.floor(Math.random() * 100) + 1;
this.hitPoints = Math.floor(Math.random() * 100) + 1;
this.printStats = function() {
console.log(`Name: ${this.name}`);
console.log(`Profession: ${this.profession}`);
console.log(`Gender: ${this.gender}`);
console.log(`Age: ${this.age}`);
console.log(`Strength: ${this.strength}`);
console.log(`Hit Points: ${this.hitPoints}`);
};
this.isAlive = () => {
if (this.hitPoints <= 0) {
console.log(`${this.name} is dead :'(`);
return false;
} else {
console.log(`${this.name} is alive!`);
console.log(`and has ${this.hitPoints}HP`);
return true;
}
}
this.attack = (opponent) => {
console.log(`Attack ${opponent.name}!`);
opponent.hitPoints -= this.strength;
}
this.levelUp = function() {
this.age += 1;
this.strength += 5;
this.hitpoints += 25;
};
}
var austin = new Character('Austin', 'Wed Dev', 'Male', 28);
var mike = new Character('Mike', 'DJ', 'Male', 43);
// calling dogs and cats makeNoise methods
austin.printStats();
console.log('..........................................');
mike.printStats();
console.log('..........................................');
austin.isAlive();
console.log('..........................................');
austin.levelUp();
console.log('..........................................');
austin.printStats();
console.log('..........................................');
while (austin.isAlive() === true && mike.isAlive() === true) {
// characters deal damage to one another
austin.attack(mike);
mike.attack(austin);
// prints stats to show changes
austin.printStats();
console.log('-------------------------------------------');
mike.printStats();
console.log('-------------------------------------------');
}
|
import React from "react";
import { connect } from "react-redux";
import { getNews } from "../../../redux/news-reducer";
import NewsPage from "./NewsPage";
import Preloader from "../../../common/preloader";
class NewsPageContainer extends React.Component {
componentDidMount() {
this.props.getNews();
this.refresh = setInterval(() => this.props.getNews(), 60000)
}
componentWillUnmiunt() {
clearInterval(this.refresh);
}
render() {
return (
<>
{this.props.isFetchingNR ? <Preloader /> : null}
<NewsPage news={this.props.news} />
</>
);
}
}
let mapStateToProps = (state) => {
return {
news: state.newsPage.news,
isFetchingNR: state.newsPage.isFetchingNR,
};
};
export default connect(mapStateToProps, { getNews })(NewsPageContainer);
|
import React, { Component } from 'react';
import './style.scss';
import logo from './logo.png';
console.log(APP_MODE);
const ipc = require('electron').ipcRenderer; //利用ipc自定义窗口的最大化,最小化,关闭,移动
class TitleBar extends Component {
constructor(props) {
super(props);
this.maxWindow = this.maxWindow.bind(this)
this.state = {
fullscreen: false
}
}
componentDidMount() {
ipc.on('window-unmaximize', () => {
this.setState({ fullscreen: false });
})
ipc.on('window-maximize', () => {
this.setState({ fullscreen: true });
})
}
//关闭窗口
closeWindow() {
ipc.send('close-app');
}
//最小化
minWindow() {
ipc.send('min-app');
}
//最大化或还原
maxWindow() {
this.setState({ fullscreen: !this.state.fullscreen });
ipc.send('max-app');
}
render() {
const { fullscreen } = this.state;
return (
<div className="justify-frame-btn-fab">
<div className="logo">
<img src={logo} />
</div>
<div className="title">Home Dashboard</div>
<div className="justifu-btn-group">
<div className="icon min" onClick={this.minWindow}>
<div className="icon-siu"></div>
</div>
<div className={fullscreen ? "icon closemax" : "icon max"} onClick={this.maxWindow}>
<div className="icon-siu"></div>
</div>
<div className="icon close" onClick={this.closeWindow}>
<div className="icon-siu"></div>
</div>
</div>
</div>
);
}
}
export default TitleBar;
|
import { expect, assert } from 'chai';
import { spy } from 'sinon';
import { matchActions, matchSubjects } from '../../src/assets/js/actions/match'
import { Subject } from 'rx';
let subjectNames = Object.keys(matchSubjects);
describe('match', () => {
it('make sure that "matchSubjects" are instances of Rx.Subject',() => {
subjectNames.forEach(x => assert.instanceOf(matchSubjects[x], Subject));
});
describe('trial', () => {
it('calls onNext from trial with argument id',() => {
let onNextSpy = spy(matchSubjects.trial, 'onNext');
let id = 'foo';
matchActions.trial({ id });
expect(onNextSpy.calledWith(id)).to.be.ok;
});
it('throws an exception if the argument id is not passed', () => {
expect(matchActions.trial.bind(null, 'foo')).to.throw(Error);
});
});
describe('start', () => {
it('calls onNext from start',() => {
let onNextSpy = spy(matchSubjects.start, 'onNext');
matchActions.start();
expect(onNextSpy).to.be.called;
});
});
describe('overtime', () => {
it('calls onNext from overtime',() => {
let onNextSpy = spy(matchSubjects.overtime, 'onNext');
matchActions.overtime();
expect(onNextSpy).to.be.called;
});
});
});
|
// test función window.controller.validateLogin
describe('Create account with email and password', () => {
it('Must return true with email and password', () => {
const email = 'test@test.com';
const password = '123456';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, true);
assert.equal(result.message, '');
});
it('Must return false with email and empty password', () => {
const email = 'test@test.com';
const password = '';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, false);
assert.equal(result.message, 'No debe dejar campos vacíos');
});
it('Must return false with empty email and password', () => {
const email = '';
const password = '12345678';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, false);
assert.equal(result.message, 'No debe dejar campos vacíos');
});
it('Must return false with empty email and empty password', () => {
const email = '';
const password = '';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, false);
assert.equal(result.message, 'No debe dejar campos vacíos');
});
it('Must return false with email and password with less than 6 characters', () => {
const email = 'test@test.com';
const password = '123';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, false);
assert.equal(result.message, 'La contraseña debe contener minimo 6 caracteres');
});
it('Must return false with non format mail', () => {
const email = 'test.com';
const password = '123';
const result = window.controller.validateLogin(email, password);
assert.equal(result.valid, false);
assert.equal(result.message, 'Debe ingresar un mail valido');
});
}); |
$(document).ready(function(e) {
listSorterInit();
initItemsButtons();
updateRowsInfo(false);
sortInit();
if ($('input[name="addnewmega"]:checked').val() == 1)
$('#is_simple_menu').hide();
else
$('.mega_menu').hide();
if ($('input[name="issimplemenu"]:checked').val() == 1)
$('#is_mega_menu').hide();
else
$('.simple_menu').hide();
if ($('#tmmegamenu_url_type').val() == 1)
$('.tmmegamenu_url_text input').show();
else
$('.tmmegamenu_url_text select').show()
$(document).on('change', '#tmmegamenu_url_type', function(){
if($(this).val() == 1)
$('.tmmegamenu_url_text select').hide(),
$('.tmmegamenu_url_text input').show()
else
$('.tmmegamenu_url_text input').hide(),
$('.tmmegamenu_url_text select').show()
});
$(document).on('change', 'input[name="addnewmega"]', function(){
if($(this).val() == 1)
$('#is_simple_menu').hide(),
$('.mega_menu').show();
else
$('#is_simple_menu').show(),
$('.mega_menu').hide();
});
$(document).on('change', 'input[name="issimplemenu"]', function(){
if($(this).val() == 1)
$('#is_mega_menu').hide(),
$('.simple_menu').show();
else
$('#is_mega_menu').show(),
$('.simple_menu').hide();
});
megamenuConstructor();
});
function initItemsButtons()
{
$('#menuOrderUp').click(function(e){
e.preventDefault();
move(true);
});
$('#menuOrderDown').click(function(e){
e.preventDefault();
move();
});
$("#simplemenu_items").closest('form').on('submit', function(e) {
$("#simplemenu_items option").prop('selected', true);
});
$("#addItem").click(add);
$("#availableItems").dblclick(add);
$("#removeItem").click(remove);
$("#simplemenu_items").dblclick(remove);
function add()
{
$(".simple_menu #availableItems option:selected").each(function(i){
var val = $(this).val();
var text = $(this).text();
text = text.replace(/(^\s*)|(\s*$)/gi,"");
if (val == "PRODUCT")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val;
val = "PRD"+val;
}
if (val == "PRODUCTINFO")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val+' (info)';
val = "PRDI"+val;
}
$(".simple_menu #simplemenu_items").append('<option value="'+val+'" selected="selected">'+text+'</option>');
});
serialize();
return false;
}
function remove()
{
$("#simplemenu_items option:selected").each(function(i){
$(this).remove();
});
serialize();
return false;
}
function serialize()
{
var options = "";
$("#simplemenu_items option").each(function(i){
options += $(this).val()+",";
});
$("#itemsInput").val(options.substr(0, options.length - 1));
}
function move(up)
{
var tomove = $('#simplemenu_items option:selected');
if (tomove.length >1)
{
alert(move_warning);
return false;
}
if (up)
tomove.prev().insertAfter(tomove);
else
tomove.next().insertBefore(tomove);
serialize();
return false;
}
}
function megamenuConstructor()
{
var megamenuContent = $('#megamenu-content');
var megamenuCol = '';
/***
Add one more row to the menu tab
***/
$(document).on('click', '#add-megamenu-row', function(){
megamenuContent.append(megamenuRowConstruct());
updateRowsInfo(true)
});
/***
Add one more col to the row of the menu tab
***/
$(document).on('click', '.add-megamenu-col', function(){
columnWidth = prompt('Select column type', 2);
if(columnWidth < 2 || columnWidth > 12)
{
alert(col_width_alert_max_text);
return;
}
parrentRow = $(this).parents('.megamenu-row').attr('id');
$(this).parents('.megamenu-row').find('.megamenu-row-content').append(megamenuColConstruct(parrentRow, columnWidth));
updateRowInfo('#'+parrentRow, true); // update row information after new col added
});
/***
Update data after any block changes
***/
$(document).on('change', '.mega_menu .megamenu-col input, .mega_menu .megamenu-col select:not([name="col-item-items"], [class="availible_items"])', function(){
updateColInfo($(this));
});
/***
Add multiple selected items to the column parameters
***/
$(document).on('click', '.add-item-to-selected', function(){
var element = $(this).parents('.megamenu-col');
element.find('.availible_items option:selected').each(function() {
var value = new Array();
if ($(this).val() == 'PRODUCT' || $(this).val() == 'PRODUCTINFO')
{
values = addProductToBlock($(this));
if (typeof(values) == 'undefined' || values.length < 1)
return;
value.push(values[0]);
value.push(values[1]);
}
else
{
value.push($(this).val());
value.push($.trim($(this).text()))
}
element.find('select[name="col-item-items"]').append('<option value="'+value[0]+'" selected="selected">'+value[1]+'</option>');
});
updateColInfo($(this));
});
/***
Add one selected item to the column parameters by doubleclick
***/
$(document).on('dblclick', 'select.availible_items option', function(){
var element = $(this).parents('.megamenu-col');
var val = $(this).val();
var text = $.trim($(this).text());
if (val == "PRODUCT")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val+' (link)';
val = "PRD"+val;
}
if (val == "PRODUCTINFO")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val+' (info)';
val = "PRDI"+val;
}
element.find('select[name="col-item-items"]').append('<option value="'+val+'" selected="selected">'+text+'</option>');
updateColInfo($(this));
});
/***
Remove multiple selected items from the column parameters
***/
$(document).on('click', '.remove-item-from-selected', function(){
var element = $(this).parents('.megamenu-col');
if (typeof(element) == 'undefined')
return;
element.find('select[name="col-item-items"] option:selected').each(function() {
element.find(this).remove();
});
updateColInfo($(this));
});
/***
Remove column button
***/
$(document).on('click', '.btn-remove-column', function(){
var column = $(this).parents('.megamenu-col');
var row = '#'+column.parents('.megamenu-row').attr('id');
column.remove();
updateRowInfo(row, true);
});
/***
Remove row button
***/
$(document).on('click', '.btn-remove-row', function(){
var row = $(this).parents('.megamenu-row');
row.remove();
updateRowsInfo(true);
});
/***
Replace all special chars by "_"
***/
$(document).on('change', 'input[name="col-item-class"]', function(){
var old_class = $(this).val();
var new_class = old_class.trim().replace(/["~!@#$%^&*\(\)_+=`{}\[\]\|\\:;'<>,.\/?"\- \t\r\n]+/g, '_');
$(this).val(new_class);
})
}
function megamenuRowConstruct()
{
html = '';
var num = [];
$('.megamenu-row').each(function() { // build array of existing rows ids
tmp_num = $(this).attr('id').split('-');
tmp_num = tmp_num[2];
num.push(tmp_num);
});
if($.isEmptyObject(num)) // check if any row already exist if not set 1
num = 1;
else // check if any row already exist if yes set max + 1
num = Math.max.apply(Math,num) + 1;
html += '<div id="megamenu-row-'+num+'" class="megamenu-row">';
html += '<div class="row">';
html += '<div class="add-column-button-container col-lg-6">';
html += '<a href="#" onclick="return false;" class="btn btn-sm btn-success add-megamenu-col">'+add_megamenu_column+'</a>';
html += '</div>';
html += '<div class="remove-row-button col-lg-6 text-right">';
html += '<a class="btn btn-sm btn-danger btn-remove-row" href="#" onclick="return false;">'+btn_remove_row_text+'</a>';
html += '</div>';
html += '</div>';
html += '<div class="megamenu-row-content row"></div>';
html += '<input type="hidden" name="row_content" />';
html += '</div>';
return html;
}
function megamenuColConstruct(parrentRow, columnWidth)
{
var html = '';
var num = [];
var parrentId = parseInt(parrentRow.replace ( /[^\d.]/g, '' ));
$('#'+parrentRow+' .megamenu-col').each(function() {
tmp_num = $(this).attr('id').split('-');
tmp_num = tmp_num[2];
num.push(tmp_num);
});
if($.isEmptyObject(num))
num = 1;
else
num = Math.max.apply(Math,num) + 1;
html +='<div id="column-'+parrentId+'-'+num+'" class="megamenu-col megamenu-col-'+num+' col-lg-'+columnWidth+'">';
html += '<div class="megamenu-col-inner">';
html += '<div class="form-group">';
html +='<label>'+col_width_label+'</label>';
html += '<select class="form-control" name="col-item-type" autocomplete="off">';
for(i=2; i<=getReminingWidth(parrentRow); i++)
{
columnWidth==i?selected='selected="selected"':selected='';
html += '<option '+selected+' value="'+i+'">col-'+i+'</option>';
}
html += '</select>';
html += '</div>';
html += '<div class="form-group">';
html +='<label>'+col_class_text+'</label>';
html += '<input class="form-control" type="text" name="col-item-class" autocomplete="off" />';
html += '<p class="help-block">'+warning_class_text+'</p>';
html += '</div>';
html += '<div class="form-group">';
html +='<label>'+col_items_text+'</label>';
html += option_list;
html += '</div>';
html += '<div class="form-group buttons-group">';
html += '<a class="add-item-to-selected btn btn-sm btn-default" href="#" onclick="return false;">'+btn_add_text+'</a>';
html += '<a class="remove-item-from-selected btn-sm btn btn-default" href="#" onclick="return false;">'+btn_remove_text+'</a>';
html += '</div>';
html += '<div class="form-group">';
html +='<label>'+col_items_selected_text+'</label>';
html += '<select multiple="multiple" style="height: 160px;" name="col-item-items" autocomplete="off"></select>';
html += '</div>';
html += '<div class="remove-block-button">';
html += '<a href="#" class="btn btn-sm btn-default btn-remove-column" onclick="return false;">'+btn_remove_column_text+'</a>';
html += '</div>';
html += '</div>';
html += '<input type="hidden" name="col_content" value="{col-'+num+'-'+columnWidth+'-()-0-[]}" />';
html += '</div>';
sortInit();
return html;
}
function updateColInfo(element)
{
var item_num = element.parents('.megamenu-col').attr('id').split('-');
item_num = item_num[2];
var col_type = element.parents('.megamenu-col').find('select[name="col-item-type"]').val();
var col_class = element.parents('.megamenu-col').find('input[name="col-item-class"]').val();
var col_content_type = 0;
var col_items = '';
var devider = '';
element.parents('.megamenu-col').find('select[name="col-item-items"] option').each(function() {
col_items += devider + $(this).val();
devider = ',';
});
updateAdminBlockWidth(element, col_type);
element.parents('.megamenu-col').find('input[name="col_content"]').val('{col-'+item_num+'-'+col_type+'-('+col_class+')-'+col_content_type+'-['+col_items+']}'); // build hidde input with parameters
updateRowInfo('#'+element.parents('.megamenu-row').attr('id'), true);
}
function updateRowInfo(row, use_ajax)
{
var data = '';
$(row+' .megamenu-col').each(function() {
data += $(this).find('input[name="col_content"]').val();
});
$(row+' input[name="row_content"]').val(data);
updateRowsInfo(use_ajax);
}
function updateRowsInfo(use_ajax)
{
var data = '';
var id_row;
var delimeter = '';
$('.megamenu-row').each(function() {
id_row = $(this).attr('id').split('-');
id_row = id_row[2];
data += delimeter+'row-'+id_row+$(this).find('input[name="row_content"]').val();
delimeter = '+';
});
$('input[name="megamenu_options"]').val(data);
if (use_ajax && $('input[name="id_tab"]').val())
{
$.ajax({
type:'POST',
url:theme_url + '&ajax',
headers: { "cache-control": "no-cache" },
dataType: 'json',
async: false,
data: {
action: 'tabupdate',
id_tab: $('input[name="id_tab"]').val(),
data: $('input[name="megamenu_options"]').val()
},
success: function(msg)
{
if (msg.error_status)
{
showErrorMessage(msg.error_status);
return;
}
showSuccessMessage(msg.success_status);
}
});
}
}
function getReminingWidth(row)
{
width = 12;
$('#'+row+' .megamenu-col').each(function() {
//alert($(this).find('select[name="col-item-type"]').val());
width = width - $(this).find('select[name="col-item-type"]').val();
});
return 12;
}
function sortInit()
{
$('#megamenu-content').sortable({
cursor: 'move',
update:function(event, ui){
updateRowsInfo(true);
}
});
$('#megamenu-content .megamenu-row-content').sortable({
cursor: 'move',
items: '> div',
connectWith: '.megamenu-row-content',
update: function(event, ui){
$(this).find('.megamenu-col').each(function(index){
index = index + 1;
id = $(this).prop('id').slice(0,-1);
$(this).prop('id', id+index);
col_data = $(this).find('input[name="col_content"]').val().split('-');
new_col_data = '';
delimiter = '';
for (i = 0; i < col_data.length; i++)
{
if (i == 1)
new_col_data += delimiter + index;
else
new_col_data += delimiter + col_data[i];
delimiter = '-';
}
$(this).find('input[name="col_content"]').val(new_col_data);
});
updateRowInfo('#'+$(this).parent().prop('id'), true);
}
});
}
function addProductToBlock(element)
{
val = element.val();
if (val == "PRODUCT")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val+' (link)';
val = "PRD"+val;
}
if (val == "PRODUCTINFO")
{
val = prompt(product_add_text);
if (val == null || val == "" || isNaN(val))
return;
text = product_id+val+' (info)';
val = "PRDI"+val;
}
return Array(val,text);
}
function updateAdminBlockWidth(col, width)
{
var columnn_width = '';
var new_class = '';
var old_class = col.parents('.megamenu-col').prop('class').split(' ');
for (i = 0; i < old_class.length; i++)
{
if (old_class[i].indexOf('col-lg') >= 0)
new_class += ' col-lg-'+width;
else
new_class += ' '+old_class[i];
}
col.parents('.megamenu-col').removeProp('class').addClass(new_class);
}
function listSorterInit()
{
$('.tablist tbody').sortable({
cursor: 'move',
items: '> tr',
update: function(event, ui){
$('.tablist tbody > tr').each(function(index){
$(this).find('.positions').text(index + 1);
});
}
}).bind('sortupdate', function() {
var orders = $(this).sortable('toArray');
$.ajax({
type: 'POST',
url: theme_url + '&ajax',
headers: { "cache-control": "no-cache" },
dataType: 'json',
data: {
action: 'updateposition',
item: orders,
},
success: function(msg)
{
if (msg.error)
{
showErrorMessage(msg.error);
return;
}
showSuccessMessage(msg.success);
}
});
});
} |
import "meteor/reactive-var";
import "meteor/session";
import "./graph_guide.html";
import "/imports/ui/components/graph_view/graph_view.js";
import "/imports/ui/components/guide_view/guide_view.js";
import {DATA_READ_ONLY} from "../../components/graph_view/graph_view";
Template.graph_guide.onCreated(function () {
let self = Template.instance();
self.showGraph = new ReactiveVar(!self.data[DATA_READ_ONLY]);
});
Template.graph_guide.helpers({
graphParams: function () {
return Template.instance().data;
},
showGraph: function () {
return Template.instance().showGraph.get();
}
});
Template.graph_guide.events({
"click #toggle_flowchart": function (evt, self) {
evt.preventDefault();
self.showGraph.set(!self.showGraph.get());
}
}); |
function alignBlocks() {
var max_height = 0;
$('.middle-side .align-content').each(function(){
if ($(this).height() > max_height) {
max_height = $(this).height()
}
})
.height(max_height);
}
$(function(){
//Cufon.replace('#company-logo h1', { fontFamily: 'Myriad Pro Bold' });
Cufon.replace('#company-logo h2', {
fontFamily: 'Myriad Pro Regular'
});
Cufon.replace('#main-navigation a', {
hover: true,
fontFamily: 'Myriad Pro Regular'
});
Cufon.replace('#header-banner h2, .big-button', {
fontFamily: 'Times New Roman'
});
Cufon.replace('.info-box h3, .info-box h4', {
fontFamily: 'Times New Roman'
});
$('.middle-side .info-box:first-child').addClass('no-delimeter')
var agent = navigator.userAgent.toLowerCase();
if((agent.indexOf('msie 6.0') == -1) && (agent.indexOf('msie 7.0') == -1)) {
$(window).load(function(){alignBlocks()})
} else {
var r = setTimeout('alignBlocks()', 3000)
}
})
|
'use strict';
const colors = require('colors');
const assert = require('assert');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let board = [];
let solution = '';
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
function printBoard() {
for (let i = 0; i < board.length; i++) {
console.log(board[i]);
}
}
function generateSolution() {
for (let i = 0; i < 4; i++) {
const randomIndex = getRandomInt(0, letters.length);
solution += letters[randomIndex];
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function generateHint(guess) {
/*
* This function checks for matches between the guess and solution
* Returns the matching letters (in Red) or letter & positions (in Green)
*
* @param: guess - the guess entered into the prompt
*
* @return: Color coded numbers
*/
let guessArray = guess.split('');
let solutionArray = solution.split('');
// Find correct letter locations
let correctLocation = 0;
let j = 0;
while(j < guessArray.length) {
if (solutionArray[j] === guessArray[j]){
correctLocation = correctLocation + 1;
}
j++;
}
// Find correct letters
let correctLetter = 0;
let i = 0;
while(i < guessArray.length) {
let guessIndex = solutionArray.indexOf(guessArray[i]);
if (guessIndex > -1) {
correctLetter = correctLetter + 1;
solutionArray[guessIndex] = null;
}
i++;
}
// Returns the color coded hint
let hint = colors.green(correctLocation) + " - " + colors.red(correctLetter);
return hint;
}
function mastermind(guess) {
/*
* This function detects if the guess matches the solution. If true, the player wins, if false it
* responds with generateHint that shows the correct postitions in the guess and ask the player to guess again.
* Also pushes the guess to the board to track.
* Should test if the guess is a string of four letters between a and h and give the player 10 turns to guess
*
* @param: guess - the inputted string of four letters
* @return: true/false
*/
// solution = 'abcd'; // Comment this out to generate a random solution
let lowerGuess = guess.toLowerCase().trim();
if (lowerGuess.length > 4){
console.log('Your guess can only be 4 letters between a - h');
} else {
if(lowerGuess === solution) {
console.log(colors.green('Correct. You win!'));
process.exit();
} else if (board.length < 10) {
let hint = generateHint(lowerGuess);
board.push(lowerGuess + ' : ' + hint);
} else if (board.length >= 10) {
console.log('You only get 10 guesses, the solution was ' + solution);
process.exit();
}
}
}
function getPrompt() {
rl.question('guess: ', (guess) => {
mastermind(guess);
printBoard();
getPrompt();
});
}
// Tests
if (typeof describe === 'function') {
solution = 'abcd';
describe('#mastermind()', () => {
it('should register a guess and generate hints', () => {
mastermind('aabb');
assert.equal(board.length, 1);
});
it('should be able to detect a win', () => {
assert.equal(mastermind(solution), 'You guessed it!');
});
});
describe('#generateHint()', () => {
it('should generate hints', () => {
let expected = ('2'.red)+"-"+('2'.white);
assert.equal(generateHint('abdc'), expected);
});
it('should generate hints if solution has duplicates', () => {
let expected = ('1'.red)+"-"+('1'.white);
assert.equal(generateHint('aabb'), expected);
});
});
} else {
generateSolution();
getPrompt();
}
|
var Bind = require('../util/Bind');
function VideoCanvas(videoDom,$videoContainer,readyCallBack){
this.drawCvs;
this.drawCtx;
this.name = name;
this.video = videoDom;
this.containerSize = {width:0,height:0};
this.canvasSize = {width:0,height:0,x:0,y:0};
this.videoSize = {width:0,height:0,aspect:0};
this.divisionCanvas = [];
this.isPlay = false;
this.isReady = false;
var _this = this;
var cts = this.containerSize,
cs = this.canvasSize;
var divisionWidth = 0;
var poster = new Image();
poster.src = this.video.getAttribute('poster');
// poster.onload = function(){};
setup = Bind(setup,this);
this.video.preload = 'auto';
this.video.addEventListener( "loadedmetadata", setup, false );
function setup(){
this.videoSize.width = this.video.videoWidth;
this.videoSize.height = this.video.videoHeight;
this.videoSize.aspect = this.videoSize.width/this.videoSize.height;
this.drawCvs = document.createElement('canvas');
this.drawCtx = this.drawCvs.getContext('2d');
$videoContainer.append(this.drawCvs);
//for test
this.drawCvs.style.position = 'absolute';
this.drawCvs.style.width = '100%';
this.drawCvs.style.height = '100%';
this.drawCvs.style.left = 0;
this.drawCvs.style.top = 0;
// for(var i=0; i<divisionNum; i++){
// var cvs = document.createElement('canvas'),
// ctx = cvs.getContext('2d');
// this.divisionCanvas[i] = {cvs:cvs,ctx:ctx,domElement:cvs};
// }
videoRender = Bind(videoRender,this);
drawVideo = Bind(drawVideo,this);
resize = Bind(resize,this);
$(window).on('resize',resize);
resize();
this.isReady = true;
if(readyCallBack)readyCallBack(this.divisionCanvas);
this.reset();
}
function resize(){
this.containerSize.width = $videoContainer.width();
this.containerSize.height = $videoContainer.height();
var condition = cts.width/this.videoSize.aspect;
if(condition < cts.height){
cs.width = cts.height*this.videoSize.aspect;
cs.height = cts.height;
}else{
cs.width = cts.width;
cs.height = condition;
}
cs.x = Math.floor((cts.width-cs.width)*0.5);
cs.y = Math.floor((cts.height-cs.height)*0.5);
this.drawCvs.width = cts.width;
this.drawCvs.height = cts.height;
console.log(this);
// divisionWidth = Math.floor(cts.width/divisionNum);
// for(var i=0; i<divisionNum; i++){
// var cvs = this.divisionCanvas[i].cvs;
// cvs.width = divisionWidth;
// cvs.height = cts.height;
// }
}
this.getCanvas = function(){
return this.divisionCanvasl;
}
var interval = 1000/30;
var then,startTime;// = Date.now();
var elapsed;
this.play = function(){
console.log("this.video", this.video);
if(!this.isReady)return;
this.video.play();
this.isPlay = true;
requestAnimationFrame(videoRender);
then = Date.now();
startTime = then;
}
this.stop = function(){
this.video.pause();
this.isPlay = false;
}
this.reset = function(){
this.video.currentTime = 0;
this.video.pause();
// drawVideo(poster);
}
function videoRender(){
if(this.isPlay){
now = Date.now();
elapsed = now - then;
if (elapsed > interval) {
then = now - (elapsed % interval);
drawVideo(this.video);
}
requestAnimationFrame(videoRender);
}
}
function drawVideo(drawTarget){
this.drawCtx.drawImage(drawTarget,cs.x,cs.y,cs.width,cs.height);
}
// setup.call(this);
return this;
};
VideoCanvas.prototype.constructor = VideoCanvas;
module.exports = VideoCanvas;
|
(function() {
'use strict';
angular
.module('jhipsterApp')
.controller('FixedDepositeAccountDeleteController',FixedDepositeAccountDeleteController);
FixedDepositeAccountDeleteController.$inject = ['$uibModalInstance', 'entity', 'FixedDepositeAccount'];
function FixedDepositeAccountDeleteController($uibModalInstance, entity, FixedDepositeAccount) {
var vm = this;
vm.fixedDepositeAccount = entity;
vm.clear = function() {
$uibModalInstance.dismiss('cancel');
};
vm.confirmDelete = function (id) {
FixedDepositeAccount.delete({id: id},
function () {
$uibModalInstance.close(true);
});
};
}
})();
|
/*
* selena
* https://github.com/enytc/selena
*
* Copyright (c) 2014 EnyTC Corporation
* Licensed under the BSD license.
*/
'use strict';
module.exports = {
/*
* GET /
*/
index: {
method: 'GET',
auth: global.requireLogin,
fn: function (req, res) {
res.status(200).render('home/index');
}
}
};
|
module.exports = {
LOGIN_PAGE_TITLE: 'Iniciar sesión en Amazon',
}
|
import React from "react";
import Logo from "../Logo";
import { MdAddShoppingCart, MdAccountCircle, MdSearch } from "react-icons/md";
import styles from "./styles.module.scss";
export default () => {
return (
<>
<nav className={styles.navbar}>
<div className={styles.container}>
<div>
<Logo className={styles.logo} />
</div>
<ul>
<li>
<a href="#" classNam={styles.selected}>
Home
</a>
</li>
<li>
<a href="#">Shop</a>
</li>
<li>
<a hef="#">Blog</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact </a>
</li>
</ul>
<div className={styles.divider}></div>
<div className={styles.socialMedia}>
<a href="#">
<MdAddShoppingCart className={styles.socialMedia} />
</a>
<a href="#">
<MdAccountCircle className={styles.socialMedia} />
</a>
<a href="#">
<MdSearch className={styles.socialMedia} />
</a>
</div>
</div>
</nav>
</>
);
};
|
import React from "react";
import VideoListItem from './video_list_item';
const VideoList = (props) => {
return <div>
<ul>
{props.videos.map(el => {
return <VideoListItem
data={el}
key={el.etag}
onVideoSelect={props.onVideoSelect}
/>
})}
</ul>
</div>
}
export default VideoList; |
import { xToken } from "../keys/monobank";
var myHeaders = new Headers();
myHeaders.append("X-Token", xToken);
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
fetch("https://api.monobank.ua/personal/client-info", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const dev = {
entry: [
'react-hot-loader/patch',
'./src/index.js',
],
output: {
path: path.resolve(__dirname, 'build/'),
filename: 'app.js',
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join('./src/', 'templates', 'index.html'),
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{loader: 'style-loader'},
{loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]'},
{loader: 'postcss-loader', options: {
plugins: () => [
require('autoprefixer')()
]
}}
]
},
{
test: /\.css$/,
exclude: path.resolve(__dirname,'./src/'),
loader: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
'file-loader?name=public/images/[name].[ext]',
],
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'file-loader?name=public/fonts/[name].[ext]'
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
pages: path.resolve(__dirname, 'src/js/pages'),
misc: path.resolve(__dirname, 'src/js/misc'),
src: path.resolve(__dirname, 'src'),
'~': path.resolve(__dirname, 'src/js')
},
},
}
const prod = {
entry: [
'react-hot-loader/patch',
'./src/index.js',
],
output: {
path: path.resolve(__dirname, 'build/'),
filename: 'app.js',
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join('./src/', 'templates', 'index.html'),
}),
new ExtractTextPlugin('style.css')
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract([
{loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]'},
{loader: 'postcss-loader', options: {
plugins: () => [
require('autoprefixer')()
]
}}
])
},
{
test: /\.css$/,
exclude: path.resolve(__dirname,'./src/'),
loader: ExtractTextPlugin.extract('css-loader')
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
'file-loader?name=public/images/[name].[ext]',
],
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'file-loader?name=public/fonts/[name].[ext]'
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
pages: path.resolve(__dirname, 'src/js/pages'),
misc: path.resolve(__dirname, 'src/js/misc'),
src: path.resolve(__dirname, 'src'),
'~': path.resolve(__dirname, 'src/js')
},
}
}
module.exports = process.env.ENV == 'production' ? prod : dev
|
const vm = new Vue({
el: '#main-app',
data() {
return {
ssh_list: [],
ssh_live_list: [],
ssh_die_list: [],
proxy_list: [],
settings: {
process_count: 20
},
temp_settings: {
process_count: 20
},
ssh_text: ''
}
}
}) |
window.eventdone = {};
window.loadAsyncScript = function(url, onLoadFunction) {
var script = document.createElement('script');
script.type = 'text/javascript';
document.body.appendChild(script);
script.onload = onLoadFunction;
script.src = url;
};
window.executeOnEventDone = function(eventName, callback) {
if (window.eventdone[eventName]) {
try {
callback();
}
catch(e) {
console.log(e);
}
}
else {
window.addEventListener(eventName, callback);
}
};
window.fireBasicEvent = function(eventName) {
if (typeof(Event) === 'function') {
var event = new Event(eventName);
}
else{
// IE compatibility
var event = document.createEvent('Event');
event.initEvent(eventName, true, true);
}
window.eventdone[eventName] = true;
window.dispatchEvent(event);
};
window.orderedListeners = {};
window.addOrderedEventListener = function(event, handler) {
if (!window.orderedListeners[event]) {
window.orderedListeners[event] = [];
window.executeOnEventDone(event, function(e) {
window.orderedListeners[event].forEach(function(handler) {
try {
handler(e);
}
catch(e) {
console.log(e);
}
});
});
}
window.orderedListeners[event].push(handler);
};
window.addEventListener('load', function() {
var scripts = document.getElementsByTagName('deferredscript');
function loadDeferredScript(i) {
if (i >= scripts.length) {
window.fireBasicEvent('beforeDeferredload');
window.fireBasicEvent('deferredload');
window.fireBasicEvent('afterDeferredload');
return;
}
var script = document.createElement('script');
script.src = scripts[i].getAttribute("src");
script.onload = script.onerror = function() {
// load next deferred script
loadDeferredScript(i + 1);
};
document.getElementsByTagName('head')[0].appendChild(script);
}
loadDeferredScript(0);
}); |
'use strict';
function CarPrototype() {
this.carName = '';
this.carColor = '';
};
var redInfernus = new CarPrototype();
redInfernus.carName = 'Infernus';
redInfernus.carColor = 'Bright red';
var blueFord = new CarPrototype();
blueFord.carName = 'Ford';
blueFord.carColor = 'Dark blue'; |
import * as actionTypes from '../actions/actionTypes';
const initialState = {
song_id:0,
audios:[],
passwordText:"Enter Password",
submitText:"Submit",
};
let reducer = function (state = initialState, action) {
switch (action.type) {
case actionTypes.UPDATEAUDIO_CONTENT:
return {
...state,
song_id:action.song_id,
audios:action.audios,
pausesong_id:action.pausesong_id,
submitText:action.submitText,
passwordText:action.passwordText
}
default:
return state;
}
};
export default reducer; |
const {model, Schema} = require("mongoose");
const tournamentSchema = new Schema({
name: String,
username: String,
restrictions: [String],
rules: [String],
active: Boolean,
participants: [{
name: String,
status: Boolean
}],
fights: [{
fighterOne: String,
fighterTwo: String,
concluded: Boolean,
winner: String
}],
round: Number,
winner: String,
user: [{
type: Schema.Types.ObjectId,
ref: "users"
}]
})
module.exports = model("Tournament", tournamentSchema); |
// Use axios for requests and set API key for every request
// Set axios default X-Riot-Token header to apikey
const axios = require('axios');
axios.defaults.headers.common['X-Riot-Token'] = require('./config.json').apiKey;
// Get a sumoner by name and returns his ID
// Takes an object with the endpoint to use and the username
module.exports.getSummonerByName = (data) => {
let promise = new Promise((resolve, reject) => {
axios.get(`https://${data.endpoint}/lol/summoner/v3/summoners/by-name/${data.username}`)
.then((user) => {
resolve({ endpoint: data.endpoint, id: user.data.accountId });
})
.catch((error) => {
reject({ error, msg: 'Unknown Username' });
});
});
return promise;
};
// Get the recent matchs of a summoner by ID
// Takes an object with an endpoint and an id property
// One referring to the endpoint in the post request the other one is the user's id
module.exports.getRecentMatchList = (data) => {
let promise = new Promise((resolve, reject) => {
axios.get(`https://${data.endpoint}/lol/match/v3/matchlists/by-account/${data.id}/recent`)
.then((matchlist) => {
resolve({ endpoint: data.endpoint, summonerID: data.id, match: matchlist.data.matches[0] });
})
.catch((rror) => {
reject({ rror, message: 'Unknown Username' });
});
});
return promise;
};
// Takes an endpoint, an accountId and a gameID and returns the participantId to unobfuscate the player.
// Also returns more precise match data
module.exports.getGamePartipantId = (data) => {
let promise = new Promise((resolve, reject) => {
axios.get(`https://${data.endpoint}/lol/match/v3/matches/${data.match ? data.match.gameId : data.gameId}?forAccountId=${data.summonerID}`)
.then((match) => {
match.data.participantIdentities.forEach((participant) => {
if (participant.player) { if (participant.player.accountId == data.summonerID) data.summoner = participant; }
});
data.summoner ? resolve({ endpoint: data.endpoint, summoner: data.summoner, match: match.data }) : reject('Summoner not found');
})
.catch((error) => {
reject(error);
});
});
return promise;
};
// Takes an endpoint, a summoner and a gameID and returns the timeline of the match
module.exports.getGameTimeline = (data) => {
let promise = new Promise((resolve, reject) => {
axios.get(`https://${data.endpoint}/lol/match/v3/timelines/by-match/${data.match.gameId}`)
.then((timeline) => {
// No need to transfer the match data anymore so just fetchs data from the player we want
// Side note : gameDuration is in seconds whereas timestamps timeline events are in ms
data.summoner.matchData = data.match.participants[data.summoner.participantId - 1];
data.summoner.matchData.duration = data.match.gameDuration;
data.summoner.matchData.gameId = data.match.gameId;
resolve({ endpoint: data.endpoint, summoner: data.summoner, timeline: timeline.data });
})
.catch((error) => {
reject(error);
});
});
return promise;
};
// Returns champion data, used for movespeed of the champion
// Takes a championID an endpoint
module.exports.getChampionData = (data) => {
let promise = new Promise((resolve, reject) => {
axios.get(`https://${data.endpoint}/lol/static-data/v3/champions/${data.summoner.matchData.championId}?locale=en_US&tags=stats`)
.then((champion) => {
data.summoner.champion = champion.data;
resolve({ summoner: data.summoner, timeline: data.timeline });
})
.catch((error) => {
reject({ error, msg: 'Static API Error' });
});
});
return promise;
};
// Takes summoner and timeline
// Fetchs the timeline of the given game to know when boots were bought
module.exports.fetchTimeline = (data) => {
let events = [];
let buy = [];
let promise = new Promise((resolve) => {
// First gather every events from the timeline and push them into an array
function fetchEvents() {
data.timeline.frames.forEach((frame, index) => {
events.push(frame.events);
if (index == data.timeline.frames.length - 1) proceedEvents();
});
}
// Recursive function :
// Then treat event lists one by one and treat every events in those lists to fetch timestamps
// Where boots are bought.
function proceedEvents() {
events.shift();
if (events[0]) {
events[0].forEach((event, index) => {
if (event) {
if (event.type === 'ITEM_PURCHASED' && event.participantId === data.summoner.participantId && Object.keys(require('./constants.js').BOOTS).includes(event.itemId.toString())) {
buy.push(event);
}
}
if (index >= events[0].length - 1) proceedEvents(events);
});
} else resolve({ summoner: data.summoner, buy });
}
fetchEvents();
});
return promise;
};
// Takes summoner + game length + buy events
// Returns the distance gained by buying boots depending on the timestamp when boots were bought
// Also uses champion data to calculate using the exact basic movespeed
module.exports.proceedData = (data) => {
let promise = new Promise((resolve) => {
// gameDuration is in seconds. Convert it to ms.
let gameDuration = 1000 * data.summoner.matchData.duration;
let firstItem = data.buy[0] ? data.buy[0] : { timestamp: gameDuration };
// Distance travelled without boots.
let withoutBoots = {
timestamp: 0,
itemId: 'champion',
stats: {
name: data.summoner.champion.name,
cost: 0,
ms: data.summoner.champion.stats.movespeed
},
timeSpent: firstItem.timestamp / 1000,
totalDistanceTravelled: data.summoner.champion.stats.movespeed * (firstItem.timestamp / 1000),
specificDistanceTravelled: data.summoner.champion.stats.movespeed * (firstItem.timestamp / 1000)
};
let stats = {
totalDistanceTravelled: withoutBoots.totalDistanceTravelled,
maxMovementSpeed: data.summoner.champion.stats.movespeed,
travelledWithBoots: 0,
gameDuration: data.summoner.matchData.duration,
};
let gameInformation = {
summonerName: data.summoner.player.summonerName,
summonerID: data.summoner.player.accountId,
gameId: data.summoner.matchData.gameId,
endpoint: require('./constants.js').REVERSE_ENDPOINTS[data.summoner.player.currentPlatformId.toUpperCase()],
shareLink: `${require('./config.json').adress}/share?gameId=${data.summoner.matchData.gameId}&summonerID=${data.summoner.player.accountId}&server=${require('./constants.js').REVERSE_ENDPOINTS[data.summoner.player.currentPlatformId.toUpperCase()]}`
};
let results = [withoutBoots];
// If cassiopeia is the last champion played
if (!data.buy[0]) {
resolve({ results, stats, gameInformation });
} else {
data.buy.forEach((buy, index) => {
if (index != data.buy.length - 1) {
// Useless data
delete buy.type;
delete buy.participantId;
// Store object's stats
buy.stats = require('./constants').BOOTS[buy.itemId];
buy.stats.totalSpeed = data.summoner.champion.stats.movespeed + require('./constants').BOOTS[buy.itemId].ms;
// Substract next boots with actual boots to get the duration of use.
// Multiply this by the actual item's ms
buy.timeSpent = (data.buy[index + 1].timestamp - buy.timestamp) / 1000;
// Distance travelled with the movespeed of the boots
buy.specificDistanceTravelled = buy.timeSpent * buy.stats.ms;
// Distance travelled with the movespeed of the boots + basic champion ms
buy.totalDistanceTravelled = buy.timeSpent * buy.stats.totalSpeed;
// Update global stats
stats.totalDistanceTravelled += buy.totalDistanceTravelled;
buy.stats.totalSpeed > stats.maxMovementSpeed ? stats.maxMovementSpeed = buy.stats.totalSpeed : stats.maxMovementSpeed += 0;
stats.travelledWithBoots += buy.specificDistanceTravelled;
results.push(buy);
} else {
// Useless data
delete buy.type;
delete buy.participantId;
// Store object's stats
buy.stats = require('./constants').BOOTS[buy.itemId];
buy.stats.totalSpeed = data.summoner.champion.stats.movespeed + require('./constants').BOOTS[buy.itemId].ms;
// As there are no next boots just substract the total duration of the game with
// last buy timestamp
buy.timeSpent = (gameDuration - buy.timestamp) / 1000;
// Distance travelled with the movespeed of the boots
buy.specificDistanceTravelled = buy.timeSpent * buy.stats.ms;
// Distance travelled with the movespeed of the boots + basic champion ms
buy.totalDistanceTravelled = buy.timeSpent * buy.stats.totalSpeed;
// Update global stats
stats.totalDistanceTravelled += buy.totalDistanceTravelled;
buy.stats.totalSpeed > stats.maxMovementSpeed ? stats.maxMovementSpeed = buy.stats.totalSpeed : stats.maxMovementSpeed += 0;
stats.travelledWithBoots += buy.specificDistanceTravelled;
results.push(buy);
resolve({ results, stats, gameInformation });
}
});
}
});
return promise;
};
// Takes an object containing results and stats.
// Used to prepare data for the share template from ejs
module.exports.renderServerSide = (res) => {
let champIconName = res.results[0].stats.name;
champIconName.includes(' ') ? champIconName = champIconName.split(' ')[0] + champIconName.split(' ')[1].toLowerCase() : champIconName = champIconName[0] + champIconName.substring(1).toLowerCase();
let minutes = new Date(res.stats.gameDuration * 1000).getHours() - 1;
(minutes > 0 && minutes < 3) ? minutes = 60: minutes = 0;
let template = {
summonerName: res.gameInformation.summonerName,
shareLink: res.gameInformation.shareLink,
championName: res.results[0].stats.name,
champIconName: `https://ddragon.leagueoflegends.com/cdn/7.14.1/img/champion/${(champIconName.includes("'") ? champIconName.split("'")[0] + champIconName.split("'")[1].toLowerCase() : champIconName)}.png`,
totalDistanceTravelled: res.stats.totalDistanceTravelled.toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
totalTeemosTravelled: (res.stats.totalDistanceTravelled / 110).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
gameDurationMinute: (minutes + new Date(res.stats.gameDuration * 1000).getMinutes()).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
gameDurationSecond: new Date(res.stats.gameDuration * 1000).getSeconds().toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
averageTravelSpeed: (((res.stats.totalDistanceTravelled / 110) / res.stats.gameDuration) * 60).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
crossedSummonersRiftTotal: (res.stats.totalDistanceTravelled / 19798).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
crossedSummonersRiftBoots: (res.stats.travelledWithBoots / 19798).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
lastBootsCost: res.results[res.results.length - 1].stats.cost.toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
extraUnitsTravelled: res.stats.travelledWithBoots.toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
extraTeemosTravelled: (res.stats.travelledWithBoots / 110).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
extraPercentageTravelled: ((res.stats.travelledWithBoots / res.stats.totalDistanceTravelled) * 100).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.'),
extraFlash: (res.stats.travelledWithBoots / 425).toLocaleString('fr-FR', { maximumFractionDigits: 2 }).replace(/,/g, '.')
};
return template;
}; |
'use strict'
let mongoose = require('mongoose')
let Schema = mongoose.Schema
let UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String
},
followedProposals: [{
type: Schema.Types.ObjectId,
ref: 'Proposal'
}],
isOrganizationAdmin: {
type: Boolean,
default: false
},
organization: {
type: Schema.Types.ObjectId,
ref: 'Organization',
default: null
},
evidences: [{
type: Schema.Types.ObjectId,
ref: 'Evidence'
}]
}, {
timestamps: true
})
module.exports = mongoose.model('User', UserSchema) |
import { routerMiddleware } from 'connected-react-router'
import { applyMiddleware, compose, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import thunkMiddleware from 'redux-thunk'
import { wsMiddleware } from '../middlewares/ws'
import createRootReducers from '../reducers'
import { SagaManager } from '../sagas'
export function configureStore (initialState = {}, history) {
/* eslint-disable no-underscore-dangle */
let composeEnhancers
if (
typeof window !== 'undefined' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ &&
// could give performance problem so we disable it production
process.env.NODE_ENV !== 'production'
) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
} else {
composeEnhancers = compose
}
/* eslint-enable */
const reducer = createRootReducers(history)
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware(
routerMiddleware(history),
thunkMiddleware,
sagaMiddleware,
wsMiddleware({
url: 'ws://localhost:8082/something'
})
)
)
)
// hot reloading
if (__DEV__ && module.hot) {
module.hot.accept('../reducers', async () => {
console.info('update reducers')
const createRootReducers = (await import('../reducers')).default
store.replaceReducer(createRootReducers(history))
})
module.hot.accept('../sagas', async () => {
console.info('update sagas')
const { SagaManager } = await import('../sagas')
SagaManager.cancelSagas(store)
SagaManager.startSagas(sagaMiddleware)
})
}
// sagaMiddleware.run(rootSaga)
SagaManager.startSagas(sagaMiddleware)
return store
}
|
import './index.scss'
import 'fullpage.js/dist/jquery.fullpage.css'
import '../common/js/common.js'
import $ from 'jquery'
import 'fullpage.js'
let JUMP_STATE = false;
let PAGE_INDEX = 0;
class Home {
constructor() {
this.speed = 200;
this.isMobile = this.checkIsMobile();
this.$menu = $('#menu');
this.$selected = $('#navSelected');
this.initialize();
}
initialize() {
this.fullPage();
this.clearHash();
this.initPage();
this.scroll((direction) => this.headerCtrl(direction));
if (!this.isMobile) {
this.addEventListener();
}
}
addEventListener() {
const self = this;
const $menu = $('.menu');
const $lis = $('.menu li');
const active = 'active';
const tag = 'tag';
$menu.find('li').hover(function(){
self.menuSelect($(this));
}, function(event) {
const $target = $lis.eq(PAGE_INDEX);
self.menuSelect($target);
}).on('click', function() {
PAGE_INDEX = $(this).index() - 1;
});
this.navigatorPage();
}
menuSelect($target) {
const offset = $target.position();
const width = $target.width();
this.$selected.animate({
left: offset.left,
width: width
}, 300);
}
isChildAndSelfOf(child, parent) {
return (child.closest(parent).length > 0);
}
initPage() {
const $navBar = $('.nav-bar');
$navBar.addClass('opaque');
$navBar.find('.logo').css('visibility', 'hidden');
}
clearHash() {
setTimeout(function(){window.scrollTo(0,0);}, 50);
}
fullPage() {
const self = this;
// const scrollHeight = document.body.scrollHeight;
// $('.fp-table, .fp-tableCell').css('height', scrollHeight);
// console.log(clientHeight);
$('#fullpage').fullpage({
autoScrolling: false,
// 不自动滚动到对应的 section
fitToSection: false,
onLeave: function(m, index) {
PAGE_INDEX = index;
const $target = $(`#menu li:eq(${index - 1})`);
const offset = $target.position();
const width = $target.width();
self.$selected.css({
left: offset.left,
width: width
});
},
afterRender: function() {
self.clearHash();
}
});
}
navigatorPage() {
const self = this;
this.$menu.on('click', 'a', function(event){
event.preventDefault();
if (!JUMP_STATE) {
JUMP_STATE = true;
} else {
return ;
}
var $target = $(this.hash);
if ($target.length) {
self.clearActives();
var targetOffset = $target.offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 600, () => {
const timeId = setTimeout(() => {
JUMP_STATE = false;
clearTimeout(timeId);
}, 100);
});
}
});
}
clearActives() {
this.$menu.find('li').removeClass('tag');
}
scroll(fn) {
var beforeScrollTop = $(window).scrollTop(),
fn = fn || function() {};
window.addEventListener("scroll", function() {
var afterScrollTop = $(window).scrollTop(),
delta = afterScrollTop - beforeScrollTop;
if( delta === 0) return false;
fn( delta > 0 ? "down" : "up" );
beforeScrollTop = afterScrollTop;
}, false);
}
headerCtrl(direction) {
this.checkIsPageHeading();
if (JUMP_STATE) return false;
const speed = this.speed;
if (direction == 'up') {
$('.nav-bar').stop().slideDown(speed);
} else {
$('.nav-bar').stop().slideUp(speed);
}
}
checkIsPageHeading() {
if($('.nav-bar .logo').css('visibility') == 'hidden') {
$('.nav-bar .logo').css('visibility', 'visible');
$('.nav-bar').removeClass('opaque');
}
}
checkIsMobile() {
return navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i);
}
}
new Home();
// Uncomment these to enable hot module reload for this entry.
if (module.hot) {
module.hot.accept();
}
|
import LongdoMap from './components/LongdoMap.vue'
import LongdoMapMarker from './components/LongdoMapMarker.vue'
import LongdoMapPopup from './components/LongdoMapPopup.vue'
export {
LongdoMap,
LongdoMapMarker,
LongdoMapPopup
}
|
import React from 'react';
import styles from "./Nav.module.css"
import Heading from "../../../Utility/Heading"
function Navbar() {
return (
<nav className={styles.nav}>
<Heading size="2rem" text="Aget" color="orange" />
</nav>
)
}
export default Navbar;
|
import styled from 'styled-components'
export default styled.input`
font-size: 12px;
&:focus {
border: 2px solid transparent;
outline: 1px solid #5E9ED6;
}
`
|
import React, { Component } from 'react';
import { Menu } from 'semantic-ui-react'
import { NavLink } from 'react-router-dom';
import Login from '../Login/Login'
import NavLogin from './NavLogin'
import NavLogout from './NavLogout'
import {connect} from 'react-redux'
import { compose } from 'redux';
import { firebaseConnect } from 'react-redux-firebase';
class NavBar extends Component {
constructor(props){
super(props)
}
state = { activeItem: 'home', open: false }
show = (dimmer) => () => this.setState({ dimmer, open: true })
close = () => this.setState({ open: false })
handleItemClick = (e, { name }) =>
(name === 'LOGIN') ? this.setState({ activeItem: name, open: true }) : this.setState({ activeItem: name })
render() {
const { activeItem } = this.state
const { auth, profile } = this.props;
const links = auth.uid ? <NavLogin profile={profile} handleItemClick={this.handleItemClick} value={activeItem} />:<NavLogout handleItemClick={this.handleItemClick} value={activeItem}/> ;
console.log(profile)
return (
<React.Fragment >
<div className='Nav'>
<Menu secondary >
<Menu.Item
as={NavLink}
to="/"
name='HOME'
active={activeItem === 'HOME'}
onClick={this.handleItemClick}
/>
{links}
<Login setModal={this.state} close={this.close} />
</Menu>
</div>
</React.Fragment>
)
}
}
const mapStateToProps = state => ({
auth: state.firebase.auth,
profile: state.firebase.profile,
});
export default compose(
firebaseConnect(),
connect(mapStateToProps),
)(NavBar); |
jQuery( function( $ ) {
var $pCactions = $( '#p-cactions' );
$pCactions.find( 'h5 a' )
// For accessibility, show the menu when the hidden link in the menu is clicked (bug 24298)
.click( function( e ) {
$pCactions.find( '.menu' ).toggleClass( 'menuForceShow' );
e.preventDefault();
})
// When the hidden link has focus, also set a class that will change the arrow icon
.focus( function() {
$pCactions.addClass( 'vectorMenuFocus' );
})
.blur( function() {
$pCactions.removeClass( 'vectorMenuFocus' );
});
// Breadcrumb slider to reveal personal toolbar options
window.cpOpen = false;
$("#nav-control-panel a").click(function(e) {
e.preventDefault();
if (window.cpOpen == false)
{
$("#breadcrumbs").animate({
marginTop: '-25px'
}, {
duration : 400,
complete: function() {
window.cpOpen = true;
$("#nav-control-panel span").addClass("control-button-up");
$("#nav-control-panel span").removeClass("control-button-down");
}
});
} else {
$("#breadcrumbs").animate({
marginTop: '-50px'
}, {
duration : 400,
complete: function() {
window.cpOpen = false;
$("#nav-control-panel span").addClass("control-button-down");
$("#nav-control-panel span").removeClass("control-button-up");
}
});
}
});
});
|
import React from 'react';
import Router from 'react-router';
import {Provider} from 'react-redux';
import Store from './js/data/store';
import Login from './js/pages/login';
import Dashboard from './js/pages/dashboard';
import Problems from './js/pages/problems';
import Problem from './js/pages/problem';
import Ranking from './js/pages/ranking';
import Announcements from './js/pages/announcements';
import Main from './js/pages/main';
import {Top} from './js/pages/top';
var remote = require('remote');
var clipboard = remote.require('clipboard');
var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var routes = (
<Route path="/" handler={Top}>
<Route name="login" path="/login" handler={Login} />
<Route name="main" handler={Main}>
<Route name="dashboard" handler={Dashboard}/>
<Route name="problems" path="/problems" handler={Problems}>
</Route>
<Route name="problem" path="/problems/:id" handler={Problem}/>
<Route name="ranking" handler={Ranking}/>
<Route name="announcements" handler={Announcements}/>
<DefaultRoute handler={Dashboard}/>
</Route>
<DefaultRoute handler={Login}/>
</Route>
);
// Patch for Electron on OS X Copy/Paste bug
function CopyPasteFunc(e){
// Command key presses
if (!e.ctrlKey && e.metaKey && !e.altKey && !e.shiftKey) {
if (e.keyCode === 67) {
// and key 'C' pressed
var selectedText = window.getSelection().toString();
if (selectedText) {
clipboard.writeText(selectedText);
}
} else if (e.keyCode === 86){
// and key 'V' pressed
var activeElement = document.activeElement;
var clipboardText = clipboard.readText();
if (clipboardText && activeElement && activeElement.type == "text") {
var currentText = activeElement.value;
var cursorPosition = activeElement.selectionStart;
if (cursorPosition != activeElement.selectionEnd) {
currentText = currentText.slice(0, cursorPosition) + currentText.slice(activeElement.selectionEnd);
}
activeElement.value = currentText.slice(0, cursorPosition) + clipboardText + currentText.slice(cursorPosition);
activeElement.selectionStart = activeElement.selectionEnd = cursorPosition + clipboardText.length;
}
}
}
}
document.addEventListener("keydown", CopyPasteFunc);
Router.run(routes, (Handler, routerState) => {
React.render((
<Provider store={Store}>
{() => <Handler routerState={routerState} />}
</Provider>
), document.getElementById("content"));
})
|
import fs from 'fs';
import pngjs from 'pngjs';
const PNG = pngjs.PNG;
function addPoint(y, x, hue) {
const _x = Math.floor(x * zoom + width * 0.5);
const _y = Math.floor(y * zoom + height * 0.5);
if (_x >= 0 && _x < width && _y >= 0 && _y < height) {
map[_y][_x] += hue;
}
}
function sineInterp(x, min, max, spread = 0, offset = Math.PI / 2) {
const a1 = Math.sin(x * Math.PI - offset);
return (a1 * (max - min) + max - spread + min) / 2;
}
function drawMap(frameNumber) {
const streams = [];
colors.forEach(() => streams.push([]));
let sum = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
sum += 1 - Math.exp(-sensitivity * map[y][x]);
}
}
const frameSensitivity = sensitivity / sum * width * height / 10;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const v = 1 - Math.exp(-frameSensitivity * map[y][x]);
for (let i = 0; i < streams.length; i++) {
streams[i].push(
v * (v * (colors[i][2][0] - colors[i][1][0]) + colors[i][1][0] - colors[i][0][0]) + colors[i][0][0],
v * (v * (colors[i][2][1] - colors[i][1][1]) + colors[i][1][1] - colors[i][0][1]) + colors[i][0][1],
v * (v * (colors[i][2][2] - colors[i][1][2]) + colors[i][1][2] - colors[i][0][2]) + colors[i][0][2],
v * (v * (colors[i][2][3] - colors[i][1][3]) + colors[i][1][3] - colors[i][0][3]) + colors[i][0][3],
);
}
}
}
for (let i = 0; i < streams.length; i++) {
const clampedArray = new Uint8ClampedArray(streams[i]);
const img_png = new PNG({
width,
height,
inputColorType: 6,
colorType: 6,
inputHasAlpha: true,
});
img_png.data = Buffer.from(clampedArray);
var buffer = PNG.sync.write(img_png);
fs.writeFileSync(`out/${i}-frame-${frameNumber}.png`, buffer);
}
}
function prepare() {
map = [];
for (let y = 0; y < height; y++) {
const row = [];
map.push(row);
}
sensitivity = 100 * zoom * zoom / 16 / spreadResolution / iterations;
if (framesN === 1) {
for (let j = 0; j < 4; j++) {
param[j] = (paramMM[j][0] + paramMM[j][1] - spread) / 2;
}
}
}
export default function calculate() {
prepare();
let lastPercent = -1;
for (let i = startFrame; i < framesN; i++) {
let x = 1;
if (framesN > 1) {
x = i / framesN;
for (let j = 0; j < 4; j++) {
let x2 = sineInterp(2 * x, 0.5, j / 3);
x2 = x2 ** 2 + x2 / 2 + 0.5;
x2 = x2 >= 1 ? (j + 1) * 2 * x ** x2 : -(j + 1) * 2 * (1 - x) ** x2
param[j] = sineInterp(
x2,
paramMM[j][0],
paramMM[j][1],
spread,
j * Math.PI / 2
);
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
map[y][x] = 0;
}
}
for (let i = 0; i < spreadResolution; i++) {
const p = spreadResolution === 1 ? 0.5 : i / (spreadResolution - 1);
const param_2 = [];
for (let j = 0; j < 4; j++) {
param_2[j] = sineInterp(p, param[j], param[j] + spread);
}
let x = 0;
let y = 0;
for (let j = 0; j < iterations; j++) {
const temp = Math.sin(param_2[0] * y) + param_2[2] * Math.cos(param_2[0] * x);
y = Math.sin(param_2[1] * x) + param_2[3] * Math.cos(param_2[1] * y);
x = temp;
addPoint(y, x, 1);
}
}
drawMap(i);
const newPercent = Math.floor((i + 1) / framesN * 100)
if (newPercent - lastPercent >= 1) {
console.log(`${newPercent}%`);
lastPercent = newPercent;
}
}
}
const resolutionScale = 8;
let width = 500 * resolutionScale;
let height = 400 * resolutionScale;
let zoom = 90 * resolutionScale;
let spreadResolution = 10;
let iterations = 1e5;
let startFrame = 0;
let framesN = 1;
let spread = 0.0005;
let paramMM = [
[1.40, 1.51],
[-1.78, -1.69],
[1.60, 1.70],
[0.90, 0.92],
];
const colors = [
// [
// [212, 212, 212, 255],
// [0, 0, 0, 255],
// [0, 0, 0, 255],
// ],
// [
// [255, 255, 255, 255],
// [0, 0, 0, 255],
// [0, 0, 0, 255],
// ],
// [
// [32, 56, 102, 255],
// [255, 255, 255, 255],
// [255, 255, 255, 255],
// ],
[
[0, 0, 0, 0],
[0, 0, 0, 255],
[0, 0, 0, 255],
],
[
[255, 255, 255, 0],
[255, 255, 255, 255],
[255, 255, 255, 255],
],
];
let sensitivity;
let map;
const param = [];
console.time('render');
if (!fs.existsSync('./out')) {
fs.mkdirSync('./out');
}
calculate();
console.timeEnd('render'); |
const createReduce = (initState, reduces) => (state = initState, action) => {
let _reduce = reduces[action.type]
if(typeof _reduce == 'function') {
if (action.payload) {
action.error && console.log('err!!!', action.payload)
return _reduce(state, action.payload, action.params)
} else {
return _reduce(state, null, action.params)
}
}
return state
}
const initState = {
name: 'hello reselect',
toggle: false
}
const userInfo2 = createReduce(initState, {
'TOGGLE_USER': (state, data, params) => {
return {...state, toggle: !state.toggle}
},
'FETCH_DATA_SUCCESS': (state, data, params) => {
console.log('%c fetch_data_SUCCESS', 'color:red', data)
return state
},
'FETCH_DATA_ERROR': (state, data, params) => {
// console.log('%c fetch_data_ERROR', 'color:red', params)
return state
}
})
/**
* for test reselect
* @param {Object} state
* @param {Object} action action
* @return {Object} same as initstate
*/
const userInfo = (state = { }, action) => {
switch (action.type) {
case 'TOGGLE_USER':
return {...state, toggle: !state.toggle}
case 'FETCH_DATA':
console.log('fetch_data_ing')
return state
case 'FETCH_DATA_LOADING':
console.log('fetch_data_LOADING')
return state
case 'FETCH_DATA_SUCCESS':
console.log('fetch_data_SUCCESS')
console.log(action.payload)
return state
case 'FETCH_DATA_ERROR':
console.log('fetch_data_ERROR')
return state
default:
return state
}
}
export default userInfo2
|
export default {
siteName: '服务登记管理系统',
minSiteMame: 'Yong Bo',
tokenKey: 'Authorization',
USER_NAME_KEY: 'USER_NAME',
MUTATION_FORM_TREE_DATA: "MUTATION_FORM_TREE_DATA",
V_FORM_COMPONENTS_NAME: 'validateMyForm',
TAX_BALANCE_EXCEL_OUT: '/oms/report/taxBalance/excelOut',
TAX_BALANCE_IMPORT_EXCEL: '/oms/report/taxBalance/importExcel',
DOWNLOAD_TEMP_SO_FILE_URL: window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + "/oms/tempSoDownload/download?fileIds=",
SO_ORDER_EXCEL_OUT: '/oms/soOrder/excelOut?type=0',
SO_ORDER_IMPORT_EXCEL: '/oms/soOrder/excelIn',
UPLOAD_AVATAR_URL:'/oms/mgr/upload',
}
|
/*JSX_OPTS
--add-search-path t/compile_error/208.nested-node_modules
*/
import "importer.jsx";
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.