text
stringlengths 7
3.69M
|
|---|
$(document).ready(function () {
$('#parkname_init_loadingModal').modal({backdrop: 'static', keyboard: false});
var init_frp_park_name = "/api/frp/init_frp_park_name";
$.ajax({
type: 'GET',
url: init_frp_park_name,
success: function (chunk, textStatus) {
$("#park_name").autocomplete({
source: chunk
});
$("#parkname_init_loadingModal").modal('hide');
},
error: function () {
$("#parkname_init_loadingModal").modal('hide');
bootbox.alert({
title: "提示信息",
message: "车产数据初始化失败,网络超时!",
size: "small"
});
},
timeout: 60000,
dataType: 'json'
});
$('#tab1').on("shown.bs.tab", function (e) {
$("#ip_list_btn").css("display", "inherit")
});
$('#tab2').on("shown.bs.tab", function (e) {
$("#ip_list_btn").css("display", "none")
});
$('#tab3').on("shown.bs.tab", function (e) {
$("#ip_list_btn").css("display", "none")
});
$('#tab5').on("shown.bs.tab", function (e) {
$("#ip_list_btn").css("display", "none")
});
$("#oprate_type").change(function () {
if ($("#oprate_type").val() == "Frp模式") {
$("#inout_net_type").css("display", "none");
$("#park_name_type").css("display", "inherit")
} else {
$("#inout_net_type").css("display", "inherit");
$("#park_name_type").css("display", "none")
}
});
$("#ip_list_btn").click(function () {
if (!$("#park_name").val()) {
bootbox.alert({
title: "提示信息",
message: "请输入有效的车场名称!",
size: "small"
});
return
}
$("#ip_list").empty();
$('#parkip_init_loadingModal').modal({backdrop: 'static', keyboard: false});
$.ajax({
type: 'GET',
url: "/api/v3/get_arm_ip_list",
data: {park_name: $("#park_name").val()},
success: function (chunk, textStatus) {
$("#parkip_init_loadingModal").modal('hide');
if (!$.isArray(chunk.result)) {
bootbox.alert({
title: "提示信息",
message: "暂不支持V2车场的arm IP获取!"
});
return
}
if (chunk.result.length > 0) {
$("#ip_list_info").css("display", "inherit");
$.each(chunk.result, function (index, value) {
$("#ip_list").append("<option value='" + value + "'>" + value + "</option>")
});
$("#ip_list").selectpicker("refresh");
} else {
bootbox.alert({
title: "提示信息",
message: "未获取到arm IP,输入的车场名称有误!"
});
}
},
error: function () {
$("#parkip_init_loadingModal").modal('hide');
bootbox.alert({
title: "提示信息",
message: "车场IP列表获取失败,请联系管理员!"
});
},
timeout: 60000,
dataType: 'json'
});
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FONT_PT_SIZES = undefined;
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _prosemirrorState = require('prosemirror-state');
var _prosemirrorTransform = require('prosemirror-transform');
var _prosemirrorView = require('prosemirror-view');
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _FontSizeCommand = require('../FontSizeCommand');
var _FontSizeCommand2 = _interopRequireDefault(_FontSizeCommand);
var _CommandMenuButton = require('./CommandMenuButton');
var _CommandMenuButton2 = _interopRequireDefault(_CommandMenuButton);
var _findActiveFontSize = require('./findActiveFontSize');
var _findActiveFontSize2 = _interopRequireDefault(_findActiveFontSize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FONT_PT_SIZES = exports.FONT_PT_SIZES = [8, 9, 10, 11, 12, 14, 18, 24, 30, 36, 48, 60, 72, 90];
var FONT_PT_SIZE_COMMANDS = FONT_PT_SIZES.reduce(function (memo, size) {
memo[' ' + size + ' '] = new _FontSizeCommand2.default(size);
return memo;
}, {});
var COMMAND_GROUPS = [{ Default: new _FontSizeCommand2.default(0) }, FONT_PT_SIZE_COMMANDS];
var FontSizeCommandMenuButton = function (_React$PureComponent) {
(0, _inherits3.default)(FontSizeCommandMenuButton, _React$PureComponent);
function FontSizeCommandMenuButton() {
(0, _classCallCheck3.default)(this, FontSizeCommandMenuButton);
return (0, _possibleConstructorReturn3.default)(this, (FontSizeCommandMenuButton.__proto__ || (0, _getPrototypeOf2.default)(FontSizeCommandMenuButton)).apply(this, arguments));
}
(0, _createClass3.default)(FontSizeCommandMenuButton, [{
key: 'render',
value: function render() {
var _props = this.props,
dispatch = _props.dispatch,
editorState = _props.editorState,
editorView = _props.editorView;
var fontSize = (0, _findActiveFontSize2.default)(editorState);
var className = String(fontSize).length <= 2 ? 'width-30' : 'width-60';
return _react2.default.createElement(_CommandMenuButton2.default, {
className: className,
commandGroups: COMMAND_GROUPS,
dispatch: dispatch,
editorState: editorState,
editorView: editorView,
label: fontSize
});
}
}]);
return FontSizeCommandMenuButton;
}(_react2.default.PureComponent);
exports.default = FontSizeCommandMenuButton;
|
import React, { useState, useEffect } from 'react';
export const CurrentActivity = () => {
const [day, setDay] = useState(1);
const [activity, setActivity] = useState('');
// Set current day into state
const currDay = () => {
let today = new Date().getDay();
setDay(today);
};
// useEffect to call both functions on render
useEffect(() => {
// This function will find the current activity based on current day and set to state
const currActivity = () => {
const activityList = {
0: 'Big Final Reveal',
1: 'Read',
2: 'Draw',
3: 'Write',
4: 'Squadding Up',
5: 'Point Share',
6: 'Voting',
};
setActivity(activityList[day]);
return activity;
};
currDay();
currActivity();
}, [activity, day]);
return <div>Current Activity: {activity}</div>;
};
|
export const FETCH_USER = "FETCH_USER";
export const FETCH_USER_SUCCESS = "FETCH_USER_SUCCESS";
export const FETCH_USER_FAILURE = "FETCH_USER_FAILURE";
|
/*
* Module code goes here. Use 'module.exports' to export things:
* module.exports.thing = 'a thing';
*
* You can import it from another modules like this:
* var mod = require('role.war.healer');
* mod.thing == 'a thing'; // true
*/
healer = {
pickup: function(creep) {
//Short circuit here to move to the appropriate room that we haven't been to yet
var helpTheseCreeps = creep.room.find(FIND_MY_CREEPS, {filter: (creep) => creep.hits < creep.hitsMax});
if(helpTheseCreeps.length > 0) {
index = 0;
result = ERR_NOT_IN_RANGE;
while(result != OK && index < helpTheseCreeps.length){
helpThisGuy = helpTheseCreeps[index];
result = creep.heal(helpThisGuy);
xdiff = Math.abs(Game.flags.trenches.pos.x - helpThisGuy.pos.x);
ydiff = Math.abs(Game.flags.trenches.pos.y - helpThisGuy.pos.y);
// console.log(xdiff +" " + ydiff);
if(result == ERR_NOT_IN_RANGE && xdiff < 3 && ydiff < 3) {
creep.say("lol");
creep.moveTo(helpThisGuy);
}
index++;
}
if(result != OK) {
creep.moveTo(Game.flags.trenches);
}
} else {
creep.moveTo(Game.flags.trenches);
}
}
}
module.exports = healer;
|
const configureStripe = require('stripe')
const bodyParser = require('body-parser')
const STRIPE_SECRET_KEY =
process.env.NODE_ENV === 'production'
? 'sk_live_MY_SECRET_KEY'
: 'sk_test_HFlmK9RxeyUAqiHwMhmJriEs004ayVg3VN'
const stripe = configureStripe(STRIPE_SECRET_KEY)
const postStripeCharge = res => (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({error: stripeErr})
} else {
res.status(200).send({success: stripeRes})
}
}
const paymentApi = app => {
app.get('/api/payments', (req, res) => {
res.send({
message: 'Hello Stripe checkout server!',
timestamp: new Date().toISOString()
})
})
app.post('/api/payments', async (req, res) => {
try {
await stripe.charges.create(req.body, postStripeCharge(res))
} catch (error) {
console.log(error.message)
}
})
return app
}
const configureRoutes = app => {
app.use(bodyParser.json())
paymentApi(app)
}
module.exports = {configureRoutes}
|
/**
* Created by Jackson on 10/20/16.
*/
(function () {
angular.module('tpt')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['fetchUser', '$routeParams', '$mdDialog'];
function ProfileController(fetchUser, $routeParams, $mdDialog) {
var vm = this;
vm.currentUser = {};
vm.user = {};
vm.editProfile = editProfile;
vm.changePassword = changePassword;
fetchUser.getUser($routeParams.user, function (response) {
vm.user = response;
});
fetchUser.getCurrentUser(function (user) {
vm.currentUser = user;
});
function editProfile() {
$mdDialog.show({
templateUrl: 'profile/edit/edit.template.html',
controller: 'EditController',
controllerAs: 'vm',
clickOutsideToClose: true
})
}
function changePassword() {
$mdDialog.show({
templateUrl: 'profile/password/password.template.html',
controller: 'PasswordController',
controllerAs: 'vm',
clickOutsideToClose: true
})
}
}
})();
|
const winLossRecordSort = (playerOne, playerTwo) => playerTwo.point_count - playerOne.point_count;
// calculate point count for players
// sort players in each pool by point count
const seedCalculator = pools => Object.values(pools)
.slice(1).filter(tournamentPool => tournamentPool.length > 0)
.map(tournamentPool => [...tournamentPool]
.sort(winLossRecordSort)
.reduce((poolWithSeeds, currentPlayer, index) => {
if (index === 0) {
return [{ ...currentPlayer, seed: 1 }];
}
const previousPlayer = poolWithSeeds[index - 1];
const currentPlayerPoints = currentPlayer.point_count;
const previousPlayerPoints = previousPlayer.point_count;
// if this player has as many points as the player before them, they should have the same seed
// if they don't have the same number of points, then their seed is there current index + 1
// (since seeds start at 1 and the index starts at 0)
const seed = currentPlayerPoints === previousPlayerPoints ? previousPlayer.seed : index + 1;
return [...poolWithSeeds, { ...currentPlayer, seed }];
}, []));
module.exports = seedCalculator;
|
/**
* TabSaver will store the currently selected tab into LocalStorage and
* create a table listing all such entries, allowing the user to reopen
* previously saved tabs.
*
* @summary TabSaver popup.js to control functionality of extension
*
* @author Martin Green
* @copyright 2016
*/
document.addEventListener('DOMContentLoaded', function() {
// Initialize localStorage
if (!localStorage.tabList) localStorage.tabList = JSON.stringify([]);
if (!localStorage.tabListBackup) localStorage.tabListBackup = JSON.stringify([]);
console.log(localStorage.tabList);
console.log(localStorage.tabList.length);
console.log(localStorage.tabListBackup.length);
createTable(); // Populate the list with all saved websites
loadTabInfo(); // Load current tab info to display in header
savePageListener(); // onClick listener for Save button
listCleanup(); // onClick listener for Clear / Restore button
}, false);
// Constructor for Tab objects
function Tab(url, title) {
this.url = url;
this.title = title;
}
function createTable() {
var tableBody = "";
var allTabs = JSON.parse(localStorage.tabList);
allTabs.forEach(function(tab) {
tableBody += "<tr><td width='16'><img src='chrome://favicon/" + tab.url +
"' width='16' height='16' /></td><td>" + tab.title + "</td><td>" + tab.url + "</td></tr>";
});
document.getElementById("tabs").innerHTML = tableBody;
addRowHandlers();
}
function loadTabInfo() {
chrome.tabs.query(
{currentWindow: true, active : true},
function(tab) {
var title = tab[0].title;
if (title.length > 45) {
title = title.substring(0, 40) + "...";
}
document.getElementById("curTab").innerHTML = "Save tab: " + title;
}
);
}
function savePageListener() {
var savePageButton = document.getElementById("save_button");
savePageButton.addEventListener("click", function() {
chrome.tabs.query(
{currentWindow: true, active : true},
function(tab) {
var currentTab = new Tab(tab[0].url, tab[0].title);
// Check if page has already been saved
if (!localStorage.tabList.includes(JSON.stringify(currentTab))) {
var tabList = JSON.parse(localStorage.tabList);
tabList.push(currentTab);
localStorage.tabList = JSON.stringify(tabList);
createTable();
}
savePageButton.value = "Saved!";
}
);
}, false);
}
function listCleanup() {
var deleteAllButton = document.getElementById("delete_button");
if (localStorage.tabList.length < 5 && localStorage.tabListBackup.length > 5) {
deleteAllButton.value = "Restore";
} else {
deleteAllButton.value = "Clear";
}
deleteAllButton.addEventListener("click", function() {
if (deleteAllButton.value == "Clear") {
console.log("removed all items");
localStorage.tabListBackup = localStorage.tabList;
localStorage.tabList = JSON.stringify([]);
document.getElementById("delete_button").value = "Restore";
} else {
console.log("restored to backup");
localStorage.tabList = localStorage.tabListBackup;
document.getElementById("delete_button").value = "Clear";
}
createTable();
document.getElementById("save_button").value = "Save";
}, false);
}
function addRowHandlers() {
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
chrome.tabs.query(
{currentWindow: true, active : true},
function(tab) {
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var title = row.getElementsByTagName("td")[1].innerHTML;
var url = row.getElementsByTagName("td")[2].innerHTML;
title = title.replace(/&/g, "&").replace(/>/g, ">")
.replace(/</g, "<").replace(/"/g, "'").replace(/'/g, '"');
url = url.replace(/&/g, "&").replace(/>/g, ">")
.replace(/</g, "<").replace(/"/g, "'").replace(/'/g, '"');
var newTab = new Tab(url, title);
var tabString = JSON.stringify(newTab);
// Homogenizes whitespace characters to allow .replace to work reliably
localStorage.tabList = localStorage.tabList.replace(/\s/g, " ");
localStorage.tabList = localStorage.tabList.replace(tabString,""); // Remove entry
localStorage.tabList = localStorage.tabList.replace("{}", ""); // Clean up empty entries
localStorage.tabList = localStorage.tabList.replace(",,", ","); // Remove leftover characters from middle ...
localStorage.tabList = localStorage.tabList.replace("[,", "["); // ... beginning ...
localStorage.tabList = localStorage.tabList.replace(",]", "]"); // ... and end
chrome.tabs.create({ url: url, index: tab[0].index + 1, openerTabId: tab[0].id });
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
);
}
|
import React, { Component } from 'react';
import dva from 'rn-dva';
import dvaLoading from 'dva-loading';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { StoreEnhancer, PersistStore } from './utils/persist';
import reducers from './reducer';
import {
App, AppSOM, AppWM, AppProfile,
} from './App';
import { middleware } from './Routes';
import userModel from './models/user';
import shopModel from './models/shop';
import systemModel from './models/system';
import applicationModel from './models/application';
import taskModel from './models/task';
import homeModel from './models/home';
import mallModel from './models/mall'
import welfareModel from './models/welfare';
import orderModel from './models/order';
import myModel from './models/my';
import userActiveModel from './models/userActive';
import upgradeModel from './models/upgrade';
import config from '../android/app/src/main/assets/requestConfig.json';
const app = dva({
extraEnhancers: [
StoreEnhancer(),
applyMiddleware(middleware),
applyMiddleware(thunk),
!__DEV__ || config.enableLogger !== '1' ? null : applyMiddleware(logger),
].filter(item => !!item),
extraReducers: {
...reducers,
},
uses: [
dvaLoading({ effects: true }),
],
models: [
userModel,
systemModel,
applicationModel,
shopModel,
taskModel,
homeModel,
welfareModel,
orderModel,
myModel,
userActiveModel,
upgradeModel,
mallModel,
],
});
const MainApp = app.start(<App />);
global.app = app;
PersistStore(app);
export default MainApp;
export const MainAppSOM = props => (
<Provider store={app._store}>
<AppSOM {...props} />
</Provider>
);
export const MainAppWM = props => (
<Provider store={app._store}>
<AppWM {...props} />
</Provider>
);
export const MainAppProfile = props => (
<Provider store={app._store}>
<AppProfile {...props} />
</Provider>
);
|
var cover;
var text;
function preload() {
cover = loadImage('./assets/cover.jpg');
text = loadImage('./assets/cover text.png');
}
function setup() {
createCanvas(windowWidth, windowHeight);
image(cover, 0, 0, cover.width*1.4, cover.height*1.4);
imageMode(CENTER);
image(text, windowWidth/2, windowHeight/2, text.width/5.5, text.height/5.5);
}
function draw() {
if (keyIsPressed == true && keyCode == ENTER) {
window.location.href="01sketchGel.html";
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
|
import React from 'react'
import CustomIcon from '../CustomIcon'
const DocsRing = (props) => (
<CustomIcon {...props}>
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="6"/>
</CustomIcon>
)
export default DocsRing
|
// get trip values set welocome page in local storage
var tripDestination = localStorage.getItem("tripDestination");
var tripPid = localStorage.getItem("tripPid");
var tripLat = Number(localStorage.getItem("tripLat"));
var tripLng = Number(localStorage.getItem("tripLng"));
var tripFromDate = localStorage.getItem('tripBegDate');
var tripToDate = localStorage.getItem('tripEndDate');
var tripName = localStorage.getItem('tripName');
// globals
var category;
var map;
var infowindow;
var latLng = {lat:tripLat,lng:tripLng};
// suppress filling map with random markers in initMap
var buttonClick = false;
var request;
var service;
var markers=[];
var mapById = document.getElementById('map');
var ourCategories = ["cafe","restaurant","transit_station","bar","night_club","park","museum"];
// array to hold activities within Categories
var savedActivities = [];
var listDiv;
var inlist = false;
var userLatLng;
var justMyMarkers = false;
function ActivityObj(place_id, name, lat, lng, category) {
this.place_id = place_id;
this.name = name;
this.lat = lat;
this.lng = lng;
this.category = category;
}
function parseSavedActivities(){
var tripObj = JSON.parse(localStorage.getItem("savedTrip"));
if (typeof tripObj === "object" && tripObj != null) {
var actArray = parse_trip_activities(tripObj);
savedActivities = [];
for (var i = 0; i < actArray.length; i++){
var actObj = actArray[i].activityObj;
savedActivities.push(new ActivityObj(actObj.place_id, actArray[i].activityName, actObj.lat, actObj.lng, actObj.category));
}
}
}
// on page load - fill saved activities, if they're there
parseSavedActivities();
// display trip name suggestion
$("#trip-name").attr("placeholder", "Suggestion: "+tripName);
// get user input for trip name
$('#saveTrip').on('click', function(){
if (typeof $("#trip-name").val() === "undefined") {
tripName = formatTripName(tripLoc, tripBegDate, tripEndDate);
}
else {
tripName = $("#trip-name").val().trim();
}
// store in Firebase
var trip = {
"location": localStorage.getItem("tripDestination"), // long name
"loc": localStorage.getItem("tripLoc"), // short name
"start_date": localStorage.getItem('tripBegDate'),
"end_date": localStorage.getItem('tripEndDate'),
"place_id": localStorage.getItem("tripPid"),
"lat": localStorage.getItem("tripLat"),
"lng": localStorage.getItem("tripLng"),
}
store_trip(tripName, trip, true); // is potentially an update - gotta remove the old name
// now add the activities
for (var i = 0; i < savedActivities.length; ++i) {
store_activity(savedActivities[i].name, savedActivities[i], false);
}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
// event handler for 'my markers' radio button
$("#my-markers").on('click', function(){
justMyMarkers = true;
clearResults(markers);
console.log("my markers button clicked");
// loop through savedActivities array and place saved markers on map
for (var i = 0; i < savedActivities.length; i++){
console.log(savedActivities[i].place_id);
var placeID = savedActivities[i].place_id;
var apiKey = "AIzaSyADdZ4KZHwZP1YQFdmKa15i5JlbUnRfJw4";
var queryURL = "https://maps.googleapis.com/maps/api/place/details/json?place_id=" + placeID + "&key=" + apiKey;
var request = {
placeId: placeID
};
var myCategory = savedActivities[i].category;
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
console.log(status)
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log("getDetail status: "+place);
var marker = new google.maps.Marker({
map: map,
label: labels[labelIndex++ % labels.length],
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});
};
});
function myMarkerWithTimeout(place, timeout) {
window.setTimeout(function() {
markers.push(createMarker(place));
console.log(place);
}, timeout);
}
// event handler for 'all markers' radio button
$("#all-markers").on('click', function(){
console.log("all markers button clicked");
buttonClick = true;
listDiv ="."+category;
initMap();
});
// event handler for category button click
$(".categoryButton").on("click", function(event){
event.preventDefault();
category = $(this).attr("btnCategory");
console.log(category + " button clicked");
buttonClick = true;
listDiv ="."+category;
initMap();
});
// MAP LOAD & RELOAD
// called on main.html load and when category buttons are clicked
function initMap(){
var options = {
zoom:14,
center:latLng
};
console.log("Loading map for: ");
console.log(latLng);
map = new google.maps.Map(mapById, options);
// the buttonClick flag is set to false on page load to prevent markers
// on map unless coming from an actType button click
if (buttonClick){
// setup paramters for Google Places request based on selected category
request = {
location: latLng,
radius: 5000,
type: [category],
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, doMarkers);
// add a listener to the map to detect rightclick. This will recenter the
// search area, clear existing markers and place
google.maps.event.addListener(map, 'rightclick', function(event, request){
map.setCenter(event.latlng);
clearResults(markers);
var request = {
location: event.latLng,
radius: 5000,
type: [category],
};
service.nearbySearch(request, doMarkers);
});
// reset flag
buttonClick = false;
} // end of category button click handler
} // end of initMap()
// loop through places in results from nearbySearch request
function doMarkers(results, status) {
if(status == google.maps.places.PlacesServiceStatus.OK){
for (var i = 0; i < results.length; i++){
addMarkerWithTimeout(results[i], i*100);
console.log(results[i]);
}
} else {
console.log(google.maps.places.PlacesServiceStatus);
}
}
// animate marker drop with bounce
// timer prevents all markers from dropping at once
function addMarkerWithTimeout(place, timeout) {
window.setTimeout(function() {
markers.push(createMarker(place));
console.log(place);
}, timeout);
}
// create a marker from a place in results from nearbySearch request
function createMarker(place) {
// place a marker on map
var iconPath = "assets/images/icons/" + category + "/marker_" + category + ".png";
marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
animation: google.maps.Animation.DROP,
title: place.name,
//icon: iconPath
});
// open infowindow when marker is clicked
google.maps.event.addListener(marker, 'click', function(){
// prepare information to display in infowindow
var rating = '';
var price = '';
openNow = '';
// if rating exists, format it for display
if (place.rating) {
rating = 'Rated: ' + place.rating +" ";
} else {
rating = '';
};
// if price_level exists, format it for display
if (place.price_level) {
if (place.price_level === 1) {price = '$'}
else if (place.price_level === 2) {price = '$$'}
else if (place.price_level === 3) {price = '$$$'}
else if (place.price_level === 5) {price = '$$$$'}
else {price = ''}
};
// if opening_hours exists, format for display
if (place.opening_hours) {
if (place.opening_hours.open_now) {
openNow = ' Open Now';
} else {
openNow = '';
}
};
// build html for infowindow
var contentString1 = ([
"<div class='info-container'>",
"<div id='heading'>",
"<h4>",
place.name,
"</h4>",
"<h6>",
place.vicinity,
"</h6>",
"</div>",
"<br>",
"<div class='info-content'>",
"<h6>",
rating,
price,
'<span class="float-right" style="color:red">',
openNow,
"</span>",
"</h6>",
"<form id='",
place.place_id,
"'>",
].join(''));
var contentString2;
var alreadyAdded = savedActivities.filter(obj => obj.name === this.title);
if (alreadyAdded.length == 0) {
contentString2 = ([
'<button id="addActivityBtn" type="submit" class="btn btn-primary float-right">',
"Add",
'</button>',
"</form>",
"</div>",
"</div>"
].join(''));
} else{
contentString2 = ([
"</form>",
"</div>",
"</div>"
].join(''));
}
var contentString = contentString1+contentString2;
// open infowindow for clicked marker
infowindow.setContent(contentString);
infowindow.open(map, this);
// event listener for 'Add' button click on inforwindow
google.maps.event.addListener(infowindow, 'domready', function(){
var uniqueID = "#"+place.place_id;
$(uniqueID).submit(function(event){
event.preventDefault();
console.log(place.name + ' -Add- button clicked');
// make initial unordered list element
// skip if already in html
var ulID = category+'-list';
if ($(listDiv).attr("list-started") == 'false') {
$(listDiv).html("");
//make initial unordered list div
var ulElement = $("<ul id='" + ulID + "'>");
$(listDiv).append(ulElement);
$(listDiv).attr("list-started", 'true');
};
// NEW ACTIVITY
// prepare an object to save in array
var placeLat = place.geometry.location.lat();
var placeLng = place.geometry.location.lng();
var savedActivity = new ActivityObj(
place.place_id,
place.name,
placeLat,
placeLng,
category
);
// check to see if this place is saved already
// and prevent duplicates if it has been
var matches = savedActivities.filter(obj => obj.place_id === place.place_id);
if (matches.length == 0) {
// save activity object to array
savedActivities.push(savedActivity);
// append list item
var hashID = "#"+ulID;
var liAndID = "<li id='" + place.place_id + "'>";
$(hashID).prepend($(liAndID).text(place.name));
$("#addActivityBtn").hide();
// store in Firebase
store_activity(savedActivity.name, savedActivity, false);
}
// handle if already in array (skip)
else if (matches.length > 0) {
console.log("That place is already in your list.")
}; // end of 'add activity' code
}); // end of $(uniqueID).submit(function(event)
}); // end of 'Add' button event listener
}); // end of marker click event to open infowindow
return marker;
} // end of createMarker()
function clearResults(markers) {
for (var m in markers) {
markers[m].setMap(null);
}
markers = [];
}
|
var MyApp = angular.module('MyApp',[]);
MyApp.controller('ListCtrl', ['$scope','$http', '$q', function($scope, $http ,$q){
$scope.name = 'sunshine1125';
function demo(){
var deferred = $q.defer(), that = this;
if (that.cache == undefined) {
$http.get('https://api.github.com/users/${$scope.name}')
.then(function(data, status, headers){
that.cache = data.data;
deferred.resolve(that.cache);
})
}else {
console.log('from cache');
deferred.resolve(that.cache);
}
return deferred.promise;
}
// 利用闭包缓存结果
function demo2() {
var defer = $q.defer(), cache;
return function() {
if (cache == undefined) {
$http.get('https://api.github.com/users/${$scope.name}')
.then(function(res) {
cache = res.data;
defer.resolve(cache);
})
}else {
console.log('from cache');
defer.resolve(cache);
}
return defer.promise;
}
}
// 点击加载
var startDemo = demo2();
$scope.load = function() {
startDemo().then(function(data){
$scope.list = data;
})
}
}])
|
import express from "express";
const router = express.Router({ mergeParams: true });
import passport from "passport";
import { facebook, facebookFailure, logout, check } from "../handlers/routes/auth";
const facebookAuth = passport.authenticate("facebook", {
scope: "email",
failureRedirect: "/api/auth/facebook/failure"
});
const attachsocketIdToSession = (req, res, next) => {
req.session.socketId = req.query.socketId;
next();
};
router.get("/facebook", attachsocketIdToSession, facebookAuth);
router.get("/facebook/callback", facebookAuth, facebook);
router.get("/facebook/failure", facebookFailure);
router.post("/logout", logout);
router.get("/check", check);
export default routerCombiner => {
routerCombiner.use("/auth", router);
};
|
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope','$http', function($scope) {
var itemsx=[{id:1,Description:"Kathmandu"},{id:1,Description:"Bhaktapur"},{id:1,Description:"Lagenkhel"},{id:1,Description:"Janakpur"},{id:1,Description:"Koshi"},{id:1,Description:"Sagarmatha"},{id:1,Description:"Gandaki"}];
// angular.forEach(response.data.d.results, function(item){
// itemsx.push(item.Report_x0020_Name);
// });
$scope.items=itemsx;
$scope.restoreItems=itemsx;
console.log(itemsx);
$scope.searchInput = function(value){
$scope.items=$scope.restoreItems;
var filtered = [];
angular.forEach($scope.items, function(item){
if(item.Description.indexOf(value)>-1) {
filtered.push(item);
}
});
$scope.items=[];
angular.forEach(filtered, function(val){
$scope.items.push(val);
});
if (value=="") { $scope.items=$scope.restoreItems; }
};
}]);
|
// getting needed dependencies
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const nocache = require('nocache');
const compression = require('compression');
const path = require('path');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUI = require('swagger-ui-express');
const Sentry = require('@sentry/node');
const Tracing = require('@sentry/tracing');
const config = require('./config/config')
const swaggerDocs = swaggerJsDoc(config.swaggerOptions);
const recordsAPI = require('./apis/records/recordsAPI');
// initializing the express application
const app = express();
// initializing sentry and attaching it to the global object
// so it can be called globally
Sentry.init({
tracesSampleRate: 0.5,
environment: process.env.NODE_ENV,
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
// enable Express.js middleware tracing
new Tracing.Integrations.Express({ app }),
],
});
global.sentryTracker = Sentry;
// making a connection to the database
mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// setting up middlewares to use for the app
app.set('etag', false);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(nocache());
app.use(compression());
app.use(express.static(path.join(__dirname)));
// setting routes/endpoints to be used
app.use('/v1/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));
app.use('/v1/records', recordsAPI);
app.use('*', (req, res) => {
return res.status(404).send('Sorry, the requested URL was not found on the server.');
})
// listening on the port the application is being run on
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
module.exports = app;
|
module.exports = {
FECAESolicitar: {
ImpNeto: {
type: "number",
default: 0
},
ImpConc: {
type: "number",
default: 0
},
ImpOpEx: {
type: "number",
default: 0
},
ImpTrib: {
type: "number",
default: 0
},
ImpIva: {
type: "number",
default: 0
},
IdIVA: {
type: "number"
},
DocNro: {
type: "string",
required: true,
minLength: 1
},
PtoVta: {
type: "number",
required: true,
minimum: 1,
maximum: 9998
},
DocTipo: {
type: "number",
default: 80
},
CbteNro: {
type: "number",
required: true
},
CbteFch: {
type: "string",
isDate: true
},
Concepto: {
type: "number",
default: 2
},
CantReg: {
type: "number",
default: 1
},
CbteTipo: {
type: "number",
required: true
},
MonId: {
type: "string",
default: "PES"
},
MonCotiz: {
type: "number",
default: 1
},
Tributos: {
type: "array",
items: [{
type: "object",
properties: {
Id: {
type: "number",
required: true
},
Desc: {
type: "string"
},
BaseImp: {
type: "number",
default: 0
},
Alic: {
type: "number",
required: true
},
Importe: {
type: "number",
default: 0
}
}
}]
}
},
FECompUltimoAutorizado: {
PtoVta: {
type: "number",
required: true,
minimum: 1,
maximum: 9998
},
CbteTipo: {
type: "number",
required: true
}
},
FECompConsultar: {
PtoVta: {
type: "number",
required: true,
minimum: 1,
maximum: 9998
},
CbteTipo: {
type: "number",
required: true
},
CbteNro: {
type: "number",
required: true,
minimum: 1,
maximum: 99999999
},
}
};
|
export const SEARCH_FOCUS = 'SEARCH_FOCUS';
export const SEARCH_BLUR = 'SEARCH_BLUR';
|
var Discord = require('discord.io');
var drole = ""; /* roleid to be applied when someone joins the server */
var serverid = ""; /* your server id */
var bot = new Discord.Client({
autorun: true, /* If false, you need to connect to the server using bot.connect(); */
token: "" /* your discordapp token */
});
bot.on('ready', function() {
console.log("Successfully connected: " + bot.username + " - (" + bot.id + ")");
});
bot.on('guildMemberAdd', function(callback) { /* Event called when someone joins the server */
if(callback.guild_id == serverid)
bot.addToRole({"serverID":serverid,"userID":callback.id,"roleID":drole},function(err,response) {
if (err) console.error(err); /* Failed to apply role */
/* some code */
});
});
|
var express = require("express");
var app = express();
app.get("/", (req, res, next) => {
res.json([
{
title: 'CAN I SUBMIT FEEDBACK WITHIN THE APP?',
desc: 'Yes! We love hearing from our app users and welcome the feedback as we work toward improving the app in the future. There are two methods within the app to provide feedback. Tap the “Profile” icon, then select Feedback. Tap the “More” icon on the bottom right of the app, then select Feedback.',
id: '0',
},
{
title: 'WHY DOES THE APP SAY I NEED TO COMPLETE AN ACTION I’VE ALREADY COMPLETED?',
desc: 'Try manually refreshing the app by dragging the screen down and releasing.',
id: '1',
},
{
title: 'HOW CAN I GET STEP-BY-STEP ROUTING TO MY DESTINATION?',
desc: 'From the My Loads menu, expand the stop details and select the blue triangle icon to the right of the address. If you agree with the disclaimer, click OK and select your preferred installed app for your step-by-step navigation. Note: You will see a disclaimer, please read the disclaimer in full and always use caution to ensure the route is safe for your load',
id: '2',
},
{
title: 'WHY ARE MY MILES NOT ACCURATE?',
desc: 'We are working to provide this data to devices sooner. Keep an eye out for this in our coming releases!',
id: '3',
},
{
title: 'HOW DO I PROVIDE SUGGESTIONS, COMMENTS OR REPORT ISSUES WITH THE APP?',
desc: 'All unread messages show at the top of your inbox. Once you’ve read a message, it will go to the bottom of your messages list. You may have to scroll down if you have a lot of messages in your inbox.',
id: '4',
},
{
title: 'WHERE DID MY MESSAGE GO AFTER I READ IT?',
desc: 'From both the More menu and your Profile, you can find the Feedback option and provide us with general feedback, request a new feature or report a system failure. You can also call 1-800-777-4968 to give feedback or report problems',
id: '5',
},
{
title: 'HOW CAN I QUICKLY ARCHIVE ALL MY MESSAGES?',
desc: 'From your Inbox, check the box next to Select All in the top left corner, then click Archive on the top right',
id: '6',
},
{
title: 'WHY DOES THE APP SAY I’M DRIVING WHEN I’M STATIONARY?',
desc: 'The app pulls your device GPS to determine whether you’re moving. Sometimes, there is an error signal and you will need to select the “I’m not driving” option to refresh your signal. You may have to attempt more than once or exit the app and restart if the issue persists.',
id: '7',
},
{
title: 'WHY AM I NOT SEEING ALL THE DETAILS I NEED FOR A LOAD?',
desc: 'The most important information is found within Load Information at the bottom of the My Loads menu. To find any additional information, expand a stop and click Additional Details.',
id: '8',
},
{
title: 'WHY AM I NOT GETTING A PUSH NOTIFICATION WHEN I RECEIVE MESSAGES?',
desc: 'First, make sure the settings on your device allow DRIVE to send notifications. To do this, go to your Settings application on your device, find the DRIVE application and make sure notifications are turned on. If they are turned on and you are still not receiving them, please contact 1-800-777-4968.',
id: '9',
},
{
title: 'CAN DRIVERS AND MANAGERS COMMUNICATE THROUGH THE APP?',
desc: 'Drivers and Managers can send messages from the app; however, drivers cannot access messages while driving.',
id: '10',
},
{
title: 'HOW DO I ENSURE THAT THE INFORMATION ON THE APP IS UP TO DATE?',
desc: 'If the information on the app does not appear to be correct, simply pull down on any page to refresh the application and retrieve current details about your workload.',
id: '11',
},
{
title: 'CAN DRIVERS AND MANAGERS COMMUNICATE THROUGH THE APP?',
desc: 'Drivers and Managers can send messages from the app; however, drivers cannot access messages while driving.',
id: '12',
},
{
title: 'WILL THIRD-PARTY APPS (I.E. WEIGH MY TRUCK) BE INTEGRATED INTO DRIVE?',
desc: 'We are always working to improve the in-app experience. With our initial release, we won’t be integrating with these applications, however, please submit feedback with any apps you would like to see!',
id: '13',
},
{
title: 'HOW DO I ENSURE THAT THE INFORMATION ON THE APP IS UP TO DATE?',
desc: 'If the information on the app does not appear to be correct, simply pull to refresh on any page to refresh the application and retrieve current details about your workload.',
id: '14',
},
]);
});
const port=process.env.PORT || 3000
app.listen(port, () => {
console.log("Server running on port " + port);
});
|
let id_check = 0;
let pw_pattern1 = /[0-9]/;
let pw_pattern2 = /[a-zA-Z]/;
let pw_pattern3 = /[~!@#$%^&*()~]/;
$("#memberJoin").on("click", function(){
if($("#userID").val().length <= 0){
alert("ID는 필수입니다.");
$("#userID").focus();
return;
} else if($("#userName").val().length<=0){
alert("이름는 필수입니다.");
$("#userName").focus();
return;
} else if($("#userPassword").val().length<=0){
alert("비밀번호는 필수입니다.");
$("#userPassword").focus();
return;
} else if(!pw_pattern1.test($("#userPassword").val())||!pw_pattern2.test($("#userPassword").val())||!pw_pattern3.test($("#userPassword").val())||$("#userPassword").val().length<=7){
alert("비밀번호는 영문, 숫자, 특수문자를 포함한 8자 이상이 되어야합니다.");
$("#userPassword").focus();
return;
} else if($("#checkPassword").val().length<=0){
alert("비밀번호를 한번 더 입력해주세요.");
$("#checkPassword").focus();
return;
} else if($("#userPassword").val() != $("#checkPassword").val()){
alert("비밀번호가 다릅니다.");
$("#userPassword").val("");
$("#checkPassword").val("");
$("#userPassword").focus();
return;
} else if($("#userBirth").val().length<=0){
alert("생년월일은 필수입니다.");
$("#userBirth").focus();
return;
} else if($("#gender").val().length<=0){
alert("성별은 필수입니다.");
$("#gender").focus();
return;
} else if($("#userPhone").val().length<=0){
alert("연락처는 필수입니다.");
$("#userPhone").focus();
return;
} else if(id_check == 0){
alert("아이디 중복체크를 해주세요.");
return;
} else{
$("#joinForm").submit();
}
})
$("#memberIdCheck").on("click", function(){
let id = $("#userID").val();
if(id == "system"){
alert("이미 사용중인 아이디입니다.");
$("#userID").val("");
$("#userID").focus();
return false;
}
$.ajax({
url:"MemberIdCheck.do?id="+id,
success:function(data){
let resultMember = data.resultMember;
let resultAdmin = data.resultAdmin;
if ($("#userID").val().length <= 0){
alert("ID는 필수입니다.");
$("#userID").focus();
} else if (resultMember > 0 || resultAdmin > 0){
alert("이미 사용중인 아이디입니다.");
$("#userID").val("");
$("#userID").focus();
} else{
let check = confirm("사용가능한 아이디입니다.", "사용하시겠습니까?");
if(check){
$("#userID").attr("readonly", true);
id_check = 1;
} else{
$("#userID").val("");
$("#userID").focus();
}
}
}
});
return false;
});
$("#adminJoin").on("click", function(){
if($("#userID").val().length <= 0){
alert("ID는 필수입니다.");
$("#userID").focus();
return;
} else if($("#userName").val().length<=0){
alert("이름는 필수입니다.");
$("#userName").focus();
return;
} else if($("#userPassword").val().length<=0){
alert("비밀번호는 필수입니다.");
$("#userPassword").focus();
return;
} else if(!pw_pattern1.test($("#userPassword").val())||!pw_pattern2.test($("#userPassword").val())||!pw_pattern3.test($("#userPassword").val())||$("#userPassword").val().length<=7){
alert("비밀번호는 영문, 숫자, 특수문자를 포함한 8자 이상이 되어야합니다.");
$("#userPassword").focus();
return;
} else if($("#checkPassword").val().length<=0){
alert("비밀번호를 한번 더 입력해주세요.");
$("#checkPassword").focus();
return;
} else if($("#userPassword").val() != $("#checkPassword").val()){
alert("비밀번호가 다릅니다.");
$("#userPassword").val("");
$("#checkPassword").val("");
$("#userPassword").focus();
return;
} else if($("#mainArea").val() == "선택하세요"){
alert("주소 선택은 필수입니다.");
return;
} else if($("#detailArea").val() == "선택하세요"){
alert("주소 선택은 필수입니다.");
return;
} else if($("#roadName").val().length<=0){
alert("도로명은 필수입니다.");
return;
} else if($("#hospital").val() == null){
alert("선택하신 주소에 해당하는 병원이 없습니다. 다른 주소를 선택해주세요.");
return;
} else if($("#hospital").val() == "선택하세요"){
alert("병원 선택은 필수입니다.");
return;
} else if($("#userPhone").val().length<=0){
alert("연락처는 필수입니다.");
$("#userPhone").focus();
return;
} else if(id_check == 0){
alert("아이디 중복체크를 해주세요.");
return;
} else{
$("#joinForm").submit();
}
})
$("#adminIdCheck").on("click", function(){
let id = $("#userID").val();
if(id == "system"){
alert("이미 사용중인 아이디입니다.");
$("#userID").val("");
$("#userID").focus();
return false;
}
$.ajax({
url:"MemberIdCheck.do?id="+id,
success:function(data){
let resultMember = data.resultMember;
let resultAdmin = data.resultAdmin;
if ($("#userID").val().length <= 0){
alert("ID는 필수입니다.");
$("#userID").focus();
} else if (resultMember > 0 || resultAdmin > 0){
alert("이미 사용중인 아이디입니다.");
$("#userID").val("");
$("#userID").focus();
} else{
let check = confirm("사용가능한 아이디입니다.", "사용하시겠습니까?");
if(check){
$("#userID").attr("readonly", true);
id_check = 1;
} else{
$("#userID").val("");
$("#userID").focus();
}
}
}
});
return false;
});
function goLogin(memberType){
if (memberType == null) {
alert("로그인이 필요합니다");
location.href = "LoginForm.do";
}
}
function birthFormat(el){
if (el.value.length == 6)
el.value = el.value.replace(/(\d\d)(\d\d)(\d\d)/g, '$1/$2/$3');
}
window.onload = function(){
engAndNumberFunc($("#userID"));
birthNumberFunc($("#userBirth"));
userPhoneNumberFunc($("#userPhone"));
}
function engAndNumberFunc(t){
let regexp = /[^a-z0-9]/gi;
t.keyup(function(){
let v = $(this).val();
$(this).val(v.replace(regexp,''));
})
}
function birthNumberFunc(t){
let regexp = /[^/0-9]/gi;
t.keyup(function(){
let v = $(this).val();
$(this).val(v.replace(regexp,''));
})
}
function userPhoneNumberFunc(t){
let regexp = /[^-0-9]/gi;
t.keyup(function(){
let v = $(this).val();
$(this).val(v.replace(regexp,''));
})
}
|
import {connect} from 'react-redux';
import {EnhanceLoading} from '../../../components/Enhance';
import OrderPageContainer from './OrderPageContainer';
import EditPageContainer from './EditPageContainer';
import helper, {fetchJson, getJsonResult, initTableCols, postOption, showError} from "../../../common/common";
import {Action} from "../../../action-reducer/action";
import {search} from "../../../common/search";
import {fetchDictionary, setDictionary} from "../../../common/dictionary";
import {getStatus} from "../../../common/commonGetStatus";
import {buildOrderPageState} from "../../../common/state";
import {getPathValue} from "../../../action-reducer/helper";
import {createCommonTabPage} from "../../../standard-business/createTabPage";
import {jump} from '../../../components/Link';
const STATE_PATH = ['payChange'];
const action = new Action(STATE_PATH);
const URL_CONFIG = '/api/bill/pay_change/config';
const CUSTOM_CONFIG = '/api/bill/pay_change/custom_config';
const URL_LIST = '/api/bill/pay_change/list';
const URL_CURRENCY = '/api/bill/pay_change/currency';
const URL_TRANSPORTINFO = '/api/bill/pay_change/transportInfo';
const getSelfState = (rootstate) => {
return getPathValue(rootstate, STATE_PATH);
};
const buildJumpState = (tabs, editConfig, value) => {
const newTabs = tabs.find(tab => tab.key === 'add') ? tabs : tabs.concat([{key: 'add', title: '新增'}]);
return {
['add']: {...editConfig, value},
tabs: newTabs,
activeKey: 'add',
status: 'page'
}
};
// 其他页面调用改单新增界面
const jumpToChange = async (item, dispatch, getState) => {
const {returnCode, returnMsg, result} = await fetchJson(`${URL_TRANSPORTINFO}/${item.id}`);
if (returnCode !== 0) return showError(returnMsg);
const costInfo = result.details.map(item => {
item.readonly= 'readonly';
return item;
});
const value = {
costInfo,
balanceId: item.supplierId || result.balanceId,
transportOrderId: {value: item.id, title: item.orderNumber},
renewalMode: 'renewal_mode_001'
};
const {status, tabs=[], editConfig={}} = getSelfState(getState());
if (status !== 'page') {
dispatch(action.assign({isJump: true, jumpData: value}))
} else {
const config = helper.deepCopy(editConfig);
config.controls[0].data[1].type = 'readonly';
const payload = buildJumpState(tabs, config, value);
dispatch(action.assign(payload));
}
jump('/bill/pay_change');
};
/**
* @description 获取改单原因, 来自于系统字典responsible_party下级
* @param {Array} partyOptions 字典责任方第一级
* @return {Array}
*/
const getRenewalReson = async (partyOptions) => {
const names = partyOptions.map(option => option.value);
const dictionaryValue = getJsonResult(await fetchDictionary(names));
return names.reduce((result, name) => result.concat(dictionaryValue[name]), []);
};
/**
* @description 控制权限
* @param payload
*/
const assignPrivilege = (payload) => {
const actions = helper.getActions('payChange', true);
if (actions.length > 0) {
payload.buttons = payload.buttons.filter(({key}) => actions.includes(key));
payload.pageReadonly = !actions.includes('edit');
if (!actions.includes('commit')){
delete payload.editConfig.footerButtons[2];
}
}
};
const uniqueArrHanlder = (tableCols=[], customConfig=[]) => {
const otherCols = customConfig.filter(o => !tableCols.map(k=>k.key).includes(o.key));
const cols = tableCols.concat(otherCols);
return cols.reduce((newCols, col) => {
if(!newCols.map(o=>o.key).includes(col.key)){
newCols.push(col);
}
return newCols
}, []);
};
const initActionCreator = () => async (dispatch, getState) => {
try{
dispatch(action.assign({status: 'loading'}));
const {index, editConfig, dicNames, tabs, activeKey} = getJsonResult(await fetchJson(URL_CONFIG));
// 添加备用字段
const customConfig = getJsonResult(await fetchJson(`${CUSTOM_CONFIG}/renewal_detail`));
editConfig.tables[0].cols = uniqueArrHanlder(editConfig.tables[0].cols, customConfig.controls);
const list = getJsonResult(await search(URL_LIST, 0, index.pageSize, {}));
const dictionary = getJsonResult(await fetchDictionary(dicNames));
dictionary['status_type'] = getJsonResult(await getStatus('renewal'));
const currency = getJsonResult(await fetchJson(URL_CURRENCY, postOption({currencyTypeCode: '', maxNumber: 65536})));
const renewalReasonOptions = await getRenewalReson(dictionary['responsible_party']);
const newState = {tabs, activeKey, editConfig, isSort: true, status: 'page'};
const payload = buildOrderPageState(list, index, newState);
setDictionary(payload.filters, dictionary);
setDictionary(payload.tableCols, dictionary);
setDictionary(payload.editConfig.controls[0].data, dictionary);
setDictionary(payload.editConfig.tables[0].cols, dictionary);
helper.setOptions('currency', payload.editConfig.tables[0].cols, currency);
helper.setOptions('renewalReason', payload.tableCols, renewalReasonOptions);
helper.setOptions('renewalReason', payload.editConfig.controls[0].data, renewalReasonOptions);
payload.tableCols = initTableCols('payChange', payload.tableCols);
assignPrivilege(payload);
// 初始化搜索条件配置
payload.filters = helper.initFilters('pay_change_sort', payload.filters);
// 初始化按钮配置
payload.buttons = helper.setExportBtns('pay_change_export', payload.buttons, payload.tableCols);
// 如果是从其它界面跳转来的
const {isJump, jumpData} = getSelfState(getState());
if (isJump) {
const config = helper.deepCopy(editConfig);
config.controls[0].data[1].type = 'readonly';
Object.assign(payload, buildJumpState(tabs, config, jumpData));
}
dispatch(action.create(payload));
} catch (e) {
showError(e.message);
dispatch(action.assign({status: 'retry'}));
}
};
const tabChangeActionCreator = (key) => {
return action.assign({activeKey: key});
};
const tabCloseActionCreator = (key) => (dispatch, getState) => {
const { tabs, activeKey } = getSelfState(getState());
const newTabs = tabs.filter(tab => tab.key !== key);
if (activeKey === key) {
let index = tabs.findIndex(tab => tab.key === key);
(newTabs.length === index) && (index--);
dispatch(action.assign({tabs: newTabs, [activeKey]: undefined, activeKey: newTabs[index].key}));
} else{
dispatch(action.assign({tabs: newTabs, [key]: undefined}));
}
};
const mapStateToProps = (state) => getSelfState(state);
const actionCreators = {
onInit: initActionCreator,
onTabChange: tabChangeActionCreator,
onTabClose: tabCloseActionCreator
};
const UIComponent = EnhanceLoading(createCommonTabPage(OrderPageContainer, EditPageContainer));
const Container = connect(mapStateToProps, actionCreators)(UIComponent);
export default Container;
export {jumpToChange};
|
describe('P.views.workouts.schedule.Selected', function() {
var View = P.views.workouts.schedule.Selected,
Model = P.models.workouts.Session;
describe('del', function() {
it('emits an "unselect" event with the date', function(done) {
var model = new Model({
date: '2014-01-01'
}),
view = new View({
model: model
});
view.$el.on('unselect', function(event, date) {
expect(date).toBe('2014-01-01');
done();
});
view.del();
});
});
describe('schedule', function() {
beforeEach(function() {
this.view = new View({
model: new Model()
});
var promise = new Promise(function() {
this.resolve = arguments[0];
this.reject = arguments[1];
}.bind(this));
spyOn(this.view.model, 'pSave').and.returnValue(promise);
});
it('must not attempt to save twice', function() {
this.view.schedule();
this.view.schedule();
expect(this.view.model.pSave.calls.count()).toBe(1);
});
describe('saved', function() {
it('sets the $state to "done"', function(done) {
var fn = this.view.onSchedule,
view = this.view;
spyOn(this.view, 'onSchedule').and.callFake(function() {
fn.apply(this, arguments);
expect(view.$state).toBe('done');
done();
});
this.view.schedule();
this.resolve();
});
});
describe('save failed', function() {
it('sets the $state to "failed"', function(done) {
var fn = this.view.onScheduleFail,
view = this.view;
spyOn(this.view, 'onScheduleFail').and.callFake(function() {
fn.apply(this, arguments);
expect(view.$state).toBe('failed');
done();
});
this.view.schedule();
this.reject({});
});
});
});
});
|
var Trie = require("../trie-ing");
var readline = require('readline');
var fs = require('fs');
var input = require("./sample/sample"); // input file is mandatory
try {
var output = require("./sample/sample_trie");
} catch (e){
var output = undefined;
}
// Decide on building a trie from the data or loading it from already built trie data structure form file
if ((!output || !output.root) || process.argv[2]) {
const start = new Date();
var trie = new Trie({maxWidth: 50});
input.forEach(item => {
item.value.name.split("_").forEach(key => {
trie.add({
key: key,
value: {name: item.value.name},
score: item.score
});
})
});
// write the built trie to a file
fs.writeFile('./sample/sample_trie.js', `const output = ${JSON.stringify(trie)}; module.exports = output;`, function (err) {
if (err) throw err;
});
const end = new Date();
console.log(`From Scratch, Time Taken: ${end - start}ms`);
} else {
const start = new Date();
var trie = new Trie(output);
const end = new Date();
console.log(`From Built Trie, Time Taken: ${end - start}ms`);
}
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('Enter Prefix> ');
rl.prompt();
rl.on('line', function(line) {
if (line === "exit") rl.close();
console.log(trie.prefixSearch(line, {limit: 10, unique: true})); // limit has to made 10
rl.prompt();
}).on('close',function(){
process.exit(0);
});
|
import { createSelector } from "reselect";
const selectFeed = state => state.feed;
export const selectFeedPost = createSelector([selectFeed], feed => feed.posts);
export const selectFeedIsLike = createSelector(
[selectFeed],
feed => feed.isLike
);
|
require('dotenv').config();
var request = require('request');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var ShortUID = require('short-uid');
var uid = new ShortUID();
var metafetch = require('metafetch');
var ejs = require('ejs');
var _ = require('lodash');
var fs = require('fs');
var metaItemString = fs.readFileSync('./views/metaItem.ejs', 'utf-8');
var knex_config = require('./knexfile');
var knex = require('knex')(knex_config[process.env.NODE_ENV]);
var bookshelf = require('bookshelf')(knex);
var TinyURL = bookshelf.Model.extend({
tableName: process.env.DB_TABLE
});
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({
extended: true
}) );
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/i/:i', function(req, res) {
request.get(req.param('i'), function(e,r,b){
if (e) {
res.status(404).send('Image Not Found');
return;
}
if (r) res.status(r.statusCode).send(b);
});
});
app.get('/', function (req, res) {
TinyURL.query(function(qb){
qb.orderBy('created_at','ASC');
}).fetchAll().then(function(urls){
var url_list = urls.toJSON();
var meta_list = _.map(url_list, function(url){
return _.assign({tiny_url: tinify(url.id), destination_url: url.destination_url, view_count: url.view_count}, url.meta_json);
});
res.render('index', {
title: 'Jean.ml Tiny URL',
meta_list: meta_list.reverse(),
access_token: uid.randomUUID(8)
});
});
});
app.post('/create', function (req, res) {
if (!(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,8}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/).test(req.body.url)) {
res.status(500).send(_.sample(nope));
return;
}
if (req.body.access_token !== process.env.KEY) {
res.status(500).send(_.sample(nope));
return;
}
metafetch.fetch(req.body.url, {
flags: {
images: false,
links: false
},
http: {
timeout: 30000
}
}, function (err, meta) {
new TinyURL().save({
id: uid.randomUUID(6),
destination_url: req.body.url,
meta_json: JSON.stringify(meta)
},
{
method: 'insert'
}).then(function(url) {
var id = url.get('id');
var destination_url = url.get('destination_url');
var meta_json = url.get('meta_json');
var view_count = url.get('view_count');
meta_json = _.assign({tiny_url: tinify(id), destination_url: destination_url, view_count: view_count}, JSON.parse(meta_json));
var result = {meta_item: ejs.render(metaItemString, {meta_json: meta_json})};
res.status(200).send(result);
}).catch(function(err){
console.log(err);
res.status(500).send(_.sample(nope));
});
});
});
app.get('/:id', function (req, res) {
if (req.params.id && req.params.id !== 'favicon.ico'){
new TinyURL({'id': req.params.id})
.fetch()
.then(function(url) {
var view_count = url.get('view_count');
var destination_url = url.get('destination_url');
url.set('view_count', view_count + 1);
url.save().then(function(u) {
res.redirect(302, destination_url);
});
}).catch(function(err){
console.log(err);
res.status(500).send('Error fetching destination url...');
});
}
});
app.listen(process.env.SERVER_PORT, function () {
console.log('Server listening on port '+ process.env.SERVER_PORT +'!');
});
function tinify(id) {
return 'https://jean.ml/' + id;
}
var nope = [
'just, no',
'not gonna happen',
'ha!... no',
'there\'s a greater chance of a roll of sushi randomly popping into existance',
'negative',
'you\'re kidding, right?',
'"never" is a bit excessive, so I\'ll just say "no"',
'I cannot oblige',
'goo.gl might work for what you need',
'"no" means "definitely not"',
'well, this is uncomfortable...',
'nyet',
'inconceivable',
'this is not... wait for it... gonna happen',
'simply no',
'talk to the hand'
];
|
var CallidForm;
var pageSize = 25;
/**********************************************************************站臺管理主頁面**************************************************************************************/
//料位管理Model
Ext.define('gigade.Ilocs', {
extend: 'Ext.data.Model',
fields: [
{ name: "boiler_type", type: "string" },
{ name: "boiler_describe", type: "string" },
{ name: "inner_boiler_number", type: "string" },
{ name: "out_boiler_number", type: "string" },
{ name: "user_username", type: "string" },
{ name: "add_time", type: "string" },
{ name: "boiler_remark",type:"string" }
]
});
var BoilerRelation = Ext.create('Ext.data.Store', {
autoDestroy: true,
pageSize: pageSize,
model: 'gigade.Ilocs',
proxy: {
type: 'ajax',
url: '/BoilerRelation/GetBoilerRelationList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
// autoLoad: true
});
BoilerRelation.on('beforeload', function () {
Ext.apply(BoilerRelation.proxy.extraParams, {
out_boiler_type: Ext.getCmp("out_boiler_type").getValue(),
innner_boiler_type: Ext.getCmp('innner_boiler_type').getValue(),
boiler_type_describe: Ext.getCmp('boiler_type_describe').getValue()
});
});
//var sm = Ext.create('Ext.selection.CheckboxModel', {
// listeners: {
// selectionchange: function (sm, selections) {
// Ext.getCmp("gdBoilerRelation").down('#edit').setDisabled(selections.length == 0);
// Ext.getCmp("gdBoilerRelation").down('#delete').setDisabled(selections.length == 0);
// }
// }
//});
Ext.onReady(function () {
var gdBoilerRelation = Ext.create('Ext.grid.Panel', {
id: 'gdBoilerRelation',
store: BoilerRelation,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: "外鍋型號", dataIndex: 'out_boiler_number', width: 222, align: 'center' },
{ header: "內鍋型號", dataIndex: 'inner_boiler_number', width: 222, align: 'center' },
{ header: "安康內鍋型號", dataIndex: 'boiler_type', width: 222, align: 'center' },
{ header: "安康內鍋型號信息", dataIndex: 'boiler_describe', width: 222, align: 'center' },
{ header: "備註", dataIndex: 'boiler_remark', width: 222, align: 'center' },
{ header: "添加人", dataIndex: 'user_username', width: 100, align: 'center' },
{ header: "添加時間", dataIndex: 'add_time', width: 222, align: 'center' }
],
tbar: [
],
dockedItems: [
{ //類似于tbar
xtype: 'toolbar',
dock: 'top',
items: [
'->',
{ xtype: 'textfield', allowBlank: true, fieldLabel: "外鍋型號", id: 'out_boiler_type', name: 'out_boiler_type', labelWidth: 60 },
{ xtype: 'textfield', allowBlank: true, fieldLabel: "內鍋型號", id: 'innner_boiler_type', name: 'innner_boiler_type', labelWidth: 60 },
{ xtype: 'textfield', allowBlank: true, fieldLabel: "對應安康內鍋型號", id: 'boiler_type_describe', name: 'boiler_type_describe', labelWidth: 110 },
{
xtype: 'button',
text: "查詢",
iconCls: 'icon-search',
id: 'btnQuery',
handler: Query
},
{
xtype: 'button',
text: "重置",
id: 'btn_reset',
listeners: {
click: function () {
Ext.getCmp("out_boiler_type").setValue("");
Ext.getCmp('innner_boiler_type').setValue("");
Ext.getCmp('boiler_type_describe').setValue("")
}
}
}
]
}],
bbar: Ext.create('Ext.PagingToolbar', {
store: BoilerRelation,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
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: [gdBoilerRelation],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
gdBoilerRelation.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
BoilerRelation.load({ params: { start: 0, limit: 25 } });
});
function Query(x) {
BoilerRelation.removeAll();
Ext.getCmp("gdBoilerRelation").store.loadPage(1, {
params: {
out_boiler_type:Ext.getCmp("out_boiler_type").getValue(),
innner_boiler_type: Ext.getCmp('innner_boiler_type').getValue(),
boiler_type_describe: Ext.getCmp('boiler_type_describe').getValue()
}
});
}
/*************************************************************************************新增*************************************************************************************************/
onAddClick = function () {
//addWin.show();
editFunction(null, BoilerRelation);
}
/*************************************************************************************編輯*************************************************************************************************/
onEditClick = function () {
var row = Ext.getCmp("gdBoilerRelation").getSelectionModel().getSelection();
//alert(row[0]);
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
} else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1) {
editFunction(row[0], BoilerRelation);
}
}
|
elements = document.querySelectorAll(’.mimg’)
var urls = [];
for (var i = 0; i < elements.length; i++) {
var url = elements[i].getAttribute(‘src’)
if (url&&url.includes(‘https’)) {
urls.push(url);
}
}
window.open(‘data:text/csv;charset=utf-8,’ + escape(urls.join(’\n’)));
|
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
var apiRouterV1 = express.Router();
app.use('/',apiRouterV1);
var productInventoryApiV1 = express.Router();
apiRouterV1.use('/products_inventory',productInventoryApiV1);
var ProductInventoryController = require('./controllers/productInventory');
var pic = new ProductInventoryController(apiRouterV1);
app.listen(port, () => {
console.log('We are live on ' + port);
});
|
import React, {Component} from "react";
import {ENDPOINT_UPDATE_PASSWORD, makeAPIRequest} from "../../app/services/apiService";
import {simpleAlert} from "../../app/services/alertService";
import {Body, Container, Content, Footer, FooterTab, Header, Title, Text, Button, Input} from "native-base";
export default class ChangePassword extends Component {
constructor(props) {
super(props);
this.state = {
mail: "",
password: "",
confirmpass: ""
};
}
submit() {
this.submitInfo();
}
submitInfo() {
const {mail, password, confirmpass} = this.state;
if (!mail || !password || !confirmpass) {
simpleAlert("Error", "You need to fill all fields", "OK");
return;
}
const body = JSON.stringify({
mail: mail,
password: password,
confirmpass: password
});
makeAPIRequest(ENDPOINT_UPDATE_PASSWORD, body)
.then((responseJSON) => {
if (responseJSON["opcode"] === 200) {
simpleAlert("Success", "Check your emails to change your password.", "OK");
} else {
simpleAlert("Password change error", responseJSON.message, "Try again");
}
}).catch((error) => {
console.error(error);
});
}
render() {
const {mail, password, confirmpass} = this.state;
return (
<Container>
<Header>
<Body>
<Title>Reset password</Title>
</Body>
</Header>
<Content>
<Input
value={mail}
onChangeText={mail => this.setState({mail})}
placeholder="mail"
returnKeyType="next"
/>
<Input
value={password}
onChangeText={password => this.setState({password})}
placeholder="current password"
returnKeyType="next"
secureTextEntry
/>
<Input
value={confirmpass}
onChangeText={confirmpass => this.setState({confirmpass})}
placeholder="confirm current password"
returnKeyType="next"
secureTextEntry
/>
</Content>
<Footer>
<FooterTab>
<Button onPress={this.submit.bind(this)} full>
<Text>Save</Text>
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
|
class Formatter {
static capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
static sanitize(string) {
return string.replace(/[^'0-9a-z- ]/gi, '')
}
static titleize(string) {
let result = [];
let ignoreWords = ["the", "a", "an", "but", "of", "and", "for", "at", "by", "from"]
string.split(" ").forEach(function(w) {
let noBueno = 0;
ignoreWords.forEach(function(iw) {
if (iw === w)
{ noBueno = 1 }
})
if (noBueno == 1) {result.push(w)}
else {result.push(Formatter.capitalize(w))}
});
return Formatter.capitalize(result.join(" "));
}
}
|
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import MovieCard from '../components/MovieCard';
import { MemoryRouter } from 'react-router-dom';
import userEvent from '@testing-library/user-event';
import {
_notOnWatchListMovie,
_onWatchListMovie,
} from './mockData/movieCardMockData';
describe('MovieCard Component', () => {
it('should render correctly', () => {
render(
<MovieCard
movies={_notOnWatchListMovie}
addToWatchList={jest.fn()}
removeFromWatchList={jest.fn()}
/>,
{ wrapper: MemoryRouter }
);
const movieTitle = screen.getByText(/Inside out/i);
const movieReleaseDate = screen.getByText(/Jun 24, 2018/i);
const moviePosters = screen.getAllByRole(/img/i);
expect(movieTitle).toBeInTheDocument();
expect(movieReleaseDate).toBeInTheDocument();
expect(moviePosters).toHaveLength(3);
});
it('should call addToWatchList function with correct id', () => {
const mockAddToWatchList = jest.fn();
render(
<MovieCard
movies={_notOnWatchListMovie}
addToWatchList={mockAddToWatchList}
removeFromWatchList={jest.fn()}
/>,
{ wrapper: MemoryRouter }
);
const moviePosters = screen.getAllByRole(/img/i);
userEvent.click(moviePosters[1]);
expect(mockAddToWatchList).toBeCalledWith(1);
});
it('should cal removeFromWatchList function with correct id', () => {
const mockRemoveFromWatchList = jest.fn();
render(
<MovieCard
movies={_onWatchListMovie}
addToWatchList={jest.fn()}
removeFromWatchList={mockRemoveFromWatchList}
/>,
{ wrapper: MemoryRouter }
);
const moviePosters = screen.getAllByRole(/img/i);
userEvent.click(moviePosters[1]);
expect(mockRemoveFromWatchList).toBeCalledWith(1);
});
});
|
Ext.define('eapp.model.Activity',
{
extend:'Ext.data.Model',
config:
{
fields:
[
'activityid',
'userid',
'groupid',
'activityName',
'activityDateStart',
'activityContent',
'activityDateEnd',
'activityState',
'reson'
]
}
});
|
function sayThanks(name) {
console.log('Thank you for your purchase '+ name + '! We appreciate your business.');
}
sayThanks('Cole');
// this allows Cole to be used in the thank you statement on the recipt.
//so it will diplay "Thank you for your purchase Cole! We appreciate your business."
|
/**
* Global configuration
*/
import { YellowBox } from 'react-native'
global.log = () => { }
global.error = () => { }
global.logImportant = () => { }
// Disable yellow box specific case by case
YellowBox.ignoreWarnings([
'Remote debugger is in a background tab which may cause apps to perform slowly. Fix this by foregrounding the tab (or opening it in a separate window).',
'Warning: componentWillUpdate is deprecated and will be removed in the next major version. Use componentDidUpdate instead. As a temporary workaround, you can rename to UNSAFE_componentWillUpdate.',
'Warning: componentWillReceiveProps is deprecated and will be removed in the next major version. Use static getDerivedStateFromProps instead.',
'Warning: componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.',
'Warning: componentWillReceiveProps has been renamed, and is not recommended for use',
'Warning: componentWillMount has been renamed, and is not recommended for use',
'Module RCTImageLoader requires main queue setup since it overrides `init` but doesn\'t implement `requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.',
"Module RNFetchBlob requires main queue setup since it overrides `constantsToExport` but doesn't implement `requiresMainQueueSetup`. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.",
'Warning: isMounted(...) is deprecated', 'Module RCTImageLoader'
])
|
'use strict';
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rimraf = require('gulp-rimraf');
var removeUseStrict = require('gulp-remove-use-strict');
var concat = require('gulp-concat');
var notify = require('gulp-notify');
var ngHtml2Js = require('gulp-ng-html2js');
var minifyHtml = require('gulp-minify-html');
var nodemon = require('gulp-nodemon');
gulp.task('clean', function(cb) {
gulp.src('src/public/_Talknotes/*', {
read: false
})
.pipe(rimraf({
force: true
}));
cb();
});
gulp.task('mergeScripts', function(cb) {
gulp.src('src/public/features/**/*.js')
.pipe(removeUseStrict({
force: true
}))
.pipe(concat('features.js'))
.pipe(uglify())
.pipe(gulp.dest('src/public/_Talknotes'));
cb();
});
gulp.task('mergePartials', function(cb) {
gulp.src('src/public/features/**/*.html')
.pipe(minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe(ngHtml2Js({
moduleName: 'Partials',
prefix: '/partials'
}))
.pipe(concat('partials.js'))
.pipe(uglify())
.pipe(gulp.dest('src/public/_Talknotes'));
cb();
});
gulp.task('build', ['clean'], function() {
return gulp.start('mergeScripts', 'mergePartials');
});
gulp.task('serve', ['build'], function() {
return nodemon({
script: 'src/server/server.js',
watch: ['src/']
});
});
|
"use strict";
const insurances = require("../models/insurances.model");
exports.findAll = function (req, res) {
insurances.findAll(function (err, insurances) {
console.log("controller");
if (err) res.send(err);
console.log("res", insurances);
res.send(insurances);
});
};
exports.create = function (req, res) {
const new_insurances = new insurances(req.body);
//handles null error
if (req.body.constructor === Object && Object.keys(req.body).length === 0) {
res.status(400).send({ error: true, message: "Tolong lengkapi datanya!" });
} else {
insurances.create(new_insurances, function (err, insurances) {
if (err) {
res.send(err);
res.json({
error: false,
message: "insurances sukses di tambahkan!",
data: insurances,
});
} else {
res.json({ success: true });
}
});
}
};
exports.findById = function (req, res) {
insurances.findById(req.params.id, function (err, insurances) {
if (err) res.send(err);
res.json(insurances);
});
};
exports.update = function (req, res) {
if (req.body.constructor === Object && Object.keys(req.body).length === 0) {
res.status(400).send({ error: true, message: "Tolong lengkapi datanya!" });
} else {
console.log(req.body);
console.log(req.params.id);
insurances.update(
req.params.id,
new insurances(req.body),
function (err, insurances) {
if (err) {
res.send(err);
res.json({ error: false, message: "insurances sukses di update" });
} else {
res.json({ success: true });
}
}
);
}
};
exports.delete = function (req, res) {
insurances.delete(req.params.id, function (err, insurances) {
if (err) {
res.send(err);
res.json({ error: false, message: "insurances sukses di hapus" });
} else {
res.json({ success: true });
}
});
};
|
import { logger } from '../utils/logger';
export const renderTestPage = () => {
logger.info('Rendering test page');
return 'Welcome to the Mic.ro test page :)';
};
|
import React from 'react';
import { StyleSheet, View,Image, ImageBackground,TouchableOpacity,Alert,Platform,ScrollView } from 'react-native';
import { Container ,Header, StyleProvider,Title, Form,Left,Right,Icon,Thumbnail ,Item, Input, Label,Content,List,CheckBox,Body,ListItem,Text,Button} from 'native-base';
import AsyncStorage from '@react-native-community/async-storage';
import * as COLOR_CONSTS from '../constants/color-consts';
import * as ROUTE_CONSTS from '../constants/route-consts';
import * as APP_CONSTS from '../constants/app-consts';
import * as API_CONSTS from '../constants/api-constants';
import getTheme from '../../native-base-theme/components';
import material from '../../native-base-theme/variables/platform';
import SubmitButton from '../components/submitButton';
import Loader from '../components/loader';
import {AppEventEmitter, AppEvent} from '../components/appEventEmitter';
export default class AddNewCourse extends React.Component {
constructor(props){
super(props);
this.state = {
loading:false,
courseName:"",
error: false,
remember: false,
institute: this.props.navigation.state.params.institute
}
this.addCourse = this.addCourse.bind(this)
this.closeButtonTapped = this.closeButtonTapped.bind(this)
}
componentDidMount(){
}
closeButtonTapped(){
this.props.navigation.goBack()
}
addCourse(){
if(this.state.courseName == "")
{
alert("Course name is required")
}
else{
this.addCourseApi()
}
}
addCourseApi(){
this.setState({
loading: true
})
var self = this;
let url = API_CONSTS.API_BASE_URL+API_CONSTS.ADD_OWN_COURSE;
// alert(url)
fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': global.token,
},
body: JSON.stringify({
title : this.state.courseName,
}),
}).then((response) => response.json())
.then((responseJson) => {
// console.log(responseJson.body)
this.setState({
loading: false
})
if(responseJson.code == 200){
this.setState({
courseName: ""
})
AsyncStorage.setItem(APP_CONSTS.COURSEADDEDNEW, "true");
AppEventEmitter.emit(AppEvent.RefreshDashBoardScreenCourses)
this.props.navigation.navigate(ROUTE_CONSTS.DASHBOARD_PAGE,{user: "",isNew: true})
}else{
alert(JSON.stringify(responseJson.message))
}
})
.catch((error) => {
this.setState({
loading: false
})
console.error(error);
});
}
// verifyUsername(){
// console.log(this.state.email)
// var self = this;
// let url = API_CONSTS.API_BASE_URL+API_CONSTS.API_VERIFY_USERNAME;
// // alert(url)
// fetch(url, {
// method: 'POST',
// headers: {
// Accept: 'application/json',
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({
// userName: this.state.email
// }),
// }).then((response) => response.json())
// .then((responseJson) => {
// console.log(JSON.stringify(responseJson))
// if(responseJson.code == 200){
// this.setState({
// errorUsername:false
// })
// }else{
// // alert(JSON.stringify(responseJson.message))
// this.setState({
// errorUsername:true
// })
// }
// })
// .catch((error) => {
// console.error(error);
// });
// }
render() {
return (
<StyleProvider style={getTheme(material)}>
<Container style={styles.container}>
<Loader
loading={this.state.loading} />
<Header style={styles.headerStyle}>
<Left>
<TouchableOpacity onPress={this.closeButtonTapped} >
<Image source={require('../../assets/bck.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} />
</TouchableOpacity>
</Left>
<Body style={{flex:3}}>
<Title style={styles.title}>Add Course</Title>
{/* <Image source={require('../../assets/logoLogin.png')} style={{ width: 80, height: 50, resizeMode: 'contain' }} /> */}
</Body>
<Right>
{/* <View style={{ padding: 10, marginTop: 1, alignItems: "flex-start" }}>
<TouchableOpacity onPress={this.closeButtonTapped}>
<Image source={require('../../assets/cart.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} />
</TouchableOpacity>
</View> */}
</Right>
</Header>
<Content>
<View style={{flex:1,marginLeft:20,marginRight:20,marginTop:30,height:APP_CONSTS.SCREEN_HEIGHT}} >
<View style={{flex:1}}>
<ListItem avatar noBorder style={{marginTop:10}}>
<Left>
<Thumbnail source={{uri: (this.state.institute !== undefined) ? this.state.institute.image : ''}} style={{width:40,height:40}} resizeMode={'center'} />
</Left>
<Body style={{justifyContent:'center',marginTop:10}}>
<Text style={{fontWeight:'500',fontSize:20}}>{this.state.institute !== undefined ? this.state.institute.title : ''}</Text>
</Body>
<Right style={{justifyContent:'center',marginRight:10,marginTop:12}}>
</Right>
</ListItem>
<View style={{marginTop:30}}>
<Form>
{this.state.errorUsername == false ? <Item floatingLabel style={{marginLeft:5}} success>
<Label>Type course name</Label>
<Input autoCapitalize="words" keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}}
onChangeText={(courseName) => {
this.setState({courseName:courseName})
}} value={this.state.courseName}/>
<Icon name='checkmark-circle' />
</Item> : this.state.errorUsername == true ?
<Item floatingLabel style={{marginLeft:5}} error>
<Label>Type course name</Label>
<Input autoCapitalize="words" keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}}
onChangeText={(courseName) => {
this.setState({courseName:courseName})
}} value={this.state.courseName}/>
<Icon name='close-circle' />
</Item> :
<Item floatingLabel style={{marginLeft:5}} >
<Label>Type course name</Label>
<Input autoCapitalize="words" keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}}
onChangeText={(courseName) => {
this.setState({courseName:courseName})
}} value={this.state.courseName}/>
</Item>
}
</Form>
</View>
<View style={{alignItems:"center",marginTop:50}}>
{/* <SubmitButton title="Log in" buttonTapAction={this.login}/> */}
<TouchableOpacity style={styles.button} onPress={this.addCourse}>
<Text style={styles.buttonText} >Add Course</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.signUp} style={{marginTop:3}}>
</TouchableOpacity>
</View>
</View>
</View>
</Content>
</Container>
</StyleProvider>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor:COLOR_CONSTS.APP_OFF_WHITE_COLOR,
},
headerStyle:{
backgroundColor:COLOR_CONSTS.APP_BLACK_COLOR
},
title:{
color:COLOR_CONSTS.APP_WHITE_COLOR,
fontSize: 16,
fontWeight:'bold'
},
button: {
width:APP_CONSTS.SCREEN_WIDTH - 60,
backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,
borderRadius: 25,
marginVertical: 10,
paddingVertical: 7,
height: 50,
justifyContent:'center'
},
buttonText: {
fontSize:20,
fontWeight:'500',
color:'#fff',
textAlign:'center',
}
});
|
import React from 'react'
import UserProfile from 'components/user/UserProfile'
export default class Profile extends React.Component {
render () {
return (
<UserProfile {...this.props}/>
)
}
}
|
var fields = {
identity:'身份',
name:'姓名',
account:'帳號',
email:'E-mail',
dorm:'宿舍',
room:'房號',
MAC:'MAC 卡號',
phone:'電話',
IP:'IP'
};
var display_fields = [ 'name','account','dorm','room','IP' ];
app.controller( 'UserListController',['$scope', '$http', function($scope,$http){
$scope.gridOptions = {
enableGridMenu: true
};
$http.get('/data/userData.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
}]);
/*
app.controller( 'UserListController', function(DTOptionsBuilder, DTColumnBuilder){
this.dtOptions = DTOptionsBuilder.fromSource('userData.json')
.withPaginationType('full_numbers');
this.dtColumns = [];
for (var field in display_fields) {
this.dtColumns.push(
DTColumnBuilder.newColumn(field).withTitle(fields[field])
);
};
});
*/
|
import React from 'react'
import { Link } from 'react-router-dom'
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { connect } from "react-redux"
import { updateUser } from '../store/utilities/user'
class Header extends React.Component {
render() {
return <AppBar style={{ flexGrow: 1, }} position="static">
<Toolbar>
<Typography style={{ flexGrow: 1, }} variant="h5" >
{this.props.title}
</Typography>
<Typography style={{ flexGrow: 1, }} variant="h6" >
<Link style={{ color: 'white', textDecoration: 'none' }} to="/portfolio">Portfolio</Link>
</Typography>
<Typography style={{ flexGrow: 1, }} variant="h6" >
<Link style={{ color: 'white', textDecoration: 'none' }} to="/transactions">Transactions</Link>
</Typography>
<Typography style={{ flexGrow: 1, }} variant="h6" >
<Link style={{ color: 'white', textDecoration: 'none' }} to="/">Log Out</Link>
</Typography>
</Toolbar>
</AppBar>
}
}
const mapDispatch = (dispatch) => {
return {
logoutUser : (payload) => dispatch(updateUser(payload))
}
}
export default connect(null, mapDispatch)(Header);
|
import React, { Component } from 'react'
class Carousel extends Component {
state = {
click: 1
}
handleChangeUp = (e) => {
if (this.state.click === 4) {
this.setState({click: 1})
} else {
this.setState({click:this.state.click+1})
}
}
handleChangeDown = (e) => {
if (this.state.click === 1) {
this.setState({click: 4})
} else {
this.setState({click:this.state.click-1})
}
}
render() {
return (
<div className="Carousel">
<button onClick={this.handleChangeDown}>Left</button>
{
this.state.click === 1 ?
<img alt="carousel" src="https://randomuser.me/api/portraits/women/2.jpg" height="100px" />
:
this.state.click === 2?
<img alt="carousel" src="https://randomuser.me/api/portraits/men/2.jpg" height="100px" />
:
this.state.click === 3 ?
<img alt="carousel" src="https://randomuser.me/api/portraits/women/1.jpg" height="100px" />
:
<img alt="carousel" src="https://randomuser.me/api/portraits/men/1.jpg" height="100px" />
}
<button onClick={this.handleChangeUp}>Right</button>
</div>
)
}
}
export default Carousel;
|
import { List, Spin, Form, Input, Button, Row, Col, message } from "antd";
import Avatar from "antd/lib/avatar/avatar";
import axios from "axios";
import { useEffect, useState } from "react";
const ApiCallDemo = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const submitData = async (data) => {
setLoading(true);
try {
await axios({
method: "post",
url: "https://jsonplaceholder.typicode.com/users",
data: data,
});
message.success("Data successfully saved");
} catch (error) {
console.log(error);
message.error("Failed to save data");
} finally {
setLoading(false);
}
};
const getUsersApi = () => {
setLoading(true);
axios.get("https://jsonplaceholder.typicode.com/users").then(
(response) => {
console.log(response.data);
setLoading(false);
setData(response.data);
},
(error) => {
console.log(error);
setLoading(false);
}
);
};
useEffect(() => {
getUsersApi();
}, []);
const layout = {
labelCol: {
span: 4,
},
wrapperCol: {
span: 16,
},
};
const onFinishForm = (values) => {
submitData(values);
};
const renderDemo = () => {
return (
<Row>
<Col span={12}>
<>
<h3>Data Users Fetch</h3>
<List
itemLayout="horizontal"
dataSource={data}
renderItem={(user) => (
<List.Item>
<List.Item.Meta
avatar={
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
}
title={<a href="https://ant.design">{user.name}</a>}
description={user.email}
>
{user.address.street}
</List.Item.Meta>
</List.Item>
)}
/>
</>
</Col>
<Col span={12}>
<h3>Data Users Post</h3>
<Form
{...layout}
onFinish={onFinishForm}
name="nest-messages" /*onFinish={onFinish} validateMessages={validateMessages}*/
>
<Form.Item
name={["name"]}
label="Name"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name={["username"]}
label="Username"
rules={[
{
required: "Username is required",
},
]}
>
<Input />
</Form.Item>
<Form.Item
name={["email"]}
label="Email"
rules={[
{
type: "email",
required: "Email is required",
},
]}
>
<Input />
</Form.Item>
<Form.Item name={["address", "street"]} label="Street">
<Input />
</Form.Item>
<Form.Item name={["address", "city"]} label="City">
<Input />
</Form.Item>
<Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 4 }}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</Col>
</Row>
);
};
if (loading === true) {
return <Spin tip="Loading...">{renderDemo()}</Spin>;
}
return renderDemo();
};
export default ApiCallDemo;
|
/**
* tools: casperjs/phantomjs
*
* This test navigates to various payment pages
* and tests that they display correctly
*
* Run command:
* casperjs test test_payment_pages.js
*
* @author J.Stone
*/
var login = 'https://voxy.com/u/login/';
var logout = 'https://voxy.com/u/logout/';
var payment_pages = [
"https://voxy.com/payment/voxytrial_7_12_120USD_24/?templateId=personalize-3box",
"https://voxy.com/payment/voxytrial_7_12_0_12/?templateId=personalize-3box",
"https://voxy.com/payment/voxytrial_7_12_0_52/?templateId=personalize-3box",
"https://voxy.com/payment/VoxyPremium_12_0_12_notrial/?templateId=inapp-valentines",
"https://voxy.com/payment/VoxyPremium_12_168USD_24_notrial/?templateId=inapp-valentines-premium",
"https://voxy.com/payment/VoxyPremium_12_0_12_notrial/?templateId=inapp-valentines",
"https://voxy.com/payment/VoxyPremium_12_0_52_notrial/?templateId=inapp-valentines",
"https://voxy.com/payment/VoxyPremium_3_0_8_notrial/?templateId=inapp-3-month-courses",
"https://voxy.com/payment/VoxyPremium_3_30USD_16_notrial/?templateId=inapp-3-month-courses",
"https://voxy.com/payment/VoxyPremium_3_0_24_notrial/?templateId=inapp-3-month-courses",
"https://voxy.com/payment/voxytrial_7_12_150USD_24/?templateId=inapp-full",
"https://voxy.com/payment/voxytrial_7_12_150USD_52/?templateId=inapp-full",
"https://voxy.com/payment/VoxyPremium_12_0_24_notrial/?templateId=inapp-monthly",
"https://voxy.com/payment/voxytutor_20_37/",
"https://voxy.com/payment/voxytutor_1_0/",
"https://voxy.com/payment/voxytutor_8_25/",
"https://voxy.com/payment/VoxyPremium_12_0_12_notrial/?templateId=inapp-stpattys",
"https://voxy.com/payment/VoxyPremium_12_204USD_48_notrial/?templateId=inapp-stpattys-premium",
"https://voxy.com/payment/VoxyPremium_12_0_52_notrial/?templateId=inapp-stpattys",
"https://voxy.com/compare/guide-stpattys/",
"https://voxy.com/compare/guide/",
"https://voxy.com/compare/credits/"
];
//casperjs setup
var utils = require('utils');
var http = require('http');
var fs = require('fs');
var x = require('casper').selectXPath;
var casper = require('casper').create({
// //verbose: true,
// //ogLevel: 'debug'
});
casper.test.begin("Check for 400 or greater response on ALL payment/compare pages", (payment_pages.length + 2), function(test) {
casper.start(login, function() {
this.fill('form#ajax-login-form', {
'username': 'newu1@voxy.com',
'password': 'things'
}, true);
});
casper.then(function() {
this.wait(1000, function() {
//check for the substring "guide/recommend/" in the url
this.test.assert((this.getCurrentUrl().indexOf("guide/recommend/") != -1), "guide is displayed");
});
});
casper.then(function(response) {
//navigate to the right payment url
for (var i = 0; i < payment_pages.length; i++) {
this.thenOpen(payment_pages[i], function() {
this.echo(this.getCurrentUrl());
this.test.assertHttpStatus(200);
if(response == undefined || response.status >= 400) {
this.test.fail("Page Failed to Load: " + this.echo(this.getCurrentUrl()));
};
});
}
});
casper.thenOpen(logout, function() {
//dump the current session and logout
test.assertUrlMatch(logout, 'logout url is displayed');
});
casper.run(function() {
test.done();
this.exit();
});
});
|
"use strict";
var enzyme_1 = require('enzyme');
var React = require('react');
var index_1 = require('./index');
describe('Form Error Component', function () {
it('should create a form error with its children, classes and id', function () {
var formError = enzyme_1.shallow(<index_1["default"] isVisible>Hello World</index_1["default"]>);
expect(formError.length).toBe(1);
expect(formError.text()).toBe('Hello World');
expect(formError.prop('id')).toBe('');
expect(formError.hasClass('bold black')).toBe(true);
expect(formError.hasClass('hide')).toBe(false);
});
it('should create a hidden form error when isVisible is false', function () {
var formError = enzyme_1.shallow(<index_1["default"] isVisible={false}/>);
expect(formError.hasClass('hide')).toBe(true);
});
it('should create a form error with the given id', function () {
var formError = enzyme_1.shallow(<index_1["default"] isVisible id={'form-error-id'}/>);
expect(formError.prop('id')).toBe('form-error-id');
});
});
|
const fs = require('fs-plus')
const load = (_file) => {
return fs.readFileSync(_file, 'utf8')
}
const save = (_file, _content) => {
fs.writeFileSync(_file, _content)
}
const edit = (_addrsFile, _fun) => {
const content = this.load(_addrsFile)
const newContent = _fun(content)
this.save(_addrsFile, newContent)
}
const loadJson = (_file) => {
return JSON.parse(fs.readFileSync(_file))
}
const saveJson = (_file, _data) => {
fs.writeFileSync(_file, JSON.stringify(_data, undefined, '\t'))
}
const editJson = (_addrsFile, _fun) => {
const json = this.loadJson(_addrsFile)
const newJson = _fun(json)
this.saveJson(_addrsFile, newJson)
}
exports.load = load
exports.save = save
exports.edit = edit
exports.loadJson = loadJson
exports.saveJson = saveJson
exports.editJson = editJson
|
import {ImmutablePropTypes, PropTypes} from 'src/App/helpers'
import {
immutableArchiveFilmsModel,
immutablePageTextModel,
immutableNichesListModel,
pageRequestParamsModel,
immutableTagArchiveListModel,
immutableSortListModel,
immutableTagArchiveListOlderOrNewerModel,
immutableSponsorsListModel,
} from 'src/App/models'
import {immutableVideoItemModel} from 'src/generic/VideoItem/models'
export const
model = process.env.NODE_ENV === 'production' ? null : ImmutablePropTypes.exact({
isLoading: PropTypes.bool,
isLoaded: PropTypes.bool,
isFailed: PropTypes.bool,
tagId: PropTypes.number,
currentPage: PropTypes.string,
lastPageRequestParams: PropTypes.nullable(pageRequestParamsModel),
pageNumber: PropTypes.number,
pageText: PropTypes.nullable(immutablePageTextModel),
pagesCount: PropTypes.number,
sponsorsList: immutableSponsorsListModel,
tagList: immutableNichesListModel,
tagArchiveList: immutableTagArchiveListModel,
sortList: immutableSortListModel,
currentSort: PropTypes.nullable(PropTypes.string),
archiveFilms: PropTypes.nullable(immutableArchiveFilmsModel),
tagArchiveListOlder: immutableTagArchiveListOlderOrNewerModel,
tagArchiveListNewer: immutableTagArchiveListOlderOrNewerModel,
itemsCount: PropTypes.number,
videoList: ImmutablePropTypes.listOf(immutableVideoItemModel),
})
|
$(document).ready(function(){
var sum=0;
psum();
//更新按钮状态
$(".cart_btn").each(function(){
btnchange($(this));
});
$(".cart_btn").click(function(){
var num=$(this).prev().children(".goods_num").val();
num++;
$(this).prev().children(".goods_num").val(num);
var $th=$(this);
btnchange($th);
var package = goods_data($th);
listajax(package);
changecarbox($th);
sidcheck();
car_goods_num();
psum();
});
$(".minus").click(function(){
var num=$(this).siblings(".goods_num").val();
num--;
$(this).siblings(".goods_num").val(num);
var $th=$(this);
btnchange($th);
var package = goods_data($th);
listajax(package);
changecarbox($th);
sidcheck();
car_goods_num();
psum();
});
$(".plus").click(function(){
var num=$(this).siblings(".goods_num").val();
num++;
$(this).siblings(".goods_num").val(num);
var $th=$(this);
btnchange($th);
var package = goods_data($th);
listajax(package);
changecarbox($th);
sidcheck();
car_goods_num();
psum();
});
//只允许数字输入
$(".goods_num").keydown(function(event){
if(!isNumber(event.which)){
return false;}
});
$(".goods_num").keyup(function(){
// count();
var $th=$(this);
btnchange($th);
var package = goods_data($th);
listajax(package);
changecarbox($th);
car_goods_num();
psum();
});
//切换到评论窗口
$('.comment_page').click(function(){
$('.main').addClass('hidden');
$('.comment').removeClass('hidden');
});
$('.goods_page').click(function(){
window.history.go();
});
});
function listdel(obj){
var gid = $(obj).parents(".carbox_list").find("input").val();
if($("#SID").val()==$(".CSID").val()){
var $th=$(".goods_box").each(function(){
var $th = $(this);
var boxid=$th.find(".goods_id").val();
if(boxid==gid){
$th.find(".goods_num").val(0);
btnchange($th.find(".goods_id"));
var package = goods_data($th.find(".goods_id"));
listajax(package);
changecarbox($th.find(".goods_id"));
car_goods_num();
psum();
}
});
}else{
$.ajax({
data:{
gid:gid
},
type:"post",
url:"controller/sidergoodsdel.php"
});
$(obj).parents(".carbox_list").remove();
car_goods_num();
psum();
}
}
function indexlistdel(obj){
var gid = $(obj).parents(".carbox_list").find("input").val();
$.ajax({
data:{
gid:gid
},
type:"post",
url:"controller/sidergoodsdel.php"
});
$(obj).parents(".carbox_list").remove();
car_goods_num();
psum();
}
function isNumber(keyCode) {
// 数字
if (keyCode >= 48 && keyCode <= 57 ) return true;
// 小数字键盘
if (keyCode >= 96 && keyCode <= 105) return true;
// Backspace, del, 左右方向键
if (keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39) return true;
return false;
}
//计算总价格
function psum(){
var psum=0;
$(".list_price").each(function(){
psum= parseFloat($(this).text())+psum;
});
$(".pricesum").html("共计<b>"+psum+"</b>元");
}
//js动态改变购物车物品
function changecarbox($th){
var sid=$("#SID").val();
var goods_num = $th.parents(".goods_box").find('.goods_num').val();
var goods_id = $th.parents(".goods_box").find('.goods_id').val();
var goods_price=parseFloat($th.parents(".goods_box").find('.goods_price').text());
var goods_name = $th.parents(".goods_box").find('.goods_name').text();
if($("#list_id_"+goods_id+" .list_num").length> 0 ){
if(goods_num<=0){
$("#list_id_"+goods_id).remove();
}
$("#list_id_"+goods_id+" .list_num").text(goods_num);
$("#list_id_"+goods_id+" .list_price").text(goods_price*goods_num+"元");
}else{
$(".order_btn").before("<div class='carbox_list' id='list_id_"+goods_id+"'><input class='CSID' type='hidden' value='"+sid+"'><input type='hidden' value='"+goods_id+"'><span class='list_name'>"+goods_name+"</span><span class='list_num'>"+goods_num+"</span><span class='list_price'>"+goods_price*goods_num+"元</span></div>");
}
}
//物品信息数量收集
function goods_data($th){
pa=$th.parents(".goods_box");
var package={
SID:$('#SID').val(),
shopfee:$('#shopfee').val(),
min_price:$('#min_price').val(),
goods_id:pa.find('.goods_id').val(),
goods_name:pa.find('.goods_name').text(),
goods_num:pa.find('.goods_num').val(),
goods_price:parseFloat(pa.find('.goods_price').text())
};
return package;
}
//储存入session
function listajax(package){
$.ajax({
url:"controller/ordersession.php",
type:"get",
data:{
package:JSON.stringify(package)
},
dataType:"json",
success:function(data){
alert("ok");
}
});
}
//物品数量按钮改变
function btnchange($th){
pa=$th.parents(".goods_box");
if(pa.find(".goods_num").val()!=0){
pa.find(".cart_btn").addClass('none');
pa.find(".cart_count").removeClass('none');
}else{
pa.find(".cart_btn").removeClass('none');
pa.find(".cart_count").addClass('none');
}
}
//动态改变红圈数字
function car_goods_num(){
if(!$(".car_goods_num").length&&$(".list_num").length){
$(".carbar-btn").append("<span class='car_goods_num'></span>");
}
var dg = 0;
$(".car_goods_num").animate({
padding:"2px"
},80);
$(".car_goods_num").animate({
padding:"0px"
},80);
$(".list_num").each(function(){
//减0 将字符串变数字
dg =$(this).text()-0+dg;
});
if(dg>0){
$(".car_goods_num").text(dg);
}else{
$(".car_goods_num").remove();
}
}
function sidcheck(){
$(".carbox_list").each(function(){
var th=$(this);
if($("#SID").val()!=th.find(".CSID").val()){
th.remove();
}
});
}
|
/*************************************************************
*
* Copyright (c) 2012-2015 MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (CUSTOM) {
CUSTOM.Augment({
Startup: function () {
// Set up event handling
EVENT = MathJax.Extension.MathEvents.Event;
TOUCH = MathJax.Extension.MathEvents.Touch;
HOVER = MathJax.Extension.MathEvents.Hover;
this.ContextMenu = EVENT.ContextMenu;
this.Mousedown = EVENT.AltContextMenu;
this.Mouseover = HOVER.Mouseover;
this.Mouseout = HOVER.Mouseout;
this.Mousemove = HOVER.Mousemove;
},
preTranslate: function (state) {
var scripts = state.jax[this.id], i, m = scripts.length,
for (i = 0; i < m; i++) {
script = scripts[i]; if (!script.parentNode) continue;
var prev = script.previousSibling;
if (prev && prev.className == "MathJax_Custom") {
prev.parentNode.removeChild(prev);
}
var jax = script.MathJax.elementJax;
var ul = HTML.Element("ul", {
className: "MathJax_Custom",
id: jax.inputID+"-Frame",
isMathJax: true,
jaxID: this.id,
oncontextmenu: EVENT.Menu,
onmousedown: EVENT.Mousedown,
onmouseover: EVENT.Mouseover,
onmouseout: EVENT.Mouseout,
onmousemove: EVENT.Mousemove,
onclick: EVENT.Click,
ondblclick: EVENT.DblClick
});
if (HUB.Browser.noContextMenu) {
span.ontouchstart = TOUCH.start;
span.ontouchend = TOUCH.end;
}
script.parentNode.insertBefore(span, script);
}
},
Translate: function (script, state) {
if (!script.parentNode) return;
var jax = script.MathJax.elementJax;
var ul = document.getElementById(jax.inputID+"-Frame");
for (t in jax.tree) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(t));
ul.appendChild(li);
}
},
postTranslate: function (state) {
// Not implemented
// var scripts = state.jax[this.id];
},
getJaxFromMath: function (math) {
return HUB.getJaxFor(math.nextSibling);
},
Zoom: function (jax, span, math, Mw, Mh) {
// Not implemented
return {Y:0, mW: mW, mH: mH, zW: zW, zH: zH};
},
Remove: function (jax) {
var div = document.getElementById(jax.inputID+"-Frame");
if (div) {
div.parentNode.removeChild(div);
}
}
});
})(MathJax.OutputJax.Custom);
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
{/*Image 组件必须要设置宽高才能显示*/}
<Image
style={[{position:'relative'},styles.backgroundImage]}
source={{uri: 'http://c.hiphotos.baidu.com/baike/pic/item/d009b3de9c82d158b62f49ef890a19d8bc3e423a.jpg'}}>
</Image>
<View style={[{position:'absolute'},styles.overlay]}>
<Text style={styles.overlayHeader}>胡歌</Text>
<Text style={styles.overlaySubHeader}>猎场</Text>
</View>
{/*<HeaderText>jony test</HeaderText>
<Text style={[styles.itemText,{fontStyle:'italic'}]}>
www.<Text style={{fontWeight:'600',textDecorationLine:'line-through'}}>
baidu</Text>.com</Text>
<View style={[styles.item,styles.itemOne]}>
<Text style={styles.itemText}>1</Text>
</View>
<View style={[styles.item,styles.itemTwo]}>
<Text style={styles.itemText}>2</Text>
</View>
<View style={[styles.item,styles.itemThree]}>
<Text style={styles.itemText}>3</Text>
</View>*/}
</View>
);
}
}
//自定义文本组件
class HeaderText extends Component {
render() {
return (
<Text style={styles.itemText}>
{this.props.children}
</Text>
);
}
}
const styles = StyleSheet.create({
overlay:{
backgroundColor:'rgba(0,0,0,0.3)',
alignItems:'center',
justifyContent:'space-around',
width:360,
},
overlayHeader:{
fontSize:33,
fontFamily:'Helvetica Neue',
fontWeight:'300',
color:'#eae7ff',
padding:10,
},
overlaySubHeader:{
fontSize:16,
fontFamily:'Helvetica Neue',
fontWeight:'300',
color:'#eae7ff',
padding:10,
paddingTop:0,
},
backgroundImage: {
flex: 1,
position:'relative',
resizeMode:'cover',//设置图片的缩放模式 包含:contain 拉伸:stretch cover
},
image: {
width: 80,
height: 100,
margin: 6,
},
item: {
backgroundColor: '#fff',
borderWidth: 1,
borderColor: "#6435c9",
margin: 6,
flex: 1
},
itemOne: {
alignSelf: 'flex-start',
},
itemTwo: {},
itemThree: {
alignSelf: 'flex-end',
flex: 2,
},
itemText: {
fontSize: 33,
fontFamily: 'Helvetica Neue',
fontWeight: '200',
color: "#6435c9",
padding: 30,
},
container: {
flex: 1,
backgroundColor: '#eae7ff',
paddingTop: 0,//paddingTop: 2
flexDirection: 'column',//设置主轴方向 row column
justifyContent: "space-around",//符合伸缩盒模型(flex-box) center 居中 flex-start flex-end space-around space-between 定义控件的位置
alignItems: 'stretch',//定义控件的缩放比例 flex-start flex-end center stretch 拉伸(默认)
},
});
|
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import { offlineActionTypes, checkInternetConnection } from 'react-native-offline';
import storage from 'redux-persist/lib/storage';
import reducer from '../reducers';
import middleware from '../middleware';
const persistConfig = {
key: 'root',
storage,
whitelist: ['authReducer', 'notificationReducer'],
};
const persistedReducer = persistReducer(persistConfig, reducer);
export default function configureStore(callback) {
const store = createStore(
persistedReducer,
middleware,
);
persistStore(store, null, () => {
checkInternetConnection().then((isConnected) => {
store.dispatch({
type: offlineActionTypes.CONNECTION_CHANGE,
payload: isConnected,
});
callback();
});
});
if (module.hot) {
module.hot.accept(() => {
const nextRootReducer = require('../reducers').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
|
var api = {
// 获取指定范围随机数方法
getRandom: function (start, end) {
return Math.random() * (end - start) + start
},
// 定义颜色数组
getColorList: ['#2080f7', '#0f0d39', '#c728cb', '#e8a3ea', '#f2d61f', '#622725', '#f40dc4', '#0df4c7'],
// 生成随机id
getRandomId: function () {
var id = ''
for (var i = 0; i < 24; i++) {
if (i === 8 || i === 16 || i === 23) {
id += 'n-c'
}
id += Math.floor(Math.random() * 10).toString(16)
}
return id
},
/*
* 根据两点坐标及半径确定圆弧所在的圆心及两点之间圆弧弧度大小
* @param{ p1, p2 } 两点坐标 { x: '', y: '' }
* @param{ r } 所需要确定圆心的半径
*/
getCenterByRAndPoint: function (p1, p2, r) {
// 当给出两点坐标的纵坐标坐标坐标相同时
if (p1.y === p2.y) {
var discX = Math.abs(p1.x - p2.x)
var centerX = (p1.x + p2.x) / 2
if (r < discX / 2) {
throw new Error('半径r不能小于两点间距离的一半')
}
var interceptY = Math.sqrt(Math.pow(r, 2) - Math.pow(discX / 2, 2)) // 圆心距离两点间连线垂直距离
// 根据余弦定理获取两点间弧度大小
var disCosA = (2 * Math.pow(r, 2) - Math.pow(discX, 2))
var lessRadian = Math.acos(0.5 * disCosA / Math.pow(r, 2))
// 根据图形可求出起始点和水平向右两点间弧度
var startAngel = 90 * Math.PI / 180 - lessRadian / 2
return {
p1: { x: centerX, y: p1.y + interceptY, startAngel: -startAngel, endAngel: -startAngel - lessRadian, drawRadialDirection: true },
p2: { x: centerX, y: p2.y - interceptY, startAngel: startAngel, endAngel: startAngel + lessRadian, drawRadialDirection: false },
lessRadian
}
} else if (p1.x === p2.x) { // 当给出两点坐标的横坐标坐标相同时
var discY = Math.abs(p1.y - p2.y)
var centerY = (p1.y + p2.y) / 2
if (r < discY / 2) {
throw new Error('半径r不能小于两点间距离的一半')
}
var interceptX = Math.sqrt(Math.pow(r, 2) - Math.pow(discY / 2, 2)) // 圆心距离两点间连线垂直距离
// 根据余弦定理获取两点间弧度大小
var disCosA = (2 * Math.pow(r, 2) - Math.pow(discY, 2))
var lessRadian = Math.acos(0.5 * disCosA / Math.pow(r, 2))
return {
p1: { x: p1.x + interceptX, y: centerY, startAngel: lessRadian / 2 - Math.PI, endAngel: - lessRadian / 2 - Math.PI, drawRadialDirection: true },
p2: { x: p2.x - interceptX, y: centerY, startAngel: -lessRadian / 2, endAngel: lessRadian / 2, drawRadialDirection: false },
lessRadian
}
}
// 当两点坐标横坐标和纵坐标均不相等时 计算斜率k
var k = -1 / ((p2.y - p1.y) / (p2.x - p1.x))
var centerPoint = { x: (p1.x + p2.x)/ 2, y: (p1.y + p2.y)/ 2 }
var b = centerPoint.y - centerPoint.x * k
// y = k * x + b 两点之间连线垂线的一次函数表达式
// (x, k * x + b)
// Math.pow(x - p1.x, 2) + Math.pow(k * x + b - p1.y, 2) = Math.pow(r, 2) 圆心到某一点的距离和r相等二次函数表达式求圆心坐标
// A * x^2 + B * x + C = 0
var A = 1 + Math.pow(k, 2)
var B = -2 * p1.x + (b - p1.y) * k * 2
var C = Math.pow(p1.x, 2) + Math.pow(b - p1.y, 2) - Math.pow(r, 2)
var disc = Math.pow(B, 2) - 4 * A * C
if (disc < 0) {
throw new Error('根据提供两点坐标和半径无法绘制出圆弧')
} else {
// 两个点 p1: { x: x1, y: y1 } p2: { x: x2, y: y2 }
var x1 = -1 * (B / (2 * A)) + Math.pow(disc, 0.5) / (-2 * A)
var x2 = -1 * (B / (2 * A)) - Math.pow(disc, 0.5) / (-2 * A)
var y1 = x1 * k + b
var y2 = x2 * k + b
// cosA = (b ^ 2 + c ^ 2 - a ^ 2) / 2 * b * c 根据余弦定理求出两点之间圆弧的弧度
var disCosA = 2 * Math.pow(r, 2) - (Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))
var lessRadian = Math.acos(disCosA / (2 * Math.pow(r, 2)))
// 求出此段弧的起点和重点以水平向右为起点
// 顺时针为正弧,逆时针为负弧
// 取水平原点和x轴数值较大一点的两点弧度为起始弧度
var startAngelFirst = getStartAndEndAngel({ x: x1, y: y1 }, r, p1, p2 )
var endAngelFirst = startAngelFirst > 0 ? startAngelFirst + lessRadian : startAngelFirst - lessRadian
var startAngelSecond = getStartAndEndAngel({ x: x2, y: y2 }, r, p1, p2 )
var endAngelSecond = startAngelSecond > 0 ? startAngelSecond + lessRadian : startAngelSecond - lessRadian
/*
* @param { startAngel } 两点之间圆弧起点弧度 - 只考虑小圆弧
* @param { endAngel } 两点之间圆弧重点弧度
* @param { drawRadialDirection } 两点之间小圆弧绘制时候逆时针还是顺时针, endAngel < 0 - 逆时针 反之顺时针
*/
return {
p1: { x: x1, y: y1, startAngel: startAngelFirst, endAngel: endAngelFirst, drawRadialDirection: endAngelFirst < 0 },
p2: { x: x2, y: y2, startAngel: startAngelSecond, endAngel: endAngelSecond, drawRadialDirection: endAngelSecond < 0 },
lessRadian: lessRadian,
}
}
},
}
/* 根据传入的圆心、半径及两个控制点确定起点和重点弧度 */
function getStartAndEndAngel(radialR, R, p1, p2) {
var horizontalPoint = { x: radialR.x + r, y: radialR.y }
var startPoint = p1.x > p2.x ? p1 : p2
var disCosA = 2 * Math.pow(R, 2) - (Math.pow(startPoint.x - horizontalPoint.x, 2) + Math.pow(startPoint.y - horizontalPoint.y, 2))
var lessRadian = Math.acos(disCosA / (2 * Math.pow(R, 2)))
return startPoint.y < radialR.y ? -lessRadian : lessRadian
}
|
function Navigation(level, extension)
{
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Section1/Index"+GetExtension(extension)+"\">Gynowars</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project2"+GetExtension(extension)+"\">Assault</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project3"+GetExtension(extension)+"\">Mars</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Section4/Index"+GetExtension(extension)+"\">Renley</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Section5/Index"+GetExtension(extension)+"\">Antarrea</a><br><br>");
Response.Write("<a class=\"navlinkB\" href=\""+GetPath(level)+"Section2/Section5/Section1/Index"+GetExtension(extension)+"\">Global</a><br><br>");
Response.Write("<a class=\"navlinkB\" href=\""+GetPath(level)+"Section2/Section5/Section2/Index"+GetExtension(extension)+"\">Grendol</a><br><br>");
Response.Write("<a class=\"navlinkB\" href=\""+GetPath(level)+"Section2/Section5/Section3/Index"+GetExtension(extension)+"\">Utopia</a><br><br>");
Response.Write("<a class=\"navlinkB\" href=\""+GetPath(level)+"Section2/Section5/Section4/Index"+GetExtension(extension)+"\">Elvia</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Section6/Index"+GetExtension(extension)+"\">Editations</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project7"+GetExtension(extension)+"\">Truth</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project8"+GetExtension(extension)+"\">Kingdoms</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project9"+GetExtension(extension)+"\">Terminal World</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project10"+GetExtension(extension)+"\">Monster Office Workplace</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project11"+GetExtension(extension)+"\">Battle Princesses</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project12"+GetExtension(extension)+"\">Sacred Offerings</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project13"+GetExtension(extension)+"\">The Way</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project14"+GetExtension(extension)+"\">Conspiratorium</a><br><br>");
Response.Write("<a class=\"navlinkA\" href=\""+GetPath(level)+"Section2/Project15"+GetExtension(extension)+"\">Conversion</a><br><br>");
}
function Title(input)
{
Response.Write("<title>");
if(input == 0)
{
Response.Write("Antarrea Projects");
}
Response.Write("</title>");
}
function Header(input)
{
Response.Write("<h2>");
if(input == 0)
{
Response.Write("Antarrea Projects");
}
Response.Write("</h2>");
}
function Content(input)
{
Response.Write("<p id=\"idCenterContent\">");
if(input == 0)
{
Response.Write("Global:");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Here are projects based in the Antarrea universe:</br>");
Response.Write("</br>");
Response.Write("Team Tactical: Crash Ball: Tactical board game centered on a battle version of football.</br>");
Response.Write("Wars of Antarrea: Table-top game where two or more armies battle for supremacy.</br>");
Response.Write("Revolutions: Invading Nations: Tactical RPG, 1st story arc.</br>");
Response.Write("Revolutions: Rebellion Against the Fist: Tactical RPG, 2nd story arc.</br>");
Response.Write("Revolutions: Return to Arms: Tactical RPG, 3rd story arc.</br>");
Response.Write("Revoultions: Post Wars: Tactical RPG, 4th story arc.</br>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Grendol:");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Here are projects based in the Grendol universe:</br>");
Response.Write("</br>");
Response.Write("Grendol: Land of the Orcish Empire: Age of Magic: CCG.</br>");
Response.Write("Grendol: Coliseum: Arena: CCG.</br>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Utopia:");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Here are projects based in the Utopia universe:</br>");
Response.Write("</br>");
Response.Write("Avia: Elemental Angels: Adventure game with RPG elements.</br>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Elvia:");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("Here are projects based in the Elvia universe:</br>");
Response.Write("</br>");
Response.Write("Nine Card: Tactical card game.</br>");
}
Response.Write("</p>");
}
function Versions(input)
{
Response.Write("Other versions of this page are here:<br>");
if(input == 0)
{
Response.Write("<a href=\"http://htkb.dyndns.org/Section2/Section5/index.html\">HTML</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org/Section2/Section5/index.php\">PHP</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:81/ASPNET/Section2/Section5/index.aspx\">ASP.NET Javascript</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:81/ASP/Section2/Section5/index.asp\">ASP Javascript</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org/Section2/Section5/index.shtml\">Perl</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:8080/JSPApplication/Section2/Section5/index.jsp\">JSP</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:8080/JSFApplication/Section2/Section5/index.xhtml\">JSF</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:81/WebApplication/Section2/Section5/index.cshtml\">ASP.NET Web App</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:81/WebForm/Section2/Section5/index.aspx\">ASP.NET Webform</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org:81/MVC/Main/Section2/Section5/index\">ASP.NET MVC App</a><br>");
Response.Write("<a href=\"http://htkb.dyndns.org/SSI/Section2/Section5/index.html\">Apache SSI</a><br>");
}
}
|
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const babel = require('gulp-babel');
const gulpIf = require('gulp-if');
const del = require('del');
const isFixedEslint = (file) => {
return file.eslint != null && file.eslint.fixed;
};
gulp.task('clean', () => {
return del('dist/**');
});
gulp.task('eslint', () => {
return gulp.src(['src/js/*.js'])
.pipe(eslint({ fix: true }))
.pipe(eslint.format())
.pipe(gulpIf(isFixedEslint, gulp.dest('src/js')))
.pipe(eslint.failAfterError());
});
gulp.task('build', ['eslint', 'clean'], () => {
return gulp.src(
[
'!src/js/jquery-3.3.1.min.js',
'src/js/*.js'
])
.pipe(babel())
.pipe(gulp.dest('dist/js'));
});
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Model = sequelize.define('Review', {
id: {
field: 'review_id',
type: DataTypes.INTEGER,
primaryKey: true
},
entityId: {
field: 'entity_id',
type: DataTypes.INTEGER,
references: {
model: 'Entity',
key: 'id'
}
},
userId: {
field: 'user_id',
type: DataTypes.INTEGER,
references: {
model: 'User',
key: 'id'
}
},
title: {
field: 'review_title',
type: DataTypes.STRING
},
review: {
type: DataTypes.TEXT
},
upvoteTally: {
field: 'upvote_tally',
type: DataTypes.INTEGER
},
downvoteTally: {
field: 'downvote_tally',
type: DataTypes.INTEGER
},
rating: {
type: DataTypes.DECIMAL(10, 0)
},
deletedAt: {
field: 'delete_time',
type: DataTypes.DATE
},
createdAt: {
field: 'create_time',
type: DataTypes.DATE
},
updatedAt: {
field: 'update_time',
type: DataTypes.DATE
}
}, {
timestamps: true,
createdAt: 'create_time',
updatedAt: 'update_time',
deletedAt: 'delete_time',
paranoid: true,
freezeTableName: true,
tableName: 'review'
});
Model.associate = function(models){
this.Entity = this.belongsTo(models.Entity, {
foreignKey: 'entityId'
});
this.User = this.belongsTo(models.User, {
foreignKey: 'userId'
});
this.Vote = this.hasMany(models.Vote, {
foreignKey: 'reviewId'
});
};
Model.prototype.toWeb = (pw) => {
let json = this.toJSON();
return json;
};
return Model;
};
|
'use strict';
{
const API = {
endpoints: {
laureate: 'http://api.nobelprize.org/v1/laureate.json?',
prize: 'http://api.nobelprize.org/v1/prize.json?'
},
queries: [{
description: 'Select a query',
endpoint: ''
},
{
description: 'All female laureates',
endpoint: 'laureate',
queryString: 'gender=female'
},
{
description: 'All Dutch laureates',
endpoint: 'laureate',
queryString: 'bornCountryCode=NL'
},
{
description: 'Physics prizes 1900-1925',
endpoint: 'prize',
queryString: 'year=1925&yearTo=25&category=physics'
},
{
description: 'Nobel Prizes 2017',
endpoint: 'prize',
queryString: 'year=2017'
},
{
description: 'Physicists working on quantum electrodynamics',
endpoint: 'laureate',
queryString: 'motivation=quantum electrodynamics'
},
]
};
function fetchJson(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status < 400) {
cb(null, xhr.response);
} else {
cb(new Error(xhr.statusText));
}
}
};
xhr.send();
}
function renderSelect() {
const root = document.getElementById('root');
const select = createAndAppend('select', root);
API.queries.forEach(query => {
const option = createAndAppend('option', select);
const url = API.endpoints[query.endpoint] + query.queryString;
option.setAttribute('value', url);
option.innerHTML = query.description;
});
select.addEventListener('change', event => {
const url = event.target.value;
console.log(url);
});
}
renderSelect();
function renderLaureates(laureates) {
const root = document.getElementById('root');
const listContainer = createAndAppend('div', root);
listContainer.id = "list-container";
laureates.forEach(laureate => {
const listItem = createAndAppend('div', listContainer);
listItem.id = 'list-item';
const table = createAndAppend('table', listItem);
const tbody = createAndAppend('tbody', table);
const tr1 = createAndAppend('tr', tbody);
const tr2 = createAndAppend('tr', tbody);
const tr3 = createAndAppend('tr', tbody);
const td1 = createAndAppend('td', tr1);
const td2 = createAndAppend('td', tr1);
const td3 = createAndAppend('td', tr3);
td1.setAttribute('class', 'label');
td1.innerHTML = 'Name:';
td2.innerHTML = laureate.firstname + ' ' + laureate.surname;
td3.innerHTML = 'Born: ' + laureate.born;
});
}
function createAndAppend(tagName, parent) {
const elem = document.createElement(tagName);
parent.appendChild(elem);
return elem;
}
const url = API.endpoints.laureate + API.queries[5].queryString;
function callback(error, data) {
if (error !== null) {
console.error(error);
} else {
renderLaureates(data.laureates);
}
}
fetchJson(url, callback);
}
|
class GrayState {
constructor() {
this.observers = [];
this.status = {};
}
attach(func) {
if (!this.observers.includes(func)) {
this.observers.push(func);
}
}
detach(func) {
this.observers = this.observers.filter((observer) => observer !== func);
}
updateStatus(val) {
this.status = val;
this.trigger();
}
trigger() {
for (let index = 0; index < this.observers.length; index++) {
this.observers[index](this.status);
}
}
}
export default new GrayState();
|
//导入excel
export function onImportExcel(files) {
console.log(this)
// 获取上传的文件对象
// const { files } = file.target;
// 通过FileReader对象读取文件
const fileReader = new FileReader();
let func = (event) => {
try {
const { result } = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, { type: 'binary' });
// 存储获取到的数据
let data = [];
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
// esline-disable-next-line
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果只取第一张表,就取消注释这行
}
}
// 最终获取到并且格式化后的 json 数据
// const uploadData = data.map(item => {
// return {
// id: Number(item['人员ID']),
// name: item['姓名'],
// idType: this.findIdType(item['证件类型'], 'string'),
// credentialsId: item['证件号码'],
// tel: item['固定电话'],
// mobile: item['移动电话']
// }
// console.log(item)
// })
message.success('上传成功!') //这里用了antd中的message组件
return data
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
return message.error('文件类型不正确!');
}
};
fileReader.onload = func
// 以二进制方式打开文件 ;
fileReader.readAsBinaryString(files[0])
}
|
import React from "react";
import {Card} from "antd";
const Basic = () => {
return (
<Card title="Basic card" extra={<span className="gx-link">More</span>}>
<p>The point of using Lorem Ipsum making it look like readable English. Various versions have evolved over the
years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
<p>Various versions have evolved over the years, sometimes by accident. The point of using Lorem Ipsum as opposed
to using 'Content here, content here', making it look like readable English.</p>
<p>Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a
piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, discovered
the source.</p>
</Card>
);
};
export default Basic;
|
var comb = require('comb');
var request = require('request');
var client = require('./client.js');
var logger = require(LIB_DIR + 'log_factory').create("experiments_client");
var ExperimentsClient = comb.define(client,{
instance : {
constructor : function(options){
options = options || {};
options.url = "experiments";
this._super([options]);
},
createSplitExperiment : function(params, callback){
request({
uri : this.host + this.url + '/split_experiment',
method : 'post',
headers : {
authorization : this.auth
},
json : params
}, callback);
},
updateSplitExperiment : function(id, params, callback){
request({
uri : this.host + this.url + '/split_experiment/' + id,
method : 'put',
headers : {
authorization : this.auth
},
json : params
}, callback);
},
getSplitExperimentById : function(id, callback){
request({
uri : this.host + this.url + '/split_experiment/' + id,
headers : {
authorization : this.auth
}
}, callback);
}
}
});
module.exports = new ExperimentsClient();
|
// ** Item List Component
import Table from './Table'
// ** Styles
import '@styles/react/apps/app-general.scss'
const GeneralList = () => {
return (
<div className='app-general-list'>
<Table />
</div>
)
}
export default GeneralList
|
import React, {useState} from "react"
import { connect } from "react-redux"
import styled from "styled-components"
import BreadCrumbC from "../../components/BreadCrumb"
import TitleC from "../../components/Title"
import FilterC from "../../components/Filter"
import ExamCardC from "../../components/ExamCard"
import PaginationC from "../../components/Pagination"
import ModalC from "../../components/Modal";
import Result from "../../components/Result"
import ButtonC from "../../components/Button"
const datas = [
{
title: "Tryout UN SMP 2019",
exams: [1,2,3]
},
{
title: "Tryout UAS SMP Sem 2 2019",
exams: [1,2,3]
}
]
const MyExams = props => {
const [isModalOpen, setIsModalOpen] = useState(false)
return (
<Wrapper>
<Modal width={300} height={390} isOpen={isModalOpen} onButtonCloseClick={() => setIsModalOpen(false)}>
<Result/>
<Button title="Review exam" btn="outline"/>
</Modal>
<MainWrap>
<BreadCrumb
links={[
{
title:"my-exams",
link:"#"
}
]}
/>
<Title title="My Exams"/>
<FiltersWrap>
<Filter
title="Exam group"
options={[]}
/>
<Filter
title="Status"
options={[]}
/>
</FiltersWrap>
<ExamCardWrap>
{datas.map((v) => (
<ExamGroupWrap>
<ExamsTitle>{v.title}</ExamsTitle>
{v.exams.map(() => (
<ExamCard
title="Matematika"
description="Lorem ipsum dono dan si memet"
source="http://pak-anang.blogpsot.com"
passingGrade="50"
duration="75"
remainingTime= "23"
questionsTotal="25"
statQuestion="12 / 2"
onClickButton ={() => setIsModalOpen(true)}
// status="submited"
status="started"
/>
))}
</ExamGroupWrap>
))}
</ExamCardWrap>
{/* <Pagination
pages={[
{
value: "1",
isFill: true
},
{
value: "2",
isFill: false
},
{
value: "3",
isFill: false
},
{
value: "4",
isFill: false
},
{
value: "5",
isFill: false
}
]}
/> */}
</MainWrap>
</Wrapper>
)
}
const Modal = styled(ModalC)`
display: flex;
flex-direction: column;
align-items: center;
right: 50%;
margin-right: -125px;
`
const Wrapper = styled.section`
margin-top: 60px;
display: flex;
flex-direction: column;
min-height: 1000px;
`
const MainWrap = styled.section`
width: 960px;
align-self: center;
display: flex;
flex-direction: column;
@media (min-width: 0px) and (max-width: 480px) {
width: 100%;
padding-left: 20px;
padding-right: 20px;
}
`
const BreadCrumb = styled(BreadCrumbC)`
margin-top: 20px;
margin-bottom: 10px;
`
const Title = styled(TitleC)`
margin-bottom: 30px;
`
const Filter = styled(FilterC)`
margin-right: 10px;
`
const FiltersWrap = styled.section`
display: flex;
margin-bottom: 50px;
`
const ExamCard = styled(ExamCardC)`
margin-bottom: 15px;
`
const ExamCardWrap = styled.section`
margin-bottom: 50px;
@media (min-width: 0px) and (max-width: 480px) {
width: 100%;
}
`
const Pagination = styled(PaginationC)`
align-self: center;
margin-bottom: 100px;
`
const ExamsTitle = styled.h5`
margin: 0px;
color: #505565;
margin-bottom: 20px;
`
const ExamGroupWrap = styled.section`
margin-bottom: 30px;
`
const Button = styled(ButtonC)`
width: 250px;
`
export default connect()(MyExams)
|
//引入 用来发送请求的 方法 一定要把路径补全
//request表示导入函数返回的
import { request } from "../../request/index.js";
//引入⽀持es7的async语法
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
/**
* 页面的初始数据
*/
data: {
//左侧的菜单数据
leftMenuList:[],
//右侧的商品数据
rightContent:[],
//表点击的左侧的菜单
currentIndex: 0,
// 右侧内容的滚动条距离顶部的距离,就是每次点击左侧菜单时,使右侧菜单跳到该菜单顶部
scrollTop: 0
},
//接口的返回数据
Cates:[],
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
/**
* 使用缓存
*
* 0 web中的本地储存和小程序中的本地储存的区别
* 1 写代码的方式不一样了
* web:localStotage.setItem("key","value") localStorage.getItem("key")
* 小程序中:wx.setStorageSync("cates",{time:Data.now(),data:this.Cates});
* 2 存的时候有,有没有做类型转换
* web:不管存入的是什么类型的数据,最终都会先调用下 toString(),把数据变成了字符串 再存入进去
* 小程序:不存在类型转换的这个操作,存什么类似的数据进去,获取的时候就是什么类型
* 1 先判断一下本地储存中有没有旧的数据
* {time:Date.now(),data:[...]
* 2 没有旧的数据,直接发送新请求
* 3 有旧的数据,同时旧的数据也没有过期,就使用本地储存中的旧数据即可
*/
// 1 获取本地存储中的数据(小程序中也是存在本地储存技术的)
const Cates = wx.getStorageSync("cates");
// 2 判断
if(!Cates){
// 不存在,发送请求获取数据,getCates就是下面的分类方法
this.getCates();
}else{
// 有旧的数据,定义一个过期时间,假设1分钟
if(Date.now() - Cates.time > 1000 * 10 * 6){
//过期,重新发送请求
this.getCates();
}else{
//获取旧的数据
this.Cates = Cates.data;
//构建左侧的菜单数据
let leftMenuList = this.Cates.map(v => v.cat_name);
//构建右侧的商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent
})
}
}
},
//获取分类数据
// getCates(){
async getCates(){
// request({
// // url: "https://api-hmugo-web.itheima.net/api/public/v1/categories"
// url: "/categories"
// })
// .then(res => {
// this.Cates = res.data.message;
// // 把接口的数据存入到本地储存中
// wx.setStorageSync("cates",{time:Date.now(),data:this.Cates});
// //构建左侧的菜单数据
// let leftMenuList = this.Cates.map(v => v.cat_name);
// //构建右侧的商品数据
// let rightContent = this.Cates[0].children;
// this.setData({
// leftMenuList,
// rightContent
// })
// })
/**
* 1 使用es7的async await来发送请求
* 这一句执行完成之前,下面的不会执行:const res=await request({url: "/categories"})
* 其实这里好像改成了同步了
*/
const res=await request({url: "/categories"});
// this.Cates = res.data.message;
//简化上面的this.Cates,已经在request中拼接了
this.Cates = res;
// 把接口的数据存入到本地储存中
wx.setStorageSync("cates",{time:Date.now(),data:this.Cates});
//构建左侧的菜单数据
let leftMenuList = this.Cates.map(v => v.cat_name);
//构建右侧的商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent
})
},
// 左侧菜单的点击事件
handleItemTap(e){
/**
* 1 获取被点击的标题身上的索引 从.wxml文件中获取
* 2 给data中的currentIndex赋值就可以了
* 3 根据不同的索引来渲染右侧的商品内容
*/
const {index} = e.currentTarget.dataset;
//更新右侧的商品数据
let rightContent = this.Cates[index].children;
this.setData({
currentIndex: index,
rightContent,
// 重新设置,右侧内容的scroll-view标签距离顶部的距离
scrolTop:0
})
}
})
|
import React from 'react'
import ReactPlayer from 'react-player/youtube'
function YTCard({videoId, height, width}) {
return (
<div className="ytCardWrapper">
<ReactPlayer
url={`https://www.youtube.com/watch?v=${videoId}`}
// height="125px"
// width="180px"
height={height}
width={width}
/>
</div>
)
}
export default YTCard
|
var socket = io.connect(window.location.href);
var DRIVE_FORWARD = 'df';
var DRIVE_BACKWARD = 'db';
var SET_DRIVE_SPEED = 'sds';
var SET_DRIVE_SPEED_FORWARD = 'sdsf';
var SET_DRIVE_SPEED_BACKWARD = 'sdsb';
var SET_DRIVE_ANGLE = 'sda';
var DRIVE_STOP = 'ds';
var TURRET_Y_ZERO = 'tyz';
var TURRET_Y_STOP = 'tyx';
var TURRET_Y_STEP_UP = 'tysu';
var TURRET_Y_STEP_DOWN= 'tysd';
var TURRET_Y_DEGREES_UP = 'tydu';
var TURRET_Y_DEGREES_DOWN = 'tydd';
var COMMAND_TURRET_Y_SET_DESIRED_ANGLE = "tya";
var COMMAND_TURRET_Y_STOP = "tys";
var COMMAND_TURRET_Y_ZERO = "tyz";
var COMMAND_TURRET_Y_DOWN = "tyd";
var COMMAND_TURRET_Y_UP = "tyu";
var COMMAND_TURRET_X_SET_DESIRED_ANGLE = "txa";
var COMMAND_TURRET_X_STOP = "txs";
var COMMAND_TURRET_X_ZERO = "txz";
var COMMAND_TURRET_X_DOWN = "txd";
var COMMAND_TURRET_X_UP = "txu";
function turretYZero() {
send_message(COMMAND_TURRET_Y_ZERO);
}
function turretYUp() {
send_message(COMMAND_TURRET_Y_UP);
}
function turretYDown() {
send_message(COMMAND_TURRET_Y_DOWN);
}
function turretYStop() {
send_message(COMMAND_TURRET_Y_STOP);
}
function turretYDegrees(degrees) {
var value = Math.abs(parseInt(degrees));
send_message(COMMAND_TURRET_Y_SET_DESIRED_ANGLE + ":" + value);
}
function turretXZero() {
send_message(COMMAND_TURRET_X_ZERO);
}
function turretXUp() {
send_message(COMMAND_TURRET_X_UP);
}
function turretXDown() {
send_message(COMMAND_TURRET_X_DOWN);
}
function turretXStop() {
send_message(COMMAND_TURRET_X_STOP);
}
function turretXDegrees(degrees) {
var value = Math.abs(parseInt(degrees));
send_message(COMMAND_TURRET_X_SET_DESIRED_ANGLE + ":" + value);
}
function messageRemoveTime(message) {
if (!message) {
console.trace();
debugger;
}
if (message.indexOf('@') !== -1) {
return message.split('@')[0];
}
return message;
}
function messageGetTime(message) {
if (message.indexOf('@') !== -1) {
time = message.split('@')[1];
return time;
}
return false;
}
function messageGetCommand(message) {
message = messageRemoveTime(message);
if (message.indexOf(':') !== -1) {
message.split(':').shift();
return message;
}
return message;
}
function messageGetArgs(message) {
message = messageRemoveTime(message);
var args = null;
if (message.indexOf(':') !== -1) {
args = message.split(':').shift();
}
}
var sent_messages = {};
function remember_sent(message) {
var orig_message = message;
var time = messageGetTime(message);
var command = messageGetCommand(message);
var args = messageGetArgs(message);
var data = {args: args, time: time, command: command};
sent_messages[message] = data;
}
var last_sent = 0;
function send_message(message) {
var diff = +new Date() - last_sent;
if (message.indexOf('sdsf') !== -1 || message.indexOf('sdsb') !== -1 || message.indexOf('sda') !== -1) {
if (diff <= 50) {
console.log(diff, 'fast');
return false;
}
}
last_sent = +new Date();
// append timestamp to message
message += "@" + +new Date();
// Send the message to the server
socket.emit('message', message);
// Remember the message that was sent
remember_sent(message);
// Check up on the message that was sent
track_message(message);
// Log the message to the console as being sent
console.log('S:' + message);
}
function track_message(message) {
setTimeout(function () {
(function (message) {
var command = messageGetCommand(message);
var time = messageGetTime(message);
if (message in sent_messages) {
var command = sent_messages[message]['command'];
console.error('message not recieved yet:', message);
}
//if (sent_messages[command] && sent_messages[command].time) {
//if (time >= sent_messages[command].time) {
//console.error('old message not recieved:', message);
//}
//}
})(message);
}, 250);
}
socket.on('message', function (message) {
if (message.indexOf('@') != -1) {
sent = message.split('@')[1];
console.log('R:' + message + "(" + (+new Date() - sent) + ")");
}
else {
if (message.startsWith("tyca:")) {
var match = message.match(/tyca:([0-9]+)/)
if (match.length == 2) {
update_turret_y_display(match[1]);
}
}
console.log('R:' + message);
}
delete sent_messages[message];
});
function update_turret_y_display(angle) {
var nurfDisplays = document.querySelectorAll('hud-nurf-angle');
if (nurfDisplays && nurfDisplays.length > 0) {
nurfDisplays[0].setAttribute('value', angle);
}
}
var last_direction;
function drive_forward() {
if (last_direction !== "forward") {
send_message(DRIVE_FORWARD);
last_direction = "forward";
}
}
function drive_backward() {
if (last_direction !== "backward") {
send_message(DRIVE_BACKWARD);
last_direction = "backward";
}
}
var last_drive_speed_backward = 0;
function set_drive_speed_backward(speed) {
speed = Math.floor(speed * (255 / 100));
if (Math.abs(speed - last_drive_speed_backward) >= 2) {
send_message(SET_DRIVE_SPEED_BACKWARD + ":" + speed);
last_drive_speed_backward = speed;
}
}
var last_drive_speed_forward = 0;
function set_drive_speed_forward(speed) {
speed = Math.floor(speed * (255 / 100));
if (Math.abs(speed - last_drive_speed_forward) >= 2) {
send_message(SET_DRIVE_SPEED_FORWARD + ":" + speed);
last_drive_speed_forward = speed;
}
}
var last_drive_angle = 0;
function set_drive_angle(angle) {
if (Math.abs(angle - last_drive_angle) >= 2) {
send_message(SET_DRIVE_ANGLE + ":" + angle);
last_drive_angle = angle;
}
}
function drive_stop() {
send_message(DRIVE_STOP);
}
$(document).ready(function () {
setTimeout(function () {
var retroJoyStickElement = document.getElementsByTagName('retro-joystick')[0];
var distance = 0;
var angle = 0;
// When joystick has changed position
retroJoyStickElement.on('change', function (stick) {
// keep track of distance
distance = this.distance
// keep track of angle
angle = this.angle
// notate when angle / distance changes
$('#retrostick-data-table-angle').html(angle);
$('#retrostick-data-table-distance').html(distance);
var maxTurnDiff = .5;
var maxAngle = 90;
var speed = distance * 2.55;
if ((angle > 270 || angle < 90) && distance > 1) {
set_drive_speed_forward(distance);
set_drive_angle(angle);
}
else if ((angle < 270 || angle > 90) && distance > 1) {
set_drive_speed_backward(distance);
set_drive_angle(angle);
}
else {
drive_stop();
}
});
}, 500);
});
// Hacky demo file
function demo(meter) {
// reasons?
if (!meter) return false;
var i = 0;
var dir = false;
function changePositionRandomly() {
if (dir === false) i++;
if (dir === true) i--;
if (i >= 100) {dir = true;}
if (i <= 0) {dir = false;}
var rand = Math.floor(Math.random() * 100);
if (i < rand + 1 && i > rand - 1) dir = !dir;
meter.setAttribute('value', i);
}
function animatePosition() {
setTimeout(function () {
changePositionRandomly();
animatePosition();
}, Math.floor(Math.random() * 75) + Math.floor(Math.random() * 75));
}
animatePosition();
}
var meters = document.querySelectorAll('hud-meter');
demo(meters[0]);
demo(meters[1]);
demo(meters[2]);
demo(meters[3]);
function demoNurfAngle(nurfDisplay) {
if (!nurfDisplay) return false;
var i = 0;
var dir = false;
function changePositionRandomly() {
if (dir === false) i++;
if (dir === true) i--;
if (i >= 90) {dir = true;}
if (i <= 0) {dir = false;}
var rand = Math.floor(Math.random() * 90);
if (i < rand + 1 && i > rand - 1) dir = !dir;
nurfDisplay.setAttribute('value', i);
}
function animatePosition() {
setTimeout(function () {
changePositionRandomly();
animatePosition();
}, Math.floor(Math.random() * 75) + Math.floor(Math.random() * 75));
}
//animatePosition();
}
$(document).ready(function () {
update_turret_y_display(0);
$("#turret-x").on('change', function (e) {
var value = e.target.value;
console.log(value);
turretXDegrees(value);
});
$("#turret-y").on('change', function (e) {
var value = e.target.value;
turretYDegrees(value);
});
$(window).on('keydown', function (e) {
// left = 37
if (e.keyCode === 37) {
var oldValue = $("#turret-x")[0].value * 1;
$("#turret-x")[0].value = oldValue - 1;
$("#turret-x").trigger('change');
}
// right = 39
else if (e.keyCode === 39) {
var oldValue = $("#turret-x")[0].value * 1;
$("#turret-x")[0].value = oldValue + 1;
$("#turret-x").trigger('change');
}
// up = 38
else if (e.keyCode === 38) {
var oldValue = $("#turret-y")[0].value * 1;
$("#turret-y")[0].value = oldValue + 1;
$("#turret-y").trigger('change');
}
// down = 40
else if (e.keyCode === 40) {
var oldValue = $("#turret-y")[0].value * 1;
$("#turret-y")[0].value = oldValue - 1;
$("#turret-y").trigger('change');
}
console.log(e.keyCode);
});
});
|
function SmoothieChart(m) {
m = m || {}
m.grid = m.grid || {
fillStyle: '#000000',
strokeStyle: '#777777',
lineWidth: 1,
millisPerLine: 1e3,
verticalSections: 2,
}
m.millisPerPixel = m.millisPerPixel || 20
m.fps = m.fps || 50
m.maxValueScale = m.maxValueScale || 1
m.minValue = m.minValue
m.maxValue = m.maxValue
m.labels = m.labels || { fillStyle: '#ffffff' }
m.interpolation = m.interpolation || 'bezier'
m.scaleSmoothing = m.scaleSmoothing || 0.125
m.maxDataSetLength = m.maxDataSetLength || 2
m.timestampFormatter = m.timestampFormatter || null
this.options = m
this.seriesSet = []
this.currentValueRange = 1
this.currentVisMinValue = 0
}
SmoothieChart.prototype.addTimeSeries = function(m, c) {
this.seriesSet.push({ timeSeries: m, options: c || {} })
}
SmoothieChart.prototype.removeTimeSeries = function(m) {
this.seriesSet.splice(this.seriesSet.indexOf(m), 1)
}
SmoothieChart.prototype.streamTo = function(m, c) {
var e = this
this.render_on_tick = function() {
e.render(m, e.seriesSet[0].timeSeries.lastTimeStamp)
}
this.start()
}
SmoothieChart.prototype.start = function() {
this.timer || (this.timer = setInterval(this.render_on_tick, 1e3 / this.options.fps))
}
SmoothieChart.prototype.stop = function() {
this.timer && (clearInterval(this.timer), (this.timer = void 0))
}
SmoothieChart.timeFormatter = function(m) {
function c(c) {
return (10 > c ? '0' : '') + c
}
return c(m.getHours()) + ':' + c(m.getMinutes()) + ':' + c(m.getSeconds())
}
SmoothieChart.prototype.render = function(m, c) {
var e = m.getContext('2d'),
g = this.options,
a = m.clientWidth,
d = m.clientHeight
e.save()
c -= c % g.millisPerPixel
e.translate(0, 0)
e.beginPath()
e.rect(0, 0, a, d)
e.clip()
e.save()
e.fillStyle = g.grid.fillStyle
e.clearRect(0, 0, a, d)
e.fillRect(0, 0, a, d)
e.restore()
e.save()
e.lineWidth = g.grid.lineWidth || 1
e.strokeStyle = g.grid.strokeStyle || '#ffffff'
if (0 < g.grid.millisPerLine)
for (
var b = c - (c % g.grid.millisPerLine);
b >= c - a * g.millisPerPixel;
b -= g.grid.millisPerLine
) {
e.beginPath()
var l = Math.round(a - (c - b) / g.millisPerPixel)
e.moveTo(l, 0)
e.lineTo(l, d)
e.stroke()
if (g.timestampFormatter) {
var k = g.timestampFormatter(new Date(b)),
h = e.measureText(k).width / 2 + e.measureText(v).width + 4
l < a - h &&
((e.fillStyle = g.labels.fillStyle), e.fillText(k, l - e.measureText(k).width / 2, d - 2))
}
e.closePath()
}
for (v = 1; v < g.grid.verticalSections; v++)
(b = Math.round((v * d) / g.grid.verticalSections)),
e.beginPath(),
e.moveTo(0, b),
e.lineTo(a, b),
e.stroke(),
e.closePath()
e.beginPath()
e.strokeRect(0, 0, a, d)
e.closePath()
e.restore()
v = l = Number.NaN
for (k = 0; k < this.seriesSet.length; k++) {
var f = this.seriesSet[k].timeSeries
isNaN(f.maxValue) || (l = isNaN(l) ? f.maxValue : Math.max(l, f.maxValue))
isNaN(f.minValue) || (v = isNaN(v) ? f.minValue : Math.min(v, f.minValue))
}
if (!isNaN(l) || !isNaN(v)) {
l = null != g.maxValue ? g.maxValue : l * g.maxValueScale
null != g.minValue && (v = g.minValue)
this.currentValueRange += g.scaleSmoothing * (l - v - this.currentValueRange)
this.currentVisMinValue += g.scaleSmoothing * (v - this.currentVisMinValue)
h = this.currentValueRange
var q = this.currentVisMinValue
for (k = 0; k < this.seriesSet.length; k++) {
e.save()
f = this.seriesSet[k].timeSeries
f = f.data
for (
var n = this.seriesSet[k].options;
f.length >= g.maxDataSetLength && f[1][0] < c - a * g.millisPerPixel;
)
f.splice(0, 1)
e.lineWidth = n.lineWidth || 1
e.fillStyle = n.fillStyle
e.strokeStyle = n.strokeStyle || '#ffffff'
e.beginPath()
var p = 0,
u = 0,
r = 0
for (b = 0; b < f.length; b++) {
var w = Math.round(a - (c - f[b][0]) / g.millisPerPixel),
t = f[b][1] - q
t = Math.max(Math.min(d - (h ? Math.round((t / h) * d) : 0), d - 1), 1)
if (0 == b) (p = w), e.moveTo(w, t)
else
switch (g.interpolation) {
case 'line':
e.lineTo(w, t)
break
default:
e.bezierCurveTo(Math.round((u + w) / 2), r, Math.round(u + w) / 2, t, w, t)
}
u = w
r = t
}
0 < f.length &&
n.fillStyle &&
(e.lineTo(a + n.lineWidth + 1, r),
e.lineTo(a + n.lineWidth + 1, d + n.lineWidth + 1),
e.lineTo(p, d + n.lineWidth),
e.fill())
e.stroke()
e.closePath()
e.restore()
}
if (!g.labels.disabled) {
g.labelOffsetY || (g.labelOffsetY = 0)
e.fillStyle = g.labels.fillStyle
b = parseFloat(l).toFixed(2)
var v = parseFloat(v).toFixed(2)
e.fillText(b, a - e.measureText(b).width - 2, 10)
e.fillText(v, a - e.measureText(v).width - 2, d - 2)
for (b = 0; b < this.seriesSet.length; b++)
(f = this.seriesSet[b].timeSeries),
(a = f.label),
(e.fillStyle = f.options.fillStyle || 'rgb(255,255,255)'),
a && e.fillText(a, 2, 10 * (b + 1) + g.labelOffsetY)
}
}
e.restore()
}
|
// 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 any plugin's vendor/assets/javascripts directory 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
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require sly.min
//= require_tree .
//= require turbolinks
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
$(function(){
if(isMobile)
$('body').addClass('mobile')
});
$(function(){
var $frame = $('.luxury-list');
var $wrap = $frame.parent();
// Call Sly on frame
$frame.sly({
horizontal: 1,
itemNav: 'forceCentered',
smart: 1,
activateMiddle: 1,
mouseDragging: 0,
touchDragging: 1,
releaseSwing: 1,
startAt: 0,
scrollBy: 1,
speed: 300,
elasticBounds: 1,
dragHandle: 1,
dynamicHandle: 1,
clickBar: 1,
// Buttons
prev: $wrap.find('.controls .prev'),
next: $wrap.find('.controls .next')
});
});
$(function(){
var $frame = $('.citations .frame');
var $wrap = $frame.parent();
// Call Sly on frame
$frame.sly({
horizontal: 1,
itemNav: 'forceCentered',
smart: 1,
activateMiddle: 1,
mouseDragging: 0,
touchDragging: 0,
releaseSwing: 1,
startAt: 0,
scrollBy: 1,
speed: 300,
elasticBounds: 1,
dragHandle: 1,
dynamicHandle: 1,
clickBar: 1,
// Buttons
prev: $wrap.find('.controls .prev'),
next: $wrap.find('.controls .next')
});
});
$(function(){
var $frame = $('.calendars');
// Call Sly on frame
$frame.sly({
horizontal: 1,
itemNav: 'forceCentered',
smart: 1,
activateMiddle: 1,
mouseDragging: 0,
touchDragging: 1,
releaseSwing: 1,
startAt: 0,
scrollBy: 1,
speed: 300,
elasticBounds: 1,
//easing: 'easeOutExpo',
dragHandle: 1,
dynamicHandle: 1,
clickBar: 1
//// Buttons
//prev: $('.months .prev'),
//next: $('.months .next')
});
$('.months li').on('click', function(e){
var $this = $(this);
if($this.hasClass('prev')) $frame.sly('prev');
if($this.hasClass('next')) $frame.sly('next');
return false;
})
});
$(function(){
var $frame = $('.media-container > .gallery');
var $controls = $frame.siblings('.controls');
var qty = $frame.find('ul.slidee > li').length;
$controls.find('span.total').html(qty);
$frame.find('ul.slidee > li').first().find('.switch.prev').addClass('disabled');
$frame.find('ul.slidee > li').last().find('.switch.next').addClass('disabled');
// Call Sly on frame
$frame.sly({
horizontal: 1,
itemNav: 'forceCentered',
smart: 1,
activateMiddle: 1,
mouseDragging: 0,
touchDragging: 1,
releaseSwing: 1,
startAt: 0,
scrollBy: 1,
speed: 300,
elasticBounds: 1,
dragHandle: 1,
dynamicHandle: 1,
clickBar: 1,
prev: $controls.find('.prev'),
next: $controls.find('.next')
});
$frame.sly('on', 'active', function(a,b){
$controls.find('span.counter').html(b+1);
});
if (!isMobile) {
$frame.find('.slidee > li > .switch').on('click', function(e){
var $this = $(this);
if($this.hasClass('prev')) $frame.sly('prev');
if($this.hasClass('next')) $frame.sly('next');
return false;
})
}
});
$(function(){
$(document).on('click', function(e){
if( !$(e.target).is('span.dropdown') && ( $(e.target).parents('span.dropdown').length == 0 ))
$('span.dropdown').removeClass('active');
});
$('span.dropdown').on('click', function(e){
var $this = $(this);
var $target = $(e.target);
$this.toggleClass('active');
if($target.is('li')) {
$target.addClass('active').siblings().removeClass('active');
$this.find('span').html($target.data('city'))
}
});
});
$(function(){
$('[data-inherited-link]').each(function(){
var $this = $(this);
var $link = $this.find($this.data('inheritedLink')).eq(0);
$this.on('click', function(){
document.location = $link.attr('href');
});
$this.hover(function(){
$link.addClass('hovered');
}, function(){
$link.removeClass('hovered');
});
});
});
$(function(){
$('.sliding-tabs').each(function(){
var $tabs = $(this);
var $activeTab = $tabs.find('li.active').eq(0);
if (!$activeTab.length) {
$activeTab = $tabs.find('li').eq(0).addClass('active');
}
var $bg = $('<div class="bg" />');
$tabs.prepend($bg);
$bg.css({
width: $activeTab.outerWidth(),
height: $activeTab.outerHeight(),
top: $activeTab.position().top,
left: $activeTab.position().left
});
$tabs.on('click', 'li', function(){
var $tab = $(this);
if($tab.is('.active')) return false;
$($tabs.find('.active').data('container')).removeClass('active');
$tab.addClass('active').siblings().removeClass('active');
$($tab.data('container')).addClass('active');
console.log($tab.position());
$bg.css({
width: $tab.outerWidth(),
height: $tab.outerHeight(),
top: $tab.position().top,
left: $tab.position().left
})
});
});
});
// smooth scroll by CSS-Tricks
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
$(function(){
$('header form .open').on('click', function(){
var $this = $(this);
if(!isMobile) {
$this.parents('form').first().addClass('active').find('input').focus();
$('#fader').addClass('active');
}
else {
document.location = $this.data('url');
}
});
$('header form .close').on('click', function(){
$('form.main-search').removeClass('active');
$('#fader').removeClass('active');
});
$(document).on('click.mainSearch', function(e){
var $target = $(e.target);
if ( !$target.is('form.main-search') && !$target.parents().is('form.main-search') ) {
$('form.main-search').removeClass('active');
$('#fader').removeClass('active');
}
});
});
// fixed menu
$(function(){
if (!isMobile) {
$(document).scroll(function(){
$('header').toggleClass('scrolled', ($(document).scrollTop() > 70));
});
}
});
$(function(){
$('#event-hat > ul > li').on('click.eventHat', function(){
$(this).toggleClass('active').siblings().removeClass('active');
});
$(document).on('click.eventHat', function(e){
if( !$(e.target).is('#event-hat > ul > li') && ( $(e.target).parents('#event-hat > ul > li').length == 0 ))
$('#event-hat > ul > li').removeClass('active');
});
});
|
'use strict';
angular.module('WarehouseDelivery', ['ngTable', 'siTable', 'ReleaseOrder', 'Contact', 'ExportDeliveries', 'ngToast', 'Loader'])
.config(['ngToastProvider', function (ngToast) {
ngToast.configure({maxNumber: 1, horizontalPosition: 'center'});
}])
.controller('WarehouseDeliveryController', function ($scope, $location, ReleaseOrderService, $sorter, ExportDeliveriesService, ngToast, LoaderService, $timeout) {
$scope.sortBy = $sorter;
$scope.errorMessage = '';
$scope.planId = '';
$scope.searchFields = ['waybill', 'deliveryDate'];//, 'programme'];
$scope.releaseOrders = [];
$scope.programmes = [];
$scope.programmeSelected = null;
$scope.documentColumnTitle = 'Waybill #';
$scope.dateColumnTitle = 'Date Shipped';
$scope.trackedDateColumnTitle = 'Tracked Date';
$scope.descriptionColumnTitle = 'Outcome Name';
function loadReleaseOrder(options) {
LoaderService.showLoader();
options = angular.extend({'paginate': 'true'}, options);
ReleaseOrderService.all(undefined, options).then(function (response) {
$scope.releaseOrders = response.results.sort();
$scope.count = response.count;
$scope.pageSize = response.pageSize;
if(options) {
if(options.from) {
$scope.fromDate = moment(Date.parse(options.from)).format('DD-MMM-YYYY');
initializing = true;
}
if(options.to) {
$scope.toDate = moment(Date.parse(options.to)).format('DD-MMM-YYYY');
initializing = true;
}
}
LoaderService.hideLoader();
}).catch(function () {
ngToast.create({content: 'Failed to load release orders', class: 'danger'});
});
}
$scope.initialize = function (urlArgs) {
this.sortBy('trackedDate');
this.sort.descending = false;
loadReleaseOrder(urlArgs);
};
$scope.goToPage = function (page) {
loadReleaseOrder(angular.extend({'page': page}, changedFilters()));
};
$scope.sortArrowClass = function (criteria) {
var output = '';
if (this.sort.criteria === criteria) {
output = 'active glyphicon glyphicon-arrow-down';
if (this.sort.descending) {
output = 'active glyphicon glyphicon-arrow-up';
}
}
return output;
};
$scope.selectReleaseOrder = function (selectedReleaseOrderId) {
$location.path('/warehouse-delivery/new/' + selectedReleaseOrderId);
};
$scope.exportToCSV = function () {
ExportDeliveriesService.export('warehouse').then(function (response) {
ngToast.create({content: response.data.message, class: 'info'});
}, function () {
var errorMessage = "Error while generating CSV. Please contact the system's admin.";
ngToast.create({content: errorMessage, class: 'danger'})
});
};
var timer, initializing = true;
$scope.$watch('[fromDate,toDate,query]', function () {
if (initializing){
initializing = false;
}
else {
if (timer) {
$timeout.cancel(timer);
}
delaySearch();
}
}, true);
function delaySearch() {
timer = $timeout(function () {
$scope.initialize(changedFilters());
}, 2000);
}
function changedFilters() {
var urlArgs = {};
if ($scope.fromDate) {
urlArgs.from = formatDate($scope.fromDate);
}
if ($scope.toDate) {
urlArgs.to = formatDate($scope.toDate);
}
if ($scope.query) {
urlArgs.query = $scope.query;
}
return urlArgs
}
function formatDate(date) {
return moment(date).format('YYYY-MM-DD')
}
})
;
|
const path = require('path');
const merge = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const AddAssetHtmlCdnWebpackPlugin = require('add-asset-html-cdn-webpack-plugin');
const commonConfig = require('./common_config.js');
const { publicPath: subPath, cdnEnv, dllCdnUrls } = require('../index');
const ROOT_PATH = process.cwd();
const cd = require(path.resolve(ROOT_PATH, 'cd.json'));
const env = process.env.BUILD_ENV;
const { entries, htmlTemplates, subPath: pagePath } = require('../getEntriesFromArgv');
const webpackConfig = merge(commonConfig, {
mode: 'production',
entry: entries,
output: {
filename: `static/js/[name]_[contenthash].js`,
chunkFilename: `static/js/[name]_[contenthash].chunk.js`,
publicPath: (cdnEnv.includes(env) && cd['cdn-path']) ? cd['cdn-path'] : pagePath ? `${subPath}/${pagePath}` : subPath,
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
},
module: {
rules: [
{
test: /\.(less|css)$/,
exclude: [path.resolve(ROOT_PATH, 'node_modules')],
use: [
{
loader: MiniCssExtractPlugin.loader,
}, {
loader: 'css-loader',
options: {
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
},
{
loader: 'less-loader',
options: {
javascriptEnabled: true,
}
}
]
},
]
},
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: {
warnings: false,
compress: {
comparisons: false,
drop_console: env === 'fat' ? false : true,
},
parse: {},
mangle: true,
output: {
comments: false,
ascii_only: true,
},
},
parallel: true,
cache: true,
sourceMap: false,
}),
new OptimizeCSSAssetsPlugin({})
],
splitChunks: {
chunks: "all",
name: true,
automaticNameDelimiter: '_',
cacheGroups: {
default: false,
vendors: false,
ace: {
test: /[\\/]node_modules[\\/]zm-tk-ace-m/,
priority: 20, // 权重越大,打包优先级越高
name: 'ace',
reuseExistingChunk: true
},
}
}
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: `static/css/[name].css`,
chunkFilename: `static/css/[name]_[id]_[hash].css`
}),
...htmlTemplates,
new AddAssetHtmlCdnWebpackPlugin(true, dllCdnUrls),
new CopyWebpackPlugin(
[{
from: path.resolve(ROOT_PATH, 'src/asserts'),
to: path.resolve(ROOT_PATH, `dist/static/asserts`),
ignore: ['*.less']
},
{
from: path.resolve(ROOT_PATH, 'favicon.ico'),
to: path.resolve(ROOT_PATH, 'dist/')
}
]),
]
});
if (process.env.npm_config_report) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = webpackConfig;
|
import React, { Component } from 'react'
import { Box, Color } from 'ink'
import TextInput from 'ink-text-input'
class QueryPage extends Component {
state = { query : '' }
render() {
return (
<Box>
<Box marginLeft={2}>
<Color cyan>
What are you looking for:
</Color>
</Box>
<Box marginLeft={1}>
<TextInput
value={this.state.query}
onChange={this.handleChange}
onSubmit={() => this.props.submitSearch(this.state.query)}
/>
</Box>
</Box>
)
}
handleChange = query => this.setState({ query })
}
export default QueryPage
|
import React from 'react';
//import ReactSignupLoginComponent from 'react-signup-login-component';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
//import 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap';
//import 'https://fonts.googleapis.com/icon?family=Material+Icons';
import './login.scss';
// import Login from './login';
// import Register from './register';
import { Login, Register } from "./index";
// import { connect } from 'tls';
//reducers
import { connect } from 'react-redux';
import { login, logout } from '../store/actionCreators';
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
isLogginActive: true
};
}
componentDidMount() {
this.props.hideEverything();
//Add .right by default
this.rightSide.classList.add("right");
}
changeState=()=> {
//ES6 Object Destructuring
const { isLogginActive } = this.state;
//We togglet component classes depending on the current active state
if (isLogginActive) {
//Right side for login
this.rightSide.classList.remove("right");
this.rightSide.classList.add("left");
} else {
//Left side for Register
this.rightSide.classList.remove("left");
this.rightSide.classList.add("right");
}
//Of course we need to toggel the isLogginActive by inversing it's previous state
this.setState(prevState => ({ isLogginActive: !prevState.isLogginActive }));
}
render() {
console.log('User'+this.props);
const { isLogginActive } = this.state;
const current = isLogginActive ? "Register" : "Login";
const currentActive=isLogginActive ? "Login" : "Register";
return (
<div className="App" style={{paddingTop:250 }}>
<div className="login" style={{ width:400}}>
<div className="container" ref={ref => (this.container = ref)}>
{isLogginActive && (
<Login containerRef={ref => (this.current = ref)} />
)}
{!isLogginActive && (
<Register containerRef={ref => (this.current = ref)} />
)}
</div>
<RightSide
current={current}
currentActive={currentActive}
containerRef={ref => (this.rightSide = ref)}
onClick={this.changeState}
/>
</div>
</div>
);
}
}
const mapStateToProps=(state)=>{
console.log('mapStateToProps', state)
return{
user:state.user
}
}
const mapDispatchToProps = {login }
export default connect(mapStateToProps,mapDispatchToProps)( LoginPage);
const RightSide = props => {
return (
<div
className="right-side"
ref={props.containerRef}
onClick={props.onClick}
>
<div className="inner-container">
<div className="text">{props.current}</div>
</div>
</div>
);
};
|
import ProdutoService from "../services/produto.service.js";
async function createProduto(req, res, next) {
try {
let produto = req.body;
if (!produto.codigo || !produto.descricao || !produto.marcaId) {
throw new Error('Os campos codigo, descricao e marca são obrigatórios!');
}
res.send(await ProdutoService.createProduto(produto));
logger.info(`/POST /produto - ${JSON.stringify(produto)}`);
} catch(err) {
next(err);
}
}
async function updateProduto(req, res, next) {
try {
let produto = req.body;
if (!produto.codigo || !produto.id || !produto.descricao || !produto.marcaId) {
throw new Error('Os campos id, nome e telefone são obrigatórios!');
}
res.send(await ProdutoService.updateProduto(produto));
logger.info(`/UPDATE /produto - ${JSON.stringify(produto)}`);
} catch(err) {
next(err);
}
}
async function getProdutos(req, res, next) {
try {
// console.log(req.query.proprietario_id);
res.send(await ProdutoService.getProdutos(req.query.produto_id));
logger.info(`/GET /produto`);
} catch(err) {
next(err);
}
}
async function getProduto(req, res, next) {
try {
res.send(await ProdutoService.getProduto(req.params.id));
logger.info(`/GET /produto - ${JSON.stringify(req.params.id)}`);
} catch(err) {
next(err);
}
}
async function deleteProduto(req, res, next) {
try {
if (!req.params.id) {
throw new Error('O id é obrigatórios!');
}
res.send(await ProdutoService.deleteProduto(req.params.id));
logger.info(`/GET /produto - ${JSON.stringify(req.params.id)}`);
} catch(err) {
next(err);
}
}
export default {
createProduto,
updateProduto,
getProdutos,
getProduto,
deleteProduto
}
|
/*
============================================
; Title: Assignment 1.5
; Author: Albert Einstein
; Date: 25 June 2017
; Modified By: Heather Peterson
; Description: This program demonstrates the
; use of JavaScript types, values, and
; and variables in an application.
;===========================================
*/
/*
The code below builds a properly formatted
header and must be included in all applications
you write. In subsequent week's we will build this
functionality into a function and place it in a separate file.
*/
var myFirstName = "Heather";
var myLastName = "Peterson";
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if (dd<10) {
dd = '0' + dd
}
if (mm<10) {
mm = '0' + mm
}
today = mm + '-' + dd + '-' + yyyy
var assignmentNum = "Assignment 1.5";
var programHeader = "\n" + myFirstName + " " + myLastName + "\n"
+ assignmentNum + "\nDate: " + today;
console.log(programHeader);
console.log("\n");
// start of program - your code goes below this line
var firstName1 = "First Name: Bear";
var firstName2 = "First Name: Lily";
var firstName3 = "First Name: Russ";
var firstName4 = "First Name: Lucy";
var firstName5 = "First Name: Bob";
var lastName1 = "Last Name: Jacobs";
var lastName2 = "Last Name: McMiller";
var lastName3 = "Last Name: Peters";
var lastName4 = "Last Name: Madison";
var lastName5 = "Last Name: Johnson";
var Address1 = "Address: 1313 Penn Hill Street Hopkins, MN";
var Address2 = "Address: 342 Smith Way Beaver, PA";
var Address3 = "Address: 4817 Jacksonville Avenue Orlando, FL";
var Address4 = "Address: 99 Perry Lane Queens, NY";
var Address5 = "Address: 2630 Riverview Street Las Vegas, NV";
var payRate1 = 20.00;
var finalPay1 = 'Pay Rate: $' + payRate1.toPrecision(3) ;
var payRate2 = 22.50;
var finalPay2 = 'Pay Rate: $' + payRate2.toPrecision(3) ;
var payRate3 = 27.00;
var finalPay3 = 'Pay Rate: $' + payRate3.toPrecision(3) ;
var payRate4 = 23.00;
var finalPay4 = 'Pay Rate: $' + payRate4.toPrecision(3) ;
var payRate5 = 25.50;
var finalPay5 = 'Pay Rate: $' + payRate5.toPrecision(3) ;
var hireDate1 = 'Hire Date: ' + ("6/09/2017");
var hireDate2 = 'Hire Date: ' + ("3/16/2017");
var hireDate3 = 'Hire Date: ' + ("8/11/2000");
var hireDate4 = 'Hire Date: ' + ("7/01/2017");
var hireDate5 = 'Hire Date: ' + ("11/20/2016");
var empHeader1 = "\n" + firstName1 + "\n" + lastName1 + "\n"
+ Address1 + "\n" + finalPay1 + "\n" + hireDate1;
var empHeader2 = "\n" + firstName2 + "\n" + lastName2+ "\n"
+ Address2 + "\n" + finalPay2 + "\n" + hireDate2;
var empHeader3 = "\n" + firstName3 + "\n" + lastName3 + "\n"
+ Address3 + "\n" + finalPay3 + "\n" + hireDate3;
var empHeader4 = "\n" + firstName4 + "\n" + lastName4+ "\n"
+ Address4 + "\n" + finalPay4 + "\n" + hireDate4;
var empHeader5 = "\n" + firstName5 + "\n" + lastName5+ "\n"
+ Address5 + "\n" + finalPay5 + "\n" + hireDate5;
//output
console.log(empHeader1);
console.log(empHeader2);
console.log(empHeader3);
console.log(empHeader4);
console.log(empHeader5);
// end of program
|
var keystone = require('keystone');
var Types = keystone.Field.Types;
/**
* Poll Model
* ==========
*/
var Poll = new keystone.List('Poll', {
track: true
});
Poll.schema.set('usePushEach', true);
Poll.add({
name: { type: String, required: true, index: true },
title: { type: String, noedit: true },
// tagLine: { type: Types.Text, index: true, initial: true, required: true },
// postTagLine: {type: Boolean, default: false, initial: true},
//state: { type: Types.Select, options: 'scheduled, active, archived', default: 'scheduled', index: true },
startDate: { type: Types.Date, index: true, initial: true, required: true },
//endDate: { type: Types.Datetime, index: true, initial: true, required: true },
// votes: { type: Types.Relationship, ref: 'PollVote', many: true, unique: true, hidden: true },
option1: {
text: {type: Types.Text, initial: true, index: true, required: true },
tagLine: { type: Types.Text, index: true, initial: true, required: true },
votes: { type: Number, index: true, noedit: true }
},
option2: {
text: {type: Types.Text, initial: true, index: true, required: true },
tagLine: { type: Types.Text, index: true, initial: true, required: true },
votes: { type: Number, index: true, noedit: true }
},
option3: {
text: {type: Types.Text, initial: true, index: true },
tagLine: { type: Types.Text, index: true, initial: true },
votes: { type: Number, index: true, noedit: true }
},
option4: {
text: {type: Types.Text, initial: true, index: true },
tagLine: { type: Types.Text, index: true, initial: true },
votes: { type: Number, index: true, noedit: true }
},
//image: { type: Types.CloudinaryImage },
totalVotes: {type: Number, index: true, noedit: true}
});
Poll.schema.pre('save', async function (next) {
if (this.option1.text) {
}
this.title = this.name;
this.option1.votes = await keystone.list('PollVote').model.count({vote: 'a', poll: this._id, isVerified: true}).exec();
this.option2.votes = await keystone.list('PollVote').model.count({vote: 'b', poll: this._id, isVerified: true}).exec();
this.option3.votes = await keystone.list('PollVote').model.count({vote: 'c', poll: this._id, isVerified: true}).exec();
this.option4.votes = await keystone.list('PollVote').model.count({vote: 'd', poll: this._id, isVerified: true}).exec();
this.totalVotes = this.option1.votes + this.option2.votes + this.option3.votes + this.option4.votes;
next();
})
Poll.relationship({ ref: 'PollVote', path: 'pollVotes', refPath: 'poll' });
/**
* Registration
*/
Poll.defaultSort = '-startDate';
Poll.defaultColumns = 'name, startDate, state, totalVotes';
Poll.register();
|
const Album = require('../models/album');
function albumsIndex(req, res) {
console.log('made it to the controller');
Album
.find()
.exec()
.then(albums => res.status(200).json(albums))
.catch(() => res.status(500).json({ message: 'Something went wrong'}));
}
function albumCreate(req,res) {
req.body.tracks = req.body.tracks.split('|');
Album
.create(req.body)
.then(album => res.status(201).json(album))
.catch(() => res.status(500).json({message: 'Something went wrong'}));
}
function albumShow(req, res) {
console.log('made it to the controller');
Album
.findById(req.params.id)
.then(album => res.json(album))
.catch(() => res.status(500).json({ message: 'Something went wrong'}));
}
function albumUpdate(req, res) {
Album
.findById(req.params.id)
.then(album => album.set(req.body))
.then(album => album.save())
.then(album => res.json(album))
.catch(() => res.status(500).json({ message: 'Something went wrong'}));
}
function albumDelete(req, res) {
Album
.findById(req.params.id)
.then(album => album.remove())
.then(() => res.status(204).end())
.catch(() => res.status(500).json({ message: 'Something went wrong'}));
}
module.exports = {
index: albumsIndex,
create: albumCreate,
show: albumShow,
update: albumUpdate,
delete: albumDelete
};
|
/**
* Dealing with routing, static and middleware
* using express js
*
* @ node.js cmd:
* >npm init
* >npm install express --save
*
*/
//look for express @ node module
var express = require('express');
//declare app as express function
var app = express();
//look for system files
var fs = require('fs');
//declare for port value
var port = process.env.PORT || 3000;
//use property = middleware for this it's style.css
app.use('/assets', express.static(__dirname + '/public'));
//get property with callback function
app.get('/', function(req, res){
fs.createReadStream(__dirname + '/index.htm').pipe(res);
});
//another get
app.get('/:id', function(req, res){
fs.createReadStream(__dirname + '/404.htm').pipe(res);
});
//event emitter, listen
app.listen(port);
|
import '@testing-library/jest-dom/extend-expect'
import { Question, AnswerOptions, Count, Results, CorrectAnswer } from '../components'
import { render, screen } from '@testing-library/react'
describe('Count', () => {
const props = {
currentQuestion: 1,
total: 9
}
const differentProps = {
currentQuestion: 0,
total: 19
}
it('renders the current question count and total, shifted by one index, passed in as props', () => {
render(<Count {...props} />)
expect(screen.getByText(/2/)).toBeInTheDocument();
expect(screen.getByText(/10/)).toBeInTheDocument();
})
it('renders a different question count and total, shifted by one index, passed in as props', () => {
render(<Count {...differentProps} />)
expect(screen.getByText(/1/)).toBeInTheDocument();
expect(screen.getByText(/20/)).toBeInTheDocument();
})
})
describe('Question', () => {
const question = 'Who threw the first brick at the Stonewall riots?';
const newQuestion = 'What cultural event sparked the birth of Chicago House music?';
it('renders a question passed as props', () => {
render(<Question content={question} />)
expect(screen.getByText('Who threw the first brick at the Stonewall riots?')).toBeInTheDocument();
})
it('renders a different question passed as props', () => {
render(<Question content={newQuestion} />)
expect(screen.getByText('What cultural event sparked the birth of Chicago House music?')).toBeInTheDocument();
})
it('renders a question with the correct class name', () => {
render(<Question content={question} />)
expect(screen.getByText('Who threw the first brick at the Stonewall riots?')).toHaveClass('question');
})
})
describe('AnswerOptions', () => {
const props = {
answerOptions: ['Jane Fonda', 'Audre Lorde', 'Harvey Milk', 'Marsha P Johnson'],
userAnswer: '',
showAnswer: false,
setUserAnswer: jest.fn()
}
it('displays answer options passed in as props', () => {
render(<AnswerOptions {...props} />)
expect(screen.getByText('Jane Fonda')).toBeInTheDocument();
expect(screen.getByText('Harvey Milk')).toBeInTheDocument();
expect(screen.getByText('Marsha P Johnson')).toBeInTheDocument();
expect(screen.getByText('Audre Lorde')).toBeInTheDocument();
})
it("displays options as radio inputs", () => {
render(<AnswerOptions {...props} />)
const options = screen.getAllByRole('radio')
expect(options.length).toBe(props.answerOptions.length)
})
it('renders answer options with the correct class name', () => {
render(<AnswerOptions {...props} />)
const options = screen.getAllByRole('radio')
options.forEach(answer => {
expect(answer).toHaveClass('input')
})
})
})
describe('CorrectAnswer', () => {
const answerColor = 'incorrect';
const answer ='Marsha P Johnson';
const nextQuestion = jest.fn()
it('renders the correct answer passed in as props', () => {
render(<CorrectAnswer
answerColor={answerColor}
answer={answer}
nextQuestion={nextQuestion}
/>)
expect(screen.getByText('Marsha P Johnson')).toBeInTheDocument();
expect(screen.getByRole('button')).toHaveTextContent('→');
})
it('renders the correct className based on answerColor', () => {
render(<CorrectAnswer
answerColor={answerColor}
answer={answer}
nextQuestion={nextQuestion}
/>)
expect(screen.getByText('Marsha P Johnson')).toHaveClass('incorrect');
})
})
describe('Results', () => {
let score = 8;
let total = 10;
const resetGame = jest.fn()
it('displays user score out of the total, passed in as props', () => {
render(<Results score={score} resetGame={resetGame} total={total} />)
expect(screen.getByText(`You got 8 out of 10`)).toBeInTheDocument();
})
it('displays a different score and different total, passed in as props', () => {
score = 5;
total = 20;
render(<Results score={score} resetGame={resetGame} total={total} />)
expect(screen.getByText(`You got 5 out of 20`)).toBeInTheDocument();
})
it("displays a 'play again' button", () => {
render(<Results score={score} resetGame={resetGame} total={total} />)
expect(screen.getByRole('button')).toHaveTextContent('Play again');
})
})
|
import React, { Component } from 'react';
import './styles.css';
class Cell extends Component {
constructor(props){
super(props);
this.state ={
hasMine : props.cell.hasMine,
hasFlag : props.cell.hasFlag,
isOpened : props.cell.isOpened,
count: props.cell.count,
game: props.cell.game
};
}
componentWillReceiveProps(nextProps) {
this.setState({
isOpened : nextProps.cell.isOpened,
hasMine : nextProps.cell.hasMine,
hasFlag : nextProps.cell.hasFlag,
count: nextProps.cell.count,
game: nextProps.cell.game
});
};
open = () =>{
this.props.open(this.props.cell);
};
rightClick = (e) =>{
e.preventDefault();
if(!this.state.isOpened){
this.props.rightClick(this.props.cell);
}
};
render (){
const{ hasMine, hasFlag, isOpened, game , count} = this.state;
let cell = () => {
if (isOpened && game === "start") {
if(count === 0){
return(
<div className='isOpened'> </div>
);
}else{
return(
<div className='isOpened'>
<span className={'number' + count}>
{count}
</span>
</div>
);
}
}else if(isOpened && game === "gameOver") {
if(hasMine && hasFlag) {
return (
<div className='foundMine'><span> X </span></div>
);
}else if (hasFlag && !hasMine) {
return (
<div className='notFoundMine'><span> X </span></div>
);
}else if (hasMine && !hasFlag) {
return (
<div className='hasMine'> </div>
);
}else if(!hasFlag && !hasMine && count === 0){
return(
<div className='isOpened'> </div>
);
}else if(!hasFlag && !hasMine && count > 0){
return(
<div className='isOpened'>
<span className={'number' + count}>
{count}
</span>
</div>
);
}
}else if (hasFlag) {
return (
<div className='hasFlag'> </div>
);
}
};
return(
<td onClick={this.open.bind(this)} onContextMenu={this.rightClick} className='cell'>
{cell()}
</td>
);
}
}
export default Cell;
|
import { render } from '@redwoodjs/testing'
import FeedPage from './FeedPage'
describe('FeedPage', () => {
it('renders successfully', () => {
expect(() => {
render(<FeedPage />)
}).not.toThrow()
})
})
|
export default async function handler(req, res) {
const { email } = req.query
const response = await fetch(`https://api.buttondown.email/v1/subscribers`, {
method: 'POST',
headers: {
Authorization: `Token ${process.env.BUTTON_DOWN_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
})
if (response.ok) {
return res.status(201).end()
}
const { email: errors } = await response.json()
return res.status(400).json({ errors })
}
|
const express = require('express');
const router = express.Router();
const initHelpers = require('../dbHelpers/tweetHelpers');
module.exports = (db) => {
const tweetHelpers = initHelpers(db);
router.get(`/:tweetId/`, (req, res) => {
const tweetId = req.params.tweetId;
const userId = req.session.user_id;
// user able to read a particular single tweet
if (userId) {
tweetHelpers.readTweet(tweetId, userId)
.then((tweet) => {
if (tweet) {
res.send(tweet.tweet)
} else {
res.sendStatus(404);
}
})
.catch(err => console.log(err));
}
});
return router;
};
|
import React from 'react';
import { config } from '../config';
import '../styles/Carrousel.scss';
import { MainSection } from './MainSection';
export const Carrousel = ({ data }) => {
return (
<div id="carrousel--tv" className="carousel slide" data-ride="carousel">
<ol className="carousel-indicators">
{data.map((e, i) =>
i === 0 ? (
<li
key={e.id}
data-target="#carrousel--tv"
data-slide-to={i.toString()}
className="active"
></li>
) : (
<li
key={e.id}
data-target="#carrousel--tv"
data-slide-to={i.toString()}
></li>
)
)}
</ol>
<div className="carousel-inner">
{data.map((e, i) =>
i === 0 ? (
<div key={e.id} className="carousel-item active">
<img
src={`${config.api.imgURL}/${config.api.imgagesSizes.poster_sizes[5]}${e.poster_path}`}
alt={`About: ${
e.title || e.original_title || e.name || e.original_name
}`}
/>
<MainSection
title={e.title || e.original_title || e.name || e.original_name}
rating={e.vote_average}
overview={e.overview}
media={e.media_type}
id={e.id}
/>
</div>
) : (
<div key={e.id} className="carousel-item">
<img
src={`${config.api.imgURL}/${config.api.imgagesSizes.poster_sizes[5]}${e.poster_path}`}
alt={`About: ${
e.title || e.original_title || e.name || e.original_name
}`}
/>
<MainSection
title={e.title || e.original_title || e.name || e.original_name}
rating={e.vote_average}
overview={e.overview}
media={e.media_type}
id={e.id}
/>
</div>
)
)}
</div>
{/* Previous & Next Buttons :v */}
<a
className="carousel-control-prev"
href="#carrousel--tv"
role="button"
data-slide="prev"
>
<span className="carousel-control-prev-icon" aria-hidden="true"></span>
<span className="sr-only">Previous</span>
</a>
<a
className="carousel-control-next"
href="#carrousel--tv"
role="button"
data-slide="next"
>
<span className="carousel-control-next-icon" aria-hidden="true"></span>
<span className="sr-only">Next</span>
</a>
</div>
);
};
|
import snapshot from '@compositor/kit-snapshot'
import 'jest-styled-components'
import * as examples from '../examples'
snapshot(examples)
|
import React, {useContext,useState,useEffect} from 'react';
import Parser from 'papaparse';
import {FilterContext} from './Filters.js';
import Painting from './Painting.js';
import PaintingDetails from './PaintingDetails.js';
import FilteringMessage from './FilteringMessage.js'
// This data file is a combination of 2 data files made by /setup.js, create with 'npm run setup'
import rossData from '../ross-data.csv';
export default function Rosses(){
// grad the FilterContext to determine the correct Rosses to show
const {getFilters} = useContext(FilterContext)
// We use a little state here, one for the data (that we only load once) and one for the results (which we fiddle with)
const [getRosses,setRosses] = useState([]);
const [isLoading,setLoading] = useState(true);
const [getFilteredRosses,setFilteredRosses] = useState([])
const [getSelectedPainting,setSelectedPainting] = useState(-1,[])
// Load the rosses
useEffect(()=>{
setLoading(true);
Parser.parse(rossData, {
header: true,
download: true,
skipEmptyLines: true,
complete: function(results) {
setRosses(results.data);
}
});
},[])
// Filter the Rosses
useEffect(()=>{
let filteredRosses = getRosses;
let sortFilterIndex = -1;
if(filteredRosses.length>0){
setLoading(true);
getFilters.forEach((filter,index)=>{
// We're gonna skip sort order till were done filtering
if(filter.category==="Sort"){
sortFilterIndex = index; // keep track of this so we don't have to search for it again in a bit
// Trees and painter aren't simple binary choices, so they get some special handeling
}else if(filter.category==="Trees"){
switch(filter.value){
case 'No Trees':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.tree === "0" && ross.trees === "0" && ross.palm_trees === "0"
})
break;
case 'One Tree':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.tree === "1" && ross.trees === "0" && ross.palm_trees === "0"
})
break;
case 'Many Trees':
filteredRosses = filteredRosses.filter((ross)=>{
return (ross.tree === "1" || ross.trees === "1") && ross.palm_trees === "0"
})
break;
case 'Palm Trees':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.tree === "0" && ross.trees === "0" && ross.palm_trees === "1"
})
break;
default:break;
}
}else if(filter.category==="Painter"){
switch(filter.value){
case 'Bob Ross':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.steve_ross === "0" && ross.diane_andre === "0" && ross.guest === "0"
})
break;
case 'Steve Ross':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.steve_ross === "1"
})
break;
case 'Diane André':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.diane_andre === "1"
})
break;
case 'A Friend of Bob Ross':
filteredRosses = filteredRosses.filter((ross)=>{
return ross.guest === "1" && ross.steve_ross === "0" && ross.diane_andre === "0"
})
break;
default:break;
}
// The bulk of filters are either "1" or "0", as strings :/
}else{
filteredRosses = filteredRosses.filter((ross)=>{
return ross[filter.value] === "1"
})
}
});
// Now we can worry about sorting, if we need to
const sortOrder = sortFilterIndex>=0 ? getFilters[sortFilterIndex].value : "In Airing Order"
switch(sortOrder){
case 'In Airing Order':
filteredRosses.sort((a,b)=>{
return a.episode === b.episode ? 0 : a.episode > b.episode ? 1 : -1;
})
break;
case 'Ordered by Title':
filteredRosses.sort((a,b)=>{
return a.painting_title === b.painting_title ? 0 : a.painting_title > b.painting_title ? 1 : -1;
})
break;
case 'Ordered by Number of Colors':
filteredRosses.sort((a,b)=>{
return a.colors.split(',').length === b.colors.split(',').length ? 0 : a.colors.split(',').length > b.colors.split(',').length ? -1 : 1;
})
break;
default:break;
}
setLoading(false);
}
setFilteredRosses([...filteredRosses]);
},[getRosses,getFilters])
// Component Will Unmount
useEffect(()=>{
return ()=>{
// This was added to have a visual of this working as componentWillUnmount for a demo, it serves no purpose.
// alert('The Rosses.js component is really going to unmount.')
}
},[])
// This compares the position of the open paintings element with those around it and returns the first element we need to place the details before in order to put in between rows
function getInsertBeforeElement(resize=false){
// Before we move the details panel to it's new home we have to reset it to the bottom or else the browser may not reflow the page properly (hiding it will cause it not to reflow if the area is outside the rendering view)
document.getElementById('painting-details').classList.remove('active')
document.getElementById('ross-paintings').after(document.getElementById('painting-details'))
// Lets got the selected images position and do the math to position the arrow diamond
const startingTop = document.querySelector('li.painting.open').getBoundingClientRect().top;
const wrapperLeft = document.getElementById('ross-paintings').getBoundingClientRect().left;
const paintingLeft = document.querySelector('li.painting.open').getBoundingClientRect().left;
const paintingWidth = document.querySelector('li.painting.open').offsetWidth
const conectorWidth = 100; // it's 0px withe with 2 50px borders
// This grabs the starting element based on it having the "open" class and moved the details panel to the appropriate position in the dom
let nextPossibleElement = document.querySelector('li.painting.open').nextSibling
while(nextPossibleElement!==null && nextPossibleElement.getBoundingClientRect().top <= startingTop){
nextPossibleElement = nextPossibleElement.nextSibling
}
// Lets reposition that diamond now
document.getElementById('connecting-bit').style.left = (paintingLeft-wrapperLeft+(paintingWidth/2)-(conectorWidth/2))+'px'
document.getElementById('connecting-bit-outline').style.left = (paintingLeft-wrapperLeft+(paintingWidth/2)-(conectorWidth/2))+'px'
// This gets the element we want to move around for the details and moved it to where we want, then makes it visible again
if(nextPossibleElement!==null){
nextPossibleElement.before(document.getElementById('painting-details'))
}else{ // In case you click on the last row, or I guess something else goes horribly wrong, place it at the
document.querySelector('li.painting:last-child').after(document.getElementById('painting-details'))
}
document.getElementById('painting-details').classList.add('active')
// scroll window into position, smooth scrolling can have weird effects, so jump to it for easier use also it's disorinting when it happens on resize, so not then
if(!resize){
window.scrollTo(0,window.scrollY+document.querySelector('li.painting.open').getBoundingClientRect().top);
}
}
window.onresize = ()=>{
if(document.querySelector('li.painting.open')!==null){
getInsertBeforeElement(true)
}
}
// This will reposition the details block and proceed to figure out what to put in it.
function displayDetails(event){
if(document.querySelector('li.painting.open')!==null){
getInsertBeforeElement()
// Update which painting we are looking at, this will be used to load the content
setSelectedPainting(document.querySelector('li.painting.open').dataset.index)
}else{
document.getElementById('painting-details').classList.remove('active')
setSelectedPainting(-1)
}
}
// The actual output of the Rosses or the loading message thats so fast you'll never see it.
return (<div>
<pre style={{display:'none'}}>
The Rosses, filtered as described above, go here.
Those filters would be:
{JSON.stringify(getFilters,null,3)}
</pre>
<FilteringMessage isFiltering={isLoading} totalCount={getRosses.length} filteredCount={getFilteredRosses.length} />
<ol id="ross-paintings" className="container flex flex-wrap mx-auto my-5">
{getFilteredRosses.map((ross,index)=>{
return (<Painting key={ross.episode} paintingIndex={index} details={ross} displayDetails={displayDetails}/>)
})}
<li id="painting-details" className="relative text-white w-full">
<div id="connecting-bit" className="absolute"> </div>
<div id="connecting-bit-outline" className="absolute"> </div>
<div id="details-wrapper" className="bg-black p-2 mx-2 my-1 relative">
<PaintingDetails paintingIndex={getSelectedPainting} details={getRosses[getSelectedPainting]} />
</div>
</li>
</ol>
</div>);
}
|
exports.login = require('./login');
exports.newpost = require('./newpost');
exports.welcome = require('./welcome');
exports.signup = require('./signup');
exports.permalink = require('./permalink');
exports.logout = require('./logout');
exports.users = require('./users');
exports.user = require('./user');
exports.manage = require('./manage');
exports.morePosts = require('./morePosts');
exports.feed = require('./feed');
exports.password = require('./password');
var path = require('path');
var fs = require('fs');
global.APP_DIR = path.dirname(require.main.filename);
global.INDEX_HTML = '';
/*
* GET home page.
*/
exports.index = function(req, res){
req.session.morePosts = 0;
if (typeof INDEX_HTML !== 'undefined' && INDEX_HTML !== '') {
res.send(INDEX_HTML);
} else {
fs.stat('html/index.html', function(err, stat) {
if (err === null) {
res.sendfile('html/index.html', {root: APP_DIR});
fs.readFile(APP_DIR + '/html/index.html', 'utf8', function(err, html) {
INDEX_HTML = html;
});
} else {
index_html = RERENDER_INDEX(res);
res.send(index_html);
return;
}
});
}
};
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'gi'), replacement);
};
global.ALLOW_FORMATTING = function(html) {
// support bolding, italicizing, underlining, strikethrough text, and hyperlinks
html = html.replaceAll('<b>', '<b>').replaceAll('</b>', '</b>');
html = html.replaceAll('<i>', '<i>').replaceAll('</i>', '</i>');
html = html.replaceAll('<u>', '<u>').replaceAll('</u>', '</u>');
html = html.replaceAll('<strike>', '<strike>') .replaceAll('</strike>', '</strike>');
html = html.replaceAll('<link>(.*)<\/link>', '<u><a href="$1">$1</a></u>');
return html;
};
global.RERENDER_INDEX = function(res) {
POSTS.find().limit(10).sort({date:-1}, function(error, docs){
if (error) {
console.log('error during rerender_index:', error);
}
res.render('index', {'name': 'Everyone', 'docs': docs}, function(err, html) {
if (err) {
console.log('error duing index render:', err);
}
html = ALLOW_FORMATTING(html);
INDEX_HTML = html;
var fs = require('fs');
fs.writeFile(APP_DIR + '/html/index.html', html, function(err) {
if(err) {
return console.log(err);
}
});
return html;
});
});
};
|
appModule.controller("ProjectsController", function($scope){
$scope.projects = [
{
id: 1,
title: "Business Process Modeling and Deployment Framework",
tech: "Java, AngularJS, Spring, MySQL",
description: `<ul>
<li>Responsible for managing the full software stack - AngularJS, Spring and MySQL</li>
<li>Literature study, design and implementation of dynamic Business Process Model (BPM) designing web application adhering to the BPMN 2.0 standard using Activiti BPMN engine</li>
<li>Enabled configurable connections to remote machines to run business process models remotely</li>
<li>Worked on implementing custom activities to run programs (R, Python, Shell) within the business process models. Wrote behaviour classes, XML definitions and integration models for these activities</li>
<li>Implemented file system workspace which enabled activities to use resources and scripts files stored both locally and remotely. Implemented the required features for workspace such as web sockets, queues, FTP pipelines etc</li>
<li>Implemented versioning of workspace files using git</li>
<li>Implemented validation of BPMN elements and thus reducing the chances of human errors while modeling.</li>
<li>This helped the users save time as the bugs in their BP models could be pointed out at design phase rather than deployment phase</li>
</ul>`
},{
id:2,
title:"Human Motion Tracking at Scale",
tech:"AngularJS, Python, Java, HTML5, Tensorflow, Dask, PostgreSQL, Redis, RabbitMQ",
description:`<ul>
Full stack developer in Mu Sigma's scalable deep learning based human detection and tracking platform<br>
Responsible for:
<ul>
<li>Design and implementation of cloud friendly and scalable architecture of this platform</li>
<li>Optimizing the user experience by design and implementation of user friendly interface</li>
<li>Back end development, implementation of ML algorithms for computation</li>
<li>Implementing business process flows using BPMN platform</li>
<li>Build process and deployment automation</li>
</ul>
Contributed in:
<ul>
<li>Reducing the overall time taken for training human detection model (End to End People Detection in</li>
<li>Crowded Scenes - ReInspect) using distributed computing features of Tensorflow</li>
<li>Enabling the code to utilize multiple CPU cores and graphic processors for parallel processing</li>
<li>Distributing Multi Hypothesis Tracking (MHT) python code processing over multiple machines using</li>
<li>Dask Distributed to enable real time human motion tracking</li>
<li>Implementation of MHT – Revisited algorithm in Python</li>
</ul>
</ul>`
}, {
id:3,
title:"Real Time Algorithmic Trading Engine",
tech:"Scala, Java, Python, R, Apache Flink, HTML5, PostgreSQL",
description:`<ul>
<li>Design and development of real time algorithmic trading engine which can use mathematical algorithms to place a trade order on the New York Stock Exchange</li>
<li>Development of a user interface to manage and visualize ticker data and the analysis. Design and development of a back end to support the architecture of this UI</li>
<li>Implementation of convergent cross mapping (CCM) algorithm to detect causality and the relationship between pairs co-integrated of tickers. Prediction of stock prices with linear modeling on causal pairs of stocks</li>
<li>Implementation of Recurrence Quantification Analysis over ticker data to determine recurring behavior of stock prices and to place trade orders accordingly</li>
<li>Research on determining change points in stock prices over time using R packages. Implementation of dummy variable regression method to determine change points</li>
</ul>`
}, {
id:4,
title:"Collaborative Development Platform (CoDevelop)",
tech:"HTML5, PHP, MySQL",
description:`CoDevelop is a SaaS based project developed on HTML5, PHP and MySQL which gives the facility of real time collaboration to software developers. Developers can collaborate over a project on the cloud and work on it as if they are working together.
<ul>
<li>Did full stack development for the project</li>
<li>Designed and developed the user interface using bootstrap framework</li>
<li>Developed back end operations of MySQL database</li>
<li>Developed the server side application using PHP in an MVC based approach</li>
</ul>`
}, {
id:5,
title:"Vehicle Sharing Android Application (VehShare)",
tech:"Android SDK, PHP, MySQL",
description:`An Android application which helps the users to find people to travel with, and thus helping them to share the fuel and meet new people. Users can register journeys or find other registered journeys and then contact each other to plan a journey together.
<ul>
<li>Designed the user interface for the app</li>
<li>Did front and development using the Android SDK and Java2SE</li>
<li>Developed web interfaces for interaction of the app with remote database (JSON parsing)</li>
<li>Designed the back end architecture of the app and implemented on MySQL database</li>
</ul>`
}
]
});
|
module.exports = {
fetchAllUsers(success){
$.ajax({
url: "api/users",
success(resp){
success(resp);
}
});
},
fetchSingleUser(id, success){
$.ajax({
url: `api/users/${id}`,
success(resp){
success(resp);
}
});
}
};
|
(function(){
'use strict';
var baseUrl = 'http://dtapi.local/';
angular.module('app')
.constant('appConstants', {
logInURL: baseUrl + 'login/index',
logOutURL: baseUrl + 'login/logout',
isLoggedURL: baseUrl + 'login/isLogged',
getSubjects: baseUrl + 'subject/getRecords',
getOneSubject: baseUrl + 'subject/getRecords/', // + id of subject
getRangeOfSubjects: baseUrl + 'subject/getRecordsRange',
countSubjects: baseUrl + 'subject/countRecords',
addSubject: baseUrl + 'subject/insertData',
editSubject: baseUrl + 'subject/update/', // + id of subject
delSubject: baseUrl + 'subject/del/', // + id of subject
getScheduleForGroup: baseUrl + 'timeTable/getTimeTablesForGroup/', // + id of group
getScheduleForSubject: baseUrl + 'timeTable/getTimeTablesForSubject/', // + id of subject
deleteSchedule: baseUrl + 'timeTable/del/', // + id of timeTable
addSchedule: baseUrl + 'timeTable/insertData',
editSchedule: baseUrl + 'timeTable/update/', // + id of timeTable
getTests: baseUrl + 'test/getRecords',
getTestBySubjectId: baseUrl + 'test/getTestsBySubject/',
countTests: baseUrl + 'test/countRecords',
addTest: baseUrl + 'test/insertData',
editTest: baseUrl + 'test/update/',
delTest: baseUrl + 'test/del/',
getTestDetailsByTest: baseUrl + 'testDetail/getTestDetailsByTest/', // + id of test
addTestDetails: baseUrl + 'testDetail/insertData',
editTestDetails: baseUrl + 'testDetail/update/', // + id of testDetails
deleteTestDetails: baseUrl + 'testDetail/del/', // + id of testDetails
getQuestionById:baseUrl + 'question/getRecords/', // + id of question,
getQuestionsRangeByTest: baseUrl + 'question/getRecordsRangeByTest/', // + id of test
countQuestionsByTest: baseUrl + 'question/countRecordsByTest/', // + id of test
delQuestions: baseUrl + 'question/del/', // + id of question
addQuestion: baseUrl + 'question/insertData',
editQuestion: baseUrl + 'question/update/',
getQuestionsByLevelRand: baseUrl + 'question/getQuestionsByLevelRand/', // + id
getAnswersByQuestionID: baseUrl + '/answer/getAnswersByQuestion/', // get question id
deleteAnswers: baseUrl + 'answer/del/', // + id of answer
getQuestionByQuestionID: baseUrl + 'question/getRecords/', // + question id
addAnswer: baseUrl + 'answer/insertData',
editAnswer: baseUrl + 'answer/update/',
getSpecialities: baseUrl + 'speciality/getRecords',
getRangeOfSpecialities: baseUrl + 'speciality/getRecordsRange',
countSpecialities: baseUrl + 'speciality/countRecords',
addSpeciality: baseUrl + 'speciality/insertData',
editSpeciality: baseUrl + 'speciality/update/',
delSpeciality: baseUrl + 'speciality/del/',
getFaculties: baseUrl + 'faculty/getRecords',
getRangeOfFaculties: baseUrl + 'faculty/getRecordsRange',
countFaculties: baseUrl + 'faculty/countRecords',
addFaculty: baseUrl + 'faculty/insertData',
editFaculty: baseUrl + 'faculty/update/',
delFaculty: baseUrl + 'faculty/del/',
getGroups: baseUrl + 'group/getRecords',
getRangeOfGroups: baseUrl + 'group/getRecordsRange',
getOneGroup: baseUrl + 'group/getRecords/', // + id of group
countGroups: baseUrl + 'group/countRecords',
addGroup: baseUrl + 'group/insertData',
editGroup: baseUrl + 'group/update/', // + id of group
delGroup: baseUrl + 'group/del/', // + id of group
getGroupsBySpeciality: baseUrl + 'group/getGroupsBySpeciality/', // + id of speciality
getGroupsByFaculty: baseUrl + 'group/getGroupsByFaculty/', // + id of faculty
getAdmins: baseUrl + 'AdminUser/getRecords',
editAdmins: '/AdminUser/update/',
delAdmins: '/AdminUser/del/',
addAdmins:'/AdminUser/insertData',
getStudents: baseUrl + 'student/getRecords',
countStudents: baseUrl + 'student/countRecords',
editStudent: baseUrl + 'student/update/',
delStudent: baseUrl + 'student/del/',
addStudents: baseUrl + 'student/insertData',
getStudentsByGroupId:baseUrl + 'student/getStudentsByGroup/',
saveTestPlayerData: baseUrl + 'TestPlayer/saveData/',
getTestPlayerData: baseUrl + 'TestPlayer/getData/',
resetSessionData: baseUrl + 'TestPlayer/resetSessionData/',
getServerTime: baseUrl + 'TestPlayer/getTimeStamp',
getEndTime: baseUrl + 'TestPlayer/getEndTime/',
saveEndTime: baseUrl + 'TestPlayer/saveEndTime/',
saveResult: baseUrl + 'result/insertData/',
getAnswersListByQuestionId: baseUrl + 'SAnswer/getAnswersByQuestion/',
checkAnswers: baseUrl + 'SAnswer/checkAnswers/',
addTestResult: baseUrl + 'Result/insertData/',
delTestResult: baseUrl + 'Result/del/', // + id of session
getTestResultByStudentId: baseUrl + 'Result/getRecordsbyStudent/', // + id of student
countTestPassesByStudent: baseUrl + 'result/countTestPassesByStudent/', // + id`s of student and test
startTestInfoInLog: baseUrl + 'log/startTest/', // + <user_id>/<test_id>
maxNumberOfStudents:(localStorage.NumberOfStudents)?JSON.parse(localStorage.NumberOfStudents):200,
numberOfTestsLevels:(localStorage.NumberOfTestLevels)?JSON.parse(localStorage.NumberOfTestLevels):5,
numberOfEntitiesPerPage:(localStorage.NumberOfEntities)?JSON.parse(localStorage.NumberOfEntities):5
})
.constant("defineUser", {
admin: "admin",
user: "student"
});
}());
|
// @flow strict
import opentelemetry from '@opentelemetry/api';
import { GraphQLInstrumentation } from '@opentelemetry/instrumentation-graphql';
import { LogLevel } from '@opentelemetry/core';
import { NodeTracerProvider } from '@opentelemetry/node';
import { ConsoleSpanExporter, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/tracing';
const provider = new NodeTracerProvider({
logLevel: LogLevel.WARN,
// plugins: {
// dns: { enabled: false, path: '@opentelemetry/plugin-dns' },
// http: { enabled: false, path: '@opentelemetry/plugin-http' },
// https: { enabled: false, path: '@opentelemetry/plugin-https' },
// pg: { enabled: false, path: '@opentelemetry/plugin-pg' },
// 'pg-pool': { enabled: false, path: '@opentelemetry/plugin-pg-pool' },
// grpc: { enabled: false, path: '@opentelemetry/plugin-grpc' },
// 'grpc-js': { enabled: false, path: '@opentelemetry/plugin-grpc-js' },
// koa: {
// enabled: false,
// // You may use a package name or absolute path to the file.
// path: '@opentelemetry/koa-instrumentation',
// },
// },
});
const graphQLInstrumentation = new GraphQLInstrumentation({
// allowAttributes: true,
// depth: 2,
// mergeItems: true,
});
graphQLInstrumentation.setTracerProvider(provider);
graphQLInstrumentation.enable();
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
// Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
provider.register();
const tracer = opentelemetry.trace;
export default (): $FlowFixMe => {
return tracer;
};
|
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['dist'],
inline: {
dev: {
options: {
cssmin: false,
uglify: false
},
src: 'src/index.html',
dest: 'dist/index.html'
},
dist: {
options: {
cssmin: true,
uglify: true
},
src: 'src/index.html',
dest: 'dist/index.html'
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'dist/index.html'
}
},
},
watch: {
app: {
files: ['src/index.html', 'src/scripts/main.js', 'src/styles/main.scss'],
options: {
livereload: true
},
tasks: ["build"]
}
},
connect: {
dist: {
options: {
port: 9000,
base: 'dist/'
}
}
},
targethtml: {
// Remove livereload and its friends
prod: {
files: {
'dist/index.html': 'dist/index.html'
}
}
},
copy: {
main: {
expand: true,
flatten: true,
src: ['src/images/*'],
dest: 'dist/images/'
},
CNAME: {
expand: true,
flatten: true,
src: ['src/CNAME'],
dest: 'dist/'
}
},
sass: {
dist: {
files: {
'src/styles/main.css': 'src/styles/main.scss'
}
}
},
'gh-pages': {
options: {
base: 'dist',
branch: 'gh-pages',
repo: 'https://github.com/initiummedia/legco_web2.git'
},
src: '**/*'
},
rsync: {
options: {
args: ["--verbose"],
exclude: [".git*","*.scss","node_modules"],
recursive: true
},
showcase: {
options: {
src: "./dist/",
dest: "/home/vagrant/web/legco_web2",
host: "showcase",
delete: true // Careful this option could cause data loss, read the docs!
}
}
},
execute: {
opencc: {
src: ['utils/s2t.js']
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-inline');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-targethtml');
grunt.loadNpmTasks('grunt-rsync');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('build', ['sass', 'clean', 'inline:dev', 'copy']);
grunt.registerTask('serve', ['connect:dist', 'watch']);
grunt.registerTask('deploy', ['sass', 'clean', 'inline:dist', 'copy', 'targethtml:prod', 'htmlmin', 'execute',
'gh-pages', 'rsync']);
};
|
// const logger = require('./loggerService');
const qs = require('../libs/qs');
module.exports = {
// 非 tabBar
toPage: function (page, isTab) {
if (isTab) {
wx.switchTab(page);
return;
}
wx.navigateTo(page);
},
backPage: function () {
wx.navigateBack();
},
qsStringify: function (data) {
return qs.stringify(data)
},
qsParse: (data) => {
return qs.parse(data, {
ignoreQueryPrefix: true
})
},
showToast: (options) => {
wx.showToast({
title: typeof (options) == 'string' ? options : options.title || options.data || options.message || options.err,
icon: options.icon || 'none',
image: options.image,
duration: options.duration || 1500,
mask: options.mask,
success: options.success,
fail: options.fail,
complete: options.complete
})
},
// async 同步
saveStorage(key, data, async) {
if (!async) {
wx.setStorageSync(key, data);
} else {
wx.setStorage({
key: key,
data: data
});
}
},
// async 同步
getStorage(key, async) {
if (!async) {
return wx.getStorageSync(key);
} else {
return wx.getStorage(key);
}
},
getSetting() {
return new Promise((resolve, reject) => {
wx.getSetting({
success: (res) => {
resolve(res);
},
fail: (error) => {
reject(reject);
}
})
});
},
chooseImage: function () {
return new Promise((resolve, reject) => {
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// res.tempFiles.path/tempFiles.size
resolve(res.tempFilePaths);
},
fail: function (err) {
reject(err);
}
})
})
},
showModal: function (options) {
return new Promise((resolve, reject) => {
wx.showModal({
title: options.title || '标题',
content: options.content || '',
confirmText: options.confirmText || '确定',
cancelText: options.cancelText || '取消',
showCancel: options.showCancel,
success: function (res) {
if (res.confirm) {
resolve(res);
} else {
reject(res);
}
}
});
})
}
}
|
// Code MovieReviews Here
import React from 'react'
import testReviews from './test-reviews.js'
const MovieReviews = () => {
return(
<div className='review-list'>
{testReviews.map(review =>
<div className='review' key={review.display_title}>
<p>{review.display_title}</p>
<p>{review.summary_short}</p>
</div>)}
</div>
)
}
export default MovieReviews
|
//Defines a mongoDB collection
function Collection(id, d) {
this.id = id; //Collection name
this.database = d; //The database containing this collection
this.shards; //The list of shards across which this collection is partitioned, or undefined if this collection is not sharded
this.alerts = new MaxHeap(function(alert){return alert.getPriority();});; //The alerts for this server sorted by priority
}
//Getters
Collection.prototype.getID = function() {
return this.id;
}
Collection.prototype.getDatabase = function() {
return this.database;
}
Collection.prototype.getShards = function() {
return this.shards;
}
Collection.prototype.getAlerts = function() {
return this.alerts;
}
//Generates a list of alerts for this collection
Collection.prototype.setAlerts = function() {
//No current alerts for databases
}
//Adds a collection to this database
Collection.prototype.addShard = function(shard) {
if (!this.shards) {
this.shards = new Array();
}
this.shards.push(shard);
}
|
module.exports = 'I m lib';
|
editFunction = function (row, store) {
var editUserFrm = Ext.create('Ext.form.Panel', {
id: 'editUserFrm',
frame: true,
plain: true,
layout: 'anchor',
labelWidth: 40,
url: '/Vote/SaveVoteMessage',
defaults: { anchor: "95%", msgTarget: "side" },
items: [
{
fieldLabel: '留言編號',
xtype: 'textfield',
id: 'message_id',
name: 'message_id',
hidden: true
},
{
xtype: 'combobox',
editable: false,
fieldLabel: "文章標題",
labelWidth: 70,
queryMode: 'remote',//remote//local
// queryMode: 'local',
id: 'article_id',
store: VoteArticleStore,
displayField: 'article_title',
valueField: 'article_id',
emptyText: '请选择',
lastQuery: '',
triggerAction: 'all',
allowBlank: false,
listeners: {
// delete the previous query in the beforequery event or set
// combo.lastQuery = null (this will reload the store the next time it expands)
beforequery: function (qe) {
VoteArticleStore.load();
}
}
},
{
xtype: 'textareafield',
name: 'message_content',
id: 'message_content',
labelWidth: 70,
maxLength:200,
maxLengthText:'輸入文字在200字以內',
allowBlank: false,
submitValue: true,
fieldLabel: '回覆內容 '
}
//,
// {
// xtype: 'radiogroup',
// fieldLabel: "活動狀態",
// id: 'message_status',
// name: 'message_status',
// columns: 2,
// defaults: {
// flex: 1,
// name: 'status'
// },
// items: [
// {
// boxLabel: "啟用", id: 'yes', inputValue: '1', checked: true
// },
// {
// boxLabel: "禁用", id: 'no', inputValue: '0'
// }
// ],
// }
],
buttons: [{
formBind: true,
disabled: true,
text: SAVE,
handler: function () {
var form = this.up('form').getForm();
if (form.isValid()) {
var myMask = new Ext.LoadMask(Ext.getBody(), { msg: 'Loading...' });
form.submit({
params: {
message_id: Ext.getCmp('message_id').getValue(),
article_id: Ext.getCmp('article_id').getValue(),
message_content: Ext.htmlEncode(Ext.getCmp('message_content').getValue())
//,
//message_status: Ext.htmlEncode(Ext.getCmp('message_status').getValue().status)
},
success: function (form, action) {
var result = Ext.decode(action.response.responseText);
myMask.hide();
if (result.success == "true") {
Ext.Msg.alert("提示信息", result.msg);
editUserWin.close();
VoteMessageStore.load();
}
else {
Ext.Msg.alert("提示信息", result.msg);
}
},
failure: function (form, action) {
myMask.hide();
Ext.Msg.alert("提示信息", result.msg);
}
});
}
}
}]
});
var editUserWin = Ext.create('Ext.window.Window', {
id: 'editUserWin',
width: 400,
title: "留言內容",
iconCls: 'icon-user-edit',
iconCls: row ? "icon-user-edit" : "icon-user-add",
layout: 'fit',
constrain: true,
closeAction: 'destroy',
modal: true,
closable: false,
items: [
editUserFrm
],
labelWidth: 60,
bodyStyle: 'padding:5px 5px 5px 5px',
tools: [
{
type: 'close',
qtip: "關閉",
handler: function (event, toolEl, panel) {
Ext.MessageBox.confirm("提示", "確定關閉?", function (btn) {
if (btn == "yes") {
Ext.getCmp('editUserWin').destroy();
VoteMessageStore.destroy();
}
else {
return false;
}
});
}
}
],
listeners: {
'show': function () {
if (row) {
editUserFrm.getForm().loadRecord(row); //如果是編輯的話
}
else {
editUserFrm.getForm().reset(); //如果是新增的話
}
}
}
});
//if (row != null) {
// if (!row.data.message_status) {
// Ext.getCmp('no').setValue(true);
// }
// else {
// Ext.getCmp('yes').setValue(true);
// }
//}
editUserWin.show();
}
|
var class_disable_decal_meshes =
[
[ "meshSetUpDelay", "class_disable_decal_meshes.html#a289f2162be36ac4e9614acd7d243d4ff", null ]
];
|
var Search = {
input: document.querySelector('#search-input'),
menu: document.querySelector('.searchMenu'),
navbar : document.querySelector('.navbar '),
start(){
this.event();
},
event(){
this.input.addEventListener('input', (evt) => {
if(evt.target.value.length > 2){
this.show();
} else {
this.hide();
}
});
this.navbar .addEventListener('mouseleave', (evt) => {
this.hide();
});
this.menu.addEventListener('mouseleave', (evt) => {
this.hide();
});
},
show(){
if(document.body.clientWidth > 995){
this.menu.classList.add('show')
}
},
hide(){
this.menu.classList.remove('show')
}
}
var FilmList = {
btn: document.querySelector('#filmListBtn'),
list: document.querySelector('#filmList'),
status: false,
start(){
this.event();
},
event(){
this.btn.addEventListener('click', () => {
this.status = !this.status;
this.showHide();
})
},
showHide(){
if(document.body.clientWidth > 995) {
this.list.classList.toggle('show');
this.btn.classList.toggle('show');
} else {
this.list.classList.remove('show');
this.btn.classList.remove('show');
}
}
};
document.addEventListener("DOMContentLoaded", function () {
Search.start();
FilmList.start();
});
|
import { combineReducers } from 'redux'
import TodoListReducer from './todo_list_reducer.js'
import UserReducer from './user_reducer.js'
import ListsReducer from './lists_reducer.js'
import ItemReducer from './item_reducer.js'
//Actions describe the fact that something happened, but don't specify how the application's state changes in response.
//This is the job of reducers.
//All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys,
// and combining their results into a single object again. Does not return obj if its reducers do not change state.
const allReducers = combineReducers({
todoList: TodoListReducer,
listOfLists: ListsReducer,
item: ItemReducer,
user: UserReducer
})
export default allReducers
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.