text
stringlengths 7
3.69M
|
|---|
// 存放图标地址
// 商品默认图片
export const defaultProductPicture =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/noPhoto.png'
//列表为空的图片
export const emptyPicture =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/emptyIcon.png'
//loadingPicture
export const loadingPicture =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/loading.gif'
// 资产默认图片
export const defaultAssetsImg =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/assets-default.png'
// 我的项目暂无数据
export const projectEmpty =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/emptyIcon.png'
// 新人必读图片
export const guideImg =
'https://bucket-showyu.oss-cn-beijing.aliyuncs.com/mobile/guide.png'
|
$(document).ready(function() {
$('#adaptive').lightSlider({
adaptiveHeight:false,
item:1,
slideMargin:0,
loop:true,
controls: false
});
$('.highlightInner').lightSlider({
item:3,
loop:false,
slideMove:2,
slideMargin: 9,
speed:600,
responsive : [
{
breakpoint:800,
settings: {
item:3,
slideMove:1,
slideMargin:6
}
},
{
breakpoint:480,
settings: {
item:2,
slideMove:1
}
}
]
});
});
|
export default {
confirm: "Confirm",
save: "Save",
cancel: "Cancel",
editInfo: "Edit Info",
nextStep: "Next",
done: "Done",
search: "Search",
choose: "Choose",
plsChoose: "Please Choose",
goBack: "Go Back",
goBackHome: "Home",
clearShoppingCart: "Clear & Go Back",
viewMyOrder: "View Order Detail",
notice: "Notice",
upload: {
uploading: "Uploading",
success: 'Upload Success',
failed: 'Upload Failed',
uploadPhoto: 'Upload Photo',
uploadAgain: 'Upload Again',
uploaded: 'Uploaded',
},
flight: {
takeoffTime: "Take Off Time",
takeoffAirport: "Take Off Airport",
landingTime: "Landing Time",
landingAirport: "Landing Airport",
route: "Airline Route"
},
form: {
invalid: "Please correct your form inputs",
},
login: {
login: "Login",
code_placeholder: "Please enter access code",
logout: "Logout"
},
bottomBar: {
home: "Home",
signUp: "SignUp",
qrCode: "QrCode",
},
purchase: {
priceList: "Price List",
choosePay: "Choose Payment",
alipay: "Alipay",
wechat: "WechatPay",
offline: "Bank Transfer",
processingNotice: "Order Processing ... Please wait",
orderOverview: "Order Overview",
freeOfCharge: "Free Of Charge",
finishOrder: "Finish Order",
cancelOrder: "Cancel Order",
gotoPay: "Pay",
paySuccess: "Pay Success!",
payCancel: "Pay cancelled",
orderCancelSuccess: "Order cancelled",
},
hotel: {
hotelName: "Hotel",
hotelInfo: "Hotel Info",
roomAllowShare: "Share",
roomType: "Room Type",
roomTypes: {
"单人间":"Single Room",
"标准间":"Standard Room",
"双人间":"Double Room",
"大床房":"King Size Room",
"双床房":"Double Room",
"高级房":"Superior Room",
"豪华大床房":"Deluxe King Room",
"豪华双床房":"Deluxe Twin Bed Room",
"高级大床房":"Superior King Room",
"高级双床房":"Superior Twin Room",
},
chooseShare: "Room Share",
buyShare: "Yes",
buyNotShare: "No",
buyShareType: "Choose Type",
buyShareTypeInvite: "Invite Somebody To Join Me",
cartDetail: "Cart Detail",
notNeed: "Skip",
checkInDate: "Check In Date",
checkOutDate: "Check Out Date",
chooseDate: "Select Date",
joinShareTitle: "Join Share",
joinSharePlaceholder: "Enter the code to join",
joinShareConfirm: "Confirm",
joinShareReset: "Re-enter",
bookingTitle: "Booking",
bookingDesc: "Select Date",
bookingListTitle: "Choose Hotel",
bookingAlmostSoldOut: "Almost Sold Out",
bookingUnavailable: "未查询到当前时间段的酒店信息",
bookingQuantity: "night | nights",
},
order: {
time: "Order Time",
num: "Order No.",
cancel: "Cancel Order",
cancelled: "Order cancelled",
cancelConfirm: "Sure to cancel order?",
detail: "Order Details",
}
}
|
///// Mapas base
var osm = L.tileLayer('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
{attribution: 'Map Data © OpenstreetMap contributors'});
var terrain = new L.StamenTileLayer("terrain");
var toner = new L.StamenTileLayer("toner");
var map = L.map('map',{
center:[16.200, -100.000],
timeDimensionControl: true,
timeDimensionControlOptions: {
position: 'bottomleft',
autoPlay: false,
timeSlider: true,
loopButton: true,
minSpeed: 0,
speedStep: 10,
maxSpeed: 100,
timeSliderDragUpdate: true,
playerOptions: {
transitionTime: 100,
loop: true,
}
},
timeDimension: true,
zoom:7,
minZoom: 6.5,
layers:[terrain, toner]
});
var googleTerrain = L.tileLayer('https://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo (map);
var googleSat = L.tileLayer('https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo (map);
var googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo (map);
var googleHybrid = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo (map);
var carto = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png",{
"attribution": "\u0026copy; \u003ca href=\"http://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors \u0026copy; \u003ca href=\"http://cartodb.com/attributions\"\u003eCartoDB\u003c/a\u003e, CartoDB \u003ca href =\"http://cartodb.com/attributions\"\u003eattributions\u003c/a\u003e", "detectRetina": false, "maxNativeZoom": 18, "maxZoom": 18, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
).addTo (map);
var baseMaps = {
"<b>Mapa en blanco y negro</b>": toner,
"<b>Mapa de calles</b>": googleStreets,
"<b>Imagen de satélite</b>": googleSat,
"<b>Mapa Híbrido</b>": googleHybrid,
"<b>Mapa de relieve</b>": googleTerrain,
"<b>Mapa de terreno</b>": terrain,
"<b>Mapa en tonos claros</b>": carto,
};
L.control.layers(baseMaps).addTo(map);
//// Mapa de estados
function edo_style(feature) {
return {
fillColor: 'white',
weight: 1.5,
opacity: 1,
color: 'black',
dashArray: '1',
fillOpacity: 0.35
};
}
L.geoJson(estados, {
style: edo_style
}).addTo(map);
//// Mapa del estado de Guerrero
function gro_style(feature) {
return {
fillColor: 'white',
weight: 5,
opacity: 1,
color: '#ad0707',
dashArray: '1',
fillOpacity: 0.1
};
}
L.geoJson(guerrero, {
style: gro_style
}).addTo(map);
//// Mapa de municipios de Guerrero
function color_pct (ct) {
return ct == "Muy alto" ? '#08519c':
ct == "Alto" ? '#3182bd':
ct == "Medio" ? '#6baed6':
ct == "Bajo" ? '#bdd7e7':
ct == "Muy bajo" ? '#eff3ff':
'#fdfcfd';
}
function style_pct (feature) {
return {
fillColor: color_pct(feature.properties.RCla_CicTr),
weight: 0.3,
opacity: 1,
color: 'black',
dashArray: '0',
fillOpacity: 0.7
};
}
//// Funciones de información por municipio
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 3,
color: '#666',
dashArray: '',
fillOpacity: 0.5
});
info.update(layer.feature.properties);
}
function resetHighlight(e) {
municipios.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
municipios = L.geoJson(municipios_gro, {
style: style_pct,
onEachFeature: onEachFeature
}).addTo(map);
////// Control de información de municipios
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>Información por municipio</h4>' + (props ?
'<b>' + props.NOMGEO + '</b><br />' +
'<br><b>Capacidad de Adaptación:</b> ' + props.CAP_ADAP +
'<br><b>Grado de Vulnerabilidad:</b> ' + props.VUL_CC
: 'Pase el cursor sobre un municipio');
};
info.addTo(map);
/////Simbología de Mapa municipios
var troplegend = L.control({position: "topleft"});
troplegend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML += "<b> Riesgo a ciclones tropicales </b></br>";
div.innerHTML += '<i style="background: #eff3ff"></i><span>Muy Bajo</span><br>';
div.innerHTML += '<i style="background: #bdd7e7"></i><span>Bajo</span><br>';
div.innerHTML += '<i style="background: #6baed6"></i><span>Medio</span><br>';
div.innerHTML += '<i style="background: #3182bd"></i><span>Alto</span><br>';
div.innerHTML += '<i style="background: #08519c"></i><span>Muy Alto</span><br>';
return div;
};
troplegend.addTo(map);
/// Simbología CICLONES
var ciclonlegend = L.control({position: "bottomright"});
ciclonlegend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
div.innerHTML += "<b> Clasificacion de ciclones tropicales</b></br>";
div.innerHTML += '<di style="background: #fa9dc2"></di><span>Perturbación tropical</span><br>';
div.innerHTML += '<de style="background: #f768a1"></de><span>Depresión tropical</span><br>';
div.innerHTML += '<to style="background: #ae017e"></to><span>Tormenta tropical</span><br>';
div.innerHTML += '<hu style="background: #7a0177"></hu><span>Huracán</span><br>';
div.innerHTML += '<dis style="background: #fcc5c0"></dis><span>Evento disipado</span><br>';
return div;
};
ciclonlegend.addTo(map);
///TimeDimension huracanes
L.TimeDimension.Layer.CDrift = L.TimeDimension.Layer.GeoJson.extend({
// CDrift data has property time in seconds, not in millis.
_getFeatureTimes: function(feature) {
if (!feature.properties) {
return [];
}
if (feature.properties.hasOwnProperty('coordTimes')) {
return feature.properties.coordTimes;
}
if (feature.properties.hasOwnProperty('times')) {
return feature.properties.times;
}
if (feature.properties.hasOwnProperty('linestringTimestamps')) {
return feature.properties.linestringTimestamps;
}
if (feature.properties.hasOwnProperty('time')) {
return [new Date(feature.properties.time).getTime()];
}
return [];
},
// Do not modify features. Just return the feature if it intersects
// the time interval
_getFeatureBetweenDates: function(feature, minTime, maxTime) {
var featureStringTimes = this._getFeatureTimes(feature);
if (featureStringTimes.length == 0) {
return feature;
}
var featureTimes = [];
for (var i = 0, l = featureStringTimes.length; i < l; i++) {
var time = featureStringTimes[i]
if (typeof time == 'string' || time instanceof String) {
time = Date.parse(time.trim());
}
featureTimes.push(time);
}
if (featureTimes[0] > maxTime || featureTimes[l - 1] < minTime) {
return null;
}
return feature;
},
});
L.timeDimension.layer.cDrift = function(layer, options) {
return new L.TimeDimension.Layer.CDrift(layer, options);
};
var startDate = new Date();
startDate.setUTCHours(0, 0, 0, 0);
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", (function(xhr) {
var response = xhr.currentTarget.response;
var data = JSON.parse(response);
var cdriftLayer = L.geoJson(data, {
style: function(feature) {
var color = "#FFF";
if (feature.properties.tf == '0') {
color = "#fa9dc2";
} else if (feature.properties.tf == '1') {
color = "#f768a1";
} else if (feature.properties.tf == '2') {
color = "#7a0177";
} else if (feature.properties.tf == '3') {
color = "#fcc5c0";
} else if (feature.properties.tf == '4') {
color = "#ae017e";
}
return {
"color": color,
"weight": 2,
"opacity": 0.9
};
}
});
var cdriftTimeLayer = L.timeDimension.layer.cDrift(cdriftLayer, {
updateTimeDimension: true,
updateTimeDimensionMode: 'replace',
addlastPoint: false,
duration: 'P7D',
});
cdriftTimeLayer.addTo(map);
var cDriftLegend = L.control({
position: 'bottomleft'
});
map.timeDimension.on('timeload', function(data) {
var date = new Date(map.timeDimension.getCurrentTime());
if (data.time == map.timeDimension.getCurrentTime()) {
var totalTimes = map.timeDimension.getAvailableTimes().length;
var position = map.timeDimension.getAvailableTimes().indexOf(data.time);
}
});
}));
oReq.open("GET", 'https://drive.google.com/file/d/1VEHygW5LHs-ijCVLIN0zK2Ol319yaUn2/view?usp=sharing'); //AQUÍ IRÍA LA URL DEL GEOJSON
oReq.send();
/// respaldo ultimas dos lineas
/// oReq.open("GET", '/tomentas1.geojson');
///oReq.send();
|
'use strict';
/* jshint node: true */
/* globals browser, describe, it, beforeAll, EC, expect, protractor, xit, afterAll */
var myactpage = require('../pages/myAccountPage.js');
afterAll(function(done) {
process.nextTick(done);
});
describe('UIDS-892 Manage Second Factor Options of EMAIL & SMS in My Account ----- ', function() {
it(browser.tc_desc('UIDS-1761 TC1 (1) Verify elements of the page (2) When Email is added in 2FA'), function() {
browser.wait(EC.visibilityOf(myactpage.twoStep.twoStepElement), 12000, '2-Step verification option is not visible');
myactpage.twoStep.twoStepElement.click();
if (browser.params.target === 'remote') {
if ( browser.mobile )
{
browser.wait(EC.visibilityOf(myactpage.twoStep.twoStepHeaderMobile), 12000, '2-Step verification header not visible');
expect(myactpage.twoStep.twoStepHeaderMobile.getText()).toEqual(browser.params.user.authentication.language.myaccount.secondFactor);
expect(myactpage.twoStep.twoStepBackBtn.isDisplayed()).toBeTruthy();
}
}
else {
browser.wait(EC.visibilityOf(myactpage.twoStep.twoStepHeaderWeb), 12000, '2-Step verification header not visible');
expect(myactpage.myAccountProfile.profileHeaderWeb.getText()).toEqual(browser.params.user.authentication.language.myaccount.secondFactor);
}
expect(myactpage.twoStep.twoStepPhoneLabel(browser.params.user.authentication.language.secondFactor.phone).getText()).toEqual(browser.params.user.authentication.language.secondFactor.phone);
expect(myactpage.twoStep.twoStepPhoneLabel(browser.params.user.authentication.language.secondFactor.email).getText()).toEqual(browser.params.user.authentication.language.secondFactor.email);
expect(myactpage.twoStep.twoStepAddPhone(browser.params.user.authentication.language.secondFactor.addPhone).getText()).toEqual(browser.params.user.authentication.language.secondFactor.addPhone);
expect(myactpage.twoStep.twoStepAddEmail(browser.params.user.authentication.language.secondFactor.addEmail).getText()).toEqual(browser.params.user.authentication.language.secondFactor.addEmail);
expect(myactpage.twoStep.twoStepIcons.count()).toBe(2);
expect((myactpage.twoStep.twoStepIcons.get(0)).isDisplayed()).toBeTruthy();
expect((myactpage.twoStep.twoStepIcons.get(1)).isDisplayed()).toBeTruthy();
if ( browser.deviceName === 'Edge'){
myactpage.twoStep.twoStepHelp.getText().then(function(text)
{
expect( text.trim().toUpperCase()).toBe(browser.params.user.authentication.language.mobnav.help);
});
}
else {
expect(myactpage.twoStep.twoStepHelp.getText()).toEqual(browser.params.user.authentication.language.mobnav.help);
}
expect(myactpage.twoStep.twoStepPhonesAdded.getText()).toEqual(browser.params.user.authentication.language.secondFactor.noPhones);
expect(myactpage.twoStep.twoStepEmailsAdded.getText()).toContain(browser.params.user.authentication.secondFactorEmailNewLocked);
});
});
|
var searchData=
[
['sort_22',['sort',['../classquick__sort.html#a7875ca82d3efe85a1cda07e48c82503e',1,'quick_sort']]],
['sortbyend_23',['sortByEnd',['../poem__sorter_8h.html#a05aa4908551441b6b26a50de308c2e9f',1,'poem_sorter.cpp']]],
['sortbystart_24',['sortByStart',['../poem__sorter_8h.html#a06e8d6d8789b8ea67ddd7c23a67acf12',1,'poem_sorter.cpp']]]
];
|
export default {
'border-radius': true,
'border-top-left-radius': true,
'border-top-right-radius': true,
'border-bottom-right-radius': true,
'border-bottom-left-radius': true,
};
|
var test = require('tape')
const functions = require('./logic');
test('returns increment number', function(t){
var expected = 1;
let createdFunction = functions.createIncrementer();
var actual = createdFunction()
t.deepEqual(actual, expected, "should return 1 ");
t.end();
});
test('returns increment number', function(t){
var expected = 2;
let createdFunction = functions.createIncrementer();
createdFunction()
var actual = createdFunction()
t.deepEqual(actual, expected, "should return 2 ");
t.end();
});
test('returns increment number', function(t){
var expected = 3;
let createdFunction = functions.createIncrementer();
createdFunction();
createdFunction();
var actual = createdFunction()
t.deepEqual(actual, expected, "should return 3 ");
t.end();
});
// test('returns random ' , function(t){
// var expected =
// });
|
{
console.log("Number.EPSILON");
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
function isEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(isEqual(0.1 + 0.2, 0.3));
}
{
console.log("Number.MAX_VALUE");
var num = 10;
num.MAX_VALUE;
console.log(Infinity > Number.MAX_VALUE);
console.log(Number.MIN_VALUE > 0);
}
{
Number.isFinite(Infinity);
Number.isFinite(NaN);
//전역 함수에도 isFinite()가 있다.
//전역 함수 isFinite()는 인수를 숫자로 암묵적 형변환해서 검사하지만 Number의 메소드 함수는 그렇지 않는다.
}
{
Number.isSafeInteger(123);
Number.isSafeInteger(1000000000000000); //true
Number.isSafeInteger(10000000000000001);//false
}
{
var numObj = 77.1234;
console.log("Number.prototype.toExponetial(여기 숫자만큼 소수아랫자리 표현) => string");
console.log(numObj.toExponential());
console.log(numObj.toExponential(4));
}
{
console.log("Number.prototype.toFixed() => string")
//()안에 들어가는 숫자에 해당하는 소숫점 아랫 자리에서 반올림.
var numObj = 12345.6789;
console.log(numObj.toFixed());
console.log(numObj.toFixed(1));
console.log(numObj.toFixed(2));
console.log(numObj.toFixed(6));
console.log(numObj.toPrecision()); //전체자리수 유효
console.log(numObj.toPrecision(1)); //전체에서 최상위 자리 빼고 반올림.
console.log(numObj.toPrecision(2)); //2자리만 유효.
}
|
function BaseType (state, options, traitList) {
this.getState = function () {
return state;
};
this.getOptions = function () {
return options;
};
this.getTraitList = function () {
return traitList;
};
}
BaseType.prototype = (new BaseType({}, {}, []));
function SpecificType(state) {
this.getType = function () {
return state.type;
};
}
function UnspecificType() {}
function withTypeTrait(state) {
this.getType = function () {
return state.type;
};
}
function withFooTrait(state) {
this.getFoo = function () {
return state.foo;
};
}
function withBarTrait(state) {
this.getBar = function () {
return state.bar;
};
}
var myType;
var MyExtendedType = SpecificType.extendType(BaseType/*, {}*/);
myType = new MyExtendedType({type: "my_extended_type"});
console.log("Object.keys(myType) : ", Object.keys(myType));
console.log("(myType instanceof MyExtendedType) ? ", (myType instanceof MyExtendedType));
console.log("(myType instanceof BaseType) ? ", (myType instanceof BaseType));
console.log("(myType instanceof SpecificType) ? ", (myType instanceof SpecificType));
console.log("myType.getType() : ", myType.getType());
var MyComposedType = UnspecificType.withTraits(withTypeTrait, withFooTrait, withBarTrait);
myType = new MyComposedType({type: "my_composed_type", foo: "foo foo", bar: "bar bar bar"});
console.log("Object.keys(myType) : ", Object.keys(myType));
console.log("(myType instanceof MyComposedType) ? ", (myType instanceof MyComposedType));
console.log("(myType instanceof BaseType) ? ", (myType instanceof BaseType));
console.log("(myType instanceof UnspecificType) ? ", (myType instanceof UnspecificType));
console.log("myType.getType() : ", myType.getType());
console.log("myType.getFoo() : ", myType.getFoo());
console.log("myType.getBar() : ", myType.getBar());
var MyCompositeType = SpecificType.extendType(BaseType).withTraits(withFooTrait, withBarTrait);
myType = new MyCompositeType({type: "my_composite_type", foo: "foo", bar: "bar bar"});
console.log("Object.keys(myType) : ", Object.keys(myType));
console.log("(myType instanceof MyCompositeType) ? ", (myType instanceof MyCompositeType));
console.log("(myType instanceof BaseType) ? ", (myType instanceof BaseType));
console.log("(myType instanceof SpecificType) ? ", (myType instanceof SpecificType));
console.log("myType.getType() : ", myType.getType());
console.log("myType.getFoo() : ", myType.getFoo());
console.log("myType.getBar() : ", myType.getBar());
var BaseTypeModule = (function () {
var
baseTypeState = {},
baseTypeOptions = {},
baseTypeTraitList = [];
function BaseType (state, options, traitList) {
this.getState = function () {
return state;
};
this.getOptions = function () {
return options;
};
this.getTraitList = function () {
return traitList;
};
}
BaseType.prototype = createType(baseTypeState, baseTypeOptions, baseTypeTraitList);
function createType(state, options, traitList) {
return (new BaseType(state, options, traitList))
}
function isBaseType(type) {
return (type instanceof BaseType);
}
function getConstructor() {
return BaseType;
}
return {
create : createType,
isBaseType : isBaseType,
getConstructor : getConstructor
};
}());
var MyTypeModule = (function (BaseTypeModule) {
var
MyType = SpecificType.extendType(BaseTypeModule.getConstructor()/*, {}*/);
function SpecificType(state) {
this.getType = function () {
return state.type;
};
}
function createType(state, options, traitList) {
return (new MyType(state, options, traitList))
}
function isMyType(type) {
return (type instanceof MyType);
}
function getConstructor() {
return MyType;
}
return {
create : createType,
isMyType : isMyType,
getConstructor : getConstructor
};
}(BaseTypeModule));
var myType = MyTypeModule.create({type: "mytype"});
console.log("Object.keys(myType) : ", Object.keys(myType));
console.log("MyTypeModule.isMyType ? ", MyTypeModule.isMyType(myType));
console.log("BaseTypeModule.isBaseType ? ", BaseTypeModule.isBaseType(myType));
|
import React from 'react';
import { NavLink } from 'react-router-dom';
import s from './AuthPageMenu.module.css';
function AuthPageMenu(props) {
return (
<div className={s.authPageMenuWrapper}>
<div className={s.navLinkWrapper}>
<NavLink to='/log_in' className={s.link} activeClassName={s.activeNavLink}>Log In</NavLink>
</div>
<div className={s.navLinkWrapper}>
<NavLink to='/sign_up' className={s.link} activeClassName={s.activeNavLink}>Sign Up</NavLink>
</div>
</div>
);
}
export default AuthPageMenu;
|
import firebase from "firebase";
const firebaseConfig = {
apiKey: "AIzaSyAwFc8II1LR2OmjTsLJGIiCJdEe130gc0A",
authDomain: "chat-app-team-78.firebaseapp.com",
databaseURL: "https://chat-app-team-78-default-rtdb.firebaseio.com",
projectId: "chat-app-team-78",
storageBucket: "chat-app-team-78.appspot.com",
messagingSenderId: "1001273283066",
appId: "1:1001273283066:web:f1947e71cb03e0887e9443",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { auth, provider, db };
|
import React from 'react'
import { Link } from 'gatsby'
import 'prismjs/themes/prism.css'
import Bio from '../components/Bio'
import { rhythm, scale } from '../utils/typography'
import { Span } from 'opentracing'
import Sift from 'sift'
class Layout extends React.Component {
render() {
const { location, title, children } = this.props
const isRootPath = location.pathname === `${__PATH_PREFIX__}/`
let header
const pageNumber = location.pathname
.split('/')
.filter(Boolean)
.pop()
const isPaginatedPath = pageNumber && Boolean(pageNumber.match(/^[0-9]+$/))
return (
<div style={{
color: `rgb(58, 65, 69)`
}}>
<div>
<Bio />
</div>
<div
style={{
marginLeft: `auto`,
marginRight: `auto`,
maxWidth: rhythm(31),
// padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`,
padding: `0 1.3125rem 2.625rem 1.3125rem`
}}
>
{children}
</div>
<footer
style={{
marginTop: rhythm(1.3),
marginBottom: rhythm(1.5),
paddingTop: rhythm(0.7),
textAlign: `center`,
fontFamily: `monospace`,
fontSize: rhythm(0.75),
borderTop: `1px solid #eee`,
}}
>
<p
style={{
marginBottom: 0,
}}
>
© {new Date().getFullYear()} All rights reserved
</p>
<p>
<strong>>_</strong> with love by
{` `}
<a href={`https://github.com/gnehcc`} target={'_blank'}>
CHENG
</a>
</p>
</footer>
</div>
)
}
}
export default Layout
|
//////////////////////////////////////////////////////
///////////////////// VIEW ///////////////////////////
//////////////////////////////////////////////////////
/*** Зависимости ***/
/*** Переменые ***/
const self = {};
const userList = document.getElementsByClassName('users-list')[0];
const messageList = document.getElementsByClassName('messages-list')[0];
/*** Методы ***/
// Установить имя
self.setName = (name) => {
let infoText = document.getElementsByClassName('info-text')[0];
infoText.textContent = name;
};
// Добавить пользователя
self.addUser = (user) => {
let item = document.createElement('li');
item.className = 'users-item';
item.innerHTML =
`<div class="users-item-login">
${user.login}
<span class="users-item-name">${user.name}</span>
</div>`;
userList.appendChild(item);
};
// Удалить пользователя
self.removeUser = (user) => {
let users = document.getElementsByClassName('users-item');
[].forEach.call(users, item => {
let name = item.getElementsByClassName('users-item-name')[0].textContent.trim();
if (name === user.name) {
userList.removeChild(item);
}
});
};
// Добавить сообщение
self.addMessage = (message, callback) => {
let item = document.createElement('li');
let photo = (message.photo ? `${message.photo}?${Math.random()}` : 'img/no-photo.jpg');
item.className = 'messages-item';
if (message.my) {
item.classList.add('my');
}
item.dataset.timestamp = message.timestamp;
item.innerHTML =
`<div class="messages-item-user">
<div class="messages-item-user-avatar">
<img src="${photo}" alt="Avatar"/>
</div>
<div class="messages-item-user-login">
<span class="messages-item-user-login-login">${message.user.login}</span>
<span class="messages-item-user-name">${message.user.name}</span>
</div>
<div class="messages-item-user-time">${message.time}</div>
</div>
<div class="messages-item-text">${message.text}</div>`;
messageList.appendChild(item);
messageList.scrollTop = messageList.scrollHeight;
if (typeof callback === 'function') {
callback(item);
}
};
// Обновить время сообщения
self.updateMessageTime = (message, time) => {
message.getElementsByClassName('messages-item-user-time')[0].textContent = time;
};
// Очистить модальное окно для загрузки фото
self.clearPhotoUploadModal = () => {
let photoWrap = document.getElementsByClassName('photo-wrap')[0],
photoBody = photoWrap.getElementsByClassName('photo-body')[0],
photoText = photoBody.getElementsByClassName('photo-body-text')[0];
photoWrap.style.display = 'none';
photoText.textContent = 'Перетащите фото сюда';
photoBody.style.borderStyle = 'dashed';
photoBody.classList.remove('loading');
};
// Установить фотографию
self.setPhoto = (login, src, my) => {
let messages = document.getElementsByClassName('messages-item-user');
src = (src ? `${src}?${Math.random()}` : 'img/no-photo.jpg');
if (my) {
document.getElementsByClassName('info-avatar-img')[0].setAttribute('src', src);
}
[].forEach.call(messages, (message) => {
let messageLogin = message.getElementsByClassName('messages-item-user-login-login')[0].textContent;
if (login === messageLogin) {
message.querySelector('.messages-item-user-avatar img').setAttribute('src', src);
}
});
};
export default self;
|
const express = require("express");
const router = express.Router();
const contentsController = require("../controllers/contentsController");
router.get('/', contentsController.read);
router.put('/', contentsController.update);
router.post('/', contentsController.create);
router.delete('/', contentsController.delete);
module.exports = router;
|
angular.module('cursos')
.controller('dashboardController', function ($window, userService, SCurso, SPersona) {
var vm = this;
vm.rangoEdades;
vm.ClasificacionGenero;
vm.init = function () {
SCurso.getRangoEdades({}, function (dataRangoEdades) {
vm.rangoEdades = vm.generarArray(dataRangoEdades);
}, function (error) {
vm.manejarExcepciones(error);
});
SCurso.getClasificacionGenero({}, function (dataClasificacionGenero) {
vm.ClasificacionGenero = vm.generarArray(dataClasificacionGenero);
}, function (error) {
vm.manejarExcepciones(error);
});
}
/**
* Controla el mensaje de error
* @param {any} error
*/
vm.manejarExcepciones = function (error) {
console.log(error)
if (error && error.data.error)
toastr.error(error.data.error);
else
toastr.error(error.toString());
console.log("Error", error);
}
vm.generarArray = function (objDto) {
objDto = objDto[0];
var lista = [];
var keys = _.keys(objDto);
for (var i = 0; i < keys.length; i++) {
var obj = { 'Cantidad': objDto[keys[i]], 'Nombre': keys[i].replace(/_/g, ' ').replace(/C/g, '')};
lista.push(obj);
}
return lista;
}
vm.irAtras = function () {
$window.history.back();
}
vm.init();
});
|
import React from 'react'
function hello(props){
return <h1> i like {props.name} and the weight is {props.weight} </h1>
}
export default hello
|
import React, { Component } from 'react';
import {
CardNumberElement,
CardExpiryElement,
CardCVCElement,
injectStripe,
} from 'react-stripe-elements';
class CheckoutForm extends Component {
state = {
errorMessage: '',
};
// initiating the radio button
getInitialState = () => {
return {
selectedOption: 'unlimited jobs',
};
};
// if error occurs, list the error that occured
handleChange = ({ error }) => {
if (error) {
this.setState({ errorMessage: error.message });
}
};
// if successfully submitted create a token
handleSubmit = formSubmitEvent => {
formSubmitEvent.preventDefault();
console.log('You have selected:', this.state.selectedOption);
if (this.props.stripe) {
this.props.stripe.createToken().then(this.props.handleResult);
console.log('Token was created');
} else {
console.log("Stripe.js hasn't loaded yet.");
}
};
// for handling radio buttons
handleOptionChange = changeEvent => {
this.setState({ selectedOption: changeEvent.target.value });
};
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="split-form">
<label>
Card number
<CardNumberElement onChange={this.handleChange} />
</label>
<label>
Expiration date
<CardExpiryElement onChange={this.handleChange} />
</label>
</div>
<div className="split-form">
<label>
CVC
<CardCVCElement onChange={this.handleChange} />
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="unlimited jobs"
checked={this.state.selectedOption === 'unlimited jobs'}
onChange={this.handleOptionChange}
className="form-check-input"
/>
Unlimited Jobs, 1 Month $299.99
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="post job (12)"
checked={this.state.selectedOption === 'post job (12)'}
onChange={this.handleOptionChange}
className="form-check-input"
/>
Post Job (12) - $99.99
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="react-tips"
value="post job"
checked={this.state.selectedOption === 'post job'}
onChange={this.handleOptionChange}
className="form-check-input"
/>
Post Job - $9.99
</label>
</div>
<div className="error" role="alert">
{this.state.errorMessage}
</div>
<button type="submit">Buy Now</button>
</form>
);
}
}
export default injectStripe(CheckoutForm);
|
const { response, request } = require('express');
const clientesGet = (req = request , res = response) => {
const query = req.query;
res.json({
msg: 'clientes get API Controller',
query
})
}
const clientesPost = (req, res = response) => {
const { id, nombre, ciudad, direccion} = req.body;
res.status(201).json({
msg: 'clientes post API Controller',
id,
nombre,
ciudad,
direccion
})
}
const clientesPut = (req, res = response) => {
const { id } = req.params;
res.json({
msg: 'clientes put API Controller',
id
})
}
const clientesDelete = (req, res = response) => {
res.json({
msg: 'clientes delete API Controller'
})
}
module.exports = {
clientesGet,
clientesPost,
clientesPut,
clientesDelete
}
|
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import hbs from 'handlebars';
import App from '../client/App';
import template from './htmlTemplate';
const router = express.Router();
router.get("/", async (req, res) => {
const hbsTemplate = hbs.compile(template);
const reactComponent = renderToString(<App />);
const finalHtml = hbsTemplate({ content: reactComponent });
res.status(200).send(finalHtml);
});
export default router;
|
import { createStore, applyMiddleware, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { reducer as formReducers } from 'redux-form'
import contactForm from '../reducers/contactForm'
import individualForm from '../reducers/individualForm'
import foundationForm from '../reducers/institutionForm'
import ktpUpload from '../reducers/ktpUpload'
const rootReducers = combineReducers({
contactForm,
individualForm,
foundationForm,
ktpUpload,
form:formReducers
})
export default createStore(
rootReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunk)
)
|
import axios from 'axios';
import { apiHost } from 'config';
import { uploadProgress } from 'modal/actions'
axios.defaults.baseURL = apiHost;
const getFileList = (options) => {
return axios.get('/file', {
params: options,
headers: {
Authorization: `JWT ${localStorage.getItem('JWT')}`
}
})
.then((res) => {
return res.data.data;
})
.catch((error) => {
if (error.response.status === 401) {
localStorage.removeItem('JWT');
return;
}
return Promise.reject(error);
});
};
const uploadFiles = (dispatch, files) => {
const formData = new FormData();
files.map(file => formData.append('file', file));
return axios.post(`/file`, formData, {
headers: {
Authorization: `JWT ${localStorage.getItem('JWT')}`
},
onUploadProgress: e => {
dispatch(uploadProgress(e.loaded/e.total));
}
})
.then((res) => {
return res.data.data;
});
};
const deleteFile = (filename) => {
return axios.delete(`/file/${filename}`, {
headers: {
Authorization: `JWT ${localStorage.getItem('JWT')}`
}
});
};
export default {
getFileList,
uploadFiles,
deleteFile
};
|
const category = {
name: '',
description: '',
parent_id: ''
}
module.exports = {
category
}
|
import dom from "../support/dom" // must load before React
import React from "react/addons"
import DetailComponent from "../../src/components/storydetail"
import contextWrapper from "../support/context"
import expect from "expect.js"
import sinon from "sinon"
const TestUtils = React.addons.TestUtils;
describe('<StoryDetail />', function() {
before('render and locate element', ()=> {
let renderTarget = document.getElementsByTagName('body')[0]
, StoryDetail = contextWrapper(DetailComponent, {
}, {
transitionTo() {
},
getParams() {
}
});
this.renderedComponent = React.render(<StoryDetail />, renderTarget);
this.div = TestUtils.findRenderedDOMComponentWithClass(
this.renderedComponent, 'st-storydetail'
);
this.el = this.div.getDOMNode();
});
describe('left arrow', ()=> {
it('should transition back to the story list', ()=> {
TestUtils.Simulate.keyDown(this.el, { keyCode: 37 });
});
});
})
|
import React, {Component} from 'react';
import './MenuItemStyle.scss';
import NavLink from 'react-router-dom/es/NavLink';
export default class MenuItem extends Component {
render() {
return (
<div className='col-xs-2'>
<div className='menu-item '>
<NavLink to={'/' + (this.props.to)} exact activeClassName='active'>{this.props.name}</NavLink>
</div>
</div>
);
}
}
|
var admin = require("firebase-admin");
var async = require('async');
var fs = require('fs');
var fs2 = require('fs');
var serviceAccount = require("./serviceAccountKey.json");
// var collectionName = process.argv[2];
// You should replae databaseURL with your own
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pilotsystem-9ab72.firebaseio.com"
});
var db = admin.firestore();
async.each(["CuentaCobrar", "CuentasPagar", "clientes", "colores", "comprobantes", "contratos", "cotizacion", "cuentasPagar_Vehiculos", "entradas", "fecha_veh", "foto_vehiculos", "mecanicos", "menu", "notas", "piezas", "reservas", "salidas", "sucursales", "suplidores", "tiposUsuario", "usuarios", "vehiculos"], function (file, callback) {
var collectionName = file
var data = {};
data[collectionName] = {};
var results = db.collection(collectionName)
.get()
.then(snapshot => {
snapshot.forEach(doc => {
data[collectionName][doc.id] = doc.data();
})
return data;
})
.catch(error => {
console.log(error);
})
results.then(dt => {
// Write collection to JSON file
fs.writeFile('Respaldos/' + file + '.json', JSON.stringify(dt), function (err) {
if (err) {
console.log(err);
}
else {
console.log('El archivo ' + file + '.json ha sido actualizado.');
}
callback();
});
}, function (err) {
if (err) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('Fallo al procesar el archivo.');
}
else {
console.log('Copia de seguridad de todos los archivos creada correctamente.');
}
});
})
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { removeAlert } from "../../redux/actions/alertsActions";
import {
createSupply,
updateSupply
} from "../../redux/actions/suppliesActions ";
import "./styles.scss";
import { measureUnits } from "../../utilities/constants";
import validate from "../../utilities/validate";
import TextInput from "../TextInput/TextInput";
import Alert from "../Alert/Alert";
class SupplyDetails extends Component {
state = {
editDisabled: true,
active: true,
barCode: "",
description: "",
family: "",
size: "",
units: "",
cost: "",
descriptionError: "",
familyError: "",
sizeError: "",
unitsError: "",
costError: ""
};
validateFormData = () => {
const { description, family, size, units, cost } = this.state;
const descriptionError = validate.getEmptyError(description);
const familyError = validate.getEmptyError(family);
const sizeError = validate.getNumberError(size);
const costError = validate.getNumberError(cost);
const unitsError = validate.getEmptyError(units);
this.setState({
descriptionError,
familyError,
sizeError,
unitsError,
costError
});
if (
descriptionError ||
familyError ||
sizeError ||
unitsError ||
costError
) {
return false;
} else {
return true;
}
};
saveSupplyData = () => {
if (this.validateFormData()) {
const {
active,
barCode,
description,
family,
size,
units,
cost
} = this.state;
const { isForNewSupply, selectedSupplyId } = this.props;
const { idToken } = this.props.auth;
const factor = measureUnits.filter(unit => unit.name === units)[0]
.factor;
const supplyData = {
selectedSupplyId,
active,
barCode,
description,
family,
size,
units,
factor,
cost
};
if (isForNewSupply) {
this.props.createSupply(supplyData, idToken);
} else {
this.props.updateSupply(supplyData, idToken);
}
}
};
changeHandler = e => {
this.setState({
[e.target.name]: e.target.value
});
};
checkHandler = e => {
this.setState({
[e.target.name]: e.target.checked
});
};
enableFormEdit = () => {
this.setState({ editDisabled: false });
};
closeModal = () => {
this.props.closeModal();
};
componentDidMount() {
const { selectedSupplyId, supplies, isForNewSupply } = this.props;
if (isForNewSupply) {
this.setState({
editDisabled: false
});
} else {
const supplyData = supplies.suppliesList.filter(
supply => supply._id === selectedSupplyId
)[0];
this.setState({
editDisabled: true,
active: supplyData.active,
barCode: supplyData.barCode,
description: supplyData.description,
family: supplyData.family._id,
size: supplyData.size,
units: supplyData.units,
cost: supplyData.cost
});
}
}
componentWillUnmount() {
this.props.removeAlert("createSupply");
this.props.removeAlert("updateSupply");
}
render() {
const {
editDisabled,
active,
barCode,
description,
family,
size,
units,
cost,
descriptionError,
familyError,
sizeError,
unitsError,
costError
} = this.state;
const { supplyFamiliesList } = this.props.supplyFamilies;
return (
<div>
<Alert triggeredBy={["createSupply", "updateSupply"]} />
<form className="form-group">
<TextInput
label="Descripcion:"
name="description"
value={description}
disabled={editDisabled}
textError={descriptionError}
changeHandler={this.changeHandler}
/>
<div className="row">
<div className="col">
<TextInput
label="Código de barras:"
name="barCode"
value={barCode}
disabled={editDisabled}
textError=""
changeHandler={this.changeHandler}
/>
</div>
<div className="col">
<div className="form-group">
<label className="mr-sm-2" htmlFor="inlineFormCustomSelect1">
Familia:
</label>
<select
className="custom-select mr-sm-2"
id="inlineFormCustomSelect1"
name="family"
value={family}
disabled={editDisabled}
onChange={this.changeHandler}
>
<option value="">Seleccione...</option>
{supplyFamiliesList.map(family => (
<option key={family._id} value={family._id}>
{family.name}
</option>
))}
</select>
{familyError ? (
<div className="option-error">{familyError}</div>
) : null}
</div>
</div>
</div>
<div className="row">
<div className="col">
<TextInput
label="Tamaño:"
name="size"
value={size}
disabled={editDisabled}
textError={sizeError}
changeHandler={this.changeHandler}
/>
</div>
<div className="col">
<div className="form-group">
<label className="mr-sm-2" htmlFor="inlineFormCustomSelect2">
Unidades:
</label>
<select
className="custom-select mr-sm-2"
id="inlineFormCustomSelect2"
name="units"
value={units}
disabled={editDisabled}
onChange={this.changeHandler}
>
<option value="">Seleccione...</option>
{measureUnits.map((unit, index) => (
<option key={index} value={unit.name}>
{unit.name}
</option>
))}
</select>
{unitsError ? (
<div className="option-error">{unitsError}</div>
) : null}
</div>
</div>
</div>
<div className="row">
<div className="col">
<TextInput
label="Costo:"
name="cost"
value={cost}
disabled={editDisabled}
textError={costError}
changeHandler={this.changeHandler}
/>
</div>
<div className="col">
<div className="form-group">
<label className="mr-sm-2" htmlFor="inlineFormCustomSelect3">
Estado:
</label>
<select
className="custom-select mr-sm-2"
id="inlineFormCustomSelect3"
name="active"
value={active}
disabled={editDisabled}
onChange={this.changeHandler}
>
<option value="true">activo</option>
<option value="false">inactivo</option>
</select>
</div>
</div>
</div>
{editDisabled ? (
<div className="row mt-4">
<div className="col text-center">
<button
type="button"
className="btn btn-primary w-100"
onClick={this.enableFormEdit}
>
Editar
</button>
</div>
<div className="col text-center">
<button
type="button"
className="btn btn-primary w-100"
onClick={this.closeModal}
>
Salir
</button>
</div>
</div>
) : (
<div className="row mt-4">
<div className="col text-center">
<button
type="button"
className="btn btn-success w-100"
onClick={this.saveSupplyData}
>
Guardar
</button>
</div>
<div className="col text-center">
<button
type="button"
className="btn btn-danger w-100"
onClick={this.closeModal}
>
Cancelar
</button>
</div>
</div>
)}
</form>
</div>
);
}
}
const mapStateToProps = state => {
return {
auth: state.authReducer,
supplies: state.suppliesReducer,
supplyFamilies: state.supplyFamiliesReducer
};
};
const mapDispatchToProps = {
createSupply,
updateSupply,
removeAlert
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SupplyDetails);
|
/* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false */
/*global FBTrace:true, XPCNativeWrapper:true, Window:true, define:true */
define([
"firebug/firebug",
"firebug/lib/trace",
"firebug/lib/object",
"firebug/dom/domBasePanel",
"firebug/dom/domPanelTree",
"firebug/dom/domProvider",
"firebug/dom/domMemberProvider",
"firebug/dom/toggleBranch",
],
function(Firebug, FBTrace, Obj, DOMBasePanel, DomPanelTree, DomProvider, DOMMemberProvider,
ToggleBranch) {
"use strict";
// ********************************************************************************************* //
// Constants
var Trace = FBTrace.to("DBG_DOM");
var TraceError = FBTrace.toError();
// ********************************************************************************************* //
// DOM Side Panel Implementation
/**
* @panel This object represents a DOM Side panel used inside the HTML panel.
*/
function DOMSidePanel()
{
}
var BasePanel = DOMBasePanel.prototype;
DOMSidePanel.prototype = Obj.extend(BasePanel,
/** @lends DOMSidePanel */
{
dispatchName: "DOMSidePanel",
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// extends Panel
name: "domSide",
parentPanel: "html",
order: 3,
enableA11y: true,
deriveA11yFrom: "console",
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Initialization
initialize: function()
{
BasePanel.initialize.apply(this, arguments);
// Content rendering
this.provider = new DomProvider(this);
this.tree = new DomPanelTree(this.context, this.provider,
new DOMMemberProvider(this.context));
this.toggles = new ToggleBranch.ToggleBranch();
this.scrollTop = 0;
},
destroy: function(state)
{
BasePanel.destroy.apply(this, arguments);
Trace.sysout("domSidePanel.destroy; scrollTop: " + this.panelNode.scrollTop);
// Save tree state
state.toggles = this.toggles;
this.tree.saveState(state.toggles);
this.tree.destroy();
// Save scroll position
state.scrollTop = this.panelNode.scrollTop;
},
hide: function()
{
BasePanel.hide.apply(this, arguments);
},
updateSelection: function(object)
{
Trace.sysout("domSidePanel.updateSelection;");
this.rebuild(false, this.scrollTop, this.toggles);
},
show: function(state)
{
BasePanel.show.apply(this, arguments);
Trace.sysout("domSidePanel.show;", state);
if (state)
{
if (state.toggles)
this.toggles = state.toggles;
if (state.scrollTop)
this.scrollTop = state.scrollTop;
}
},
});
// ********************************************************************************************* //
// Registration
Firebug.registerPanel(DOMSidePanel);
return DOMSidePanel;
// ********************************************************************************************* //
});
|
var guid = require('../../utils.js').guid;
var myJsPlumb = require('../../myJsPlumb.js');
var myPanZoom = require('../../myPanZoom.js');
var LogicCard = require('../LogicCard/LogicCard.jsx');
var Tree = React.createClass({
componentDidMount: function() {
console.log("Tree component did mount.");
var _this = this;
jsPlumb.ready(function() {
// FIXME: Race condition bug.
myJsPlumb.drawConnections();
});
$(GlobalEvents).on('global_tree:changed', function(ev) {
console.log("The tree changed.");
_this.forceUpdate();
});
myPanZoom.initializePanZoom();
},
componentDidUpdate: function(prevProps, prevState) {
console.log("Tree componentDidUpdate");
myJsPlumb.drawConnections();
},
componentWillUnmount: function() {
$(GlobalEvents).off('global_tree:changed');
},
resetTree: function(childContext) {
console.log("Resetting the tree.");
GTC.resetTree().refresh();
},
zoom: function(ev) {
},
_dragScreen: function(ev) {
console.log("Dragging.");
},
render: function() {
console.log("Re-rendered.");
var _this = this;
// Draw out all the logic cards from the currentTree.
logicCardViews = {};
var currentTree = GTC.getTree();
// console.log(currentTree);
for (i in currentTree) {
// This uuid is different from the cardID; otherwise the virtual DOM
// gets confused.
var uuid = guid();
var settings = {};
$.extend(settings, currentTree[i], {
key: uuid,
ref: currentTree[i].cardID
});
logicCardViews[i] = React.createElement(LogicCard, settings);
}
// console.log(logicCardViews);
return (
<div id="tree-screen" tabIndex="1">
<div id="tree-display" onWheel={_this.zoom}>
{logicCardViews}
</div>
</div>
);
}
});
module.exports = Tree;
|
import Layout from "./components/layout";
// Components
import MainContent from "./components/Index/MainContent";
export default function App() {
return (
<Layout>
<MainContent></MainContent>
</Layout>
);
}
|
if (typeof addthis_widget=="undefined"){
var addthis_widget='addthis';
var at12O='http://s7.addthis.com/';
var at12o='http://s7.addthis.com/services/';
function at12Y( ){
addthis_url=encodeURIComponent(addthis_url); addthis_title=encodeURIComponent(addthis_title); addthis_title=addthis_title.replace(/'/g,'\\\'');
var at12y='<a href="'+at12I('')+'\" onclick=\"return addthis_to()\">'; at12y+='<img src="'+baseURL+'images/root/button1-bm.gif" width="125" height="16" border="0" style="border: none; padding: 0px" alt="AddThis Social Bookmarking Widget" /></a>';
document.write(at12y);
}
function at12I(at12r){return 'http://www.addthis.com/bookmark.php?v=12&winname=addthis&pub='+addthis_pub+'&s='+at12r+'&url='+addthis_url+'&title='+addthis_title; }
function addthis_to(at12r){if (at12r=='favorites'){addthis_url=decodeURIComponent(addthis_url); addthis_title=decodeURIComponent(addthis_title); if (document.all)window.external.AddFavorite(addthis_url,addthis_title); else window.sidebar.addPanel(addthis_title,addthis_url,''); return false; }window.open(at12I(at12r),'addthis','scrollbars=yes,menubar=no,width=620,height=400,resizable=yes,toolbar=no,location=no,status=no'); return false; }
}
at12Y();
|
import { faApple, faWindows, faLinux, faGithub } from '@fortawesome/free-brands-svg-icons'
import { faMicrochip } from '@fortawesome/free-solid-svg-icons'
const release = 'v0.17.2';
export const buttons = {
"osx": {
icon: faApple,
desc: "MacOS",
link: `https://github.com/GarlicoinOrg/Garlicoin/releases/download/${release}/garlicoin-0.17.2-osx64.tar.gz`
},
"windows64": {
icon: faWindows,
desc: "Windows (64-bit)",
link: `https://github.com/GarlicoinOrg/Garlicoin/releases/download/${release}/garlicoin-0.17.2-win64.zip`
},
"windows": {
icon: faWindows,
desc: "Windows (32-bit)",
link: `https://github.com/GarlicoinOrg/Garlicoin/releases/download/${release}/garlicoin-0.17.2-win32.zip`
},
"linux": {
icon: faLinux,
desc: "Linux",
link: `https://github.com/GarlicoinOrg/Garlicoin/releases/download/${release}/garlicoin-0.17.2-x86_64-linux-gnu.tar.gz`
},
"RPI": {
icon: faMicrochip,
rotate: 90,
desc: "Raspberry Pi",
link: `https://github.com/GarlicoinOrg/Garlicoin/releases/download/${release}/garlicoin-0.17.2-arm-linux-gnueabihf.tar.gz`
},
"github": {
icon: faGithub,
desc: "Source Code",
link: `https://github.com/GarlicoinOrg/Garlicoin/archive/${release}.tar.gz`
}
};
|
import axios from 'axios'
import { getAddressIP } from './address'
const address = getAddressIP('prometheus.address')
const BASE_API = `http://${address}/api/v1`
// create an axios instance
const service = axios.create({
baseURL: BASE_API // url = base url + request url
})
// request interceptor
service.interceptors.request.use(
config => {
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (response.status !== 200) {
return Promise.reject(res)
}
return res
}, (error) => {
if (error.response) {
if (error.response.status === 401) {
return false
}
return Promise.reject(error)
} else {
return Promise.reject(error)
}
}
)
export default service
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
//= require_self
function answerParamName(fieldId) {
return "solution[answers][" + fieldId + "]";
}
function showNotice(notice) {
var noticeSelector = $("#notice");
noticeSelector.html(notice).show();
setTimeout(function() { noticeSelector.fadeOut() }, 2000);
}
function removeErrorMessages() {
$(".help-block").remove();
$(".form-group").removeClass("has-error");
}
function newMadLibCreated(event, data, status, xhr) {
removeErrorMessages();
$("#new_mad_lib input[type=submit]").attr("value", "Fill In");
$("#mad_lib_text").before("<p class='form-control-static'>" + data["text"] + "</p>").remove();
var fieldsHtml = [];
for(var field in data["fields"])
{
field = data["fields"][field];
fieldsHtml.push("<div class='form-group form-group-field'>" +
"<label for='" + answerParamName(field["id"]) + "' class='col-sm-2 control-label'>" + field["label"] + ":</label>" +
"<div class='col-sm-10'><input type='text' name='" + answerParamName(field["id"]) + "' id='" + answerParamName(field["id"]) + "' class='form-control' value=''></div>" +
"</div>");
}
$("#new_mad_lib .form-group:last").before(fieldsHtml.join(""));
$("#new_mad_lib").append("<input type='hidden' name='solution[mad_lib_id]' value='" + data["id"] + "'>");
showNotice("New Mad Lib created");
$("#new_mad_lib")
.attr("action", "/solutions")
.unbind()
.on("ajax:success", newSolutionCreated);
}
function creatingNewMadLibFailed(event, xhr, status, error) {
var errors = $.parseJSON(xhr.responseText);
if (errors["text"]) {
$("#mad_lib_text").next(".help-block").remove();
$("#mad_lib_text").after("<span class='help-block'>" + errors["text"][0] + "</span>").parents(".form-group").addClass("has-error");
}
}
function newSolutionCreated(event, data, status, xhr) {
removeErrorMessages();
var answersHtml = [];
for(var answer in data["answers"]) {
answer = data["answers"][answer];
answerParamName(answer["id"]);
answersHtml.push("<div class='form-group form-group-field'>" +
"<label class='col-sm-2 control-label'>" + answer["field_label"] + ":</label>" +
"<div class='col-sm-10'><p class='form-control-static'>" + answer["text"] + "</p></div>" +
"</div>");
}
$("#new_mad_lib .form-group-field").remove();
$("#new_mad_lib .form-group:last").before(answersHtml.join(""));
$("#new_mad_lib .form-group:last").before("<div class='form-group'>" +
"<label class='col-sm-2 control-label'>Result:</label>" +
"<div class='col-sm-10'><p class='form-control-static'>" + data["result"] + "</p></div>" +
"</div>");
$("#new_mad_lib input[type=hidden]").remove();
$("#new_mad_lib input[type=submit]").before("<a id='start_again' class='btn btn-default' href='#'>Start again</a>").remove();
showNotice("Your solution has been created");
$("#new_mad_lib").unbind();
$("#start_again").one("click", startAgain);
}
function startAgain() {
$("#new_mad_lib .form-group:last").prevAll(".form-group").remove();
$("#start_again").before("<input type='submit' class='btn btn-default' value='Create'>").remove();
$("#new_mad_lib .form-group:last").before("<div class='form-group'>" +
"<label class='col-sm-2 control-label' for='mad_lib_text'>Template:</label>" +
"<div class='col-sm-10'><textarea class='form-control' cols='40' id='mad_lib_text' name='mad_lib[text]' rows='10'></textarea></div>" +
"</div>");
$("#new_mad_lib")
.attr("action", "/mad_libs")
.unbind()
.on("ajax:success", newMadLibCreated).on("ajax:error", creatingNewMadLibFailed);
}
$(function() {
var newMadLibForm = $("#new_mad_lib");
if (newMadLibForm.length) {
$(".container").prepend("<div id='notice_container'><p id='notice' class='alert alert-success'></p></div>");
newMadLibForm.on("ajax:success", newMadLibCreated).on("ajax:error", creatingNewMadLibFailed);
}
});
|
var mongoose = require('mongoose');
var PaymentSchema = new mongoose.Schema({
paymentType: {type: String},
paymentMethod : {type: String},
created : {type : Date,default : Date.now},
paymentDate : {type : Date},
amount : {type : Number, min: 0 },
createBy: { type: mongoose.Schema.ObjectId, ref: 'Staff'},
isVoid : {type : Boolean, default: false }
});
var Payment = mongoose.model('Payment', PaymentSchema);
module.exports =Payment;
|
/**
* Kata 4 Transform Observable Solution
* @author Dr. Michael Menzel
*/
$(document).ready(function(){
$('#run').click(function(){
var planeType777 = "Boeing 777";
var planeType747 = "Boeing 747";
// 1) create a function getPlaneInfo(planeType) that returns an Observable of article infos
// 1a) create an observable that emits the plane type
// 1b) use the wikipediaService to fetch an article (wikipediaService.fetchArticleObservable)
// 1c) use the wikipediaService.parseArticleInfo method to transform the article to an planeInfo object
// 2) use the getPlaneInfo function to create observables for planeType777 and planeType747
// 3) combine the observables to one observable that emits plane info object {numberBuild: ..., typeName:...} with the summed numberBuild
// 4) subscribe to the observable to print the article with output.logArticleInfo
output.log(planeType777 + " " + planeType747);
});
});
|
/// <reference path="jquery-1.11.0.js" />
$(function(){
//鼠标经过输入框变成圆角
fillet();
phbqh();
$(".secedeBtn").click(function () {//退出登录请求
$.post("/ajax/loginAjax.ashx", { "parameter": "secede" }, function (data) {
var timestamp = Date.parse(new Date());//获取一个时间戳
var data = JSON.parse(data);
if (data.Success) {
window.location.href = "/index.aspx" + "?xiaoyi=" + timestamp;
} else {
window.location.href = window.location.href + "?xiaoyi=" + timestamp;
}
})
});
})
//鼠标经过输入框变成圆角 border-radius:10px;
function fillet(){
$("#fillet").hover(function(){
$(this).animate({'border-radius':'25px'});
},function(){
$(this).animate({'border-radius':'10px'});
});
}
//热门排行榜切换效果
function phbqh() {
$(".phbbtn").click(function () {
var indexs = $(this).index();
$(this).addClass("rmph-bg").siblings(".phbbtn").removeClass("rmph-bg");//切换样式
$(".commodity-con-l-main-list").eq(indexs).show().siblings(".commodity-con-l-main-list").hide();
});
}
|
const routes = require('express').Router()
const { Food, Category } = require('../models')
routes.get('/', (req, res, next) => {
Category.findAll()
.then(categories => {
res.render('pages/categories', { categories })
})
.catch(next)
})
routes.get('/add', (req, res, next) => {
res.render('pages/categories/form')
})
routes.post('/add', (req, res, next) => {
Category.create({ ...req.body })
.then(_ => {
res.redirect('/categories')
})
.catch(err => {
res.render('pages/categories/form', { err })
})
})
routes.get('/:id/edit', (req, res, next) => {
Category.findByPk(req.params.id)
.then(category => res.render('pages/categories/form', { category }))
.catch(next)
})
routes.post('/:id/edit', (req, res, next) => {
Category.findByPk(req.params.id)
.then(category => category.update({ ...req.body }))
.then(_ => res.redirect('/categories'))
.catch(err => {
// check error type !!
next(err)
})
})
routes.get('/:id/delete', (req, res, next) => {
Category.destroy({ where: { ...req.params }})
.then(_ => res.redirect('/categories'))
.catch(next)
})
module.exports = routes
|
import * as types from './actionTypes';
const initialSmurfs = [];
export const smurfsReducer = (state = initialSmurfs, action) => {
switch (action.type) {
case types.FETCH_SMURFS:
return state.concat(action.payload)
default:
return state;
}
}
const initialValues = {
id: '',
name: '',
age: '',
height: ''
}
export const formReducer = (state = initialValues, action) => {
switch (action.type) {
case types.ON_INPUT_CHANGE:
return {
...state,
[action.payload.name]: action.payload.value
}
default:
return state;
}
}
|
module.exports = {
"files": [
"icons/*.svg"
],
"fontName": "Awesomecons",
"classPrefix": "ai-",
"baseClass": "ai",
"fixedWidth": true,
"types": ["eot", "woff", "ttf", "svg"] // this is the default
}
|
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Message = mongoose.model('Message');
/* GET home page. */
/*
router.get('/api/messages', function(req, res, next) {
// find all the messages... send back as json with text and date
Message.find({}, function(err, messages, count) {
res.json(messages.map(function(msg) {
return {'text':msg.text, 'date':msg.dateSent};
}));
});
});
*/
router.get('/api/messages', function(req, res) {
console.log(req.query.lastRetrievalDate);
var q = {};
if (req.query.lastRetrievalDate) {
q.dateSent = {$gt:new Date(req.query.lastRetrievalDate)};
console.log(q);
}
Message.find(q).sort('dateSent').exec(function(err, messages, count) {
console.log('messages:', messages);
console.log('err:', err);
res.json(messages.map(function(ele) {
return {
'text': ele.text,
'date': ele.dateSent
};
}));
});
});
router.post('/api/message', function(req, res, next) {
console.log(req.body);
var m = new Message({
text: req.body.message,
dateSent: Date.now()
});
m.save(function(err, message, count){
if(err) {
console.log(err);
return res.send(500, 'Oops - 500 error!')
} else {
res.json({id: message._id});
}
})
});
module.exports = router;
|
import { settingsDefaults } from './state/settings'
export const LOCAL_STORAGE_KEY = ''
const appStateDefaults = {
version: process.env.version,
settings: {
...settingsDefaults,
},
}
export default appStateDefaults
|
Ext.Loader.setConfig({ enabled: true });
Ext.Loader.setPath('Ext.ux', '/Scripts/Ext4.0/ux');
Ext.require([
'Ext.form.Panel',
'Ext.ux.form.MultiSelect',
'Ext.ux.form.ItemSelector',
'Ext.ux.CheckColumn'
]);
var pageSize = 25;
Ext.define('gigade.MailGroup', {
extend: 'Ext.data.Model',
fields: [
{ name: "row_id", type: "int" },
{ name: "group_name", type: "string" },
{ name: "remark", type: "string" },
{ name: "status", type: "int" },
{ name: "group_code", type: "string" },
{ name: "callid", type: "int" },
]
});
var CallidForm;
var MailGroupStore = Ext.create('Ext.data.Store', {
model: 'gigade.MailGroup',
autoLoad:true,
proxy: {
type: 'ajax',
url: '/MailGroup/MailGroupList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
Ext.define('gigade.MailMapUser', {
extend: 'Ext.data.Model',
fields: [
{ name: "user_name", type: "string" },
{ name: "nameemail", type: "string" },
{ name: "row_id", type: "int" }]
});
var MailMapStore = Ext.create('Ext.data.Store', {
model: 'gigade.MailMapUser',
autoLoad:true,
proxy: {
type: 'ajax',
url: '/MailGroup/MailUserList?pagers=0',
reader: {
type: 'json',
root: 'data'
}
},
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
var row = Ext.getCmp("MailGroup").getSelectionModel().getSelection();
Ext.getCmp("MailGroup").down('#edit').setDisabled(selections.length == 0);
////Ext.getCmp("MailGroup").down('#remove').setDisabled(selections.length == 0);
Ext.getCmp("MailGroup").down('#callid').setDisabled(selections.length == 0);
if (row != "") {
if (row[0].data.status == 0) {
Ext.getCmp("MailGroup").down('#edit').setDisabled(true);
Ext.getCmp("MailGroup").down('#callid').setDisabled(true);
}
}
}
}
});
Ext.onReady(function () {
var MailGroup = Ext.create('Ext.grid.Panel', {
id: 'MailGroup',
store: MailGroupStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: "群組名稱", dataIndex: 'group_name', width: 150, align: 'center' },
{ header: "群組編碼", dataIndex: 'group_code', width: 150, align: 'center' },
{ header: "人數", dataIndex: 'callid', align: '120', align: 'center' },
{ header: "備註", dataIndex: 'remark', align: '120', align: 'center' },
{
header: "啓用", dataIndex: 'status', align: '120', align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (value == 1) {
return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.row_id + ")'><img hidValue='0' id='img" + record.data.row_id + "' src='../../../Content/img/icons/accept.gif'/></a>";
}
else {
return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.row_id + ")'><img hidValue='1' id='img" + record.data.row_id + "' src='../../../Content/img/icons/drop-no.gif'/></a>";
}
}
},
],
tbar: [
{ xtype: 'button', text: "新增", id: 'add', iconCls: 'ui-icon ui-icon-user-add', handler: onAddClick },
{ xtype: 'button', text: "編輯", id: 'edit', iconCls: 'ui-icon ui-icon-user-edit', disabled: true, handler: onEditClick },
// { xtype: 'button', text: "刪除", id: 'remove', iconCls: 'ui-icon ui-icon-user-delete', disabled: true, handler: onRemoveClick },
{ xtype: 'button', text: "人員管理", id: 'callid', iconCls: 'ui-icon ui-icon-user-suite', disabled: true, handler: onCallidClick },
//{
// xtype: 'button', text: "刷新", id: 'refresh', handler: function () {
// window.location.reload(true);
// }
//},
'->',
{ text: ' ' }
],
bbar: Ext.create('Ext.PagingToolbar', {
store: MailGroupStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: "當前顯示記錄" + ': {0} - {1}' + "總計" + ': {2}',
emptyMsg: "沒有記錄可以顯示"
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: sm
});
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [MailGroup],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
MailGroup.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
MailGroupStore.load({ params: { start: 0, limit: 25 } });
});
//*********新增********//
onAddClick = function () {
editFunction(null, MailGroupStore);
}
//*********編輯********//
onEditClick = function () {
var row = Ext.getCmp("MailGroup").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert("提示信息","沒有選擇一行!");
}
else if (row.length > 1) {
Ext.Msg.alert("提示信息", "只能選擇一行!");
} else if (row[0].data.status == 1) {
editFunction(row[0], MailGroupStore);
}
else {
Ext.Msg.alert("提示信息","請先啓用此群組");
}
}
//*********刪除********//
onRemoveClick = function () {
var row = Ext.getCmp("MailGroup").getSelectionModel().getSelection();
if (row.length < 0) {
Ext.Msg.alert("提示信息","沒有選擇一行!");
}
else {
Ext.Msg.confirm("確認信息", Ext.String.format("刪除選中 {0} 條數據?", row.length), function (btn) {
if (btn == 'yes') {
var rowIDs = '';
for (var i = 0; i < row.length; i++) {
rowIDs += row[i].data.row_id + '|';
}
Ext.Ajax.request({
url: '/MailGroup/DeleteMailGroup',
method: 'post',
params: { rowID: rowIDs },
success: function (form,action) {
var result = Ext.decode(form.responseText);
if (result.success) {
Ext.Msg.alert("提示信息", "刪除成功!");
}
else {
Ext.Msg.alert("提示信息", "刪除失敗!");
}
MailGroupStore.load();
},
failure: function () {
Ext.Msg.alert("提示信息", "刪除失敗!");
MailGroupStore.load();
}
});
}
});
}
}
//******更改狀態******//
function UpdateActive(row_id) {
var activeValue = $("#img" + row_id).attr("hidValue");
$.ajax({
url: "/MailGroup/UpMailGroupStatus",
data: {
"id": row_id,
"active": activeValue
},
type: "POST",
dataType: "json",
success: function (msg) {
if (activeValue == 1) {
$("#img" + id).attr("hidValue", 0);
$("#img" + id).attr("src", "../../../Content/img/icons/accept.gif");
MailGroupStore.load();
} else {
$("#img" + id).attr("hidValue", 1);
$("#img" + id).attr("src", "../../../Content/img/icons/drop-no.gif");
MailGroupStore.load();
}
},
error: function (msg) {
Ext.Msg.alert("提示信息", "操作失敗");
MailGroupStore.load();
}
});
}
//*********人員管理********//
onCallidClick = function () {
var row = Ext.getCmp("MailGroup").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert("提示信息", "沒有選擇一行!");
}
else if (row.length > 1) {
Ext.Msg.alert("提示信息", "只能選擇一行!");
}
else if (row[0].data.status == 1) {
var groupId = Ext.getCmp('MailGroup').getSelectionModel().getSelection()[0].data.row_id;
Ext.Ajax.request({
url: '/MailGroup/QueryUserById',
params: { groupId: groupId },
success: function (response) {
var a = response.responseText;
var arr = a.split(",");
if (!CallidForm) {
CallidForm = Ext.create('widget.window', {
title: "人員管理", closable: true,
closeAction: 'hide',
modal: true,
width: 500,
minWidth: 500,
height: document.documentElement.clientHeight / 2,
layout: 'fit',
bodyStyle: 'padding:5px;',
items: [{
xtype: 'itemselector',
name: 'itemselector',
id: 'itemselector-field',
toListTitle: '已選',
fromListTitle: '可選',
height: document.documentElement.clientHeight / 2 - 100,
store: MailMapStore,
displayField: 'nameemail',
valueField: 'row_id',
allowBlank: true,
msgTarget: 'side'
}, {
xtype: 'textfield',
name: 'groupId',
hidden: true
}],
fbar: [{
xtype: 'button',
text: "重置",
id: 'reset',
handler: function () {
Ext.getCmp("itemselector-field").reset();
return false;
}
},
{
xtype: 'button',
text: "保存",
id: 'save',
handler: function () {
var callid = Ext.getCmp("itemselector-field").getValue();
Ext.Ajax.request({
url: '/MailGroup/AddCallid',
params: { groupId: Ext.getCmp('MailGroup').getSelectionModel().getSelection()[0].data.row_id, callid: callid },
success: function (response, opts) {
var result = eval("(" + response.responseText + ")");
Ext.Msg.alert("提示信息", result.msg);
CallidForm.hide();
MailGroupStore.load();
},
failure: function (response) {
var result = eval("(" + response.responseText + ")");
Ext.Msg.alert("提示信息", result.msg);
}
});
}
}]
});
}
// alert('nnnn');
CallidForm.show();
Ext.getCmp("itemselector-field").setValue(arr);
},
failure: function (response) {
var resText = eval("(" + response.responseText + ")");
alert(resText.rpackCode);
}
});
}
else {
Ext.Msg.alert("提示信息", "請先啓用此群組");
}
}
|
import * as d3 from 'd3';
import FMLegendComponent from '../includes/FMLegend';
import FMS from 'js/constants/financial-mechanisms.json5';
export function fmcolour(fmid) {
return FMS[fmid].colour;
}
export default {
beforeCreate() {
this.FMS = FMS;
},
components: {
'fm-legend': FMLegendComponent,
},
computed: {
// TODO: make the constants arrays, and the objects pre-computed
FM_ARRAY() {
return d3.values(this.FMS);
},
},
methods: {
fmcolour,
getFilterClassFm(fm) {
if (!this.filters.fm)
return;
if (this.isSelectedFm(fm))
return "selected";
if (this.isDisabledFm(fm))
return "disabled";
},
isSelectedFm(fm) {
if (!this.filters.fm) return;
return this.filters.fm == fm.name;
},
isDisabledFm(fm) {
if (!this.filters.fm) return;
return this.filters.fm != fm.name;
},
toggleFm(fm, etarget) {
// don't filter by zero-valued items
if (fm.value == 0) return;
const fmname = fm.name;
this.filters.fm = this.filters.fm == fmname ?
null : fmname;
},
},
};
|
'use strict';
process.env.SESSION_SECRET = '123secret';
const config = require('../../../config');
describe('config', () => {
test('should calculate expiration date correctly', () => {
const expirationDate = config.token.calculateExpirationDate();
expect(expirationDate).toEqual(expect.any(Date));
});
test('should have expiresIn as a number', () => {
expect(config.token.expiresIn).toEqual(expect.any(Number));
});
test('codeToken should have expiresIn as a number', () => {
expect(config.codeToken.expiresIn).toEqual(expect.any(Number));
});
test('refreshToken should have expiresIn as a number', () => {
expect(config.refreshToken.expiresIn).toEqual(expect.any(Number));
});
test('should have db timeToCheckExpiredTokens as a number', () => {
expect(config.db.timeToCheckExpiredTokens).toEqual(expect.any(Number));
});
test('should have session maxAge as a number', () => {
expect(config.session.maxAge).toEqual(expect.any(Number));
});
test('should have session secret as a string', () => {
expect(config.session.secret).toEqual('123secret');
});
});
|
const Post1 = () => {
return <div>Here is a post!!!</div>;
};
export default Post1;
|
/* eslint-disable quote-props */
/* eslint-disable no-multi-spaces */
/* eslint-disable comma-dangle */
/* eslint-disable no-console */
import cors from 'cors';
import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
import { io } from './util/socketio-server';
// import AWS from 'aws-sdk';
// console.log('AWS is :', AWS);
// const credentials = new AWS.SharedIniFileCredentials({
// // profile: 'live2vod',
// profile: 'dnops_sandbox',
// });
// AWS.config.credentials = credentials;
// AWS.config.update({ region: 'ap-southeast-2' });
// Initialize the Express App
const app = new Express();
const server = require('http').createServer(app);
const client = require('socket.io').listen(server);
// console.log('socketIO is :', socketIO);
io(client);
// Set Development modes checks
const isDevMode = process.env.NODE_ENV === 'development' || false;
const isProdMode = process.env.NODE_ENV === 'production' || false;
// Run Webpack dev server in development mode
if (isDevMode) {
// Webpack Requirements
// eslint-disable-next-line global-require
const webpack = require('webpack');
// eslint-disable-next-line global-require
const config = require('../webpack.config.dev');
// eslint-disable-next-line global-require
const webpackDevMiddleware = require('webpack-dev-middleware');
// eslint-disable-next-line global-require
const webpackHotMiddleware = require('webpack-hot-middleware');
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
watchOptions: {
poll: 1000,
},
}));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
// Import required modules
import WorkflowAWSRouter from './api/aws/Workflow/routes';
import ChannelAWSRouter from './api/aws/Channel/routes';
import InputAWSRouter from './api/aws/Input/routes';
import MpChannelAWSRouter from './api/aws/MpChannel/routes';
/******
* ***********
* ***********
* CLI GENERATED API INSERTION
* ***********
* ***********
******/
//Generated App Test with `Genapp`
import GenappAWSRouter from './api/aws/Genapp/routes';
import GenappRouter from './api/Genapp/routes';
import genappData from './api/Genapp/dummyData';
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import postRouter from './routes/post.routes';
import { postData } from './dummyData';
import userRouter from './api/user/user.router';
import { signup, signin, protect } from './util/auth';
import ChefRouter from './api/Chef/routes';
import chefData from './api/Chef/dummyData';
import FoodRouter from './api/Food/routes';
import foodData from './api/Food/dummyData';
import ShopcartRouter from './api/Shopcart/routes';
import shopcartData from './api/Shopcart/dummyData';
import LocationRouter from './api/Location/routes';
import locationData from './api/Location/dummyData';
import OrderRouter from './api/Order/routes';
import orderData from './api/Order/dummyData';
import ChannelRouter from './api/Channel/routes';
import channelData from './api/Channel/dummyData';
import MpchannelRouter from './api/Mpchannel/routes';
import mpChannelData from './api/Mpchannel/dummyData';
import InputRouter from './api/Input/routes';
import inputData from './api/Input/dummyData';
import WorkflowRouter from './api/Workflow/routes';
import workflowData from './api/Workflow/dummyData';
import PencilRouter from './api/Pencil/routes';
import pencilData from './api/Pencil/dummyData';
import BookRouter from './api/Book/routes';
import bookData from './api/Book/dummyData';
import ShipmentRouter from './api/Shipment/routes';
import shipmentData from './api/Shipment/dummyData';
import SearchRouter from './api/Search/routes';
import searchData from './api/Search/dummyData';
import SocialRouter from './api/Social/routes';
import socialData from './api/Social/dummyData';
import serverConfig from './config';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
if (process.env.NODE_ENV !== 'test') {
mongoose.connect(serverConfig.mongoURL, (error) => {
try {
// feed some dummy data in DB.
chefData();
foodData();
locationData();
orderData();
channelData();
genappData();
workflowData();
inputData();
pencilData();
postData();
// recipeData();
searchData();
bookData();
socialData();
shipmentData();
shopcartData();
} catch (e) {
console.error('Please make sure Mongodb is installed and running!', e); // eslint-disable-line no-console
throw error;
}
});
}
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }), cors());
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }), cors());
app.use(Express.static(path.resolve(__dirname, '../dist/client')));
app.use('/signup', signup);
app.use('/signin', signin);
app.use('/api/pencils', protect);
app.use('/api/user', userRouter);
/*
* AWS SDK Resource interaction
*/
app.use('/api/aws', WorkflowAWSRouter);
app.use('/api/aws', ChannelAWSRouter);
app.use('/api/aws', InputAWSRouter);
app.use('/api/aws', MpChannelAWSRouter);
/*
* API ROUTES
*/
app.use('/api', WorkflowRouter);
app.use('/api', ChannelRouter);
app.use('/api', InputRouter);
app.use('/api', MpchannelRouter);
/******
* ***********
* ***********
* CLI GENERATED API INSERTION
* ***********
* ***********
******/
/*
* AWS SDK Resource interaction
*/
app.use('/api/aws', GenappAWSRouter);
/*
* API ROUTES
*/
app.use('/api', GenappRouter);
app.use('/api', postRouter);
app.use('/api', FoodRouter);
app.use('/api', ChefRouter);
app.use('/api', PencilRouter);
app.use('/api', BookRouter);
app.use('/api', ShopcartRouter);
app.use('/api', LocationRouter);
app.use('/api', OrderRouter);
app.use('/api', ShipmentRouter);
app.use('/api', SearchRouter);
app.use('/api', SocialRouter);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${isProdMode ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
</head>
<body>
<div id="root">${process.env.NODE_ENV === 'production' ? html : `<div>${html}</div>`}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${isProdMode ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${isProdMode ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${isProdMode ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = isProdMode ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
server.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
|
import {
GET_ALL_SHOP_REQUEST,
GET_ALL_SHOP_SUCCESS,
GET_ALL_SHOP_FAIL,
POST_SHOP_REQUEST,
POST_SHOP_SUCCESS,
POST_SHOP_FAIL,
PUT_SHOP_REQUEST,
PUT_SHOP_SUCCESS,
PUT_SHOP_FAIL,
GET_BY_ID_SHOP_REQUEST,
GET_BY_ID_SHOP_SUCCESS,
GET_BY_ID_SHOP_FAIL,
DELETE_SHOP_REQUEST,
DELETE_SHOP_SUCCESS,
DELETE_SHOP_FAIL,
} from "../constants/shopConstants";
import {
getShopDataApi,
postShopDataApi,
putShopDataApi,
deleteShopDataApi,
} from "../apis/shopapis";
export const getShopDataAction = () => async (dispatch) => {
dispatch({ type: GET_ALL_SHOP_REQUEST });
try {
let { data } = await getShopDataApi();
dispatch({ type: GET_ALL_SHOP_SUCCESS, payload: data.result });
} catch (err) {
dispatch({
type: GET_ALL_SHOP_FAIL,
payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,
});
}
};
export const postShopDataAction = (data) => async (dispatch) => {
dispatch({ type: POST_SHOP_REQUEST });
try {
let { data: rdata } = await postShopDataApi(data);
if (rdata.status === "failed") {
throw Error(rdata.message);
}
dispatch({ type: POST_SHOP_SUCCESS });
} catch (err) {
dispatch({
type: POST_SHOP_FAIL,
payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,
});
}
};
export const putShopDataAction = (data) => async (dispatch) => {
dispatch({ type: PUT_SHOP_REQUEST });
try {
await putShopDataApi(data);
dispatch({ type: PUT_SHOP_SUCCESS });
} catch (err) {
dispatch({
type: PUT_SHOP_FAIL,
payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,
});
}
};
export const getShopDataByIdAction = (id) => async (dispatch) => {
dispatch({ type: GET_BY_ID_SHOP_REQUEST });
try {
let { data } = await getShopDataApi(id);
dispatch({ type: GET_BY_ID_SHOP_SUCCESS, payload: data.result });
} catch (err) {
dispatch({
type: GET_BY_ID_SHOP_FAIL,
payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,
});
}
};
export const deleteShopDataAction = (id) => async (dispatch) => {
dispatch({ type: DELETE_SHOP_REQUEST });
try {
await deleteShopDataApi(id);
dispatch({ type: DELETE_SHOP_SUCCESS });
} catch (err) {
dispatch({
type: DELETE_SHOP_FAIL,
payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,
});
}
};
|
function runTest()
{
FBTest.openNewTab(basePath + "console/grouping/simpleLogs.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.enableConsolePanel(function(win)
{
var tasks = new FBTest.TaskList();
tasks.push(verifyLogs, win, 12, 2, "testButton1", "Verify grouped logs");
tasks.push(verifyLogs, win, 51, "", "testButton2", "Verify not grouped logs");
tasks.run(function()
{
FBTest.testDone();
});
});
});
});
}
function verifyLogs(callback, win, numberOfLogs, expectedCounterValue, buttonId, message)
{
FBTest.progress(message);
FBTest.clearConsole();
var config = {
tagName: "div",
classes: "logRow",
counter: numberOfLogs
};
FBTest.waitForDisplayedElement("console", config, function(row)
{
// Let any additional logs to be created (which would be wrong,
// but we want to catch such case too).
setTimeout(function()
{
onVerify(callback, numberOfLogs, expectedCounterValue);
}, 200);
});
FBTest.click(win.document.getElementById(buttonId));
}
function onVerify(callback, numberOfLogs, expectedCounterValue)
{
var panelNode = FBTest.getPanel("console").panelNode;
// Iterate over all counters and check that they are equal to 2
var rows = panelNode.getElementsByClassName("logCounter");
FBTest.compare(numberOfLogs, rows.length, "There must be an expected number of logs");
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
var isNumberType = typeof(expectedCounterValue) == "number";
var actual = isNumberType ? parseInt(row.textContent, 10) : row.textContent;
// Log only failures
if (expectedCounterValue !== actual)
FBTest.compare(expectedCounterValue, actual, "The log counter must match");
}
callback();
}
|
var functions________________5________8js____8js__8js_8js =
[
[ "functions________5____8js__8js_8js", "functions________________5________8js____8js__8js_8js.html#ab27251817da599582cf26c85368b4d78", null ]
];
|
// index.js
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form'
import sites from './sites'
import github from './github'
import imageCredit from './imageCredit'
import color from './color'
import textColor from './textColor'
import background from './background';
const rootReducer = combineReducers({
sites,
github,
imageCredit,
color,
textColor,
background,
form: formReducer.plugin({
AddSiteForm: (state, action) => {
switch(action.type) {
case 'ADD_SITE':
return undefined;
default:
return state
}
}
})
});
export default rootReducer;
|
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios');
const { encodeWebSocketEvents, decodeWebSocketEvents, WebSocketContext, Publisher } = require('@fanoutio/grip');
const operations = require('./dbOps');
const { Session, SessionManager } = require("./session");
const { Turn, Theory } = require("./sessionObjects");
const websocketEventParser = async function(req, res, next) {
if(req.is("application/websocket-events")) {
let cid = req.headers['connection-id'];
if (Array.isArray(cid)) {
cid = cid[0];
}
const inEventsEncoded = await new Promise(resolve => {
let body = '';
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function() {
resolve(body);
});
});
const inEvents = decodeWebSocketEvents(inEventsEncoded);
const wsContext = new WebSocketContext(cid, {}, inEvents);
req.wsContext = wsContext;
next();
} else {
next();
}
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(websocketEventParser);
app.set("trust proxy", true);
let pushpinIPs;
const server = http.createServer({}, app);
const sessionManager = new SessionManager();
const refreshPublisher = function() {
const config = pushpinIPs.map((ip) => {
return {
'control_uri': 'http://' + ip + ":5561"
}
});
const publisher = new Publisher(config);
sessionManager.setPublisher(publisher);
}
const setup = async function() {
let IS_PROD;
if (process.env.LANDSCAPE === "PRODUCTION") {
IS_PROD = true;
} else {
IS_PROD = false;
}
console.log(JSON.stringify({level: "info", message: "Production: " + IS_PROD}));
if (IS_PROD) {
axios.get("http://prouter.prouter/pushpinIPs").then((response) => {
pushpinIPs = response.data.ips;
refreshPublisher();
console.log(JSON.stringify({level: "info", message: "pushpin IPs: " + pushpinIPs}));
return Promise.resolve();
});
} else {
pushpinIPs = ["localhost"];
refreshPublisher();
return Promise.resolve();
}
}
app.get("/createGame/:numSectors/", function(req, res, next) {
const numSectors = parseInt(req.params.numSectors);
const theme = req.query.theme || "space";
operations.pickGame(numSectors).then(({game, gameCode}) => {
if (game == undefined) {
res.json({success: false});
} else {
res.json({success: true, game: game.json(theme), gameCode});
}
});
});
app.get("/joinGame/:gameCode/", function(req, res, next) {
const theme = req.query.theme || "space";
operations.getGameByGameCode(req.params.gameCode).then(({game, gameCode}) => {
if (game == undefined) {
res.json({found: false});
} else {
res.json({found: true, game: game.json(theme), gameCode});
}
});
});
app.post("/createSession/:numSectors/", function(req, res, next) {
const numSectors = parseInt(req.params.numSectors);
const theme = req.body.theme || "space";
sessionManager.createSession(numSectors, req.body.name).then(async ({playerID, playerNum, session}) => {
const gameJson = await session.gameJson(theme);
const stateJson = await session.stateJson(theme);
console.log(JSON.stringify({level: "info", action: "Create Session", sectors: numSectors, name: req.body.name, success: true }));
res.json({
playerID,
playerNum,
game: gameJson,
state: stateJson
});
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Create Session", sectors: numSectors, name: req.body.name, success: false, error: err.message }));
})
});
app.post("/joinSession/:sessionCode/", function(req, res, next) {
const theme = req.body.theme || "space";
sessionManager.joinSession(req.params.sessionCode, req.body.name).then(async ({playerID, playerNum, session}) => {
if (session == undefined) {
console.log(JSON.stringify({level: "info", action: "Join Session", name: req.body.name, sessionCode: req.params.sessionCode, found: false}));
res.json({ found: false });
} else {
console.log(JSON.stringify({level: "info", action: "Join Session", name: req.body.name, sessionCode: req.params.sessionCode, found: true}));
const gameJson = await session.gameJson(theme);
const stateJson = await session.stateJson(theme);
res.json({
found: true,
playerID,
playerNum,
game: gameJson,
state: stateJson
});
}
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Join Session", name: req.body.name, sessionCode: req.params.sessionCode, error: err.message }));
});
});
app.get("/reconnectSession/:sessionCode", function(req, res, next) {
const sessionCode = req.params.sessionCode;
const playerNum = parseInt(req.query.playerNum);
const theme = req.query.theme || "space";
Session.findByCode(sessionCode).then(async (session) => {
const gameJson = await session.gameJson(theme);
const stateJson = await session.stateJson(theme);
const players = await session.getPlayers();
const myPlayers = players.filter((player) => player.num === playerNum);
if (myPlayers.length == 0) {
console.log(JSON.stringify({level: "info", action: "Reconnect Session", sessionCode, playerNum, found: false}));
res.json({
found: false
});
} else {
console.log(JSON.stringify({level: "info", action: "Reconnect Session", sessionCode, playerNum, found: true}));
const player = myPlayers[0];
res.json({
found: true,
game: gameJson,
state: stateJson,
playerID: player.playerID,
playerNum: player.num,
playerName: player.name
});
}
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Reconnect Session", sessionCode, playerNum, error: err.message }));
});
});
app.post("/setColor", function(req, res, next) {
const playerID = parseInt(req.query.playerID);
const color = parseInt(req.query.color);
sessionManager.setColor(playerID, color).then((allowed) => {
console.log(JSON.stringify({level: "info", action: "Set Color", playerID, color, allowed}));
res.json({allowed});
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Set Color", playerID, color, error: err.message }));
});
});
app.post("/castKickVote", function(req, res, next) {
const sessionID = parseInt(req.query.sessionID);
const playerID = parseInt(req.query.playerID);
const kickPlayerID = req.body.kickPlayerID;
const vote = req.body.vote;
sessionManager.castKickVote(sessionID, playerID, kickPlayerID, vote).then((allowed) => {
console.log(JSON.stringify({level: "info", action: "Cast Kick Vote", sessionID, playerID, kickPlayerID, vote, allowed}));
res.json({allowed});
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Cast Kick Vote", sessionID, playerID, kickPlayerID, vote, error: err.message}));
});
});
app.post("/startSession/", function(req, res, next) {
const sessionID = parseInt(req.query.sessionID);
const playerID = parseInt(req.query.playerID);
sessionManager.startSession(sessionID, playerID).then((result) => {
console.log(JSON.stringify({level: "info", action: "Start Session", sessionID, playerID, allowed: result }));
res.json({allowed: result});
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Start Session", sessionID, playerID, error: err.message }));
});
});
app.post("/submitTheories/", function(req, res, next) {
const sessionID = parseInt(req.query.sessionID);
const playerID = parseInt(req.query.playerID);
const turn = req.body.turn;
const theme = req.body.theme || "space";
const theories = req.body.theories.map((t) => Theory.fromJson(t, theme));
sessionManager.submitTheories(sessionID, playerID, theories, turn).then(({ allowed, successfulTheories}) => {
console.log(JSON.stringify({level: "info", action: "Submit Theories", sessionID, playerID, theories: theories.map((t) => t.json(theme)), allowed: allowed, successfulTheories: successfulTheories.map((t) => t.json(theme))}));
res.json({
allowed,
successfulTheories: successfulTheories.map((t) => t.json(theme))
});
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Submit Theories", sessionID, playerID, theories: theories.map((t) => t.json(theme)), error: err.message }));
});
});
app.post("/readConference/", function(req, res, next) {
const sessionID = parseInt(req.query.sessionID);
const playerID = parseInt(req.query.playerID);
sessionManager.readConference(sessionID, playerID).then((allowed) => {
console.log(JSON.stringify({level: "info", action: "Read Conference", sessionID, playerID, allowed }));
res.json({ allowed })
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Read Conference", sessionID, playerID, error: err.message }));
});
});
app.post("/makeMove/", function(req, res, next) {
const sessionID = parseInt(req.query.sessionID);
const playerID = parseInt(req.query.playerID);
const sectors = req.body.timeCost;
const turnData = Object.assign({
sessionID: req.query.sessionID,
playerID: req.query.playerID,
time: new Date()
}, req.body.turn);
const theme = req.body.theme || "space";
const turn = Turn.fromJson(turnData, theme);
sessionManager.makeMove(sessionID, playerID, turn, sectors).then((allowed) => {
console.log(JSON.stringify({level: "info", action: "Make Move", turnType: turn.turnType, sessionID, playerID, timeCost: sectors, turn: turn.json(theme), allowed}));
res.json({ allowed });
}).catch((err) => {
console.log(JSON.stringify({level: "error", action: "Make Move", turnType: turn.turnType, sessionID, playerID, timeCost: sectors, turn: turn.json(theme), error: err.message }));
});
});
app.post("/refreshPushpin/", function(req, res, next) {
res.json({});
pushpinIPs = req.body.ips;
refreshPublisher();
console.log(JSON.stringify({level: "info", message: "Received request to refresh pushpin ips: " + pushpinIPs }));
});
app.post("/listenSession/:sessionID/:theme?", async function(req, res, next) {
const theme = req.params.theme || "space";
const wsContext = req.wsContext;
if (wsContext.isOpening()) {
console.log(JSON.stringify({level: "info", message: "Received listen request for session " + req.params.sessionID }));
wsContext.accept();
wsContext.subscribe(req.params.sessionID + "-" + theme);
const outEvents = wsContext.getOutgoingEvents();
const outEventsEncoded = encodeWebSocketEvents(outEvents);
res.writeHead(200, wsContext.toHeaders());
res.write(outEventsEncoded);
res.end();
} else if (wsContext.inEvents.some((e) => e.type === "TEXT")) {
const textEvent = wsContext.inEvents.find((e) => e.type === "TEXT");
const playerID = JSON.parse(textEvent.content).id;
console.log(JSON.stringify({level: "info", message: "Websocket identified for player " + playerID}));
sessionManager.setPlayerConnected(playerID, true).then(() => {
res.writeHead(200, Object.assign(
{"Set-Meta-PlayerID": playerID.toString()},
wsContext.toHeaders()));
res.end();
});
} else if (wsContext.inEvents.some((e) => e.type === "CLOSE" || e.type === "DISCONNECT")) {
const playerID = req.header("Meta-PlayerID");
console.log(JSON.stringify({level: "info", message: "Websocket closed for player " + playerID}));
sessionManager.setPlayerConnected(playerID, false).then(() => {
res.writeHead(200, wsContext.toHeaders());
res.end();
});
} else {
res.writeHead(200, wsContext.toHeaders());
res.end();
}
});
setup().then(() => {
console.log(JSON.stringify({level: "info", message: "Starting server..."}));
server.listen(8000);
});
|
import React, { Component } from 'react'
import Main from '../components/Main/Main'
class App extends Component {
constructor() {
super()
this.state = {
teams: [
{id: 1, name: 'Reikland Reavers', image: '../../images/bb-human.png'},
{id: 2, name: 'Da Deff Skwadd', image: '../../images/bb-orc.png'},
{id: 3, name: 'Grudge Bearers', image: '../../images/bb-dwarf.png'},
{id: 4, name: 'Darkside Cowboys', image: '../../images/bb-darkelf.png'},
{id: 5, name: 'Khornes Killers', image: '../../images/bb-chaos.png'},
{id: 6, name: 'Tombstone Terrors', image: '../../images/bb-undead.png'}
],
scores: [ 0, 0],
selected: [
{id: 1},
{id: 2}]
}
}
modifyScore = (teamOption, value) => {
this.setState({scores: this.state.scores[teamOption] + value})
};
_OnSelect = (teamOption, option) => {
this.setState({selected: this.state.selected[teamOption] = option})
}
render() {
return (
<Main
teams = {this.state.teams}
scores = {this.state.scores}
selected = {this.state.selected}
modifyScore = {this.modifyScore}
_OnSelect = {this._OnSelect} />
)
}
}
export default App;
|
var gulp = require('gulp'),
given = require('gulp-if'),
jsx = require('gulp-react'),
rename = require('gulp-rename'),
minifyjs = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps');
gulp.task('build', function() {
gulp.src('./src/react-infinite-list.jsx')
.pipe(sourcemaps.init())
.pipe(jsx())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
gulp.task('buildproduction', function() {
gulp.src("./src/react-infinite-list.jsx")
.pipe(rename("react-infinite-list.min.jsx"))
.pipe(jsx())
.pipe(minifyjs())
.pipe(gulp.dest('dist'));
})
gulp.task('default', ['build', 'buildproduction']);
|
import React from "react";
import renderer from "react-test-renderer";
import MiniLineGraph from "./index";
test("MiniLineGraph renders correctly", () => {
const tree = renderer
.create(<MiniLineGraph data={[5, 10, 5, 20, 8, 15, 5, 10, 5, 20, 8, 15]} />)
.toJSON();
expect(tree).toMatchSnapshot();
});
|
const btns = Array.from(document.querySelectorAll('.shower'))
const allDoubles= Array.from(document.getElementsByClassName('doubleBtn'))
const show = idx => {
const inputs = document.querySelectorAll(`#form${idx} .input`)
const double = document.querySelectorAll(`#form${idx} .doubleBtn`)
const selections = document.querySelectorAll(`#form${idx} .selection`)
const radios = document.querySelectorAll(`#form${idx} .radio`)
Array.from(inputs).forEach(inpt => inpt.readOnly = !inpt.readOnly)
Array.from(double)[0].style.maxHeight === '0px' ? Array.from(double)[0].style.maxHeight = '41px' : Array.from(double)[0].style.maxHeight = '0px'
Array.from(selections).forEach(slct => slct.disabled = !slct.disabled)
Array.from(radios).forEach(rd=> rd.disabled = !rd.disabled)
}
const initialize = () => allDoubles.forEach(btn => btn.style.maxHeight = '0px')
document.addEventListener('load', initialize())
btns.forEach((btn, idx) => btn.addEventListener('click', () => show(idx) ))
|
/**
* Created by chadsfather on 28/12/15.
*/
var mongoose = require('mongoose'),
autoIncrement = require('mongoose-auto-increment');
var UserSchema = mongoose.Schema({
'_id': 'Number',
'username': 'String',
'password': 'String',
'email': 'String',
'firstname': 'String',
'lastname': 'String',
'birthdayday': 'String',
'birthdaymonth': 'String',
'birthdayyear': 'String',
'emailsended': {
'type': 'Bool',
'default': false
},
'emailverifyed': {
'type': 'Bool',
'default': false
},
'location': {
'type': 'String',
'default': null
},
'userfolder': {
'type': 'String',
'default': null
},
'routesfolder': {
'type': 'String',
'default': null
},
'logintype': {
'type': 'String',
'default': 'form'
},
'locale': {
'type': 'String',
'default': 'en'
},
'role': {
'type': 'String',
'default': 'user'
}
});
var IdiomsSchema = mongoose.Schema({
'_id': 'Number',
'key': 'String',
'translates': {}
});
var LanguagesSchema = mongoose.Schema({
'_id': 'Number',
'languages': []
});
/**
* Iniciamos mongo con el plugin de autoincremento
*/
autoIncrement.initialize(mongoose.connect(process.env.MONGOLAB_URI));
/**
* Schema para usuarios
*/
UserSchema.plugin(autoIncrement.plugin, 'User');
//UserSchema.plugin(passportLocalMongoose);
/**
* Schema para idiomas
*/
IdiomsSchema.plugin(autoIncrement.plugin, 'Idioms');
/**
* Schema para lenguages
*/
LanguagesSchema.plugin(autoIncrement.plugin, 'Languages');
exports.model = function(model) {
var models = {
'User': mongoose.model('User', UserSchema),
'Idioms': mongoose.model('Idioms', IdiomsSchema),
'Languages': mongoose.model('Languages', LanguagesSchema)
};
return models[model];
};
|
module.exports = {
swDest: 'sw-inj.js',
swSrc: 'sw.js',
globDirectory: "src/dist",
globPatterns: [
"**/*.{html,ico,svg,png,js,css}"
],
globIgnores: ['bundle.js'], // 忽略的文件
};
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('Userinfo', new Schema({
name: String,
sex: String,
age: Number,
address:String,
rank: Number,
ticket: String
// comment:[{body:String,date:Date}],
// tags:[{title:String}],
// date:{type:Date,default:Date.now},
// hidden: Boolean,
// mete:{
// vores:Number,
// favs: Number
// }
}))
|
const deploymentSchema = require('../../schemas/deploymentschema');
const deploymentTemplateSchema = require('../../schemas/deploymenttemplateschema');
module.exports.getAllDeployments = () => new Promise((resolve, reject) => {
deploymentSchema.find({}, function (err, data) {
if (err) {
reject(err)
} else {
console.log(data);
resolve(data);
}
});
});
module.exports.getAllDeploymentTemplate = () => new Promise((resolve, reject) => {
deploymentTemplateSchema.find({}, function (err, data) {
if (err) {
reject(err)
} else {
console.log(data);
resolve(data);
}
});
});
module.exports.deleteDeploymentList = (id) => new Promise((resolve, reject) => {
deploymentSchema.deleteOne({ _id : id }, function (err, data) {
if (err) {
reject(err)
} else {
console.log(data);
resolve("Deleted successfully");
}
});
});
module.exports.addDeploymentList = (data) => new Promise((resolve, reject) => {
var deploymentObject = new deploymentSchema({
name: data.name,
versions: data.versions,
url: data.url
});
deploymentObject.save(function (err) {
if (err) {
reject(err);
} else {
console.log('UserObject saved successfully!');
resolve('UserObject saved successfully!');
}
});
});
|
import CampaignObjectives from '../models/ad/campaignObjectives';
import AdFormats from '../models/ad//adFormats';
import CallToActions from '../models/ad/callToActions';
// https://developers.facebook.com/docs/marketing-api/validation/v2.12
// https://www.facebook.com/business/ads-guide
// const Mapping = {
// [AdFormat]: {
// [CampaignObjective]: [CallToActions]
// }
// }
const imageMapping = {
[CampaignObjectives.reach]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.call_now,
CallToActions.contact_us,
CallToActions.download,
CallToActions.get_directions,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.send_message,
CallToActions.request_time,
CallToActions.save,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.brand_awareness]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.contact_us,
CallToActions.download,
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.get_showtimes,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.post_engagement]: [
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.shop_now,
],
[CampaignObjectives.page_likes]: [],
[CampaignObjectives.event_responses]: [
CallToActions.view_event,
],
[CampaignObjectives.app_installs]: [
CallToActions.install_now,
CallToActions.use_app,
CallToActions.book_travel,
CallToActions.download,
CallToActions.learn_more,
CallToActions.listen_now,
CallToActions.play_game,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
],
};
const videoMapping = {
[CampaignObjectives.reach]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.call_now,
CallToActions.contact_us,
CallToActions.download,
CallToActions.get_directions,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.send_message,
CallToActions.request_time,
CallToActions.save,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.brand_awareness]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.call_now,
CallToActions.contact_us,
CallToActions.download,
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.get_showtimes,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.post_engagement]: [
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.shop_now,
],
[CampaignObjectives.page_likes]: [],
[CampaignObjectives.event_responses]: [
CallToActions.view_event,
],
[CampaignObjectives.app_installs]: [
CallToActions.install_now,
CallToActions.use_app,
CallToActions.book_travel,
CallToActions.download,
CallToActions.learn_more,
CallToActions.listen_now,
CallToActions.play_game,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
],
[CampaignObjectives.lead_generation]: [
CallToActions.subscribe,
CallToActions.sign_up,
CallToActions.learn_more,
CallToActions.apply_now,
CallToActions.download,
CallToActions.get_quote,
],
[CampaignObjectives.video_views]: [
CallToActions.shop_now,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.book_travel,
CallToActions.download,
CallToActions.watch_more,
CallToActions.send_message,
CallToActions.listen_now,
],
[CampaignObjectives.conversions]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.contact_us,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.play_game,
CallToActions.get_offer,
],
[CampaignObjectives.store_visits]: [
CallToActions.call_now,
CallToActions.get_directions,
CallToActions.get_offer,
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.order_now,
CallToActions.shop_now,
],
};
const carouselMapping = {
[CampaignObjectives.reach]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.call_now,
CallToActions.contact_us,
CallToActions.download,
CallToActions.get_directions,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.send_message,
CallToActions.request_time,
CallToActions.save,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.brand_awareness]: [
CallToActions.apply_now,
CallToActions.book_travel,
CallToActions.contact_us,
CallToActions.download,
CallToActions.learn_more,
CallToActions.send_message,
CallToActions.get_showtimes,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
CallToActions.listen_now,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.link_clicks]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.contact_us,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.get_offer,
],
[CampaignObjectives.app_installs]: [
CallToActions.install_now,
CallToActions.use_app,
CallToActions.book_travel,
CallToActions.download,
CallToActions.learn_more,
CallToActions.listen_now,
CallToActions.play_game,
CallToActions.shop_now,
CallToActions.sign_up,
CallToActions.watch_more,
],
[CampaignObjectives.lead_generation]: [
CallToActions.subscribe,
CallToActions.sign_up,
CallToActions.learn_more,
CallToActions.apply_now,
CallToActions.download,
CallToActions.get_quote,
],
[CampaignObjectives.conversions]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.watch_more,
CallToActions.apply_now,
CallToActions.donate_now,
CallToActions.contact_us,
CallToActions.request_time,
CallToActions.see_menu,
CallToActions.send_message,
CallToActions.listen_now,
CallToActions.play_game,
],
[CampaignObjectives.product_catalog_sales]: [
CallToActions.shop_now,
CallToActions.book_travel,
CallToActions.learn_more,
CallToActions.get_showtimes,
CallToActions.sign_up,
CallToActions.download,
CallToActions.open_link,
CallToActions.donate_now,
CallToActions.listen_now,
],
};
const collectionMapping = {
[CampaignObjectives.link_clicks]: [],
[CampaignObjectives.conversions]: [],
[CampaignObjectives.store_visits]: [],
};
const CallToActionMapping = {
//video
[AdFormats.video]: videoMapping,
[AdFormats.slideshow]: videoMapping,
//image
[AdFormats.image]: imageMapping,
//carousel
[AdFormats.carousel]: carouselMapping,
//collection
[AdFormats.collection]: collectionMapping,
}
export default CallToActionMapping;
|
export * from './dog'
export * from './validate-dog'
|
import { Link } from 'react-router-dom'
import '../static/css/get.css'
function Get(){
return (
<div className="get_note">
<div className="get_note_item">
<div><img src="https://t7.baidu.com/it/u=2295206085,4139296147&fm=193&f=GIF" /></div>
<div>hello word</div>
<button><Link to="/detailed?id=1">详情页</Link></button>
</div>
<div className="get_note_item">
<div><img src="https://t7.baidu.com/it/u=2295206085,4139296147&fm=193&f=GIF" /></div>
<div>hello word</div>
<button>
<Link to="/detailed?id=1">详情页</Link>
</button>
</div>
</div>
)
}
export default Get
|
/*
Crie uma variável qualquer, que receba um array com alguns valores aleatórios
- ao menos 5 - (fica por sua conta os valores do array).
*/
var vetor = [3,5,4,6,7];
/*
Crie uma função que receba um array como parâmetro, e retorne esse array.
*/
function myArray(arg){
return arg;
}
/*
Imprima o segundo índice do array retornado pela função criada acima.
*/
myArray(vetor)[1];
/*
Crie uma função que receba dois parâmetros: o primeiro, um array de valores; e o
segundo, um número. A função deve retornar o valor de um índice do array que foi passado
no primeiro parâmetro. O índice usado para retornar o valor, deve ser o número passado no
segundo parâmetro.
*/
function myFunction(vetor, indice){
return vetor[indice];
}
/*
Declare uma variável que recebe um array com 5 valores, de tipos diferentes.
*/
var array = [1, 'string', null, true, 1.73];
/*
Invoque a função criada acima, fazendo-a retornar todos os valores do último
array criado.
*/
myFunction(array,0);
myFunction(array,1);
myFunction(array,2);
myFunction(array,3);
myFunction(array,4);
/*
Crie uma função chamada `book`, que recebe um parâmetro, que será o nome do
livro. Dentro dessa função, declare uma variável que recebe um objeto com as
seguintes características:
- esse objeto irá receber 3 propriedades, que serão nomes de livros;
- cada uma dessas propriedades será um novo objeto, que terá outras 3
propriedades:
- `quantidadePaginas` - Number (quantidade de páginas)
- `autor` - String
- `editora` - String
- A função deve retornar o objeto referente ao livro passado por parâmetro.
- Se o parâmetro não for passado, a função deve retornar o objeto com todos
os livros.
*/
function book(nomeLivro){
var livros = {
'o simbolo perdido': {
quantidadePaginas: 300,
autor: 'dan brown',
editora: 'arqueiro'
},
'uma breve historia do tempo': {
quantidadePaginas: 300,
autor: 'stephen hawking',
editora: 'intrinseca'
},
'a startup enxuta': {
quantidadePaginas: 300,
autor: 'eric ries',
editora: 'leya'
}
};
return !nomeLivro ? livros : livros[nomeLivro];
}
/*
Usando a função criada acima, imprima o objeto com todos os livros.
*/
book();
/*
Ainda com a função acima, imprima a quantidade de páginas de um livro qualquer,
usando a frase:
"O livro [NOME_DO_LIVRO] tem [X] páginas!"
*/
var nomeLivro = 'uma breve historia do tempo';
'O livro ' + nomeLivro + ' tem ' + book(nomeLivro).quantidadePaginas + ' páginas!';
/*
Ainda com a função acima, imprima o nome do autor de um livro qualquer, usando
a frase:
"O autor do livro [NOME_DO_LIVRO] é [AUTOR]."
*/
'O autor do livro ' + nomeLivro + ' é ' + book(nomeLivro).autor + '.';
/*
Ainda com a função acima, imprima o nome da editora de um livro qualquer, usando
a frase:
"O livro [NOME_DO_LIVRO] foi publicado pela editora [NOME_DA_EDITORA]."
*/
'O livro ' + nomeLivro + ' foi publicado pela editora ' + book(nomeLivro).editora + '.';
|
import React, {Component} from "react";
import {Button, Card, Dropdown, Icon, Menu} from "antd";
function handleMenuClick(e) {
console.log('click', e);
}
const menu = (
<Menu onClick={handleMenuClick}>
<Menu.Item key="1">1st item</Menu.Item>
<Menu.Item key="2">2nd item</Menu.Item>
<Menu.Item key="3">3rd item</Menu.Item>
</Menu>
);
class Multiple extends Component {
render() {
return (
<Card className="gx-card" title="Multiple">
<Button type="primary">primary</Button>
<Button>secondary</Button>
<Dropdown overlay={menu}>
<Button>
Actions <Icon type="down"/>
</Button>
</Dropdown>
</Card>
);
}
}
export default Multiple;
|
import "./NullData.css"
class NullData extends React.Component {
render(){
return (
<div className={this.state.showState}>暂无数据</div>
)}
constructor(props){
super(props);
this.state={
showState:"NULL_DATA_hidden",
timmer:null
};
}
componentDidMount(){
const time=setTimeout(function(){
this.setState({showState:"NULL_DATA_show"})
}.bind(this),1000)
this.setState({timmer:time})
}
componentWillUnmount(){
clearTimeout(this.state.timmer)
}
}
export default NullData
|
var commandText = function(text){
return "[[g;#EEEEEE;]" + text + "]";
}
var titleText = function(text){
return "[[u;inherit;]" + text + "]";
}
var App = {
motd: function(ret){
if (typeof ret === 'undefined') ret = false;
var greetText =
"####################################################################################\n"+
"|[[b;#00DE12;]\t _ ]\t|\n"+
"|[[b;#00DE12;]\t _ __ ___ _ __ _ __ (_) ___ _ __ _ _ _ __ ___ ___ ___ _ __ ___ ]\t|\n"+
"|[[b;#00DE12;]\t| '__/ _ \\| '_ \\| '_ \\| |/ _ \\ '_ \\| | | | '_ \\ / _ \\ / __/ _ \\| '_ ` _ \\ ]\t|\n"+
"|[[b;#00DE12;]\t| | ( (_) ) | | | | | | | __/ (_) | |_| | | | | __/( (_| (_) | | | | | |]\t|\n"+
"|[[b;#00DE12;]\t|_| \\___/|_| |_|_| |_|_|\\___| .__/ \\__. |_| |_|\\___( )___\\___/|_| |_| |_|]\t|\n"+
"|[[b;#00DE12;]\t |_| |___/ ]\t|\n"+
"|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t |\n"+
"|\tHi, I'm " + commandText('Ronnie Pyne') + " - Full Stack PHP Web Developer in Sydney, Australia. \t|\n"+
"|\tPlease type " + commandText('menu') + " for a list of commands. \t\t\t\t\t\t\t\t\t|\n"+
"|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t |\n"+
"####################################################################################\n";
if (!ret) {
this.echo("\n" + greetText);
} else {
return greetText;
}
},
menu: function(){
this.echo();
this.echo("| " + commandText("motd") + " - Display Message of the Day");
this.echo();
this.echo("| " + commandText("about") + " - Summary of me");
this.echo("| " + commandText("projects") + " - Some recent projects of mine");
this.echo("| " + commandText("skills") + " - What I can do");
this.echo("| " + commandText("awards") + " - Awards and features for my work");
this.echo();
this.echo("| " + commandText("github") + " - Das github");
this.echo("| " + commandText("linkedin") + " - How I connect for work things");
this.echo("| " + commandText("facebook") + " - My personal social area");
this.echo("| " + commandText("twitter") + " - When 140 characters is enough");
this.echo();
this.echo("| " + commandText("contact") + " - Contact me")
this.echo("| " + commandText("credits") + " - Credits for this website");
this.echo();
this.echo("| " + commandText("all") + " - Run all commands");
this.echo();
},
github: function(){
this.echo();
this.echo("| http://www.github.com/perverse");
this.echo();
},
facebook: function(){
this.echo();
this.echo("| http://www.facebook.com/perverse");
this.echo();
},
linkedin: function(){
this.echo();
this.echo("| https://www.linkedin.com/profile/view?id=298500285");
this.echo();
},
twitter: function(){
this.echo();
this.echo("| http://www.twitter.com/perverse_8P");
this.echo();
},
about: function(){
this.echo();
this.echo("| Name: " + commandText('Ronnie Pyne'));
this.echo("| DOB: 25/11/1985");
this.echo("| Location: " + commandText('Surry Hills, NSW'));
this.echo();
this.echo("| Vocation: I am a Full Stack Web Developer (primarily " + commandText('PHP') + ", " + commandText('Node.js') + ") and DevOps (Linux, AWS) specialist.");
this.echo("| I have been coding in a commercial environment for " + commandText('over 12 years.'));
this.echo("| My main weapons of choice on the front end are " + commandText('Angular.js') + " and " + commandText('jQuery.'));
this.echo();
this.echo("| Employment: I am currently " + commandText("freelancing") + " in the " + commandText("Sydney, NSW") + " area, but am always open to interesting opporunities of all kinds. Get in touch if you'd like to discuss a proposal!");
this.echo();
},
projects: function(){
this.echo();
this.echo("| " + commandText('Lendlease Digital Signage DSP/CMS') + " https://goo.gl/aZgIrW // Lead Developer");
this.echo("| " + commandText('SimplyAskIt') + " http://www.simplyaskit.com.au // Backend Developer");
this.echo("| " + commandText('Audi - Land of Quattro') + " http://www.holler.com.au/work/audi-loq // Backend Lead");
this.echo("| " + commandText('Heineken - Open Your City') + " http://www.holler.com.au/work/open-your-city // Backend Lead");
this.echo("| " + commandText('Betta Electrical') + " http://www.betta.com.au // Backend Developer");
this.echo("| " + commandText('Baptist World Aid Australia') + " http://www.baptistworldaid.org.au // Backend Lead");
this.echo();
},
skills: function(){
this.echo();
this.echo("| " + commandText('Languages'));
this.echo();
this.echo("| " + commandText('PHP') + " ##[[g;#00DE12;]#################################################] ##");
this.echo("| " + commandText('Linux') + " ##[[g;#42D100;]###############################################] ##");
this.echo("| " + commandText('Node.js') + " ##[[g;#5BD100;]############################################] ##");
this.echo("| " + commandText('Javascript') + " ##[[g;#5BD100;]############################################] ##");
this.echo("| " + commandText('CSS') + " ##[[g;#99D100;]#########################################] ##");
this.echo("| " + commandText('HTML5') + " ##[[g;#B2D100;]#######################################] ##");
this.echo("| " + commandText('MongoDB') + " ##[[g;#D1B900;]############################] ##");
this.echo("| " + commandText('.NET MVC (C#)') + " ##[[g;#D16200;]###########] ##");
this.echo();
this.echo("| " + commandText("Frameworks and CMS"));
this.echo();
this.echo("| " + commandText('Laravel') + " ##[[g;#42D100;]###############################################] ##");
this.echo("| " + commandText('AngularJS') + " ##[[g;#42D100;]###############################################] ##");
this.echo("| " + commandText('Silverstripe') + " ##[[g;#5BD100;]#############################################] ##");
this.echo("| " + commandText('Sails.js') + " ##[[g;#99D100;]#########################################] ##");
this.echo("| " + commandText('Express') + " ##[[g;#B2D100;]########################################] ##");
this.echo("| " + commandText('Symfony') + " ##[[g;#D1B900;]################################] ##");
this.echo("| " + commandText('Zend Framework') + " ##[[g;#D1B900;]############################] ##");
this.echo();
this.echo("| " + commandText("Other"));
this.echo();
this.echo("| " + commandText('AWS') + " ##[[g;#5BD100;]############################################] ##");
this.echo("| " + commandText('Grunt/Gulp') + " ##[[g;#B2D100;]#######################################] ##");
this.echo("| " + commandText('Virtualbox') + " ##[[g;#B2D100;]#######################################] ##");
this.echo("| " + commandText('Docker') + " ##[[g;#B2D100;]#####################################] ##");
this.echo("| " + commandText('Vagrant') + " ##[[g;#D13F00;]#########] ##");
this.echo();
},
contact: function(){
this.echo();
this.echo("| " + commandText("Email") + ": ronniepyne@gmail.com");
this.echo("| " + commandText("LinkedIn") + ": http://www.linkedin.com/profile/view?id=298500285");
this.echo();
},
credits: function(){
this.echo();
this.echo("| Site built by " + commandText('Ronnie Pyne'));
this.echo("| Using " + commandText('Jquery Terminal Emulator') + " by " + commandText('Jakub Jankiewicz') + ": http://terminal.jcubic.pl");
this.echo();
},
awards: function(){
this.echo();
this.echo("| " + commandText('FWA Site of the Day') + ", 24th September 2013 | Audi - Land of Quattro http://www.thefwa.com/site/audi-australia-land-of-quattro");
this.echo("| " + commandText('Google Sandbox') + " | Audi - Land of Quattro http://www.thinkwithgoogle.com/campaigns/audi-australia-land-of-quattro.html");
this.echo();
},
all: function(){
this.clear();
this.exec('motd');
this.exec('about');
this.exec('projects');
this.exec('skills');
this.exec('awards');
this.exec('github');
this.exec('linkedin');
this.exec('facebook');
this.exec('twitter');
this.exec('contact');
this.exec('credits');
},
ls: function(){
this.exec('menu');
}
}
jQuery(document).ready(function($) {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
window.location.href = "https://www.linkedin.com/profile/view?id=298500285";
} else {
$('body').terminal(App, {
greetings: function(cb){
cb(App.motd(true));
},
onBlur: function() {
// prevent loosing focus
return false;
},
completion: true,
checkArity: false
});
}
});
|
// Start by creating a variable `message`
let nanombre = "Jaime";
let namelength = nanombre.length;
let message = "My name is " + nanombre + " and my name is " + nanombre.length + " characters long";
console.log(message);
|
function runTest()
{
FBTest.openNewTab(basePath + "console/3078/issue3078.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.enableConsolePanelAndReload(function()
{
var panel = FBTest.getSelectedPanel();
// Ensure that the console starts scrolled to bottom.
panel.clear();
// Wait that the last log appears.
// This ensures that at least one message has been logged and that the scrollbar
// has appeared.
FBTest.waitForDisplayedText("console", "299", function()
{
var scrolled = FW.FBL.isScrolledToBottom(panel.panelNode);
if (!scrolled)
{
FBTest.progress("isScrolledToBottom offsetHeight: " +
panel.panelNode.offsetHeight + ", scrollTop: " +
panel.panelNode.scrollTop + ", scrollHeight: " +
panel.panelNode.scrollHeight);
}
FBTest.ok(scrolled, "Panel must be scrolled to the bottom");
FBTest.testDone();
});
});
});
});
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.dynamicClass = undefined;
var _models = require('./../models');
var storageRegister = { // eslint-disable-line
Products: {
isCached: true,
maxKey: 0
},
Users: {
isCached: true,
maxKey: 0
},
Images: {
isCached: true,
maxKey: 0
},
detailPost: {
isCached: true,
maxKey: 0
},
listPosts: {
isCached: true,
maxKey: 0
}
};
var dynamicClass = exports.dynamicClass = function dynamicClass(name, args) {
// eslint-disable-line
return new _models.models[name](args); // eslint-disable-line
};
exports.default = storageRegister;
|
import React from 'react'
import { SignUpUser } from "../actions/userActions";
import { connect } from 'react-redux'
import { Button, Form, Grid, Header, Image, Segment, Checkbox } from 'semantic-ui-react'
import { Redirect } from "react-router";
class SignUp extends React.Component {
state = {
user_name: '',
password: '',
passwordConfirmation: '',
first_name: '',
last_name: '',
email:'',
profile_picture: '',
phone: '',
location: '',
signedUp: false,
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
if (this.state.password !== this.state.passwordConfirmation){
alert(`password don't match, try again`)
} else{
this.setState({ signedUp: true })
this.props.SignUpUser(this.state.user_name, this.state.password, this.state.first_name, this.state.last_name, this.state.email, this.state.profile_picture, this.state.phone, this.state.location )
}
}
renderSignUpForm = () => {
return <div className='login-form'>
<style>{`
body > div,
body > div > div,
body > div > div > div.login-form {
height: 101%;
}
`}</style>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 400 }}>
<Segment stacked>
{/* <Image src='./images/login-logo.png' width='200px' verticalAlign='middle'/> */}
<Header as='h1' color='grey' textAlign='center'>
Sign Up
</Header>
<Form size='large' onSubmit={this.handleSubmit}>
<Form.Group >
<Form.Input width={8} name="first_name" value={this.state.first_name} type="text" placeholder="First Name" onChange={this.handleChange} />
<Form.Input width={8} name="last_name" value={this.state.last_name} type="text" placeholder="Last Name" onChange={this.handleChange} />
</Form.Group>
<Form.Input name="email" value={this.state.email} type="text" placeholder="Email" onChange={this.handleChange} />
<Form.Input name="profile_picture" value={this.state.profile_picture} type="text" placeholder="Profile Picture Link" onChange={this.handleChange} />
<Form.Input name="user_name" value={this.state.user_name} type="text" placeholder="username" onChange={this.handleChange} />
<Form.Input name="location" value={this.state.location} type="text" placeholder="location" onChange={this.handleChange} />
<Form.Input name="phone" value={this.state.phone} type="text" placeholder="phone" onChange={this.handleChange} />
<Form.Input name="password" value={this.state.password} type="password" placeholder="Password" onChange={this.handleChange}/>
<Form.Input name="passwordConfirmation" value={this.state.passwordConfirmation} type="password" placeholder="Confirm Password" onChange={this.handleChange}/>
<Form.Field control={Checkbox} label={{ children: 'I agree to the Terms and Conditions' }} />
<Button fluid size='large'>
SignUp
</Button>
</Form>
Already have an account? <a href='/login'>Login</a>
</Segment>
</Grid.Column>
</Grid>
</div>
}
render(){
//console.log("sign-up", this.state.phone)
return this.state.signedUp ? <Redirect to="/login" /> : <div>{this.renderSignUpForm()}</div>
}
}
export default connect(null, { SignUpUser })(SignUp)
|
$(document).ready(function() {
console.log("document before1")
var doorStatus;
$.get("trigger.php", function(data) {
console.log("document middle1")
doorStatus=data;
});
console.log($doorStatus)
console.log("document after1")
});
|
let Product = require('../models/productModel')
let Customer = require('../models/customerModel')
var product = new Product()
var customer = new Customer()
exports.index = function (request, response) {
Product.get(function (err, products) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
} else {
response.json(
{
status: 'success',
code: 200,
message: 'List of products',
data: products
}
)
}
})
}
exports.newCategory = function (request, response) {
product.category = request.body.category
product.save(function (err) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
} else {
response.json({
status: 'success',
code: 200,
message: 'category saved!',
data: product
})
}
})
}
exports.newProduct = function (request, response) {
let product = {
name: request.body.name,
description: request.body.description,
images: [
{
filename: request.file.filename,
path: '/images/' + request.file.filename,
mimetype: request.file.mimetype,
originalname: request.file.originalname,
size: request.file.size
}
]
}
Product.updateOne({ "_id": request.body.categoryId }, { $push: { 'listProducts': product } }, function (err) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
} else {
response.json(
{
status: 'success',
code: 200,
message: 'product agregated!'
}
)
}
})
}
exports.detailProduct = function (request, response) {
Product.find({ "_id": request.params.id }, { listProducts: { $elemMatch: { "name": request.params.name } } }, function (err, product) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
} else {
response.json(
{
status: 'success',
code: 200,
message: 'product found!',
data: product
}
)
}
})
}
exports.editProduct = function (request, response) {
var producto = request.body
let product = {
name: producto.editname,
description: producto.editdescription,
images: [
{
_id: producto.imageId,
filename: request.file.filename,
path: '/images/' + request.file.filename,
mimetype: request.file.mimetype,
originalname: request.file.originalname,
size: request.file.size
}
]
}
Product.findOneAndUpdate({ '_id': producto.categoryId, 'listProducts._id': producto.productId }, { $set: { 'listProducts.$': product } }, function (err) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
} else {
response.json(
{
status: 'success',
code: 200,
message: 'product updated!'
}
)
}
})
}
exports.delete = function (request, response) {
Product.updateOne({ "_id": request.body.idCategory }, { $pull: { "listProducts": { "_id": request.body.idProduct } } }, function (err) {
if (err) {
response.json(
{
status: "error",
code: 500,
message: err
}
)
} else {
response.json(
{
status: "success",
code: 200,
message: "product deleted!"
}
)
}
});
}
exports.contact = function (request, response) {
customer.name = request.body.name
customer.lastname = request.body.lastname
customer.phone = request.body.phone
customer.email = request.body.email
customer.product = request.body.product
customer.save(function (err) {
if (err) {
response.json(
{
status: 'error',
code: 500,
message: err
}
)
}
response.json({
status: 'success',
code: 200,
message: 'contact saved!',
data: customer
})
})
}
exports.showCustomers = function (request, response) {
Customer.get(function (err, customer) {
if (err) {
response.json(
{
status: "error",
code: 500,
message: err
}
)
} else {
response.json(
{
status: "success",
code: 200,
message: "customers!",
data: customer
}
)
}
})
}
/*
curl --header "Content-Type: application/json" \
--request POST \
--data '{"category":"cupcakes","description":"abcdxyz","file":"imagen","name":"pastel", "price":"20000"}' \
http://localhost:3000/api/product
*/
/*
curl --header "Content-Type: application/json" \
--request POST \
--data '{"nombre":"cupcakes","genero":"abcdxyz"}' \
http://localhost:3001/api/persona
*/
|
var myExtension = {
init: function() {
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget;
var win = doc.defaultView;
doc.onkeydown = function(e) {
if (e.ctrlKey && e.shiftKey && e.altKey) {
win.open("https://www.google.com/search?client=ubuntu&channel=fs&q=define " + content.getSelection(), '_blank');
}
}
}
}
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false);
myExtension.init();
},false);
|
const mongoose = require('mongoose');
var vaccinMarocSchema = new mongoose.Schema({
date:{
type:String
} ,
nbr:{
type:Number
}
},{collection:"vaccin_maroc"});
const vm = mongoose.model('vaccin_maroc', vaccinMarocSchema);
module.exports = vm;
|
var colors=["Aqua", "Beige", "Blue", "Coral", "Cyan", "Gold", "Green", "YellowGreen"];
var finished = false;
var numbGuess = 0;
function do_game() {
var randomNumb = (Math.floor(Math.random() * 8));
var target = colors[randomNumb];
var user_guess;
alert(target);
while (!finished) {
user_guess = prompt("I am thinking of one of these colors: \n\n" +
colors.join(", ") + "\n\nWhat color am I thinking of?\n");
numbGuess++;
finished = check_guess(user_guess, target);
}
}
function check_guess(user_guess, target) {
if (colors.indexOf(user_guess) < 0) {
alert("Sorry, I dont recognize your color\n\n" + "Please try again");
return false;
}
else if (user_guess == target) {
myBody=document.getElementsByTagName("body")[0];
myBody.style.background=target;
alert("Congratulations! You have guessed the color!\n\n" +
"It took you " + numbGuess + " to finish the game\n\n" + "You can see the color in the background.");
return true;
}
else if (user_guess > target) {
alert("Sorry, your guess is not correct!\n\n" +
"Hint: your color is alphabetically higher than mine.\n\n" + "Please try again");
return false;
}
else if (user_guess < target) {
alert("Sorry, your guess is not correct!\n\n" +
"Hint: your color is alphabetically lower than mine.\n\n" + "Please try again");
return false;
}
}
|
import React from 'react';
import { connect } from "react-redux";
import styled from 'styled-components'
import Header from './header';
import { Redirect } from 'react-router-dom'
import TransactionCard from './transactionCard';
const FlexedDiv = styled.div`
display: flex;
padding : 40px;
flex-direction: row;
flex-wrap : wrap;
justify-content: space-between;
`
class Transactions extends React.Component {
render() {
let history = this.props.user.history ? this.props.user.history.map((item, index) => {
let data = item.split("^");
return (<TransactionCard
symbol={data[0]}
quantity={data[3]}
purchased={data[2]}
price={data[1]}
/>)
}
): ""
return <div>
{this.props.user.email ? <></> : <Redirect to="/" />}
<Header title="Transactions"></Header>
<h3 style={{textAlign : 'center',padding : '25'}}>Transaction History</h3>
<FlexedDiv>
{history}
</FlexedDiv>
</div>
}
}
const mapState = (state) => {
return {
user: state.user
}
}
export default connect(mapState, null)(Transactions)
|
import React, { Component } from 'react';
import Firebase from 'firebase';
import config from './config';
import './App.css';
import './responsive.css'
import VenueList from './components/VenueList';
const switchIcon = require('./icons/switch-screen-icon.svg');
// https://developers.google.com/maps/documentation/javascript/tutorial converted to react below
class App extends Component {
constructor(props) {
super(props);
Firebase.initializeApp(config);
this.state = {
map: {}, // once this is set to the global google map it can be passed to children who need access to the google map for methods/ references
infoWindow: {}, // reference to the infowindow for outside access
venues: [], // contain our current fetched venues
markerArray: [], // container for markers
currentMarkerIndex: -1, // state management to determine which marker is selected from list
previouslySelectedMarker: {}, // initialize the state to track markers
filteredMarkerRefs: [], // stores the filtered marker references
query: "",
apiKey: "AIzaSyBZypGBE4lhAMF5B_yS9_JjohVFVC78mhs",
authDomain: "safelocation-518d0.firebaseapp.com",
databaseURL: "https://safelocation-518d0.firebaseio.com"
}
}
previouslySelectedMarker = undefined; // initialze marker tracking for the animation (could be converted to a state if it needs to be passed, but not necessary)
//Gowri firebase stuff
writeUserData = () => {
// Firebase.database().ref('/').set(this.state);
console.log('DATA SAVED');
}
getUserData = () => {
let ref1 = Firebase.database().ref("/LocationComments1").set("foo111");
let ref = Firebase.database().ref('/LocationComments');
// console.log("ref1 = " + ref1.value);
ref.on('value', snapshot => {
console.log("values " + snapshot.numChildren());
const state = snapshot.val();
console.log('DATA RETRIEVED' + snapshot.val());
// this.setState(state);
});
}
// gowri end firebase
componentDidMount() {
console.log('Mounting');
this.getUserData();
this.getVenues(); // fetch foursquare data, note it is asynchronous
}
componentDidUpdate(prevProps, prevState) {
// check on previous state
// only write when it's different with the new state
if (prevState !== this.state) {
this.writeUserData();
}
}
//method which will add css classes that act like hamburger menus
toggleMapMenu = () => {
let venueList = document.querySelector('.venue-list');
let mapContainer = document.querySelector('.map-container');
let menuIcon = document.querySelector('.menu');
venueList.classList.toggle('close-filter');
mapContainer.classList.toggle('open-map');
menuIcon.classList.toggle('map-open-menu');
}
loadMap = () => {
loadScript("https://maps.googleapis.com/maps/api/js?key=AIzaSyBPUthWOHE1Q15YBcoYHutTRaiE1xrZ69U&callback=initMap");
window.initMap = this.initMap; // set the global variable initMap to our initMap method (for callback access)
}
/// FOURSQUARE API RELATED FUNCTIONS/// FOURSQUARE API RELATED FUNCTIONS/// FOURSQUARE API
updateQuery = (query) => {
this.setState({
query: query
},(this.filterMarkers)
)
}
filterVenueArray = (query) => { // filters the list of items on the left hand of app
let filterResults = this.state.venues.filter((FilteredVenue) => {
let name = FilteredVenue.name.toLowerCase(); // convert it to lowercase so we can use regex to match against venue names
let regex = new RegExp(query);
//construct a regular expression based on query and compare it against the name
if (name.match(regex)) {
return true;
} else {
return false;
}
})
this.setState({
filteredVenues : this.state.venues,
venues: filterResults
},(()=> console.log(filterResults)))
}
getVenues = () => {
const endPoint = 'https://api.foursquare.com/v2'; //the api url
const parameters = {
client_id: "NRGQG3Z25DSMLYUKPTODJY1ZOQTI0NVONSZICDVVOLXTQ1MK",
client_secret: "J35TCWD20UY10TYUR0RS2V5XQ0MJLFPBT02TJRK33425RVPP",
query: "coffee", //can be changed depending on if we add a query component to our app
ll: "38.9897,-76.9378", // just a locale near myself, but also can be customized
intent: "browse", // browse, match
radius: 10000, // in meters
limit: 100, // limit of 50
v: "20180323" // this is the version given under 'getting started' of docs
}
fetch(`${endPoint}/venues/search?ll=${parameters.ll}&intent=${parameters.intent}&radius=${parameters.radius}&limit=${parameters.limit}&query=${parameters.query}&client_id=${parameters.client_id}&client_secret=${parameters.client_secret}&v=${parameters.v}`)
.then(res => res.json())
.then(data => {
//NOTE: SetState can take in a 2nd parameter, which is a callback that is run after the state has been set
this.setState({
venues: data.response.venues, // pull data and store it in the app state
},this.loadMap()) // note loadmap must wait until venues are loaded so that the markers can be made
})
.catch(error => {
console.log("Error: "+ error);
})
}
// using similar endpoint as getVenues we will now change intent to match instead
searchVenues = (query) => {
const endPoint = 'https://api.foursquare.com/v2'; //the api url
const parameters = {
client_id: "NRGQG3Z25DSMLYUKPTODJY1ZOQTI0NVONSZICDVVOLXTQ1MK",
client_secret: "J35TCWD20UY10TYUR0RS2V5XQ0MJLFPBT02TJRK33425RVPP",
query: query, //can be changed depending on if we add a query component to our app
ll: "38.7916449,-77.119759", // just a locale near myself, but also can be customized
intent: "match", // browse, match
radius: 10000, // in meters
limit: 20, // limit of 50
v: "20180323" // this is the version given under 'getting started' of docs
}
//https://api.foursquare.com/v2/venues/search?ll=38.7916449,-77.119759&intent=search&radius=10000&limit=20&client_id=NRGQG3Z25DSMLYUKPTODJY1ZOQTI0NVONSZICDVVOLXTQ1MK&client_secret=J35TCWD20UY10TYUR0RS2V5XQ0MJLFPBT02TJRK33425RVPP&v=20180323&query=food
fetch(`${endPoint}/venues/search?ll=${parameters.ll}&intent=${parameters.intent}&radius=${parameters.radius}&limit=${parameters.limit}&query=${parameters.query}&client_id=${parameters.client_id}&client_secret=${parameters.client_secret}&v=${parameters.v}`)
.then(res => res.json())
.then(data => {
//NOTE: SetState can take in a 2nd parameter, which is a callback that is run after the state has been set
this.setState({
queryVenueArray: data.response.venues // pull data and store it in the app state
},this.loadMap()) // note loadmap must wait until venues are loaded so that the markers can be made
})
.catch(error => {
console.log("Error: "+ error);
})
}
/// GOOGLE MAPS RELATED FUNCTIONS /// GOOGLE MAPS RELATED FUNCTIONS ////// GOOGLE
//MARKER RELATED FUNCTIONS
//method allows us to determine which marker to use in our marker array for opening the info window
setCurrentMarker = (index) => {
this.setState({
currentMarkerIndex : index
})
}
//show infoWindow and populate its contents
showInfoWindow(marker) { // takes a marker ref object
this.setContent(marker.contentString);
this.open(marker.map, marker);
}
//remove marker from map
removeMarker = (Marker) => {
Marker.setMap(null);
//map is the refernce to window google maps
}
//add marker to map
showMarker = (Marker) => {
Marker.setMap(this.state.map); // note all markers reference their map through marker.map
}
// TODO: ADD ANIMATION TO selected marker
// toggleBounce = () => { // take marker run animation method
// // if previous marker does not exist, animate current marker
// //if previous marker does exist, deanimate, animate current
// //this.state.filteredMarkerRefs[this.state.currentMarkerIndex] this is the selected marker's ref
// // previouslySelectedMarker is the state tracking the previous filtered marker's ref
// // method to animate marker .setAnimation(window.google.maps.Animation.BOUNCE) // deactiv: .setAnimation(null)
// console.log(this);
// console.log(this.state.filteredMarkerRefs[this.state.currentMarkerIndex]);
// if (this.previouslySelectedMarker === {}) { // if there is not a previous marker// its an empty object
// this.state.filteredMarkerRefs[this.state.currentMarkerIndex].setAnimation(window.google.maps.Animation.BOUNCE);
// this.previouslySelectedMarker = this.state.filteredMarkerRefs[this.state.currentMarkerIndex] // store marker for next call
// } else {
// this.previouslySelectedMarker.setAnimation(null); // stop previous marker's animation
// this.state.filteredMarkerRefs[this.state.currentMarkerIndex].setAnimation(window.google.maps.Animation.BOUNCE); // animate current marker
// this.previouslySelectedMarker = this.state.filteredMarkerRefs[this.state.currentMarkerIndex] // store marker for next method call
// }
// }
// method works but when put into the marker's click listener or the filter list item on click it fails
filterMarkers = () => { // filters actual map markers to hide/show
let filteredMarkerArray = this.state.markerArray.filter((FilteredMarker) => {
let name = FilteredMarker.filterProperty.toLowerCase(); // convert it to lowercase so we can use regex to match against venue names
let regex = new RegExp(this.state.query);
//construct a regular expression based on query and compare it against the name
if (name.match(regex)) {
return true;
} else {
return false;
}
})
// use the filteredMarkerArray to iterate over markers to be shown, use the markerArray to set all the markers to null
this.state.markerArray.map((marker) => {
this.removeMarker(marker); // removes all markers from map
return true;
})
filteredMarkerArray.map((marker) => {
this.showMarker(marker); // reveals filtered markers
return true;
})
this.setState({filteredMarkerRefs:filteredMarkerArray})
return filteredMarkerArray;
}
initMap = () => {
// note that window.google is used here because it is necessary to generate it from the global environment
//initialize our map object
let map = new window.google.maps.Map(document.getElementById('map'), {
center: {lat: 38.7916449, lng: -77.119759},
zoom: 10
});
this.setState({map:map}) // set reference to map in the app state
let bounds = new window.google.maps.LatLngBounds();
//generate a single infoWindow
let infowindow = new window.google.maps.InfoWindow({
});
//this function below generates our markers and infoWindows based off of the loaded venues' data
let markers = []; // initialize an array to reference all generated markers
this.state.venues.map((targetVenue) => {
//dynamically change the contentString based on venue
let contentString= `<div class="info-window"><h5>${targetVenue.name}</h5>
<p>${targetVenue.location.formattedAddress.join(', ')}</p></div>
`;
let url = "http://maps.google.com/mapfiles/ms/icons/";
url += "green" + "-dot.png";
//generate dynamic markers
let marker = new window.google.maps.Marker({
position: {lat: targetVenue.location.lat, lng: targetVenue.location.lng},
map: map,
title: targetVenue.name,
icon: {
url: url
},
contentString: contentString,
filterProperty: targetVenue.name // this property allows us to filter the marker references for management
});
//add a listener to our marker
marker.addListener('click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
// add marker to temporary array to store in state at a later time
markers.push(marker);
bounds.extend(marker.getPosition());
return true;
})
// update the app state to include marker references
this.setState({
markerArray: markers,
infoWindow: infowindow,
filteredMarkerRefs: markers
})
map.fitBounds(bounds); // fit map to markers
}
render() {
// filter the array based on our query before passing it down to our child componenents
let filteredMarkerArray = this.state.markerArray.filter((FilteredMarker) => {
let name = FilteredMarker.filterProperty.toLowerCase(); // convert it to lowercase so we can use regex to match against venue names
let regex = new RegExp(this.state.query);
//construct a regular expression based on query and compare it against the name
if (name.match(regex)) {
return true;
} else {
return false;
}
})
return (
<main>
<span className="menu" onClick={this.toggleMapMenu}> <img src={switchIcon} alt="button to swap between google map and venues menu"/> </span>
<VenueList locations={this.state.venues}
venueMarkers={filteredMarkerArray}
changeMarkerIndex={this.setCurrentMarker}
openInfoWindow={this.showInfoWindow.bind(this.state.infoWindow)} // binding the infoWindow reference allows us to trigger the proper object methods
toggleBounce={this.toggleBounce}
updateQuery={this.updateQuery}
query={this.state.query}
/>
<div className="map-container">
<div id="map"></div>
</div>
</main>
);
}
}
/*
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"async defer></script>
*/
function loadScript(url) {
let index = window.document.getElementsByTagName('script')[0]; // target the first script tag
let script = window.document.createElement('script'); // generate our script tag
script.src = url; // set the url
script.async = true;// give our script tag the async attr
script.defer = true; // give our script tag the defer attr
index.parentNode.insertBefore(script, index);
// insert our script in front of all the scripts
}
export default App;
|
//皮肤组件初始化
function skininit() {
skin = ['PapayaWhip', 'Lavender', 'PaleGreen', 'PaleTurquoise', 'LightBlue', 'Bisque'];
var skins = document.getElementById('skin').getElementsByTagName('li');
for(var i = 0; i < skins.length; i ++) {
skins[i].style.backgroundColor = skin[i];
}
}
//换皮肤,同时加一个透明度;
function skinChange(num) {
var body = document.getElementsByTagName('body');
var color = skin[num];
body[0].style.backgroundColor = color;
body[0].style.opacity = 1;
}
|
import React, { Component } from 'react';
import './DetailView.css'
import ExerciseImage from '../ExerciseImage/ExerciseImage';
export class DetailView extends Component {
render() {
if (!Object.keys(this.props.detail).length) {
return (
<div className='detail-view'>
<h3 className='detail-placeholder'>Please Select a workout to view Detail</h3>
</div>
)
}
const { name,
description,
equipment,
category,
muscles,
imageUrls } = this.props.detail;
return (
<div className='detail-view'>
<h3 className='detail-tab-title'>{name}</h3>
<h4>Category: {category.name}</h4>
<ExerciseImage imageUrls={imageUrls}/>
<div className='description-section'>
<h4>Exercise Description: </h4>
<div className="detail-description"
dangerouslySetInnerHTML={{ __html: description }}>
</div>
</div>
<div className='muscles-section'>
<h4>Muscles Worked: </h4>
<p>{muscles.map(e => e.name).join(', ')}</p>
</div>
<div className='equipment-section'>
<h4>Equipment Needed : </h4>
<p>{equipment.map(e => e.name).join(', ')}</p>
</div>
</div>
)
}
}
|
import React from 'react';
import Icon1 from '../../images/analistic.svg';
import Icon2 from '../../images/growing.svg';
import Icon3 from '../../images/coder.svg';
import { ServicesContainer, ServicesWrapper, ServicesCard, ServicesIcon, ServicesH1, ServicesH2, ServicesP } from './ServicesElements';
const Services = () => {
return (
<ServicesContainer id='services'>
<ServicesH1>Our Activities</ServicesH1>
<ServicesWrapper>
<ServicesCard>
<ServicesIcon src={Icon1}/>
<ServicesH2>Reduce expenses</ServicesH2>
<ServicesP>We help reduce your fess and increase your overall revenue.</ServicesP>
</ServicesCard>
<ServicesCard>
<ServicesIcon src={Icon2}/>
<ServicesH2>Virtual offices</ServicesH2>
<ServicesP>We help reduce your fess and increase your overall revenue.</ServicesP>
</ServicesCard>
<ServicesCard>
<ServicesIcon src={Icon3}/>
<ServicesH2>Premium Benefits</ServicesH2>
<ServicesP>We help reduce your fess and increase your overall revenue.</ServicesP>
</ServicesCard>
</ServicesWrapper>
</ServicesContainer>
)
}
export default Services
|
const {Schema,model} = require("mongoose")
const notificationSchema = new Schema({
notice:{
type:String,
required:true,
trim:true
},
createedTime:{
type:Date,
default:new Date()
}
},{timestamps:true})
const Notice = model('Notice', notificationSchema)
module.exports = Notice
|
import ConferenceRouter from './components/conferenceRouter';
export { ConferenceRouter };
|
'use strict'
const redis = require('redis')
const parameters = requireRoot('../parameters')
const debug = require('debug')('app:redis')
const Promise = require('bluebird')
// Promisify redis
Promise.promisifyAll(redis.RedisClient.prototype)
Promise.promisifyAll(redis.Multi.prototype)
let client
/**
* Get redis client
* @return {RedisClient}
*/
exports.getClient = function () {
return client
}
/**
* Starts the connection with Redis
*/
exports.startClient = function () {
const eventNames = ['ready', 'connect', 'reconnecting', 'error', 'end', 'warning']
// Connection uri
const redisUrl = process.env.TEST_MODE ? parameters.test.redisConnectionUri : parameters.redisConnectionUri
// Client initialization
client = redis.createClient({
url: redisUrl,
retry_strategy: function (options) {
debug('Redis Reconnecting attempt ' + options.attempt)
return Math.min(options.attempt * 50, 5000)
}
})
// Clients event debug
if (debug.enabled) {
eventNames.forEach(function (eventName) {
client.on(eventName, function (e) {
if (e) { debug(eventName, e) } else { debug(eventName) }
})
})
}
return client
}
|
import { parkHTMLConverter } from "./parks.js"
import { getParks, useParks} from "./ParkProvider.js"
const contentTarget = document.querySelector(".parksDropDown")
export const ParksSelect = () => {
getParks()
.then(() => { let parks = useParks()
render(parks)
})
}
const eventHub = document.querySelector(".container")
const render = parksCollection => {
contentTarget.innerHTML = `
<section class="parkDetails">
<select class="dropdown" id="parkSelect">
<option value="0">Please select a park...</option>
${
parksCollection.map((park) => `
<option value= "${park.id}">"${park.fullName}"</option>`
)
}
</select>
</section>
`
}
contentTarget.addEventListener( "change", event => {
if (event.target.id === "parkSelect") {
const customEvent = new CustomEvent("parkSelected", {
detail: {
parkThatWasChosen:event.target.value
}
})
eventHub.dispatchEvent(customEvent)
}
})
|
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import localforage from 'localforage';
import loadAndWatchFeatherJSResource from '../lib/loadAndWatchFeatherJSResource'
import { socket } from "../lib/feathersClient";
import Web3Monitor from '../lib/Web3Monitor';
// views
import Profile from './../components/views/Profile'
import SignIn from './../components/views/SignIn'
import ViewMilestone from './../components/views/ViewMilestone'
import Causes from './../components/views/Causes'
import EditCause from './../components/views/EditCause'
import ViewCause from './../components/views/ViewCause'
import NotFound from './../components/views/NotFound'
import Campaigns from './../components/views/Campaigns'
import EditCampaign from './../components/views/EditCampaign'
import ViewCampaign from './../components/views/ViewCampaign'
import EditMilestone from './../components/views/EditMilestone'
// components
import MainMenu from './../components/MainMenu'
import Loader from './../components/Loader'
/**
* This container holds the application and its routes.
* It is also responsible for loading application persistent data.
* As long as this component is mounted, the data will be persistent, if passed as props to children.
*/
class Application extends Component {
constructor() {
super()
this.state = {
milestones: [],
causes: [],
campaigns: [],
web3: undefined,
currentUser: undefined,
isLoading: true,
hasError: false,
wallet: undefined,
};
localforage.config({
name: 'giveth',
});
this.handleWalletChange = this.handleWalletChange.bind(this);
}
componentWillMount(){
// Load causes and campaigns. When we receive first data, we finish loading.
// This setup is a little ugly, because the callback is being called
// again and again by loadAndWatchFeatherJSResource whenever data changes.
// Yet the promise will be resolved the first time.
// But he, it works! ;-)
Promise.all([
new Promise((resolve, reject) => {
new loadAndWatchFeatherJSResource('causes', {}, (resp, err) => {
if(resp) {
this.setState({ causes: resp })
resolve()
} else {
reject()
}
})
})
,
new Promise((resolve, reject) => {
new loadAndWatchFeatherJSResource('campaigns', {}, (resp, err) => {
if(resp) {
this.setState({ campaigns: resp })
resolve()
} else {
reject()
}
})
})
]).then(() => this.setState({ isLoading: false, hasError: false }))
.catch((e) => {
console.log('error loading', e)
this.setState({ isLoading: false, hasError: true })
})
socket.on('reconnect', () => {
if (this.state.wallet && this.state.wallet.unlocked) {
socket.emit('authenticate', { signature: this.state.wallet.signMessage().signature });
}
})
// QUESTION: Should rendering with for this to load?
// new Web3Monitor(({web3}) => {
// this.setState({
// web3
// })
// })
}
handleWalletChange(wallet) {
if (wallet) {
localforage.setItem('keystore', wallet.getKeystore());
this.setState({
wallet,
currentUser: wallet.getAddresses()[0],
});
} else {
if (this.state.wallet) this.state.wallet.clear();
localforage.removeItem('keystore');
this.setState({
wallet,
currentUser: undefined,
});
}
}
render(){
return(
<Router>
<div>
<MainMenu authenticated={(this.state.currentUser)}/>
{ this.state.isLoading &&
<Loader className="fixed"/>
}
{ !this.state.isLoading && !this.state.hasError &&
<div>
{/* Routes are defined here. Persistent data is set as props on components */}
<Switch>
<Route exact path="/" component={props => <Causes causes={this.state.causes} currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/dacs" component={props => <Causes causes={this.state.causes} currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/dacs/new" component={props => <EditCause isNew="true" currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/dacs/:id" component={ViewCause}/>
<Route exact path="/dacs/:id/edit" component={props => <EditCause currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/campaigns" component={props => <Campaigns campaigns={this.state.campaigns} currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/campaigns/new" component={props => <EditCampaign isNew="true" currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/campaigns/:id" component={props => <ViewCampaign currentUser={this.state.currentUser} {...props} /> }/>
<Route exact path="/campaigns/:id/edit" component={props => <EditCampaign currentUser={this.state.currentUser} {...props}/>} />
<Route exact path="/campaigns/:id/milestones/new" component={props => <EditMilestone isNew={true} currentUser={this.state.currentUser} {...props} />}/>
<Route exact path="/campaigns/:id/milestones/:milestoneId" component={props => <ViewMilestone currentUser={this.state.currentUser} {...props} />}/>
<Route exact path="/campaigns/:id/milestones/:milestoneId/edit" component={props => <EditMilestone currentUser={this.state.currentUser} {...props} />}/>
<Route exact path="/signin" render={props => <SignIn wallet={this.state.wallet} handleWalletChange={this.handleWalletChange} provider={this.state.web3 ? this.state.web3.currentProvider : undefined} {...props}/>} />
<Route exact path="/profile" component={props => <Profile currentUser={this.state.currentUser} wallet={this.state.wallet} {...props}/>} />
<Route component={NotFound}/>
</Switch>
</div>
}
{ !this.state.isLoading && this.state.hasError &&
<center>
<h2>Oops, something went wrong...</h2>
<p>The Giveth dapp could not load for some reason. Please try again...</p>
</center>
}
</div>
</Router>
)
}
}
export default Application
|
$(document).ready(function() {
// Array of objects for each character
var characters = [
{
// Obi-Wan Kenobi
name: "Obi-Wan Kenobi",
className: "obi-wan-kenobi",
healthPoints: 120,
attackPower: 8,
counterAttackPower: 10, // unknown
image: "./assets/images/obi-wan-kenobi.jpg"
},
{
// Luke Skywalker
name: "Luke Skywalker",
className: "luke-skywalker",
healthPoints: 100,
attackPower: 12, // unknown
counterAttackPower: 5,
image: "./assets/images/luke-skywalker.jpg"
},
{
// Darth Sidious
name: "Darth Sidious",
className: "darth-sidious",
healthPoints: 150,
attackPower: 14, // unknown
counterAttackPower: 20,
image: "./assets/images/darth-sidious.jpg"
},
{
// Darth Maul
name: "Darth Maul",
className: "darth-maul",
healthPoints: 180,
attackPower: 10, // unknown
counterAttackPower: 25,
image: "./assets/images/darth-maul.jpg"
}
];
// Creating variables to hold page elements to be used later
var characterChoices = $(".character-choices");
var enemyChoices = $(".enemy-choices");
var currentDefender = $(".current-defender");
var controls = $(".controls");
var message = $(".message");
var themeSong = new Audio("./assets/audio/star-wars.mp3");
var gameTitle = $(".game-title");
var fightArea = $('.fight-area');
gameTitle.hide();
fightArea.hide();
function gameIntro() {
themeSong.play();
$(".intro").show();
setTimeout(function() {
$(".logo").hide();
}, 12000);
}
// Game intro
var startScreen = $(".start-screen");
var playButton = $(".play-intro");
var skipIntro = $(".skip-intro");
playButton.on("click", function() {
startScreen.hide();
gameIntro();
setTimeout(function() {
game();
$(".game-container").addClass("slide-in");
}, 26000);
});
skipIntro.on("click", function() {
startScreen.hide();
game();
});
// Creating a game function
function game() {
gameTitle.show();
fightArea.show();
// Creating attack button
var btnAttack = $("<button>");
btnAttack.addClass("btn-attack");
btnAttack.text("Attack");
// Game Reset
characterChoices.empty();
message.html("<h2>Choose your character</h2>");
var enemiesRemaining = 3;
var characterChosen = false;
var enemyChosen = false;
var yourCharacter;
var yourEnemy;
var remainingEnemies;
// Character stats
var yourHealthPoints;
var baseAttackPower;
var yourAttackPower;
var enemyName;
var enemyHealthPoints;
var enemyCounterAttack;
// Loop to create buttons for each character
for ( var i = 0; i < characters.length; i++ ) {
// Creating a <button> for each character
var characterButton = $("<button>");
characterButton.addClass("btn-character").addClass(characters[i].className).val(characters[i].name);
// Adding data values to the button
characterButton.attr("data-health-points", characters[i].healthPoints);
characterButton.attr("data-attack-power", characters[i].attackPower);
characterButton.attr("data-enemy-health", characters[i].healthPoints);
characterButton.attr("data-counter-attack", characters[i].counterAttackPower);
// Creating an <img> for each character
var characterImage = $("<img>")
characterImage.addClass("character-image");
characterImage.attr("src", characters[i].image);
// Creating span for health points
var healthPointsSpan = $("<span>");
healthPointsSpan.addClass("health-points");
healthPointsSpan.text(characters[i].healthPoints);
// Appending items to characterButton
characterButton.append(characters[i].name);
characterButton.append(characterImage);
characterButton.append(healthPointsSpan);
// Appending characterButton to the character choices div
characterChoices.append(characterButton);
}
// Choose your character
characterChoices.on("click", ".btn-character", function() {
// Storing the button in a variable
var btnCharacter = $(".btn-character");
// If you haven't chosen a character to play
if( !characterChosen && !enemyChosen ) {
// Stores the chosen character in a variable
yourCharacter = ($(this));
// Sets your health points
yourHealthPoints = yourCharacter.attr("data-health-points");
console.log("Your Health: " + yourHealthPoints);
// Sets your base attack power
baseAttackPower = yourCharacter.attr("data-attack-power");
yourAttackPower = parseInt(baseAttackPower);
console.log("Attack Power: " + baseAttackPower);
// Adding "btn-enemy" class to all buttons
btnCharacter.addClass("btn-enemy");
// Removes "btn-enemy" class from the chosen character
yourCharacter.removeClass("btn-enemy");
remainingEnemies = $(".btn-enemy");
// Adds "your-character" class to the chosen character
yourCharacter.addClass("your-character");
// Appends characters that were not chosen back into character choices div
characterChoices.empty();
characterChoices.append(remainingEnemies);
characterChosen = true;
message.html("<h2>Choose your opponent</h2>");
}
// If you've chosen a character but not an opponent
else if ( characterChosen && !enemyChosen ) {
yourEnemy = ($(this));
yourEnemy.toggleClass("btn-enemy");
remainingEnemies = $(".btn-enemy");
// Switches enemyChosen to true
enemyChosen = true;
// Adds "current-enemy" class to the chosen character
yourEnemy.addClass("current-enemy");
// Sets enemy's name
enemyName = yourEnemy.val();
// Sets enemy's health points
enemyHealthPoints = yourEnemy.attr("data-enemy-health");
console.log("Enemy Health: " + enemyHealthPoints);
// Sets enemy's counter attack power
enemyCounterAttack = yourEnemy.attr("data-counter-attack");
console.log("Counter Attack: " + enemyCounterAttack);
characterChoices.empty();
characterChoices.append(yourCharacter);
characterChoices.append(btnAttack);
characterChoices.append(this);
message.html("<h2>FIGHT!!!</h2>");
}
});
// Attack button
$(document).on("click", ".btn-attack", function() {
// When your opponent's health reaches 0 or below
if ( enemyHealthPoints - parseInt(yourAttackPower) <= 0 ) {
// Still increasing your attack power by your base power
yourAttackPower = yourAttackPower + parseInt(baseAttackPower);
enemiesRemaining--;
characterChoices.empty();
characterChoices.append(remainingEnemies);
if ( enemiesRemaining > 0 ) {
message.html("<p>You have defeated " + enemyName + "!<br />Choose your next opponent.</p>");
// Switches enemyChosen to false
enemyChosen = false;
}
else {
message.html("<p>You have defeated all of your opponents! GAME OVER!!!</p>");
characterChoices.append(yourCharacter);
message.append(restartButton);
}
}
// When your health reaches 0 or below
else if ( yourHealthPoints - parseInt(enemyCounterAttack) <= 0 ) {
message.html("<p>You have been defeated...GAME OVER!!!");
// Reducing your health to 0
$(".your-character").find($(".health-points")).text(0);
message.append(restartButton);
}
else if (characterChosen && enemyChosen ) {
// Message
message.html("<p>You attacked " + enemyName + " for " + yourAttackPower + " damage.<br />" + enemyName + " attacked you back for " + enemyCounterAttack + " damage.</p>");
enemyHealthPoints = enemyHealthPoints - yourAttackPower;
yourAttackPower = yourAttackPower + parseInt(baseAttackPower);
yourHealthPoints = yourHealthPoints - enemyCounterAttack;
console.log("Your Attack Power: " + yourAttackPower);
// Reducing your health and updating the value displayed in the button
$(".your-character").find($(".health-points")).text(yourHealthPoints);
console.log("Your Health: " + yourHealthPoints);
// Reducing your enemy's health and updating the value displayed in the button
console.log("Enemy Health: " + enemyHealthPoints);
$(".current-enemy").find($(".health-points")).text(enemyHealthPoints);
}
});
} // End of game function
// Creating restart button
// var restartButton = $("<button>");
// restartButton.addClass("btn-restart");
// restartButton.text("Restart");
// $(document).on("click", ".btn-restart", function() {
// game();
// });
}); // End of document ready function
|
function ckEditor() {
ClassicEditor
.create(document.querySelector('#body'))
.catch(error => {
console.error(error);
});
}
function checkAllCheckboxes() {
const selectAll = document.getElementById('select_all');
const allCheckBoxes = document.getElementsByClassName('checkBoxes');
if(selectAll) {
selectAll.addEventListener('click', function () {
for (let i = 0; i < allCheckBoxes.length; i++) {
if (this.checked) {
allCheckBoxes[i].checked = true;
} else {
allCheckBoxes[i].checked = false;
}
}
});
}
}
function contentLoader() {
var div_box = "<div class='loader'><div class='loader-inner'><div class='lds-ellipsis'><div></div><div></div><div></div><div></div></div></div></div>";
$('body').prepend(div_box);
$('.loader').delay(700).fadeOut(600, function() {
$(this).remove();
});
}
function loadUsersOnline() {
$.ajax({
type: "GET",
url: '../admin/ajax/users_online.php',
success: function(data){
$('.users_online').text(data);
}
});
var updateUsers = setInterval(function() {
loadUsersOnline();
}, 500);
clearTimeout(updateUsers);
}
function init() {
ckEditor();
checkAllCheckboxes();
contentLoader();
loadUsersOnline();
}
window.onload = init;
|
/* eslint-env node */
const fs = require( "fs" );
const { babel } = require( "@rollup/plugin-babel" );
const { nodeResolve } = require( "@rollup/plugin-node-resolve" );
const commonjs = require( "@rollup/plugin-commonjs" );
const replace = require( "@rollup/plugin-replace" );
const { replacements } = require( "./build/dist-replace.js" );
const isCoverage = process.env.BUILD_TARGET === "coverage";
module.exports = {
input: "src/qunit.js",
output: {
file: "qunit/qunit.js",
sourcemap: isCoverage,
format: "iife",
exports: "none",
// eslint-disable-next-line no-multi-str
banner: "/*!\n\
* QUnit @VERSION\n\
* https://qunitjs.com/\n\
*\n\
* Copyright OpenJS Foundation and other contributors\n\
* Released under the MIT license\n\
* https://jquery.org/license\n\
*/",
intro: function() {
// Define the (partial) ES6 Map polyfill for "fuzzysort".
// Per https://github.com/qunitjs/qunit/issues/1508:
// 1. Must not leak as global variable, since it's not full Map implementation.
// 2. Must be seen by fuzzysort as-is (e.g. not get renamed as normal
// variables in an imported file would be).
return fs.readFileSync(
__dirname + "/src/html-reporter/es6-map.js",
"utf8"
).toString().trim();
}
},
plugins: [
replace( {
preventAssignment: true,
delimiters: [ "", "" ],
...replacements
} ),
nodeResolve(),
commonjs(),
babel( {
babelHelpers: "bundled",
babelrc: false,
presets: [
[ "@babel/preset-env", {
targets: {
ie: 9
}
} ]
]
} )
]
};
|
import { renderString } from '../../src/index';
describe(`Strip SGML/XML tags and replace adjacent whitespace by one space.`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{% set some_html = "<div><strong>Some text</strong></div>" %}
{{ some_html|striptags }}`);
});
});
|
var searchData=
[
['arhandler_2ecs_64',['ARHandler.cs',['../_a_r_handler_8cs.html',1,'']]]
];
|
var Post = require('../../models/post');
/**
* Expose the "PostsAdministration" Controller.
*/
module.exports = new PostsAdministrationController;
/**
* Constructor for the PostsAdministrationController.
* @constructor
*/
function PostsAdministrationController() {}
/**
* Renders the posts' administration panel.
* @param {http.IncomingMessage} req Node/Express request object.
* @param {http.ServerResponse} res Node/Express response object.
*/
PostsAdministrationController.prototype.index = function(req, res) {
var post = new Post(req.app);
post.find(function(err, rows) {
res.render('admin/posts/index', {
rows: rows,
title: 'Posts Administration'
});
});
};
|
import React from 'react';
import Prod from './Product/Product';
import Error from '../UI/Error/Error';
import classes from './Products.css';
const Products = (props) => {
const productList = props.error
? <Error>{props.errorMessage}</Error> :
props.data.length === 0 ? null
: (
<div className={classes.products}>
{props.data.map((product) => (<Prod
image={product.image}
title={product.title}
key={product.id}
clicked={() => props.getProductDetail(product.id)}
/>))
}
</div>
)
;
return productList;
}
export default Products;
|
const mongoose = require('mongoose')
const collectionSchema = new mongoose.Schema({
owner: {
type: String,
require: true
},
picture: {
type: String
},
title: {
type: String
},
description: {
type: String
},
topic: {
type: String
},
author: {
type: Boolean
},
year: {
type: Boolean
},
comments: {
type: Boolean
},
items_ids: {
type: [String]
}
})
module.exports = Collection = mongoose.model("collection", collectionSchema)
|
import { Linking } from 'react-native';
import { genericErrorAlert } from './genericAlerts';
export const displayErrors = Object.freeze (
{
"APPLE_MAPS" : {
functionalityRequiredErrorMessage : "You must have apple maps installed to use this",
errorMessage : "Unable to give directions"
},
"WEB_PAGE" : {
functionalityRequiredErrorMessage : "You must have a browser installed to use this",
errorMessage : "Unable to open link"
}
}
)
export const generateAppleMapsUrl = (source, dest) => {
return `http://maps.apple.com/?saddr=${ source.latitude },${ source.longitude }&daddr=${ dest.latitude },${ dest.longitude }`
}
export const genericOpenUrl = (url, displayError) => {
Linking.canOpenURL (url).then ( (supported) =>
{
if (!supported)
genericErrorAlert (displayError.functionalityRequiredErrorMessage)
else {
return Linking.openURL (url).then ( (data) =>
{
console.log (data);
}
).catch ( (error) =>
{
console.log (error)
genericErrorAlert (displayError.functionalityRequiredErrorMessage)
}
)
}
}
).catch ( (error) =>
{
console.log (error);
genericErrorAlert (displayError.errorMessage)
}
)
}
export const openMaps = (url) => {
genericOpenUrl (url, displayErrors.APPLE_MAPS)
}
export const openWebPage = (url) => {
genericOpenUrl (url, displayErrors.WEB_PAGE);
}
|
import React from "react";
import "./ColoredButton.css";
const ColoredButton = ({color, addCircle})=>{
return (
<button
className="ColoredButton-btn"
style={{backgroundColor:color}}
onClick={()=>addCircle(color)}
>
{color}
</button>
)
}
export default ColoredButton;
|
const express = require('express')
const app = express()
var path = require('path');
const port = 5000
// function middlewar
const d = new Date()
const hours = d.getHours()
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
const dayName = days[d.getDay()]
function acces (req, res, next) {
if (['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'].includes(dayName)&&(hours >= 9 && hours <= 17 ) ) {
return next()
}
else {
res.send("site is closed")
}
}
app.use(acces)
// html page to express route
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/home', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/services', function(req, res) {
res.sendFile(path.join(__dirname + '/ourservice.html'));
});
app.get('/contact', function(req, res) {
res.sendFile(path.join(__dirname + '/contact.html'));
});
app.use(express.static('public'));
app.listen(port , (error) => {
error ? console.log(error)
:
console.log(`Server is running on port ${port}..`)
})
|
import React from 'react';
import { connect } from 'react-redux';
import { Button, message } from 'antd';
import AppContentUserPerson from '../../app-content-user/app-content-user-person/index.js';
import { doChangePracticeAppointmentStep } from '../../../../redux/action/practice';
import './index.css';
export class AppContentPracticeAppointmentSecond extends React.Component{
constructor(props){
super(props);
this.handleLast = this.handleLast.bind(this);
this.handleNext = this.handleNext.bind(this);
}
handleLast(){
this.props.onChangePracticeAppointmentStep(0);
}
handleNext(){
const { personSelectedRowKeys, person, onChangePracticeAppointmentStep } = this.props;
if(person.length === 0){
message.info('请先添加练习人员')
}
else{
if(personSelectedRowKeys.length === 0){
message.info('请选择练习人员')
}
else{
onChangePracticeAppointmentStep(2);
}
}
}
render(){
return (
<div>
<div className="app-content-practice-appointment-secondSteps-content">
<AppContentUserPerson beCanSelected={true}/>
</div>
<div className="app-content-practice-appointment-secondSteps-action">
<Button type="primary" className="app-content-practice-appointment-secondSteps-action-last" onClick={this.handleLast}>上一步</Button>
<Button type="primary" onClick={this.handleNext}>下一步</Button>
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
person: state.user.person,
personSelectedRowKeys: state.user.personSelectedRowKeys
}
}
const mapDispatchToProps = (dispatch) => {
return {
onChangePracticeAppointmentStep: (step) => dispatch(doChangePracticeAppointmentStep(step))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AppContentPracticeAppointmentSecond);
|
import { getSchema } from 'Test/factories'
import createTableProps from '../TableProps'
describe('TableProps', () => {
test('createTableProps', () => {
const schema = getSchema()
const props = createTableProps({
schema,
columns: [{
name: 'firstName',
caption: 'Name'
}, 'age'],
perPage: 10,
fetchParams: {
isAdmin: true
}
})
expect(props.schema).toBe(schema)
expect(props._isTableProps).toBe(true)
expect(props.columns).toHaveLength(1) // age is not recognized as a column
expect(props.columns[0].field.name).toBe('firstName')
expect(props.columns[0].caption).toBe('Name')
expect(props.perPage).toBe(10)
expect(props.showHeader).toBe(true)
expect(props.showFooter).toBe(true)
expect(props.fetchParams).toEqual({
isAdmin: true
})
})
})
|
var fs = require('fs');
var Set = require('./set.js').Set;
var DICTIONARY_FILE = "./dictionary.txt";
var cache = null;
module.exports = function () {
if (cache) { return cache; }
try {
// Not important to be asynchronous here, since we
// do this just once and not under load.
var dictionary = fs.readFileSync(DICTIONARY_FILE, { encoding: "utf-8" });
} catch (e) {
return null;
}
var words = dictionary.split('\n');
cache = new Set(words);
return cache;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.