text
stringlengths
7
3.69M
var express = require('express') var router = express.Router() var lottoSpecs = require('../../lottoSpecs.js') router.get('/', (req, res) => { //res.json(lottoSpecs(req.query.name)) res.send(true) }) module.exports = router
var imglist = document.getElementById("imglist"); var imgs = document.getElementsByClassName("img"); var imgdetail = document.getElementById("imgdetail"); var contain = document.getElementById("imgs"); var details = document.getElementById("details"); var close = document.getElementsByTagName("span")[0]; var pre = document.getElementById("pre"); var next = document.getElementById("next"); var text = document.getElementById("text"); var num = document.getElementById("num"); var len = imgs.length; var currentindex; close.onclick = function(){ contain.style.display = "block"; details.style.display = "none"; } for(var i =0;i<len;i++){ (function(val){ imgs[val].onclick = function(){ slide(val); imgdetail.className ="bigimg"; contain.style.display = "none"; details.style.display = "block"; currentindex = val; if(imglist.childNodes.length==1){ for(var i = 0;i<len;i++){ var img = document.createElement("img"); img.src = imgs[i].src; img.className = "img"; imglist.appendChild(img); (function(n){ img.onclick = function(){ slide(n); } })(i); } } } })(i); } function slide(index){ if(index==len){ currentindex = 0; } else if(index < 0){ currentindex = len-1; } else{ currentindex = index; } num.innerHTML = (index+1)+"/"+len ; imgdetail.src = imgs[currentindex].src; text.innerHTML = imgs[currentindex].alt; } pre.onclick = function(){ slide(--currentindex); } next.onclick =function (){ slide(++currentindex); }
const path = require('path'); const { merge } = require('webpack-merge'); const base = require('../../webpack.config.base'); const commonId = require('../../webpack-plugin/commonId.js'); const {url, name} = require('./config'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = merge( { entry: './index.js', output: { path: path.join(__dirname, './lib'), filename: '[name][hash].js', }, plugins: [new (commonId(url, name))(), new CleanWebpackPlugin(),], externals: ['@feitu/imis'] }, base, );
/** * Author: raven * Date: 2015/01/19 14:40 * Converting excel files to word files, using Windows JScript. */ var fso = new ActiveXObject("Scripting.FileSystemObject"); var curDir = "."; var fileArr = []; listExcelFiles(curDir); convertExcelToWord(fileArr); function listExcelFiles(dir) { var folder = fso.GetFolder(dir); var fileEnumerator = new Enumerator(folder.Files); while (!fileEnumerator.atEnd()) { var file = fileEnumerator.item(); var ext = fso.GetExtensionName(file); var fileInfo = {}; if (ext == "xls" || ext == "xlsx") { fileArr.push(file.Path); } fileEnumerator.moveNext() } var folderEnumerator = new Enumerator(folder.SubFolders); while (!folderEnumerator.atEnd()) { var folder = folderEnumerator.item(); listExcelFiles(folder.Path); folderEnumerator.moveNext(); } } function convertExcelToWord(fileList) { var length = fileList.length; if (length == 0) { return; } var excelApp = new ActiveXObject("Excel.Application"); excelApp.Visible = true; excelApp.DisplayAlerts = false; var wordApp = new ActiveXObject("Word.Application"); wordApp.Visible = true; var doc; var docRange; var sheetCount; var sheet; for (var i = 0; i < length; i ++) { var excelPath = fileList[i]; var workbook = excelApp.Workbooks.Open(excelPath); doc = wordApp.Documents.Add(); docRange = doc.Range(); var docPath = excelPath.substr(0, excelPath.length - 4) + ".doc"; sheetCount = workbook.WorkSheets.Count; for(var j = 0; j< sheetCount; j ++) { sheet = workbook.WorkSheets(j + 1); sheet.UsedRange.Copy(); docRange.PasteExcelTable(false, true, false); docRange.Collapse(0); docRange.InsertParagraphAfter(); docRange.Collapse(0); } doc.SaveAs(docPath); doc.Close(); workbook.Close(); } excelApp.Quit(); wordApp.Quit(); }
function ProjectAnalyseCtrl($scope, $http, $localStorage, $modal, $stateParams, SweetAlert, userPhotoService, Constants) { $scope.projectId = $stateParams.id; $scope.CashFlowChartTypeReport = true; var today = new Date(); $scope.CategoryFilter = { Account: { Id: null, }, FilterDate: new Date(), FilterMonth: today.getMonth(), FilterYear: today.getFullYear(), }; $scope.AccountFilter = { FilterDate: new Date(), FilterMonth: today.getMonth(), FilterYear: today.getFullYear(), }; $scope.SelectedCategory = null; $scope.Categories = []; $scope.Accounts = []; $scope.AnalyseData = {}; $scope.onload = function () { $scope.LoadProjectAnalyseInformation($scope.projectId); $scope.LoadTransactionSummaryByMonthYear($scope.projectId); $scope.loadProjectCategories($scope.projectId); $scope.loadProjectAccounts($scope.projectId); $scope.loadJarsAnalyseData($scope.projectId); } $scope.chartByAccountObject = {}; $scope.chartByAccountObject.type = "PieChart"; $scope.chartByAccountObject.options = { } $scope.chartByAccountObject.data = { "cols": [ { id: "t", label: "Day", type: "string" }, { id: "s", label: "Income", type: "number" }], "rows": [] }; $scope.chartByCategoryIncomeObject = {}; $scope.chartByCategoryIncomeObject.type = "PieChart"; $scope.chartByCategoryIncomeObject.options = { title: 'Income', }; $scope.chartByCategoryIncomeObject.data = { "cols": [ { id: "t", label: "Day", type: "string" }, { id: "s", label: "Balance", type: "number" }], "rows": [] }; $scope.chartByCategoryExpenseObject = {}; $scope.chartByCategoryExpenseObject.type = "PieChart"; $scope.chartByCategoryExpenseObject.options = { title: 'Expense', }; $scope.chartByCategoryExpenseObject.data = { "cols": [ { id: "t", label: "Day", type: "string" }, { id: "s", label: "Balance", type: "number" }], "rows": [] }; $scope.chartObject = {}; //$scope.chartObject.type = "LineChart"; $scope.chartObject.type = "google.charts.Bar"; $scope.chartObject.options = { title: 'Cashflow & Forecast', colors: ['#388E3C', '#FF9800', '#5D4037'], // Gives each series an axis that matches the vAxes number below. series: { 0: { targetAxisIndex: 0 } }, hAxis: { ticks: [], format: 'MM/yyy' } }; $scope.chartObject.data = { "cols": [ { id: "1", label: "", type: "string" }, { id: "2", label: "Income", type: "number" }, { id: "3", label: "Expense", type: "number" }, { id: "4", label: "Balance", type: "number" }], "rows": [] }; $scope.chartCategoryBudget = {}; //$scope.chartCategoryBudget.type = "LineChart"; $scope.chartCategoryBudget.type = "google.charts.Bar"; $scope.chartCategoryBudget.options = { title: 'Category Budget', colors: ['#607D8B', '#BDBDBD'], // Gives each series an axis that matches the vAxes number below. series: { 0: { targetAxisIndex: 0 } }, hAxis: { ticks: [], format: 'MM/yyy' } }; $scope.chartCategoryBudget.data = { "cols": [ { id: "1", label: "", type: "string" }, { id: "2", label: "Balance", type: "number" }, { id: "4", label: "Budget", type: "number" }], "rows": [] }; $scope.TotalMonthlyIncome = 0; $scope.SelectedMonthYearForJARSAnalyse = new Date(); $scope.chartJarsAnalyseObject = {}; $scope.chartJarsAnalyseObject.type = "google.charts.Bar"; $scope.chartJarsAnalyseObject.options = { }; $scope.chartJarsAnalyseObject.data = { "cols": [ { id: "t", label: "Day", type: "string" }, { id: "s", label: "Balance", type: "number" }], "rows": [] }; $scope.changeCashFlowChartType = function(isReportType) { $scope.CashFlowChartTypeReport = isReportType; $scope.LoadTransactionSummaryByMonthYear($scope.projectId); } $scope.loadProjectCategories = function(projectId) { $http.get(Constants.WebApi.Project.GetAvailableCategories, { params: { projectId: projectId } }).then(function (response) { // this callback will be called asynchronously // when the response is available $scope.Categories = response.data; }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Category Failed!", type: "warning" }); }); } $scope.loadProjectAccounts = function (projectId) { $http.get(Constants.WebApi.Project.GetAccounts, { params: { projectId: projectId } }).then(function (response) { // this callback will be called asynchronously // when the response is available $scope.Accounts = response.data.Accounts; }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Project Account Failed!", type: "warning" }); }); } $scope.LoadProjectAnalyseInformation = function (projectId) { var transactionFilter = { ProjectId: projectId }; $http.post(Constants.WebApi.Project.LoadProjectAnalyseInformation, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available var analysingData = response.data; $scope.AnalyseData = analysingData; }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Analyse Information Failed!", type: "warning" }); }); } $scope.LoadTransactionSummaryByMonthYear = function (projectId) { var transactionFilter = { ProjectId: projectId, FilterId: 1, IsIncome: true, IsUpcoming: true, IsUnclearOnly: ($scope.CashFlowChartTypeReport? false: true), Category: null, Account: null, FromDate: new Date(2016, 1), EndDate: new Date(2017, 0), }; $http.post(Constants.WebApi.Project.LoadTransactionSummaryByMonthYear, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available var transSums = response.data; $scope.chartObject.data.rows = []; //$scope.chartObject.options.hAxis.ticks = []; for(var i = 0;i < transSums.length; i ++) { var hAxisCol = transSums[i].Title; //$scope.chartObject.options.hAxis.ticks.push(hAxisCol); var val = [ { v: hAxisCol }, { v: transSums[i].Income }, { v: transSums[i].Expense }, { v: transSums[i].Balance }, ]; var c = { c: val }; $scope.chartObject.data.rows.push(c); } }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Summary Failed!", type: "warning" }); }); } $scope.LoadTransactionSummaryByCategory = function (projectId) { var fromDate = today; fromDate.setYear($scope.CategoryFilter.FilterYear); var endDate = fromDate; if ($scope.CategoryFilter.FilterMonth > 0) { fromDate.setFullYear($scope.CategoryFilter.FilterYear, $scope.CategoryFilter.FilterMonth, 1); // first day of month endDate = new Date(); endDate.setFullYear(fromDate.getFullYear(), fromDate.getMonth() + 1, 0); // last day of month } var transactionFilter = { ProjectId: projectId, Account: { Id: $scope.CategoryFilter.Account.Id, }, FromDate: fromDate, EndDate: endDate, }; $http.post(Constants.WebApi.Project.LoadTransactionSummaryByCategory, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available var transSums = response.data; $scope.chartByCategoryExpenseObject.data.rows = []; $scope.chartByCategoryIncomeObject.data.rows = []; for (var i = 0; i < transSums.length; i++) { var val = [ { v: transSums[i].Title }, { v: transSums[i].Balance }, ]; var c = { c: val }; if (transSums[i].Income != 0) { $scope.chartByCategoryIncomeObject.data.rows.push(c); } else { $scope.chartByCategoryExpenseObject.data.rows.push(c); } } }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Summary Failed!", type: "warning" }); }); }; $scope.LoadTransactionSummaryByAccount = function (projectId) { var fromDate = today; fromDate.setYear($scope.AccountFilter.FilterYear); var endDate = fromDate; if ($scope.AccountFilter.FilterMonth > 0) { fromDate.setFullYear($scope.AccountFilter.FilterYear, $scope.AccountFilter.FilterMonth, 1); // first day of month endDate = new Date(); endDate.setFullYear(fromDate.getFullYear(), fromDate.getMonth() + 1, 0); // last day of month } var transactionFilter = { ProjectId: projectId, FilterId: 1, IsIncome: true, IsUpcoming: true, IsUnclearOnly: false, Category: null, Account: null, FromDate: fromDate, EndDate: endDate, }; $http.post(Constants.WebApi.Project.LoadTransactionSummaryByAccount, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available var transSums = response.data; $scope.chartByAccountObject.data.rows = []; for (var i = 0; i < transSums.length; i++) { var val = [ { v: transSums[i].Title }, { v: transSums[i].Balance }, ]; var c = { c: val }; $scope.chartByAccountObject.data.rows.push(c); } }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Summary Failed!", type: "warning" }); }); }; $scope.LoadTransactionCategorySummaryByMonthYear = function (projectId, categoryId) { var transactionFilter = { ProjectId: projectId, FilterId: 1, IsUpcoming: true, IsUnclearOnly: false, Category: { Id: categoryId }, Account: null, FromDate: new Date(2016, 1), EndDate: new Date(2017, 0), }; $http.post(Constants.WebApi.Project.LoadTransactionCategorySummaryByMonthYear, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available var transSums = response.data; $scope.chartCategoryBudget.data.rows = []; for (var i = 0; i < transSums.length; i++) { var hAxisCol = transSums[i].Title; var val = [ { v: hAxisCol }, { v: transSums[i].Balance }, { v: transSums[i].Budget }, ]; var c = { c: val }; $scope.chartCategoryBudget.data.rows.push(c); } }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Summary Failed!", type: "warning" }); }); } $scope.loadJarsAnalyseData = function(projectId) { var transactionFilter = { ProjectId: projectId, IsIncome: true, FromDate: $scope.SelectedMonthYearForJARSAnalyse, EndDate: $scope.SelectedMonthYearForJARSAnalyse, }; $http.post(Constants.WebApi.Project.LoadMonthTotalIncome, transactionFilter).then(function (response) { // this callback will be called asynchronously // when the response is available $scope.TotalMonthlyIncome = response.data; $scope.loadJarsAnalyseChart($scope.TotalMonthlyIncome); }, function (response) { // called asynchronously if an error occurs // or server returns response with an error status. SweetAlert.swal({ title: "Error!", text: "Load Monthly Income For JARS Failed!", type: "warning" }); }); } $scope.loadJarsAnalyseChart = function(totalIncome) { $scope.chartJarsAnalyseObject.data.rows = []; var transSums = []; var NEC = [ { v: 'NEC' }, { v: 0.55 } ]; var LTSS = [ { v: 'LTSS' }, { v: 0.1 } ]; var EDU = [ { v: 'EDU' }, { v: 0.1 } ]; var FFA = [ { v: 'FFA' }, { v: 0.1 } ]; var PLAY = [ { v: 'PLAY' }, { v: 0.1 } ]; var GIVE = [ { v: 'GIVE' }, { v: 0.05 } ]; transSums.push(NEC); transSums.push(LTSS); transSums.push(EDU); transSums.push(FFA); transSums.push(PLAY); transSums.push(GIVE); for (var i = 0; i < transSums.length; i++) { var amount = transSums[i][1].v * totalIncome; var val = [ { v: transSums[i][0].v }, { v: amount }, ]; var c = { c: val }; $scope.chartJarsAnalyseObject.data.rows.push(c); } } $scope.setCategoryFilterAccount = function(accountId) { $scope.CategoryFilter.Account = { Id: accountId }; $scope.LoadTransactionSummaryByCategory($scope.projectId); } $scope.setCategoryFilterDate = function (month, year) { $scope.CategoryFilter.FilterMonth = month; $scope.CategoryFilter.FilterYear = year; $scope.LoadTransactionSummaryByCategory($scope.projectId); } $scope.setAccountFilterDate = function (month, year) { $scope.AccountFilter.FilterMonth = month; $scope.AccountFilter.FilterYear = year; $scope.LoadTransactionSummaryByAccount($scope.projectId); } $scope.setJARSAnalyseDate = function(month, year) { $scope.loadJarsAnalyseData($scope.projectId); } $scope.$watch('CategoryFilter', function (newVal, oldVal) { if (newVal != null && newVal.FilterDate != null) { $scope.setCategoryFilterDate(newVal.FilterDate.getMonth(), newVal.FilterDate.getFullYear()); } }, true); $scope.$watch('AccountFilter', function (newVal, oldVal) { if (newVal != null && newVal.FilterDate != null) { $scope.setAccountFilterDate(newVal.FilterDate.getMonth(), newVal.FilterDate.getFullYear()); } }, true); $scope.$watch('SelectedMonthYearForJARSAnalyse', function (newVal, oldVal) { if (newVal != null) { $scope.setJARSAnalyseDate(newVal.getMonth(), newVal.getFullYear()); } }, true); $scope.setSelectedCategory = function(cat) { $scope.SelectedCategory = cat; $scope.LoadTransactionCategorySummaryByMonthYear($scope.projectId, cat.Id); } }; // color style https://www.google.com/design/spec/style/color.html#color-color-palette
import { COMENZAR_DESCARGA_PERSONAS, COMENZAR_DESCARGA_PERSONAS_EXITO, COMENZAR_DESCARGA_PERSONAS_ERROR, OBTENER_PERSONA_ELIMINAR, PERSONA_ELIMINADO_EXITO, PERSONA_ELIMINADO_ERROR } from '../types' import clienteAxios from '../config/axios' import { AGREGAR_PERSONA, AGREGAR_PERSONA_EXITO, AGREGAR_PERSONA_ERROR } from '../types/personaType'; // crear nueva persona export function crearNuevaPersonaAction(persona) { return (dispatch) => { dispatch(nuevaPersona()); clienteAxios.post('/personas', persona) .then(respuesta => { dispatch( agregarPersonaExito(persona)) }) .catch(error => { dispatch( agregarPersonaError()) }) } } export const nuevaPersona = () => ({ type: AGREGAR_PERSONA }) export const agregarPersonaExito = persona => ({ type: AGREGAR_PERSONA_EXITO, payload: persona }) export const agregarPersonaError = () => ({ type: AGREGAR_PERSONA_ERROR }) //obtener estado de personas export function obtenerPersonasAction() { return (dispatch) => { dispatch(obtenerPersonasComienzo()) // consultar la api clienteAxios.get('/personas') .then(respuesta => { dispatch(descargaPersonasExito(respuesta.data)) }) .catch(error => { console.log(error); dispatch(descargaPersonasError()) }) } } export const obtenerPersonasComienzo = () => ({ type: COMENZAR_DESCARGA_PERSONAS }) export const descargaPersonasExito = personas => ({ type: COMENZAR_DESCARGA_PERSONAS_EXITO, payload: personas }) export const descargaPersonasError = () => ({ type: COMENZAR_DESCARGA_PERSONAS_ERROR }) // Eliminar Persona export function borrarPersonaAction(id) { return (dispatch) => { dispatch(obtenerPersonaElmimnar()) clienteAxios.delete(`personas/${id}`) .then(respuesta => { dispatch(eliminarPersonaExito(id)) }) .catch(error => { dispatch(eliminarPersonaError()) }) } } export const obtenerPersonaElmimnar = () => ({ type: OBTENER_PERSONA_ELIMINAR }) export const eliminarPersonaExito = id => ({ type: PERSONA_ELIMINADO_EXITO, payload: id }) export const eliminarPersonaError = () => ({ type: PERSONA_ELIMINADO_ERROR })
/** * Cool JavaScript file to do really cool things... really really cool things */ function loadagencies() { console.log("in loadagencies"); var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) { var agenciesArray = JSON.parse(req.responseText); var agencySelect = document.getElementById("agencies"); for (i = 0; i < agenciesArray.length; i++) { var agency = agenciesArray[i]; var option = document.createElement("option"); option.text = agency.agncyAddress + " " + agency.agncyCity; option.value = agency.agencyId; agencySelect.add(option); } } }; req.open("GET", "http://10.187.133.64:9090/JSPDay4/rs/agency/getallagencies", true); req.send(); } function loadagents(agencyid) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) { var agentsArray = JSON.parse(req.responseText); var agentSelect = document.getElementById("agents"); for (i=0; i<agentsArray.length; i++) { var agent = agentsArray[i]; var option = document.createElement("option"); option.text = agent.agtFirstName + " " + agent.agtMiddleInitial + " " + agent.agtLastName; option.value = agent.agentId; agencySelect.add(option); } } }; req.open("GET", "http://10.187.133.64:9090/JSPDay4/rs/agent/getagencyagents/" + agencyid, true); req.send(); } function loadselectedagent(agent) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) { var agent = JSON.parse(req.responseText); var agentDiv = document.getElementById("agent"); agentDiv.innerHTML = "agentid: " + agent.agentId + "<br />" + "agtFirstName: " + agent.agtFirstName + "<br />" + "agtMiddleInitial: " + agent.agtMiddleInitial + "<br />" + "agtLastName: " + agent.agtLastName + "<br />" + "agtBusPhone: " + agent.agtBusPhone + "<br />" + "agtEmail: " + agent.agtEmail + "<br />" + "agtPosition: " + agent.agtPosition + "<br />" + "agtAgencyId: " + agent.agencyId + "<br />"; } }; req.open("GET", "http://10.187.133.64:9090/JSPDay4/rs/agent/getagencyagents/" + agentid); req.send(); } function clearSelect(selectObject) { for (i=0; i<=selectObject.length; i++) { selectObject.remove(i); } }
export default function reducer(state={ shopping_items: [], current_item: { 'id': '', 'title': '', 'img_path': '', 'cost': 0, }, num_of_items: 0, curr_item_index: 0, }, action) { switch(action.type) { case 'FETCH_SHIPPING_ITEMS': return { ...state, current_item: action.payload[0], shopping_items: action.payload, curr_item_index: 0, num_of_items: action.payload.length, }; case 'ROTATE_CURRENT_ITEM': let curr_item_index = state.curr_item_index + action.shift; if(curr_item_index === -1) curr_item_index = state.num_of_items - 1; else if(curr_item_index === state.num_of_items) curr_item_index = 0; let current_item = state.shopping_items[curr_item_index]; return { ...state, curr_item_index: curr_item_index, current_item: current_item, }; default: break; } return state; }
import styled from "styled-components"; const APIPathWrapper = styled.span` display: block; margin-bottom: 1em; `; export default function APIPath({ path }) { return ( <APIPathWrapper> <b> <pre>API Path: {path}</pre> </b> </APIPathWrapper> ); }
import './App.css'; import Wrapper from './components/Wrapper'; import Globalstate from './Context/Globalstate'; import "./components/all.min.css"; import CartModal from './components/CartModal'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Checkout from './components/Checkout'; function App() { return ( <Globalstate> <Router> <div className="App"> <Switch> <Route path='/' exact component={Wrapper} /> <Route path='/checkout' exact component={Checkout} /> </Switch> <CartModal/> </div> </Router> </Globalstate> ); } export default App;
var view={ displayMessage: function(msg){ var messageArea = document.getElementById('messageArea-' + controller.gameActive); messageArea.innerHTML = msg; $(messageArea).addClass('show'); var a = controller.guesses; setTimeout(function () { if ((!controller.gameOver) && a == controller.guesses) {$(messageArea).removeClass('show');}}, 3000); }, displayHit:function(location){ $('.js-robot').children('#' + location).addClass('hit'); $('.js-robot').children('#' + location).removeClass('wait-shot'); }, displayMiss:function(location){ $('.js-robot').children('#' + location).addClass('miss'); $('.js-robot').children('#' + location).removeClass('wait-shot'); } }; var model = { boardSize:10, numShips: 10, shipLength: 3, shipsSunk:0, ShipsLive: 10, ships:[ {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:4, heals: 4}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:3, heals: 3}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:3, heals: 3}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}], generateShipLocations: function(){ var locations; for (var i = 0; i < this.numShips; i++){ this.shipLength = this.ships[i].Length; do { locations = this.generateShip(); }while(this.collision(locations)); this.ships[i].space = unique(this.spaceGeneration(locations)); this.ships[i].locations = locations; } }, generateShip: function(){ var direction = Math.floor(Math.random() * 2); var row, col; if (direction === 1){ row = Math.floor(Math.random() * this.boardSize); col = Math.floor(Math.random() * (this.boardSize - this.shipLength)); } else { row = Math.floor(Math.random() * (this.boardSize - this.shipLength)); col = Math.floor(Math.random() * this.boardSize); } var newShipLocations = []; for (var i = 0; i < this.shipLength; i++){ if (direction === 1){ newShipLocations.push(row + '' + (col + i)); } else{ newShipLocations.push((row + i) + '' + col); } } return newShipLocations; }, collision: function(locations){ console.log(locations); var a = false; for (var i=0; i < this.numShips; i++){ var ship = model.ships[i]; console.log(ship.space); for (var j = 0; j < locations.length; j++){ var s = (ship.space.indexOf(locations[j]) - 0) console.log(s); if (((ship.space.indexOf(locations[j])) - 0) >=0){ a = true; } } } console.log(a);return a; }, spaceGeneration: function(locations){ var space = []; var space2 = []; for (var i = 0; i < locations.length; i++){ loc = locations[i]; loc = +loc - 11; for (var q = 0; q < 3; q++){ var s1 = ([(loc + q)]) var s2 =([(loc + q) + 10]); var s3 =([(loc + q) + 20]); if ((s1 >= 0) && (s1 <=9)){ s1 = '0' + s1; } if ((s2 >= 0) && (s2 <=9)){ s2 = '0' + s2; } if ((s3 >= 0) && (s3 <=9)){ s3 = '0' + s3; } space.push(s1); space.push(s2); space.push(s3); console.log(s1 + ' ,'+ s2 + ' ,'+ s3); }; if ((+locations [i]+1)%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]) % 10 == 0){ space[d] = -99; } } } if ((+locations [i])%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]+1) % 10 == 0){ space[d] = -99; } } } } return unique(space); }, fire: function(guess){ for (var i=0; i < this.numShips; i++){ var ship = this.ships[i]; var index = ship.locations.indexOf(guess); if (index >= 0){ ship.hits[index] = 'hit'; ship.heals = ship.heals - 1; view.displayHit(guess); view.displayMessage('Ранен! Еще жизней: '+ ship.heals ); if (this.isSunk(ship)){ model.shipsSunk++; model.ShipsLive = model.ShipsLive -1; view.displayMessage('Корабль потоплен!' ); var messageArea = document.getElementById('numShips-user'); messageArea.innerHTML = ('Корабли противника: ' + model.ShipsLive); console.log(model.ships[i].space.length); for (var q = 0; q < model.ships[i].space.length; q++){ var id = ship.space[q]; $('#' + id).addClass('miss'); console.log(id); } } return true; } } view.displayMiss(guess); view.displayMessage('Пусто'); return false }, isSunk: function(ship){ for (var i=0; i < ship.Length; i++){ if (ship.hits[i] !=='hit'){ return false; } } return true; } }; var modelRobot = { boardSize:10, numShips: 10, shipLength: 3, shipsSunk:0, ShipsLive: 10, ships:[ {locations: ['0', '0', '0', '0' ], hits: ['', '', ''], hitLoc: [], space: [], Length:4, heals: 4}, {locations: ['0', '0', '0' ], hits: ['', '', ''], hitLoc: [], space: [], Length:3, heals: 3}, {locations: ['0', '0', '0' ], hits: ['', '', ''], hitLoc: [], space: [], Length:3, heals: 3}, {locations: ['0', '0'], hits: ['', '', ''], hitLoc: [], space: [], Length:2, heals: 2}, {locations: ['0', '0'], hits: ['', '', ''], hitLoc: [], space: [], Length:2, heals: 2}, {locations: ['0', '0'], hits: ['', '', ''], hitLoc: [], space: [], Length:2, heals: 2}, {locations: ['0'], hits: ['', '', ''], hitLoc: [], space: [], Length:1, heals: 1}, {locations: ['0'], hits: ['', '', ''], hitLoc: [], space: [], Length:1, heals: 1}, {locations: ['0'], hits: ['', '', ''], hitLoc: [], space: [], Length:1, heals: 1}, {locations: ['0'], hits: ['', '', ''], hitLoc: [], space: [], Length:1, heals: 1}], generateShipLocations: function(){ var locations; for (var i = 0; i < this.numShips; i++){ this.shipLength = this.ships[i].Length; do { locations = this.generateShip(); }while(this.collision(locations)); this.ships[i].space = unique(this.spaceGeneration(locations)); this.ships[i].locations = locations; } }, generateShip: function(){ var direction = Math.floor(Math.random() * 2); var row, col; if (direction === 1){ row = Math.floor(Math.random() * this.boardSize); col = Math.floor(Math.random() * (this.boardSize - this.shipLength)); } else { row = Math.floor(Math.random() * (this.boardSize - this.shipLength)); col = Math.floor(Math.random() * this.boardSize); } var newShipLocations = []; for (var i = 0; i < this.shipLength; i++){ if (direction === 1){ newShipLocations.push(row + '' + (col + i)); } else{ newShipLocations.push((row + i) + '' + col); } } return newShipLocations; }, collision: function(locations){ console.log(locations); var a = false; for (var i=0; i < this.numShips; i++){ var ship = modelRobot.ships[i]; console.log(ship.space); for (var j = 0; j < locations.length; j++){ var s = (ship.space.indexOf(locations[j]) - 0) console.log(s); if (((ship.space.indexOf(locations[j])) - 0) >=0){ a = true; } } } console.log(a);return a; }, spaceGeneration: function(locations){ var space = []; var space2 = []; for (var i = 0; i < locations.length; i++){ loc = locations[i]; loc = +loc - 11; for (var q = 0; q < 3; q++){ var s1 = ([(loc + q)]) var s2 =([(loc + q) + 10]); var s3 =([(loc + q) + 20]); if ((s1 >= 0) && (s1 <=9)){ s1 = '0' + s1; } if ((s2 >= 0) && (s2 <=9)){ s2 = '0' + s2; } if ((s3 >= 0) && (s3 <=9)){ s3 = '0' + s3; } space.push(s1); space.push(s2); space.push(s3); console.log(s1 + ' ,'+ s2 + ' ,'+ s3); }; if ((+locations [i]+1)%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]) % 10 == 0){ space[d] = -99; } } } if ((+locations [i])%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]+1) % 10 == 0){ space[d] = -99; } } } } return unique(space); }, displayHit:function(location){ $('.js-user').children('#' + location).addClass('hit'); $('.js-user').children('#' + location).removeClass('wait-shot'); }, displayMiss:function(location){ $('.js-user').children('#' + location).addClass('miss'); $('.js-user').children('#' + location).removeClass('wait-shot'); }, fire: function(guess){ for (var i=0; i < this.numShips; i++){ var ship = this.ships[i]; var index = ship.locations.indexOf(guess); if (index >= 0){ ship.hits[index] = 'hit'; ship.hitLoc.push('' + guess); ship.heals = ship.heals - 1; this.displayHit(guess); view.displayMessage('Ранен! Еще жизней: '+ ship.heals ); if (this.isSunk(ship)){ modelRobot.shipsSunk++; modelRobot.ShipsLive = modelRobot.ShipsLive -1; view.displayMessage('Корабль потоплен!' ); var messageArea = document.getElementById('numShips-robot'); messageArea.innerHTML = ('Ваши корабли: ' + modelRobot.ShipsLive); console.log(modelRobot.ships[i].space.length); modelRobot.ships[i].hitLoc = []; for (var q = 0; q < modelRobot.ships[i].space.length; q++){ var id = ship.space[q]; $('.js-user').children('#' + id).addClass('miss'); $('.js-user').children('#' + id).removeClass('wait-shot'); console.log(id); } } return true; } } this.displayMiss(guess); view.displayMessage('Пусто'); console.log(guess + ' пусто'); return false }, isSunk: function(ship){ for (var i=0; i < ship.Length; i++){ if (ship.hits[i] !=='hit'){ return false; } } return true; } }; var controller = { guesses: 0, gameActive: 'user', gameOver: false, processGuess: function(guess){ if(this.gameActive == 'robot'){ var location = guess; this.guesses++; var hit = modelRobot.fire(location); if (hit && modelRobot.shipsSunk === modelRobot.numShips){ this.gameOver = true; view.displayMessage('Вы проиграли..'); var messageArea = document.getElementById('numShips-robot'); messageArea.innerHTML = ('Все корабли потоплены'); $('.user-wait').addClass('hide'); setTimeout(function(){$('.reload-bt').removeClass('hide')}, 2000); }; if(!hit){ this.gameActive = 'user'; setTimeout(function(){$('.user-wait').removeClass('hide')}, 500); } else{ smart.shot(); } } else{ var location = guess; this.guesses++; var hit = model.fire(location); if (hit && model.shipsSunk === model.numShips){ this.gameOver = true; view.displayMessage('Вы победили!'); var messageArea = document.getElementById('numShips-user'); messageArea.innerHTML = ('Все корабли потоплены'); $('.user-wait').addClass('hide'); setTimeout(function(){$('.reload-bt').removeClass('hide')}, 2000); }; if(!hit){ this.gameActive = 'robot'; smart.shot(); $('.user-wait').addClass('hide'); } } }, displayMessage: function(msg){ var messageArea = document.getElementById('messageArea-robot'); messageArea.innerHTML = msg; $(messageArea).addClass('show'); var a = controller.guesses; setTimeout(function () { if ((!controller.gameOver) && a == controller.guesses) {$(messageArea).removeClass('show');}}, 3000); }, }; var smart = { LocationView: function(){ for ( i=0; i < modelRobot.numShips; i++){ modelRobot.ships[i].space = unique(modelRobot.spaceGeneration(modelRobot.ships[i].locations)); for (q=0; q < modelRobot.ships[i].locations.length; q++){ $('.js-user').children('#' + modelRobot.ships[i].locations[q]).addClass('pre-hit'); } } $('.js-user').children('td').addClass('wait-shot'); }, valueGeneration: function(){ var position = 0; var hit = 0; var hit2 = 0; var value =[]; for ( t=0; t < modelRobot.numShips; t++){ if (modelRobot.ships[t].hitLoc.length == 1){ hit = idFix(modelRobot.ships[t].hitLoc[0]); console.log('раз ' + hit); if (($('.js-user').children('#' + idFix(+hit+1)).attr("class") != undefined) && ($('.js-user').children('#' + idFix(+hit+1)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(+hit+1)); }; if (($('.js-user').children('#' + idFix(+hit-1)).attr("class") != undefined) && ($('.js-user').children('#' + idFix(+hit-1)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(hit-1)); }; if (($('.js-user').children('#' + idFix(+hit+10)).attr("class") != undefined) && ($('.js-user').children('#' + idFix(+hit+10)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(+hit+10)); }; if (($('.js-user').children('#' + idFix(+hit-10)).attr("class") != undefined) && ($('.js-user').children('#' + idFix(+hit-10)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(hit-10)); }; return value; } if (modelRobot.ships[t].hitLoc.length == 2){ hit = idFix(Array.min(modelRobot.ships[t].hitLoc)); console.log(hit + ' хит'); hit2 = idFix(Array.max(modelRobot.ships[t].hitLoc)); console.log(hit2 + ' хит2'); console.log(value + ' валуе два'); if (($('.js-user').children('#' + idFix(hit-(hit2 - hit))).attr("class") != undefined )&&($('.js-user').children('#' + idFix(hit-(hit2 - hit))).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(hit-(hit2 - hit))); }; if (($('.js-user').children('#' + idFix(+hit+((hit2 - hit)*2))).attr("class") != undefined)&&($('.js-user').children('#' + idFix(+hit+((hit2 - hit)*2))).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(+hit+((hit2 - hit)*2))); }; return value; } if (modelRobot.ships[t].hitLoc.length == 3){ hit = idFix(Array.min(modelRobot.ships[t].hitLoc)); hit2 = idFix(Array.max(modelRobot.ships[t].hitLoc)); var a = (hit2 - hit) / 2; if (($('.js-user').children('#' + idFix(hit - a)).attr("class") != undefined)&&($('.js-user').children('#' + idFix(hit - a)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(hit - a)); }; if (($('.js-user').children('#' + idFix(+hit + a * 3)).attr("class") != undefined)&&($('.js-user').children('#' + idFix(+hit + a * 3)).attr("class").indexOf('wait-shot') >=0)){ value.push(idFix(+hit + a * 3)); }; return value; } }; for ( i=0; i < 100; i++){ i = idFix(i); if ($('.js-user').children('#' + i).attr("class").indexOf('wait-shot') >=0){ value.push(i); } }; return value; }, shot: function(){ var value = this.valueGeneration(); console.log(value); position = value[Math.floor(Math.random() * value.length)]; position = '' + position; if (!controller.gameOver){ setTimeout(function () {controller.processGuess(position); }, 800); $('.js-user').children('#' + position).removeClass('wait-shot'); } }, gamer: function(){ this.LocationView(); setTimeout(function () { smart.shot();}, 1000); } }; Array.min = function( array ){ return Math.min.apply( Math, array ); }; Array.max = function( array ){ return Math.max.apply( Math, array ); }; function idFix(i){ if (('' + i).length === 1){ i = '0' + i; } else{ i = '' + i; }; return i; } function unique(arr) { var obj = {}; for (var i = 0; i < arr.length; i++) { var str = arr[i]; obj[str] = true; } return Object.keys(obj); }; $(document).ready(function() { $("td").click(function () { if ((controller.gameActive == 'user')&&(!controller.gameOver) && (($(this).attr("class") == undefined))){ console.log($(this).attr("class")); controller.processGuess($(this).attr("id")); } }); }); function start(){ model.generateShipLocations(); smart.LocationView(); $('.js-user').children().removeClass('hit'); $('.robot').removeClass('hide'); $('.shipBox').addClass('hide'); $('.user').addClass('right'); $('.start-bt').addClass('hide'); setTimeout(function(){$('.user-wait').removeClass('hide');}, 2000); } function startBtnHide(){ $('.text-help').removeClass('hide'); for (t=0; t< 10; t++){ for(d = 0; d < modelRobot.ships[t].locations.length; d++){ if (modelRobot.ships[t].locations[d] === '0'){ return }; } }; $('.text-help').addClass('hide'); setTimeout(function() {$('.start-bt').removeClass('hide');}, 1000 ); } // перетаскивание var drop = { idFix: function(i){ if (('' + i).length === 1){ i = '0' + i; } else{ i = '' + i; }; return i; }, locWritter: function(shipDl){ table = document.getElementById('table').getBoundingClientRect(); $('#table').children().children().children('td').removeClass('drop-hit'); $('#table').children().children().children('td').removeClass('space'); for (i=1; i<=10; i++){ ship = $('#ship' + i).children('div'); locWr = drop.locDetector(ship); console.log('лок вр ' + locWr); if (this.locCorrect(locWr)){ for (e=0; e < locWr.length; e++){ $('#table').children().children().children('#' + locWr[e]).addClass('drop-hit'); modelRobot.ships[(i - 1)].locations[e] = locWr[e]; }; space = this.spaceGeneration(locWr); for (w=0; w < space.length; w++){ $('#table').children().children().children('#' + space[w]).addClass('space'); }; }else{ this.shipToBox('ship' + i); modelRobot.ships[(i - 1)].locations = ['0']; } } $('.text-help').addClass('hide'); startBtnHide(); }, shipToBox: function(ship){ document.getElementById(ship).style.top = '0px'; document.getElementById(ship).style.left = '0px'; document.getElementById(ship).style.opacity = '1'; document.getElementById(ship).style.transition = '0.2s, left 0.4s linear, top 0.4s linear'; }, locDetector: function(shipDet){ table = document.getElementById('table').getBoundingClientRect(); locDt=[]; for (e=0; e < shipDet.length; e++){ div = shipDet[e].getBoundingClientRect(); column = Math.floor(((div.left + div.width / 2) - table.left) / (table.width/10)); line = Math.floor(((div.top + div.height / 2) - table.top) / (table.height/10)); locDt.push('' + line + column); }console.log('лок дт ' + locDt); return locDt; }, locCorrect: function(id){ console.log(id); for (a=0; a < id.length; a++){ if ((document.getElementById(id[a]) === null) ){ console.log('1'); return false } if (($('#table').children().children().children('#' + id[a]).attr("class") !== undefined) ){ console.log('2'); console.log($('#' + id[a]).attr("class")); if ($('#table').children().children().children('#' + id[a]).attr("class").length > 0){ return false } } } return true }, spaceGeneration: function(locations){ var space = []; var space2 = []; for (var i = 0; i < locations.length; i++){ locSp = locations[i]; locSp = +locSp - 11; for (var q = 0; q < 3; q++){ var s1 = ([(locSp + q)]) var s2 =([(locSp + q) + 10]); var s3 =([(locSp + q) + 20]); if ((s1 >= 0) && (s1 <=9)){ s1 = '0' + s1; } if ((s2 >= 0) && (s2 <=9)){ s2 = '0' + s2; } if ((s3 >= 0) && (s3 <=9)){ s3 = '0' + s3; } space.push(s1); space.push(s2); space.push(s3); console.log(s1 + ' ,'+ s2 + ' ,'+ s3); }; if ((+locations [i]+1)%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]) % 10 == 0){ space[d] = -99; } } } if ((+locations [i])%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]+1) % 10 == 0){ space[d] = -99; } } } } return unique(space); }, noContextMenuOnShip: function(){ var ship = document.getElementsByClassName('shipInBox'); for (i=0 ; i < ship.length; i++){ ship[i].oncontextmenu = (function(e){ $(e.target).parent().toggleClass('rotate'); $('.shipBox').removeClass('rotate'); id = $(e.target).parent().attr('id'); drop.shipToBox(id); drop.hitDelOnDrag($('#' + id).children('div')); $('.start-bt').addClass('hide'); return false; }); } }, hitDelOnDrag: function(shipDel){ locDd = this.locDetector(shipDel); console.log(locDd); for(i=0; i < locDd.length; i++){ $('#table').children().children().children('#' + locDd[i]).removeClass('drop-hit'); locDd[i] = '' + locDd[i]; if($('#table').children().children().children('#' + locDd[i]).length == 0){ return } }; space = this.spaceGeneration(locDd); for(i=0; i < space.length; i++){ $('#table').children().children().children('#' + space[i]).removeClass('space'); }; } } $(function() { $('.shipInBox').draggable({ start: function(){ elem = $(this).attr('id'); document.getElementById(elem).style.opacity = '1'; document.getElementById(elem).style.transition = '0s'; $('.space').html('<div></div>'); ship = $('#' + elem).children('div'); drop.hitDelOnDrag(ship); $('.start-bt').addClass('hide'); }, stop: function(){ elem = $(this).attr('id'); document.getElementById(elem).style.opacity = '0'; drop.locWritter($(this)); $('.space').html(''); } }); }); window.onload = drop.noContextMenuOnShip;
import constants from '../../constants.js' export { filterOptionsList } const filterOptionsList = (selectInput) => { const inputId = selectInput.id // Always filter by the initial option list!! const initialOptionList = constants.initialOptionListsData[inputId] const inputContainer = document.querySelector(`.input-container#input-${inputId}`) const optionsList = inputContainer.querySelector('.option-list') const filterCriteria = selectInput.value.toLowerCase() const filteredOptions = initialOptionList.filter(option => { const optionValue = option.innerHTML.toLowerCase() return optionValue.includes(filterCriteria) }) optionsList.innerHTML = '' filteredOptions.forEach(option => optionsList.appendChild(option)) }
/** @format */ // 搜索 const request = require("./request"); const transformResponse = (response) => { return { hasMore: response.result.hasMore, songCount: response.result.songCount, songs: response.result.songs.map((song) => { return { id: song.id, name: song.name, artists: song.artists, album: song.album, pay: song.fee === 1, }; }), }; }; module.exports = (query) => { const data = { s: query.keywords, type: query.type || 1, // 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频 limit: query.limit || 10, offset: query.offset ? (query.offset - 1) * (query.limit || 10) : 0, }; return request("POST", `https://music.163.com/weapi/search/get`, data, { crypto: "weapi", cookie: query.cookie, proxy: query.proxy, }).then((response) => { const { status, body } = response; if (status !== 500) { return { status, body: { result: transformResponse(body), //body, }, }; } return { status, body, }; }); };
'use strict'; const chai = require('chai'); const should = chai.should(); // eslint-disable-line const expect = chai.expect; // eslint-disable-line const TEST_NAME = 'Environment spec'; const CLOUD_FORMATION_DIR = __dirname + '/mocks'; const Environment = require('../../../src/lib/environment/Environment'); const InquirerPromptAssertions = require('../../../util/InquirerPromptAssertions'); describe(TEST_NAME, () => { it('should load prompts from the parameters from a valid template file', () => { let env = new Environment(TEST_NAME,CLOUD_FORMATION_DIR,{cloudFormationTemplatePattern:'vpc.yml'}); return env.loadEnvironmentParametersAsPrompts() .then((prompts) => { prompts.should.exist; prompts.length.should.be.eql(4); prompts[0].name.should.be.eql('VpcCIDR'); prompts[0].default.should.be.eql('10.10.0.0/16'); prompts[0].type.should.be.eql('String'); prompts[1].name.should.be.eql('EnvironmentName'); expect(prompts[1].default).to.be.undefined; prompts[1].type.should.be.eql('String'); prompts[2].name.should.be.eql('SubnetOffset'); prompts[2].default.should.be.eql('8'); prompts[2].type.should.be.eql('String'); prompts[3].name.should.be.eql('NumberOfSubnets'); prompts[3].default.should.be.eql('6'); prompts[3].type.should.be.eql('String'); }); }); it('should load all the parameter types as prompts', () => { let env = new Environment(TEST_NAME,CLOUD_FORMATION_DIR,{cloudFormationTemplatePattern:'all-the-types.yml'}); return env.loadEnvironmentParametersAsPrompts() .then((prompts) => { prompts.should.exist; prompts.length.should.be.eql(7); InquirerPromptAssertions.sames(prompts, [ {'type':'String','name':'VpcCIDR','default':'172.19.0.0/16','message':'Please enter a String for VpcCIDR => ','description':'VPC CIDR'}, {'type':'Number','name':'NodeCount','default':1,'message':'Please enter a Number for NodeCount => ','description':'NodeCount is a Number.'}, {'type':'Number','name':'DatabaseCount','message':'Please enter a Number for DatabaseCount => ','description':'DatabaseCount is a Number.'}, {'type':'String','name':'Username','default':'usprod','message':'Please enter a String for Username => ','description':'Username is a String.'}, {'type':'String','name':'Encrypted','default':'true','message':'Please enter a String for Encrypted => ','description':'Encrypted is a String.'}, {'type':'String','name':'Environment','message':'Please enter a String for Environment => ','description':'Environment Name'}, {'type':'String','name':'Password','message':'Please enter a String for Password => ','description':'Password is a String.'} ]); }); }); it('should load all ssm parameter types via directory', () => { let env = new Environment(TEST_NAME,CLOUD_FORMATION_DIR,{cloudFormationTemplatePattern:'vpc_ssm_params.yml'}); return env.loadEnvironmentParametersAsPrompts() .then((prompts) => { prompts.should.exist; prompts.length.should.be.eql(4); InquirerPromptAssertions.sames(prompts,[ {'type':'String','name':'VpcCIDR','default':'172.19.0.0/16','message':'Please enter a String for VpcCIDR => ','description':'VPC CIDR'}, {'type':'String','name':'EnvironmentName','message':'Please enter a String for EnvironmentName => ','description':'Environment Name'}, {'type':'Number','name':'SubnetOffset','default':10,'message':'Please enter a Number for SubnetOffset => ','description':'Offset of the subnet from the VPC CIDR'}, {'type':'Number','name':'NumberOfSubnets','default':4,'message':'Please enter a Number for NumberOfSubnets => ','description':'Number of Subnets to create'} ]); }); }); it('should load the parameters from multiple valid template files in a directory and dedupe them', () => { let env = new Environment(TEST_NAME,CLOUD_FORMATION_DIR,{cloudFormationTemplatePattern:'*pc.yml'}); return env._loadCloudFormationParams() .then((params) => { params.should.exist; params.should.be.eql([ { 'ParameterKey': 'VpcCIDR', 'DefaultValue': '10.10.0.0/16', 'NoEcho': false, 'Description': 'VPC CIDR', 'ParameterConstraints': {}, 'ParameterType': 'String', _meta:{ '_retrievedFrom': 'simple-vpc.yml' } }, { 'ParameterKey': 'EnvironmentName', 'NoEcho': false, 'Description': 'Environment Name', 'ParameterConstraints': {}, 'ParameterType': 'String', _meta:{ '_retrievedFrom': 'simple-vpc.yml' } }, { 'ParameterKey': 'NumberOfSubnets', 'DefaultValue': '6', 'NoEcho': false, 'Description': 'Number of Subnets to create', 'ParameterConstraints': {}, 'ParameterType': 'String', _meta:{ '_retrievedFrom': 'simple-vpc.yml' } }, { 'ParameterKey': 'SubnetOffset', 'DefaultValue': '8', 'NoEcho': false, 'Description': 'Offset of the subnet from the VPC CIDR', 'ParameterConstraints': {}, 'ParameterType': 'String', _meta:{ '_retrievedFrom': 'vpc.yml' } } ]); }); }); });
const nodeChallenge = require('./information.js'); console.log(nodeChallenge); const cowsay = require('cowsay'); console.log(cowsay.say({ text : `Hello, I'm ${nodeChallenge.name} from ${nodeChallenge.campus} campus!`, e : "oO", T : "U " }));
$(function () { window.location.hash="#"; $(window).on('hashchange', function(){ console.log("Detected hash change event") render(decodeURI(window.location.hash)); }); $("#newuser_submit").on('click',function(){ console.log($("#newuser").val()) var request = $.ajax({ url:window.location.origin+"/addmember", method: "POST", dataType: "text", data:{ newuser:$("#newuser").val(), circle : window.location.pathname.split('/')[2] }, success:function(data){ console.log(data) if(data == -1) { alert($("#newuser").val()+" : No such user") } else if(data == 0) { alert($("#newuser").val()+" : User already present in circle") } else if(data == -2) { alert($("#newuser").val()+" : Request already sent to user") } else { alert(" Request sent to user : "+$("#newuser").val()) } } }); }); function render(url) { var temp = url.split('/')[0]; var map = { // The Homepage. '#members': function() { $("#ranking").hide(); $("#statistics").hide(); url = window.location.origin+"/members/"+window.location.pathname.split('/')[2] console.log(url) var request = $.ajax({ url:url, method: "GET", dataType: "html", success:function(data){ console.log(data) document.getElementById("members").innerHTML = data $('#members').show() $('#add').show() } }); }, '#ranking': function() { $('#members').hide() $("#statistics").hide(); $("#add").hide() url = window.location.origin+"/ranking/"+window.location.pathname.split('/')[2] console.log(url) var request = $.ajax({ url:url, method: "GET", dataType: "html", success:function(data){ console.log(data) document.getElementById("ranking").innerHTML = data $('#ranking').show() } }); } }; // Execute the needed function depending on the url keyword (stored in temp). if(map[temp]){ map[temp](); } } });
export default function workflow(inputField, workflowFields) { let $inputField; if (!inputField instanceof jQuery) { $inputField = $(inputField); } else { $inputField = inputField; } if ($inputField.is(':checkbox')) { const inputFieldIsChecked = $inputField.is(':checked'); if (workflowFields.constructor === Array) { for (let elem of workflowFields) { if (inputFieldIsChecked) { elem.removeClass('hide-form-group'); } else { elem.addClass('hide-form-group'); } } } else { if (inputFieldIsChecked) { workflowFields.removeClass('hide-form-group'); } else { workflowFields.addClass('hide-form-group'); } } } else if ($inputField.is('select') && $inputField.attr('multiple') === 'multiple') { const fieldValueArray = $.makeArray($inputField.find('option:selected').map((index, value) => $(value).text())); for (let [key, currentWorkflowField] of Object.entries(workflowFields)) { if (fieldValueArray.indexOf(key) === -1) { if (currentWorkflowField.constructor === Array) { for (let elem of currentWorkflowField) { elem.addClass('hide-form-group'); } } else { currentWorkflowField.addClass('hide-form-group'); } } else { if (currentWorkflowField.constructor === Array) { for (let elem of currentWorkflowField) { elem.removeClass('hide-form-group'); } } else { currentWorkflowField.removeClass('hide-form-group'); } } } } }
/* import {values} from 'lodash' import { Schema, string, boolean, date, required, oneOf } from 'sapin' import {objectId} from '../common/validate' */ export const NotificationTypes = { ClientDocumentCreated: 'CLIENT_DOCUMENT_CREATED', ClientDocumentModified: 'CLIENT_DOCUMENT_MODIFIED', ClientDocumentArchived: 'CLIENT_DOCUMENT_ARCHIVED', ClientArchived: 'CLIENT_ARCHIVED', ClientFileCreated: 'CLIENT_FILE_CREATED', ClientLinkCreated: 'CLIENT_LINK_CREATED' } /* export const notificationSchema = new Schema({ id: objectId, userId: objectId(required), type: string(required, oneOf(values(NotificationTypes))), isRead: boolean, isArchived: boolean, createdOn: date, modifiedOn: date }) */
import * as types from '../mutation-type' import Vue from 'vue' let axios = Vue.prototype.$axios const state = { userInfo: {} //用户信息 } // getters const getters = { getUserInfo: (state) => { if( window.location.href.indexOf('login') != -1 ) return false; if( JSON.stringify(state.userInfo) == '{}' ){ let userInfo = JSON.parse( window.localStorage.getItem('userInfo') ); if( !userInfo ){ window.location.href="/login" } state.userInfo = userInfo } return state.userInfo } } // actions const actions = { //用户 loginDo ({ commit, state }, params ) { return new Promise( (resolve, reject)=>{ axios.post('/api/login_do', params).then((response) => { // commit(types.SET_USER_INFOR,response.data) resolve(response.data) }).catch((error) => { reject( error ) }) } ) }, //用户对应的权限 getUserRoot ({ commit, state }, params ) { return new Promise( (resolve, reject)=>{ console.log(params) axios.get('/api/getUserRoot', {params}).then((response) => { // commit(types.SET_USER_INFOR,response.data) resolve(response.data) }).catch((error) => { reject( error ) }) } ) }, //获取出来的权限放进userInfo,进行遍历 setUserInfo ({ commit, state }, params ) { return new Promise( (resolve, reject)=>{ // console.log(params.key,params.value) let userInfo = state.userInfo console.log(userInfo) userInfo[params.key] = params.value console.log( userInfo ) commit(types.SET_USER_INFOR,userInfo) console.log(userInfo) resolve(userInfo) } ) }, //获取授权用户 getRootList ({ commit, state }, ) { return new Promise( (resolve, reject)=>{ axios.get('/api/getRootList').then((response) => { resolve(response.data) }).catch((error) => { reject( error ) }) } ) }, //改权限 editRoot ({ commit, state }, params ) { return new Promise( (resolve, reject)=>{ axios.get('/api/editRoot', {params}).then((response) => { resolve(response.data) }).catch((error) => { reject( error ) }) } ) }, //退出登录 loginOut ({ commit, state }, params ) { return new Promise( (resolve, reject)=>{ commit(types.SET_USER_INFOR,'') resolve({ code: 200 }) } ) } } // mutations const mutations = { [types.SET_USER_INFOR](state, userInfo) { state.userInfo = userInfo if( userInfo == '' ){ window.localStorage.removeItem('userInfo') }else{ window.localStorage.setItem('userInfo', JSON.stringify(userInfo) ) } } } export default { namespaced: true, state, getters, actions, mutations }
var oSelectedTabs = { stylesheets: [], forms: [], images: [], miscellaneous: [], resize: [], accessibility: [] }, aNavItems = ["stylesheets", "forms", "images", "miscellaneous", "tools","resize", "accessibility"], aBoxItems = ["tools-codestandard", "tools-ajaxdebugger", "disable-all-styles", "disable-inline-styles", "disable-embedded-styles", "disable-linked-style-sheets", "show-passwords", "remove-maxlength-attributes", "hide-all-images", "hide-background-images", "show-alt-text-note", "show-dimensions-note", "show-paths-note", "display-color-picker", "display-ruler", "topographic-view"]; initStorage(); function initStorage() { for (var a = 0; a < aNavItems.length; a++)localStorage.setItem(aNavItems[a], ""); for (a = 0; a < aBoxItems.length; a++)localStorage.setItem(aBoxItems[a], "") } function clearTabStorage(a) { var b, c = aNavItems.length; for (b = 0; b < c; b++)oStorage.del(aNavItems[b], a); c = aBoxItems.length; for (b = 0; b < c; b++)oStorage.del(aBoxItems[b], a) } function getFeatureState(a, b) { return oStorage.into(a, b) } function setFeatureState(a, b, c) { c ? oStorage.del(a, b) : oStorage.add(a, b) } function toggleFeatureState(a, b) { oStorage.into(a, b) ? oStorage.del(a, b) : oStorage.add(a, b) } var oStorage = { add: function (a, b) { var c = localStorage.getItem(a).split(","); c.unshift(b); localStorage.setItem(a, c) }, del: function (a, b) { for (var c = localStorage.getItem(a).split(","), d = 0; d < c.length; d++)c[d] == b && c.splice(d, 1); localStorage.setItem(a, c) }, into: function (a, b) { for (var c = localStorage.getItem(a).split(","), d = 0; d < c.length; d++)if (c[d] == b)return !0 }, toggleFeature: function (a, b) { return this.into(a, b) ? (this.del(a, b), !0) : (this.add(a, b), !1) } }; chrome.tabs.onUpdated.addListener(function (a, b) { b.status === "loading" && clearTabStorage(a) }); chrome.tabs.onRemoved.addListener(function (a) { clearTabStorage(a) });
import { Circle as CircleStyle, Fill, Stroke, Style } from "ol/style"; import VectorLayer from "ol/layer/Vector"; import VectorSource from "ol/source/Vector"; import GeoJSON from "ol/format/GeoJSON"; import { getCenter } from "ol/extent"; import { dialog } from "./init"; export const topAppBarRight = document.querySelector( ".top-app-bar__section--align-end" ); const appBarTitle = document.getElementsByClassName("top-app-bar__title")[0]; const sidebarContent = document.querySelector(".sidebar__content"); export const sidebar = document.querySelector(".sidebar"); export const content = document.getElementsByClassName("content")[0]; /* * removes the content below the appBar. */ export const removeContent = () => { content.innerHTML = ""; }; /* * creates the grid layout containing description. * @returns {HTMLElement} grid - a div with a MDCGrid inside. */ export const createGrid = () => { const grid = document.createElement("div"); const gridInner = document.createElement("div"); grid.classList.add("mdc-layout-grid"); gridInner.classList.add("mdc-layout-grid__inner"); grid.appendChild(gridInner); return grid; }; /* * changes the top appbar title. * @param {string} title - the new title to display. * @returns {boolean} - true if title changed successfully, false otherwise. */ export const setTitle = title => { if (!title) { return false; } appBarTitle.innerHTML = title; return true; }; /* * remove old video links from the top-app-bar and add add a new one. * @param {object} params - function parameter object. * @param {string} params.title - the video title. * @param {string} params.id - youtube video id. * @returns {boolean} - true in case of success, false otherwise. */ export const addVideoLink = ({ title, videoId } = {}) => { if (!videoId) { return false; } removeVideoLink(); topAppBarRight.appendChild(getVideoLink({ title, videoId })); return true; }; /* * remove the video link from the top-app-bar */ export const removeVideoLink = () => { if (topAppBarRight.children.length === 3) { topAppBarRight.removeChild(topAppBarRight.children[2]); } }; /* * creates a top-app-bar video link. * @param {object} params - function parameter object. * @param {string} params.title - the video title. * @param {string} params.videoId - youtube video id. * @returns {domElement} - image link which opens a modal with the video. */ export const getVideoLink = ({ title, videoId } = {}) => { if (!videoId) { return false; } const videoLink = document.createElement("button"); videoLink.classList.add( "material-icons", "mdc-top-app-bar__action-item", "mdc-icon-button" ); videoLink.ariaLabel = "video"; videoLink.innerHTML = "live_tv"; videoLink.title = "Erklärungsvideo"; videoLink.addEventListener("click", () => { dialogTitle.innerHTML = `Dokumentation ${title}`; dialogContent.innerHTML = getVideoElement(videoId); dialog.open(); }); return videoLink; }; export const getVideoElement = videoId => `<div class="videoWrapper"><iframe width="560" height="349" src="https://www.youtube.com/embed/${videoId}?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>`; /* * calculates the title based on the window.width. * @returns {string} title - title to use based on the current window.width. */ export const getTitle = () => { const width = window.innerWidth; const title = width <= 550 ? "Waldmonitoring" : "Waldmonitoring mit Sentinel Satellitenbildern"; return title; }; /* * hide the appBar title */ export const hideTitle = () => { appBarTitle.style.display = "none"; }; /* * show the appBar title */ export const showTitle = () => { appBarTitle.style.display = "block"; }; export const impressum = { tite: "IMRESSUM", content: `Dies ist ein Forschungsprojekt der BFH-HAFL im Auftrag bzw. mit Unterstützung des BAFU. Im Rahmen dieses Projektes sollen vorhandene, möglichst schweizweit flächendeckende und frei verfügbare Fernerkundungsdaten für konkrete Use-Cases und mit einem klaren Mehrwert für die Praxis eingesetzt werden. Das Hauptziel dieses Projektes ist die Implementierung von Kartenviewern sowie Geodiensten zu den entsprechenden Use-Cases. <br /></br /> <strong>Zur Zeit sind die bereitgestellten Daten und Services ausschliesslich für Testzwecke gedacht.</strong> <br /> <h4 style="margin-bottom:8px">Ansprechpersonen:</h4> <strong>BFH-HAFL:</strong> Alexandra Erbach (+41 31 910 22 75, <a href="mailto:alexandra.erbach@bfh.ch">alexandra.erbach@bfh.ch</a>)<br /> <strong>Website/Geodienste:</strong> Karten-Werk GmbH, Hanskaspar Frei, (+41 79 360 72 83, <a href="mailto:hkfrei@karten-werk.ch">hkfrei@karten-werk.ch</a>)</p>` }; export const getLayerInfo = overlay => { return `<div> <h4>Legende:</h4> <img src="https://geoserver.karten-werk.ch//wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&height=15&LAYER=${overlay.layername}&legend_options=forceLabels:on" alt="legende"/> <h4>Beschreibung:</h4> <section>${overlay.description}</section> </div>`; }; export const dialogTitle = document.querySelector("#dialog-title"); export const dialogContent = document.querySelector("#dialog-content"); export const searchResults = document.querySelector(".autocomplete"); /* * set the position of the search result box below the search input. */ export const positionSearchResultContainer = () => { const searchInput = document.querySelector(".mdc-text-field"); const searchMetrics = searchInput.getBoundingClientRect(); searchResults.style.left = `${searchMetrics.left}px`; searchResults.style.width = `${searchMetrics.width}px`; }; /* * debounce function for the places search * Returns a function, that, as long as it continues to be invoked, will not * be triggered. The function will be called after it stops being called for * N milliseconds. If `immediate` is passed, trigger the function on the * leading edge, instead of the trailing. * credits:https://davidwalsh.name/javascript-debounce-function */ export const debounce = (func, wait, immediate) => { var timeout; return function () { var context = this, args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; /* * geojson display styles. */ const image = new CircleStyle({ radius: 5, fill: null, stroke: new Stroke({ color: "red", width: 4 }) }); const styles = { Point: new Style({ image: image }), LineString: new Style({ stroke: new Stroke({ color: "yellow", width: 4 }) }), MultiLineString: new Style({ stroke: new Stroke({ color: "yellow", width: 4 }) }), MultiPoint: new Style({ image: image }), MultiPolygon: new Style({ stroke: new Stroke({ color: "yellow", width: 4 }), fill: new Fill({ color: "rgba(255, 0, 0, 0.3)" }) }), Polygon: new Style({ stroke: new Stroke({ color: "blue", lineDash: [4], width: 4 }), fill: new Fill({ color: "rgba(0, 0, 255, 0.1)" }) }), GeometryCollection: new Style({ stroke: new Stroke({ color: "magenta", width: 2 }), fill: new Fill({ color: "magenta" }), image: new CircleStyle({ radius: 10, fill: null, stroke: new Stroke({ color: "magenta" }) }) }), Circle: new Style({ stroke: new Stroke({ color: "red", width: 2 }), fill: new Fill({ color: "rgba(255,0,0,0.2)" }) }) }; /* * get the right style for a geojson. * @param {object} feature - geojson feature. * @returns {object} ol/Style object. */ const styleFunction = function (feature) { return styles[feature.getGeometry().getType()]; }; /* * Adds a Geojson Object to the openlayers map * @param {object} geojson - valid geojson object * @returns {object} geojsonLayer - ol VectorLayer instance or null in case of failure */ export const displayGeojson = ({ geojson, map } = {}) => { if (!geojson || !map) { return false; } removeGeojsonOverlays(map); const vectorSource = createOlVectorSource(geojson); const geojsonLayer = new VectorLayer({ source: vectorSource, style: styleFunction, zIndex: map.getLayers().getLength() }); geojsonLayer.type = "geojson"; map.addLayer(geojsonLayer); const extent = vectorSource.getExtent(); map.getView().setCenter(getCenter(extent)); return geojsonLayer; }; /* * Removes every Geojson overlay from the openlayers map * @param {object} map - openlayers map object. * @returns {boolean} true in case of success, false otherwise. */ export const removeGeojsonOverlays = map => { if (!map) { return false; } map.getLayers().forEach(layer => { if (layer.type === "geojson") { map.removeLayer(layer); } }); return true; }; /* * creates an openLayers vector source object based on geojson. * @param {object} geojson - the geojson used by the source. * @returns {object} VectorSource - ol/source/Vector object */ const createOlVectorSource = geojson => { return new VectorSource({ features: new GeoJSON().readFeatures(geojson) }); }; /* * opens the sidebar to display legends, infos etc. * @param {object} params * @param {DomElement} params.content - the content to display inside the sidebar. */ export const openSidebar = ({ content = null } = {}) => { sidebar.style.zIndex = 5; sidebar.style.transform = "scale(1)"; if (content) { sidebarContent.appendChild(content); } }; export const closeSidebar = () => { sidebarContent.innerHTML = ""; sidebar.style.transform = "scale(0,1)"; window.setTimeout(() => { sidebar.style.zIndex = -1; }, 400); };
$(function(){ tinymce.init({ selector:'#FormAddAlert_message', plugins: "link, image, code", branding: false, //statusbar: false, menubar: false, toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent hr | removeformat | link image | code', image_list: siteData.data('url')+"/admin/tinyMceImages" }); $('.save-btn').click(function(e){ e.preventDefault(); $('#FormAddAlert_save').val(1); $(this).parents('form').submit(); $('#FormAddAlert_save').val(0); }); });
import React from 'react'; import {withStyles} from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; import Grid from "@material-ui/core/Grid"; import Card from "@material-ui/core/Card"; const styles = (theme) => ({ card: { padding: theme.spacing(3), paddingTop: theme.spacing(5), paddingBottom: theme.spacing(4), width: theme.spacing(31), }, root: { minWidth: 345, marginTop: 8, marginBottom: 8, }, media: { height: 140, }, image: { height: theme.spacing(16), width: theme.spacing(16) }, textStyle: { marginTop: theme.spacing(2), marginBottom: theme.spacing(2), fontFamily: "'Montserrat', sans-serif", textTransform: 'uppercase', } }); const ShowcaseCard = ({classes, image, text}) => { return ( <Card className={classes.card}> <Grid container justify="center" alignItems="center" direction="column"> <img src={image} className={classes.image} alt=""/> <Typography variant="h6" color="textSecondary" className={classes.textStyle} style={{fontWeight: 400}}> {text} </Typography> </Grid> </Card> ); }; export default withStyles(styles, {withTheme: true})(ShowcaseCard);
import User from './user' import Database from '../../../server' class Session extends Database.Model { get tableName () { return 'admin_sessions' } user() { return this.belongsTo(User, 'user_id') } } export default Session
export default async function(ctx) { let res = await ctx.models.mail.getErrorCode(this.postData); // let error = {}; // for (let item of res.data) { // for (let jtem in item) { // error[jtem] = item[jtem]; // } // } return res.data }
const express = require('express') const app = express() const { createArtist, listArtists, getArtistById, updateArtist, removeArtist } = require('./controllers/artists'); const { createAlbum, listAlbums, getAlbumById, updateAlbum, removeAlbum } = require('./controllers/albums'); const { createSong, listSongs, getSongsByAlbum, getSongsByArtist, findSongById, updateSong, removeSong } = require('./controllers/songs'); app.use(express.json()); // app.get('/', (req, res) => { // res.send('Hello World') // }); app.post('/artists', createArtist); app.get('/artists', listArtists); app.get('/artists/:id', getArtistById); app.patch('/artists/:id', updateArtist); app.delete('/artists/:id', removeArtist); //albums app.post('/artists/:artistId/albums', createAlbum); app.get('/albums', listAlbums); app.get('/albums/:id', getAlbumById); app.patch('/albums/:id', updateAlbum); app.delete('/albums/:id', removeAlbum); //songs app.post('/albums/:albumId/songs', createSong); app.get('/songs', listSongs); app.get('/albums/:albumId/songs', getSongsByAlbum); app.get('/artists/:artistId/songs', getSongsByArtist); app.get('/songs/:songId', findSongById); app.patch('/songs/:songId', updateSong); app.delete('/songs/:songId', removeSong); module.exports = app
let eggs = []; let running = true; function Egg(positions, side){ // console.log(positions, side); this.side = side; this.status = 0; this.positions = positions; this.speed = 1; this.move = function(){ this.status++; if(this.status > 4) resetgame(); } this.show = function(){ if(this.status > 0) { this.pos = this.positions[this.status-1]; image(I.egg[this.status-1], this.pos.x, this.pos.y); // image(I.egg[this.status-1], 100,100); } } } function eggpos(p){ const positions = [ [{x:8, y:26},{x:73, y:61},{x:134, y:63},{x:142, y:80}], [{x:5, y:178},{x:45, y:206},{x:135, y:210},{x:155, y:235}], [{x:600, y:177},{x:550, y:203},{x:450, y:215},{x:415, y:235}], [{x:600, y:26},{x:560, y:60},{x:465, y:75},{x:435, y:100}] ]; return positions[p]; // for(let i = 0 ; i < positions.length; i++){ // for(let o = 0; o < positions[i].length; o++){ // console.log(o); // image(I.egg[o],positions[i][o].x,positions[i][o].y) // } // } } function startEggs(){ eggGen(); } function eggGen() { let place = floor(random(4)); eggs.push(new Egg(eggpos(place), stringyPlace(place))) console.log(char.s) if(char.s != 'menu'){ setTimeout(eggGen, 3000*upspeed); } } function updateEggs(){ for(let i = 0; i < eggs.length; i++){ // console.log(egg); // console.log(eggs[i]) eggs[i].move(); } moves = 0; if(char.s != 'menu'){ setTimeout(updateEggs, 2000*upspeed); } redraw(); }
import React from 'react'; import {withRouter,Switch, Route} from 'react-router-dom'; import TestManagerComponent from './component'; import TestEditor from '../test-editor/container'; class TestManagerContainer extends React.Component{ render () { return ( <Switch> <Route exact path={`${this.props.match.url}`} render ={(props) =>{ return <TestManagerComponent testList={this.props.testList} {...props} />; }}/> <Route path={`${this.props.match.url}/add-test`} render ={(props) =>{ return <TestEditor {...props} />; }}/> <Route path={`${this.props.match.url}/edit-test/:id`} render ={(props) =>{ return <TestEditor testId={props.match.params.id} {...props} />; }}/> </Switch> ); } } let TestManager = withRouter(TestManagerContainer); export default TestManager;
kompair .controller('HomeCtrl', ['sharedProperties', HomeCtrl]) .controller('ResultsCtrl', ['sharedProperties', 'CommonRoutines', ResultsCtrl]) .controller('CompairCtrl', ['sharedProperties', CompairCtrl]) .controller('LoginCtrl', ['sharedProperties', '$firebaseAuth', LoginCtrl]) .controller('SignUpCtrl', ['sharedProperties', '$firebaseAuth', SignUpCtrl]) .controller('MainCtrl', ['$scope', 'sharedProperties', MainCtrl]) .controller('EditCtrl', ['sharedProperties', EditCtrl]) .controller('MainCtrl', ['$scope', '$state', 'sharedProperties', MainCtrl]); function HomeCtrl(sharedProperties) { var vm = this; vm.oShared = sharedProperties; vm.oShared.bSingedIn = false; vm.SignIn = function() { vm.oShared.bSingedIn = true; } } function ResultsCtrl(sharedProperties, CommonRoutines) { var res = this; res.arrResults = [{ id: 1, stars: 4, answers: 2, views: 36, title: 'Apple vs Orange', arrCategories: ['Food', 'Natural'] }, { id: 2, stars: 4, answers: 9, views: 219, title: 'Apple vs Android', arrCategories: ['Technology', 'Artificial'] }, { id: 3, stars: 0, answers: 0, views: 3, title: 'Blue vs Orange', arrCategories: ['Color', 'Natural'] }, { id: 4, stars: 7, answers: 14, views: 623, title: 'Apple vs Banana', arrCategories: ['Fruits', 'Natural'] }, { id: 5, stars: 7, answers: 14, views: 623, title: 'Apple vs Blackberry', arrCategories: ['Phones', 'Phones', 'Phones', 'Phones', 'Technology'] }, { id: 6, stars: 7, answers: 14, views: 623, title: 'Orange vs NewBlack', arrCategories: ['Series'] }, { id: 7, stars: 7, answers: 14, views: 623, title: 'Hillary vs Orange', arrCategories: ['Politics'] }]; res.oCompair = { id: 1, stars: 4, answers: 2, views: 36, title: 'Apple vs Orange', arrCategories: ['Food', 'Natural'], thumbsUp: 10, thumbsDown: 20, oCompairItem: [{ item: "Apple" }, { item: "Orange" }], oCamparables: [{ catId: 1, catType: "Text", catName: "Scientific", catValues: [ "This is some text about Apple", "This is some text about Orange" ] }, { catId: 2, catType: "OrderedList", catName: "Nutrients", catValues: [ ["Alpha", "Beta", "Gamma"], ["Delta", "Theta", "Omega"] ] }, { catId: 1, catType: "UnOrderedList", catName: "Physical", catValues: [ ["0.5 lbs", "6 cms"], ["0.76lbs", "5.3 cms"] ] }] }; res.oShared = sharedProperties; res.oService = { GetCompare: function(id) { //return CommonRoutines.FindItemInArray(res.arrResults, 'id', id, 'item'); return res.oCompair; } } res.Helper = { GetCompare: function(id) { res.oShared.oCompair = res.oService.GetCompare(id); res.oShared.ChangeStateTo('kompair.compare'); } } } function CompairCtrl(sharedProperties) { var com = this; //com.oShared = sharedProperties; com.oCompair = sharedProperties.oCompair; } function EditCtrl(sharedProperties) { var ed = this; ed.oShared = sharedProperties; ed.oCompair = angular.copy(sharedProperties.oCompair); //ed.oCompair = sharedProperties.oCompair; ed.Helper = { BackToCompare: function(sType) { if (sType == 'update') { sharedProperties.oCompair = ed.oCompair; // Service to update in DB and in return func call this ed.oShared.ChangeStateTo('kompair.compare'); } else { ed.oShared.ChangeStateTo('kompair.compare'); } } } } function SignUpCtrl(sharedProperties, $firebaseAuth) { var su = this; su.oShared = sharedProperties; su.SignUp = function() { var auth = $firebaseAuth(); auth.$createUserWithEmailAndPassword(su.user.email, su.user.password); su.oShared.ChangeStateTo('kompair.home'); }; } function LoginCtrl(sharedProperties, $firebaseAuth) { var lo = this; lo.oShared = sharedProperties; lo.user = {}; lo.SignIn = function() { lo.firebaseUser = null; lo.error = null; var auth = $firebaseAuth(); auth.$signInWithEmailAndPassword(lo.user.email, lo.user.password).then(function(firebaseUser) { lo.oShared.ChangeStateTo('kompair.home'); lo.oShared.bSingedIn = true; lo.oShared.sSignedInUserId = lo.user.email; }).catch(function(error) { switch (error.code) { case "auth/invalid-email": lo.sErrorMessage = "The email address provided is incorrect."; break default: case "auth/wrong-password": lo.sErrorMessage = "The password entered is incorrect."; break lo.sErrorMessage = "Sorry. Something went wrong. Please try again."; break; } }); }; } function MainCtrl($scope, sharedProperties) { var main = this; main.oShared = sharedProperties; $scope.$on("$ionicView.beforeEnter", function(event, data) { // handle event //return; console.log("State Params: ", data.stateId); //main.showNavHeader = sharedProperties.bSingedIn; //main.showNavHeader = data.stateId === "tabs.home" || data.stateId === "tabs.results" || data.stateId === "tabs.answer" || data.stateId === "tabs.logged_in_home" || data.stateId === "tabs.answer2" || data.stateId === "tabs.new" ? false : true; }); $scope.$on("$ionicView.enter", function(event, data) { // handle event return; console.log("State Params: ", data.stateId); }); $scope.$on("$ionicView.afterEnter", function(event, data) { // handle event //$state.transitionTo($state.current, $state.$current.params, { reload: true, inherit: true, notify: true }); return; console.log("State Params: ", data.stateId); }); };
class Cell { constructor() { this.pos = { posX: '', posY: '', } this.isActive = false; this.propertiesCSS = null; this.nameClass = ''; this.state = ''; } createCell(x, y, row) { let cell = document.createElement('td'); cell.classList.add('cell'); cell.id = x + '-' + y; this.propertiesCSS = cell; row.appendChild(cell); } }
const { User } = require('../../models'); module.exports = function(req, res) { User.findByIdAndUpdate(req.params.id, req.body, { new: true }) .then(({ firstName, lastName }) => res.send({ message: `${firstName} ${lastName} was updated` }) ) .catch(err => res.send({ message: err })); };
export const buttonHiddenStateToggle = (el) => { el.classList.toggle("hidden"); }; export const headerMenuToggle = () => { zoobooks().elements()["maintenance"].classList.toggle("active"); }; export const headerMenuHide = () => { zoobooks().elements()["maintenance"].classList.remove("active"); };
module.exports = (sequelize, Sequelize) => { const Task = sequelize.define("task", { task_uid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, }, task_title: { type: Sequelize.STRING, allowNull: false, }, task_description: { type: Sequelize.TEXT, }, task_category: { type: Sequelize.STRING, allowNull: false, }, task_category_id: { type: Sequelize.INTEGER, allowNull: false, }, task_due_date: { type: Sequelize.DATE, allowNull: false, defaultValue: new Date(), }, task_priority: { type: Sequelize.STRING, }, created_user_uid: { type: Sequelize.INTEGER, }, is_active: { type: Sequelize.BOOLEAN, allowNull: false, } }); return Task; };
import { Button, SafeAreaView, ScrollView, StyleSheet, Text, View, } from 'react-native'; import React from 'react'; const Info = ({navigation}) => { return ( <View style={styles.container}> <SafeAreaView> <ScrollView contentInsetAdjustmentBehavior="automatic"> <View style={styles.textContainer}> <Text style={styles.khmerText}> ទីងមោងគឺជាផ្នែកបុរាណមួយនៃទំនៀមទម្លាប់របស់ខ្មែរ។{' '} </Text> <Text style={styles.khmerText}> ទីងមោង​ត្រូវបានគេគិតថា គឺជារូប ​ដើម្បី​បញ្ចៀស​​នូវ​ឧបទ្រព​ចង្រៃ​គ្រប់​ប្រភេទនិង រារាំងវិញ្ញាណអាក្រក់។ </Text> <Text style={styles.khmerText}> ឥឡូវយើងស្ថិតក្នុងស្ថានភាពមួយដែលទាមទារឱ្យយើង </Text> <Text style={styles.khmerText}>រួបរួមគ្នាប្រុងប្រយ័ត្ន។</Text> <Text style={styles.khmerText}> គោលដៅនៃកម្មវិធីនេះគឺដើម្បីចែករំលែកព័ត៌មានអំពីសុវត្ថិភាព និងបង្កើនការយល់ដឹងជាសកលទាក់ទងនឹងការប្រយុទ្ធប្រឆាំងនឹងជម្ងឺ Covid-19 ។ </Text> <Text style={styles.khmerText}> ប៉ុន្តែទីងមោងត្រូវបានរចនាឡើងជាហ្គេមដែលអ្នកនឹងទទួលបានពិន្ទុ </Text> <Text style={styles.khmerText}> ដើម្បីបង្កើនកម្រិតនៃការការពារ ទីងមោង របស់អ្នក។ </Text> <Text style={styles.khmerText}> ជួយខ្លួនអ្នកដោយការការពារអ្នកដទៃ។ </Text> <Text style={styles.khmerText}> អរគុណ </Text> <View style={styles.submitButton}> <Button color={'white'} title="ទទួលយកល័ក្ខខ័ណ្ឌ" onPress={() => navigation.navigate('Profile', {name: 'Profile'}) } /> </View> </View> </ScrollView> </SafeAreaView> </View> ); }; const styles = StyleSheet.create({ container: { backgroundColor: '#e85143', justifyContent: 'center', alignItems: 'center', width: '100%', }, textContainer: { marginTop: 40, marginLeft: 20, marginRight: 20, textAlign: 'left', }, khmerText: { color: '#fff', fontSize: 18, margin: 6, }, submitButton: { marginTop: 30, marginLeft: 20, backgroundColor: '#0066A2', borderColor: '#0066A2', height: 50, width: 150, fontSize: 20, fontWeight: 'bold', }, }); export default Info;
//全局的公共数据 import * as type from '../mutations-type' import {PAGE_SIZE} from "../../config"; const state = { pageSize: PAGE_SIZE } const actions = {} const mutations = { [type.SAVE_PAGE_SIZE](state, {pageSize}) { state.pageSize = pageSize } } export default { state, actions, mutations }
import React from 'react'; import './Profile.css'; import profileBackground from '../assets/profile-background.jpg'; import Posts from './Posts'; function Profile() { return ( <section className="profile"> <p className="profile-background-image"> <img src={profileBackground} alt="Profile background" /> </p> <div>ava + description</div> <Posts /> </section> ); } export default Profile;
Polymer.IronResizableBehavior = { properties: { _parentResizable: { type: Object, observer: "_parentResizableChanged" }, _notifyingDescendant: { type: Boolean, value: !1 } }, listeners: { "iron-request-resize-notifications": "_onIronRequestResizeNotifications" }, created: function() { this._interestedResizables = [], this._boundNotifyResize = this.notifyResize.bind(this) }, attached: function() { this.fire("iron-request-resize-notifications", null, { node: this, bubbles: !0, cancelable: !0 }), this._parentResizable || (window.addEventListener("resize", this._boundNotifyResize), this.notifyResize()) }, detached: function() { this._parentResizable ? this._parentResizable.stopResizeNotificationsFor(this) : window.removeEventListener("resize", this._boundNotifyResize), this._parentResizable = null }, notifyResize: function() { this.isAttached && (this._interestedResizables.forEach(function(e) { this.resizerShouldNotify(e) && this._notifyDescendant(e) }, this), this._fireResize()) }, assignParentResizable: function(e) { this._parentResizable = e }, stopResizeNotificationsFor: function(e) { var i = this._interestedResizables.indexOf(e); i > -1 && (this._interestedResizables.splice(i, 1), this.unlisten(e, "iron-resize", "_onDescendantIronResize")) }, resizerShouldNotify: function(e) { return !0 }, _onDescendantIronResize: function(e) { return this._notifyingDescendant ? void e.stopPropagation() : void(Polymer.Settings.useShadow || this._fireResize()) }, _fireResize: function() { this.fire("iron-resize", null, { node: this, bubbles: !1 }) }, _onIronRequestResizeNotifications: function(e) { var i = e.path ? e.path[0] : e.target; i !== this && (this._interestedResizables.indexOf(i) === -1 && (this._interestedResizables.push(i), this.listen(i, "iron-resize", "_onDescendantIronResize")), i.assignParentResizable(this), this._notifyDescendant(i), e.stopPropagation()) }, _parentResizableChanged: function(e) { e && window.removeEventListener("resize", this._boundNotifyResize) }, _notifyDescendant: function(e) { this.isAttached && (this._notifyingDescendant = !0, e.notifyResize(), this._notifyingDescendant = !1) } }; Polymer.IronSelection = function(e) { this.selection = [], this.selectCallback = e }, Polymer.IronSelection.prototype = { get: function() { return this.multi ? this.selection.slice() : this.selection[0] }, clear: function(e) { this.selection.slice().forEach(function(t) { (!e || e.indexOf(t) < 0) && this.setItemSelected(t, !1) }, this) }, isSelected: function(e) { return this.selection.indexOf(e) >= 0 }, setItemSelected: function(e, t) { if (null != e && t !== this.isSelected(e)) { if (t) this.selection.push(e); else { var i = this.selection.indexOf(e); i >= 0 && this.selection.splice(i, 1) } this.selectCallback && this.selectCallback(e, t) } }, select: function(e) { this.multi ? this.toggle(e) : this.get() !== e && (this.setItemSelected(this.get(), !1), this.setItemSelected(e, !0)) }, toggle: function(e) { this.setItemSelected(e, !this.isSelected(e)) } }; Polymer.IronSelectableBehavior = { properties: { attrForSelected: { type: String, value: null }, selected: { type: String, notify: !0 }, selectedItem: { type: Object, readOnly: !0, notify: !0 }, activateEvent: { type: String, value: "tap", observer: "_activateEventChanged" }, selectable: String, selectedClass: { type: String, value: "iron-selected" }, selectedAttribute: { type: String, value: null }, fallbackSelection: { type: String, value: null }, items: { type: Array, readOnly: !0, notify: !0, value: function() { return [] } }, _excludedLocalNames: { type: Object, value: function() { return { template: 1 } } } }, observers: ["_updateAttrForSelected(attrForSelected)", "_updateSelected(selected)", "_checkFallback(fallbackSelection)"], created: function() { this._bindFilterItem = this._filterItem.bind(this), this._selection = new Polymer.IronSelection(this._applySelection.bind(this)) }, attached: function() { this._observer = this._observeItems(this), this._updateItems(), this._shouldUpdateSelection || this._updateSelected(), this._addListener(this.activateEvent) }, detached: function() { this._observer && Polymer.dom(this).unobserveNodes(this._observer), this._removeListener(this.activateEvent) }, indexOf: function(e) { return this.items.indexOf(e) }, select: function(e) { this.selected = e }, selectPrevious: function() { var e = this.items.length, t = (Number(this._valueToIndex(this.selected)) - 1 + e) % e; this.selected = this._indexToValue(t) }, selectNext: function() { var e = (Number(this._valueToIndex(this.selected)) + 1) % this.items.length; this.selected = this._indexToValue(e) }, selectIndex: function(e) { this.select(this._indexToValue(e)) }, forceSynchronousItemUpdate: function() { this._updateItems() }, get _shouldUpdateSelection() { return null != this.selected }, _checkFallback: function() { this._shouldUpdateSelection && this._updateSelected() }, _addListener: function(e) { this.listen(this, e, "_activateHandler") }, _removeListener: function(e) { this.unlisten(this, e, "_activateHandler") }, _activateEventChanged: function(e, t) { this._removeListener(t), this._addListener(e) }, _updateItems: function() { var e = Polymer.dom(this).queryDistributedElements(this.selectable || "*"); e = Array.prototype.filter.call(e, this._bindFilterItem), this._setItems(e) }, _updateAttrForSelected: function() { this._shouldUpdateSelection && (this.selected = this._indexToValue(this.indexOf(this.selectedItem))) }, _updateSelected: function() { this._selectSelected(this.selected) }, _selectSelected: function(e) { this._selection.select(this._valueToItem(this.selected)), this.fallbackSelection && this.items.length && void 0 === this._selection.get() && (this.selected = this.fallbackSelection) }, _filterItem: function(e) { return !this._excludedLocalNames[e.localName] }, _valueToItem: function(e) { return null == e ? null : this.items[this._valueToIndex(e)] }, _valueToIndex: function(e) { if (!this.attrForSelected) return Number(e); for (var t, i = 0; t = this.items[i]; i++) if (this._valueForItem(t) == e) return i }, _indexToValue: function(e) { if (!this.attrForSelected) return e; var t = this.items[e]; return t ? this._valueForItem(t) : void 0 }, _valueForItem: function(e) { var t = e[Polymer.CaseMap.dashToCamelCase(this.attrForSelected)]; return void 0 != t ? t : e.getAttribute(this.attrForSelected) }, _applySelection: function(e, t) { this.selectedClass && this.toggleClass(this.selectedClass, t, e), this.selectedAttribute && this.toggleAttribute(this.selectedAttribute, t, e), this._selectionChange(), this.fire("iron-" + (t ? "select" : "deselect"), { item: e }) }, _selectionChange: function() { this._setSelectedItem(this._selection.get()) }, _observeItems: function(e) { return Polymer.dom(e).observeNodes(function(e) { this._updateItems(), this._shouldUpdateSelection && this._updateSelected(), this.fire("iron-items-changed", e, { bubbles: !1, cancelable: !1 }) }) }, _activateHandler: function(e) { for (var t = e.target, i = this.items; t && t != this;) { var s = i.indexOf(t); if (s >= 0) { var n = this._indexToValue(s); return void this._itemActivate(n, t) } t = t.parentNode } }, _itemActivate: function(e, t) { this.fire("iron-activate", { selected: e, item: t }, { cancelable: !0 }).defaultPrevented || this.select(e) } };
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ function AnimationSlider() { this.timerlen = 5; this.slideAniLen = 1000; this.timerID = new Array(); this.startTime = new Array(); this.obj = new Array(); this.endHeight = new Array(); this.moving = new Array(); this.endSlideUpCallback = new Array(); this.dir = new Array(); } AnimationSlider.prototype.slidedown = function(objname){ if(this.moving[objname]) return; if(document.getElementById(objname).style.display != "none") return; // cannot slide down something that is already visible this.moving[objname] = true; this.dir[objname] = "down"; this.startslide(objname); } AnimationSlider.prototype.slidedownup = function(objname, endSlideUpCallback){ this.slidedown(objname); this.endSlideUpCallback[objname] = endSlideUpCallback; setTimeout("eXo.core.Notification.AnimationSlider.slideup('" + objname + "')", 3000); } AnimationSlider.prototype.slideup = function(objname){ if(this.moving[objname]) return; if(document.getElementById(objname).style.display == "none") return; // cannot slide up something that is already hidden this.moving[objname] = true; this.dir[objname] = "up"; this.startslide(objname); } AnimationSlider.prototype.startslide = function(objname){ this.obj[objname] = document.getElementById(objname); this.endHeight[objname] = parseInt(this.obj[objname].style.height); this.startTime[objname] = (new Date()).getTime(); if(this.dir[objname] == "down"){ this.obj[objname].style.height = "1px"; } this.obj[objname].style.display = "block"; this.timerID[objname] = setInterval('eXo.core.Notification.AnimationSlider.slidetick(\'' + objname + '\');',this.timerlen); } AnimationSlider.prototype.slidetick = function(objname){ var elapsed = (new Date()).getTime() - this.startTime[objname]; //this.obj[objname].innerHTML = this.obj[objname].style.height; if (elapsed > this.slideAniLen) this.endSlide(objname); else { var before = "before:" + this.obj[objname].id + "-" + this.obj[objname].style.height + "-"; var d =Math.round(elapsed / this.slideAniLen * this.endHeight[objname]); if(this.dir[objname] == "up") d = this.endHeight[objname] - d; this.obj[objname].style.height = d + "px"; } return; } AnimationSlider.prototype.endSlide = function(objname){ clearInterval(this.timerID[objname]); if(this.dir[objname] == "up") { this.obj[objname].style.display = "none"; if(this.endSlideUpCallback[objname]) { this.endSlideUpCallback[objname](objname); } } this.obj[objname].style.height = this.endHeight[objname] + "px"; delete(this.moving[objname]); delete(this.timerID[objname]); delete(this.startTime[objname]); delete(this.endHeight[objname]); delete(this.obj[objname]); delete(this.dir[objname]); return; } function Notification(){ this.msgId = 0; if (eXo.core.Topic != null) { eXo.core.Topic.subscribe("/eXo/portal/notification", function(event){ eXo.core.Notification.addMessage(event.message); }) } } Notification.prototype.deleteBox = function(objname) { var el = document.getElementById(objname); el.parentNode.removeChild(el); } Notification.prototype.addMessage = function(msg) { var currBoxId = "messageBox_" + this.msgId++; var msgEl = document.createElement('div'); msgEl.id = currBoxId; msgEl.style.width= "200px"; msgEl.style.height = "75px"; msgEl.style.display = "none"; msgEl.className = "messageBox"; msgEl.innerHTML = "<div id='messageContent'>" + msg + "</div>"; var msgsEl = document.getElementById("msgs"); if (msgsEl == null) { document.body.appendChild(document.createElement('div')).id = "msgs"; msgsEl = document.getElementById("msgs"); } msgsEl.appendChild(msgEl); eXo.core.Notification.AnimationSlider.slidedownup(currBoxId, this.deleteBox); } eXo.core.Notification = new Notification(); eXo.core.Notification.AnimationSlider = new AnimationSlider();
/** * @license * Copyright (C) 2012 Pyrios * * 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. */ /** * @fileoverview * Registers a language handler for TCL * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-tcl">proc foo {} {puts bar}</pre> * * I copy-pasted lang-lisp.js, so this is probably not 100% accurate. * I used http://wiki.tcl.tk/1019 for the keywords, but tried to only * include as keywords that had more impact on the program flow * rather than providing convenience. For example, I included 'if' * since that provides branching, but left off 'open' since that is more * like a proc. Add more if it makes sense. * * @author pyrios@gmail.com */ PR['registerLangHandler']( PR['createSimpleLexer']( [ ['opn', /^\{+/, null, '{'], ['clo', /^\}+/, null, '}'], // A line comment that starts with ; [PR['PR_COMMENT'], /^#[^\r\n]*/, null, '#'], // Whitespace [PR['PR_PLAIN'], /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], // A double quoted, possibly multi-line, string. [PR['PR_STRING'], /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"'] ], [ [PR['PR_KEYWORD'], /^(?:after|append|apply|array|break|case|catch|continue|error|eval|exec|exit|expr|for|foreach|if|incr|info|proc|return|set|switch|trace|uplevel|upvar|while)\b/, null], [PR['PR_LITERAL'], /^[+\-]?(?:[0#]x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i], // A single quote possibly followed by a word that optionally ends with // = ! or ?. [PR['PR_LITERAL'], /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/], // A word that optionally ends with = ! or ?. [PR['PR_PLAIN'], /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i], // A printable non-space non-special character [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/] ]), ['tcl']);
// @flow import { Animated } from 'react-native'; import { RenderSearchResults, topValue, lowValue, } from '../RenderSearchResults'; const defaultProps = (stats: Object = { maxPrice: 100, minPrice: 50 }) => ({ show: 'list', setCurrentSearchStats: jest.fn(), data: { allAvailableBookingComHotels: { stats, }, }, }); it('it initiales correctly when it should show list', () => { // $FlowExpectedError: Passing only props needed for this test const Component = new RenderSearchResults(defaultProps()); expect(Component.mapAnimation).toEqual(new Animated.Value(topValue)); expect(Component.listAnimation).toEqual(new Animated.Value(0)); }); it('it initiales correctly when it should show list', () => { // $FlowExpectedError: Passing only props needed for this test const Component = new RenderSearchResults({ show: 'map' }); expect(Component.mapAnimation).toEqual(new Animated.Value(0)); expect(Component.listAnimation).toEqual(new Animated.Value(lowValue)); });
import get from '../../lib/get'; const o = {p:[{l:{i:{ a: 12 }}}]} console.log(get(o,"p[0].l.i.a"))
const mongoose = require("mongoose"); const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: [true, "User is required"] }, company: String, website: String, location: String, status: { type: String, required: [true, "Status is required"] }, skills: { type: [String], required: [true, "Skill is required"], validate: [ value => value.length > 0 && value.every(v => v.length > 0), "Skills are required" ] }, bio: String, githubUsername: String, experience: [ { title: { type: String, required: [true, "Title is required"] }, company: { type: String, required: [true, "Company is required"] }, location: String, from: Date, to: { type: Date, validate: [ function(value) { return value.getTime() > this.from.getTime(); }, "To date must be later than From date" ] }, current: { type: Boolean, default: false }, description: String } ], education: [ { school: { type: String, required: [true, "School is required"] }, degree: { type: String, required: [true, "Degree is required"] }, fieldOfStudy: { type: String, required: [true, "Field of Study is required"] }, from: Date, to: { type: Date, validate: [ function(value) { return value.getTime() > this.from.getTime(); }, "To date must be later than From date" ] }, current: { type: Boolean, default: false }, description: String } ], social: { youtube: String, twitter: String, facebook: String, linkedin: String, instagram: String }, created: { type: Date, default: Date.now }, updated: { type: Date } }); module.exports = mongoose.model("Profile", ProfileSchema);
import { storiesOf, html } from "@open-wc/demoing-storybook"; import '../LionDemoInput.js' storiesOf('Demo|Lion elements', module) .add('Lion Demo Input', () => html`<lion-demo-input></lion-demo-input>`);
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools'; import resolvers from './../resolvers/resolver'; const typeDefs = `type Person { id: String, age: Int name: String gender: String books: [String] } type Query { persons(age: Int): [Person], person(id: String): Person } type Mutation { addPerson(age: Int, name: String, gender: String, books: [String]): Person deletePerson(id: String!): Person updatePerson(id: String!, name: String!): Person } ` const schema = makeExecutableSchema({ typeDefs, resolvers }); // addMockFunctionsToSchema({ schema }) export default schema;
// the database config for pool module.exports = { /* // for local db dev: { connectionLimit: 100, // important host: '127.0.0.1', port: '3306', user: 'root', password: 'Hello000', database: 'yaloc3', charset: 'utf8', debug: false } // */ /* // for remote db dev: { connectionLimit: 20, // important // host: '192.168.100.213', // host: '124.204.33.42:9702', host: '127.0.0.1', port: '3306', user: 'root', password: 'password', database: 'yaxt4', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '127.0.0.1', port: '3306', user: 'root', password: 'password', database: 'yaxt4', charset: 'utf8', debug: false } */ /* // 高河正式外网 dev: { connectionLimit: 10, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. // connectTimeout: 60 * 60 * 1000, // aquireTimeout: 60 * 60 * 1000, // timeout: 60 * 60 * 1000, host: '60.220.238.150', port: '16387', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt', charset: 'utf8', debug: false }, pro: { connectionLimit: 10, // important host: '60.220.238.150', port: '16387', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt', charset: 'utf8', debug: false } */ /* // 高河正式 dev: { connectionLimit: 20, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. // connectTimeout: 60 * 60 * 1000, // aquireTimeout: 60 * 60 * 1000, // timeout: 60 * 60 * 1000, host: '192.168.118.198', port: '3306', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '192.168.118.198', port: '3306', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt', charset: 'utf8', debug: false } */ /* // 9000web dev: { connectionLimit: 10, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. host: '192.168.118.199', port: '3306', user: 'root', password: 'password', database: 'yaxt', charset: 'utf8', debug: false }, pro: { connectionLimit: 10, // important host: '192.168.118.199', port: '3306', user: 'root', password: 'password', database: 'yaxt', charset: 'utf8', debug: false } */ // 测试 /* dev: { connectionLimit: 20, // important // host: '192.168.100.213', // host: '124.204.33.42:9702', connectTimeout: 60 * 60 * 1000, aquireTimeout: 60 * 60 * 1000, timeout: 60 * 60 * 1000, host: '192.168.118.200', port: '3306', user: 'webapp', password: 'webgroup', database: 'yaxt', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '192.168.118.200', port: '3306', user: 'webapp', password: 'webgroup', database: 'yaxt', charset: 'utf8', debug: false } */ /* dev: { connectionLimit: 20, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. host: '60.220.238.150', port: '16387', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt4', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '60.220.238.150', port: '16387', user: 'yadb', password: 'Yadb@2018#123', database: 'yaxt', charset: 'utf8', debug: false } */ /* dev: { connectionLimit: 20, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. host: '127.0.0.1', port: '23306', user: 'yadb', password: 'yadb@123', database: 'yaxt_yanshi', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '127.0.0.1', port: '23306', user: 'yadb', password: 'yadb@123', database: 'yaxt_yanshi', charset: 'utf8', debug: false } */ dev: { connectionLimit: 20, // important // waitForConnections: true, // If true, the pool will queue the connection request and call it when one becomes available. host: '192.168.0.247', port: '3306', user: 'yadb', password: 'yadb@123', database: 'yaxt', charset: 'utf8', debug: false }, pro: { connectionLimit: 20, // important host: '192.168.0.236', port: '3306', user: 'yadb', password: 'Yadb@2020#123', database: 'yaxt', charset: 'utf8', debug: false } } /* In addition to passing these options as an object, you can also use a url string. For example: var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700') */
import React from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; export const KickedPage = () => { const navigate = useNavigate(); const { state } = useLocation(); return ( <main className='simple-wrapper'> <p className='simple-heading'>Oh no!</p> <p className='simple-subhead'>You were kicked for {state?.kickReason}.</p> <div className='simple-section'> <button onClick={() => navigate('/')}>Go back home</button> </div> </main> ); };
function setup(){ var cnv = createCanvas(1500,500); background(255); } function draw(){ circle(0,0,400,400) }
/* * * scaleManagementNutrientsController.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * */ 'use strict'; /** * The controller for the Scale Management Nutrient Statement Controller. */ (function () { angular.module('productMaintenanceUiApp').controller('ScaleManagementNutrientStatementController', scaleManagementNutrientStatementController); scaleManagementNutrientStatementController.$inject = ['ScaleManagementApi','ngTableParams','urlBase','DownloadService', 'PermissionsService' ,'$scope', '$stateParams']; /** * Constructs the controller. * * @param scaleManagementApi The API to fetch data from the backend. * @param ngTableParams The API to set up the report table. * @param urlBase The base url used for building export requests. * @param downloadService The service used for downloading a file. */ function scaleManagementNutrientStatementController(scaleManagementApi, ngTableParams, urlBase, downloadService, permissionsService, $scope, $stateParams) { var self = this; self.NUTRIENT_CODE = "nutrient code"; self.STATEMENT_ID = "statement id"; self.UNKNOWN_ERROR = "An unknown error occurred."; self.EMPTY_STRING = ""; self.METRIC_MEASURE_SYSTEM = "M"; self.COMMON_MEASURE_SYSTEM = "C"; self.VARIES_LABEL = " varies"; self.PAGE_SIZE = 20; /** * Informational text for the user adding sub-ingredients. * * @type {string} */ self.SUB_NUTRIENT_TEXT = "A sub-nutrient cannot be added that exists as a sub-nutrient already, " + "or as a sub-nutrient of those sub-nutrients. An nutrient also cannot be added as a " + "sub-nutrient if it exists as a super nutrient, or a super nutrient of those super nutrient."; /** * The type of data the user has selected. For basic search, this is nutrientCode, or statement id * search. * * @type {string} */ self.selectionType = null; /** * The options for the date picker on the popup. * * @type {Object} */ self.datePickerOptions = {minDate: new Date()}; /** * Whether or not the user is editing nutrient statement. * * @type {boolean} */ self.isEditing = false; /** * Whether or not user is adding an nutrient statement. * * @type {boolean} */ self.isAddingNutrientStatement = false; self.nutrientStatement = {}; /** * Keeps track of current request. * * @type {number} */ self.latestRequest = 0; /** * Whether or not effective date picker is visible. * * @type {boolean} */ self.effectiveDatePickerOpened = false; /** * The ngTable object that will be waiting for data while the report is being refreshed. * * @type {?} */ self.defer = null; /** * Whether or not the search search panel is collapsed or open. * * @type {boolean} */ self.searchPanelVisible = true; /** * Whether or not the controller is waiting for data. * * @type {boolean} */ self.isWaiting = false; /** * Whether or not this is the first search with the current parameters. * * @type {boolean} */ self.firstSearch = true; /** * Index of data that is being edited. * * @type {number} */ self.previousEditingIndex = null; /** * The ngTable object that will be waiting for data while the report is being refreshed. * * @type {?} */ self.defer = null; /** * The paramaters passed from the ngTable when it is asking for data. * * @type {?} */ self.dataResolvingParams = null; /** * The number of records to show on the report. * * @type {number} */ self.PAGE_SIZE = 20; /** * Whether or not a user is adding an nutrition statement. * * @type {boolean} */ self.isAddingNutrientStatement = false; /** * The data being shown in the report. * * @type {Array} */ self.data = null; /** * Whether or not to ask the backed for the number of records and pages are available. * * @type {boolean} */ self.includeCounts = true; /** * The nutrient code to be used to search for the nutrient rounding rules. * * @type {Integer} */ self.nutrientCode = null; /** * Tracks whether or not the user is waiting for a download. * * @type {boolean} */ self.downloading = false; /** * Is Waiting for Mandated nutrients. * * @type {boolean} */ self.isMandatedWaiting = false; /** * Current non zero list. * @type {Array} */ self.currentNonZeroNutrientList = []; /** * Whether the current nutrient statement code is available. * * @type {boolean} */ self.isNutrientStatementCodeAvailable = null; /** * Message to display for deleted nutrient statement. * * @type {string} */ self.deleteMessage = null; /** * Max time to wait for excel download. * * @type {number} */ self.WAIT_TIME = 1200; /** * The message to display about the number of records viewing and total (eg. Result 1-100 of 130). * @type {String} */ self.resultMessage = null; /** * The departments array. * @type {string[]} */ self.departmentArray = [ {id: 131, isSelected: false}, {id: 151, isSelected: false}, {id: 161, isSelected: false}, {id: 213, isSelected: false}, {id: 301, isSelected: false}, {id: 601, isSelected: false}, {id: 603, isSelected: false}, {id: 701, isSelected: false}, {id: 901, isSelected: false}]; /** * Whether every row is selected. * * @type {boolean} */ self.selectAll = false; /** * Remaining available characters for the serving label. * * @type {number} */ self.servingTextCharacterRemainingCharacterCount = 22; /** * Current String for the serving size label * * @type {string} */ self.servingLabel = ""; /** * Show varies label when Servings Per Container = 999. * * @type {string} */ self.showVariesLabel = ""; /** * Servings Per Container value = 999;. * * @type {number} */ self.servingPerContainerVariesVary = 999; self.isCheckExistNLEA2016Waiting = false; self.isExistNLEA2016 = false; /** * Initialize the controller. */ self.init = function(){ if(self.removedNutrientStatement) { self.modifyMessage = null; self.error = null; self.data = null; self.searchPanelVisible = true; self.removedNutrientStatement = false; } self.selectionType = self.STATEMENT_ID; self.disableNumberInputFeatures("measureQuantity"); self.disableNumberInputFeatures("metricQuantity"); if($stateParams && $stateParams.ntrStmtCode){ self.searchSelection = $stateParams.ntrStmtCode; self.newSearch(); } }; /** * Returns wheter or not the user can edit nutrient statements. * * @returns {*} */ self.canEditNutrientStatements = function() { return permissionsService.getPermissions("SM_NTRN_02", "EDIT"); }; /** * set data to null */ self.selectionTypeChanged = function(){ self.data = null; }; const MINUTES_TO_MILLISECONDS = 60000; /** * Returns whether or not the user is currently downloading a CSV, * * @returns {boolean} True if the user is downloading product information CSV and false otherwise. */ self.isDownloading = function(){ return self.downloading; }; /** * Returns the text to display in the search box when it is empty. * * @returns {string} The text to display in the search box when it is empty. */ self.getTextPlaceHolder = function(){ return 'Enter ' + self.selectionType + 's to search' }; /** * Issue call to newSearch to call back end to fetch all nutrition codes. */ self.searchAll = function (){ self.newSearch(true); }; /** * Set the value as a date so date picker understands how to represent value. */ self.setDateForDatePicker = function(nutrientStatement){ if(self.nutrientStatement.effectiveDate != null) { self.nutrientStatement.effectiveDate = new Date(self.nutrientStatement.effectiveDate.replace(/-/g, '\/')); } }; /** * Gets current results for dropdown by calling api. * @param query */ self.getCurrentDropDownResults = function(measureSystem, query){ var request = ++self.latestRequest; if (!(query === null || !query.length || query.length === 0)) { var requestParams = {searchString: query, measureSystem: measureSystem, page: 0, pageSize: self.pageSize}; // If we're searching for the metric unit of measure and the common UOM has been set, then // constrain on the form types that match the common UOM's form. if (measureSystem == self.METRIC_MEASURE_SYSTEM && self.nutrientStatement.nutrientCommonUom != null) { requestParams.form = self.nutrientStatement.nutrientCommonUom.form; } scaleManagementApi. findNutrientUomByRegularExpression(requestParams, //success function (results) { if(request === self.latestRequest) { self.valueList = results.data; } }, //error function(results) { if (request === self.latestRequest) { self.valueList = []; } } ); } else { self.valueList = []; } }; /** * Open the effective date picker to select a new date. */ self.openEffectiveDatePicker = function(){ self.effectiveDatePickerOpened = true; self.options = { minDate: new Date() }; }; /** * Cancel edit of row for nutrients statement */ self.cancelEdit = function() { self.nutrientStatement = null; self.isEditing = false; self.isAddingNutrientStatement = false; self.previousEditingIndex = null; }; /** * Clears the search box. */ self.clearSearch = function () { self.searchSelection = null; }; /** * Initiates a new search. */ self.newSearch = function(findAll){ self.modifyMessage = null; self.modifyError = null; self.deleteMessage = null; self.firstSearch = true; self.nutrientCode = null; self.previousEditingIndex = null; self.findAll = findAll; self.tableParams.page(1); self.isAddingNutrientStatement = false; self.tableParams.reload(); }; /** * Callback for when the backend returns an error. * * @param error The error from the backend. */ self.fetchError = function(error) { self.isWaiting = false; self.data = null; self.isAddingNutrientStatement = false; self.isEditing = false; self.isCheckExistNLEA2016Waiting = false; if (error && error.data) { if(error.data.message != null && error.data.message != "") { self.setError(error.data.message); } else { self.setError(error.data.error); } } else { self.setError(self.UNKNOWN_ERROR); } }; /** * Sets the controller's error message. * * @param error The error message. */ self.setError = function(error) { self.error = error; }; /** * Initialize a new nutrient statement. */ self.createNutrientStatement = function () { self.deleteMessage = null; self.isEditing = false; self.isAddingNutrientStatement = true; self.nutrientStatement= {effectiveDate: new Date()}; self.getAvailableMandatedNutrients({nutrientStatementCode: null}); self.updateServingLabelComponents(); self.updateShowVariesLabelComponents(); }; /** * Checks to see if any nutrients are null. * * @returns {boolean} */ self.isAnyNutrientsNull = function () { if(self.nutrientStatement != null) { if(self.nutrientStatement.nutrientStatementDetailList != null){ if(self.nutrientStatement.nutrientStatementDetailList.length > 0) { for (var x = 0; x < self.nutrientStatement.nutrientStatementDetailList.length; x++) { var obj = self.nutrientStatement.nutrientStatementDetailList[x]; if(obj == null || obj.nutrient == null){ return true; } } } } } return false; }; /** * Adds an nutrient to the nutrient statement. */ self.addNutrient = function(){ if(self.nutrientStatement == null) { self.nutrientStatement = {nutrientStatementDetailList: []}; } else if(self.nutrientStatement.nutrientStatementDetailList == null) { self.nutrientStatement.nutrientStatementDetailList = []; } for(var index =0; index < self.currentNonZeroNutrientList.length; index++) { self.nutrientStatement.nutrientStatementDetailList.splice(index, 0, self.currentNonZeroNutrientList[index]); self.nutrientStatement.nutrientStatementDetailList[index].isNewElement = true; } self.currentNonZeroNutrientList = []; }; /** * Populates current nutrient list based on search query string. * * @param query search string */ self.getCurrentNutrientCodeList = function(query){ var thisRequest = ++self.latestRequest; if (!(query === null || !query.length || query.length === 0)) { scaleManagementApi. getNutrientsByRegularExpression({ searchString: query, currentNutrientList: self.getCurrentNutrientList() }, //success function (results) { if(thisRequest === self.latestRequest) { self.currentNutrientList = results.data; } }, //error function (results) { if(thisRequest === self.latestRequest) { self.currentNutrientList = []; } } ); } else { self.currentNutrientList = []; } }; /** * Get current ingredient codes of selected ingredient. */ self.getCurrentNutrientList = function(){ var currentNutrientCodeList = []; var detail; for(var index = 0; index < self.nutrientStatement.nutrientStatementDetailList.length; index++){ detail = self.nutrientStatement.nutrientStatementDetailList[index]; if (detail.nutrient != null && detail.nutrient.nutrientCode != null) { currentNutrientCodeList.push(detail.nutrient.nutrientCode); } } return currentNutrientCodeList; }; /** * Takes in new or modified data and creates or updates nutrient Statement */ self.addNutrientStatement = function () { if(self.nutrientStatement != null && self.isAddingNutrientStatement) { var nutrientStatement = angular.copy(self.nutrientStatement); nutrientStatement.effectiveDate = $scope.convertDate(nutrientStatement.effectiveDate); this.isWaiting = true; scaleManagementApi.addStatement(nutrientStatement, self.loadData, self.fetchError); } else if(self.nutrientStatement != null && self.isEditing){ self.saveNutritionStatement(); } else { self.error = "No changes detected"; } }; /** * Check weather fields that are needed for an update or new statement are filled out. * * @returns {boolean} True if some information is missing and false otherwise. */ self.isRequiredNutrientInfoMissing = function () { return !(self.nutrientStatement != null && self.nutrientStatement.nutrientStatementNumber != null && (self.servingTextCharacterRemainingCharacterCount>=0) && self.nutrientStatement.measureQuantity != null && self.nutrientStatement.nutrientMetricUom != null && self.nutrientStatement.metricQuantity != null && self.nutrientStatement.servingsPerContainer != null && self.nutrientStatement.effectiveDate != null && self.nutrientStatement.nutrientCommonUom != null && (self.isNutrientStatementCodeAvailable == 'Available' || self.isEditing)); }; /** * Calls the method to get data based on tab selected. * * @param page The page to get. */ self.getReportByTab = function (page) { if (self.findAll) { self.getReportByAll(page); return; } switch (self.selectionType) { case self.NUTRIENT_CODE: { self.getReportByNutrientCode(page); break; } case self.STATEMENT_ID: { self.getReportByStatementId(page); break; } } }; /** * Calls the API method to get data for all. * * @param page */ self.getReportByAll = function (page) { scaleManagementApi.queryForNutrientStatementsByAll({ page: page, pageSize: self.PAGE_SIZE, includeCounts: self.includeCounts }, self.loadData, self.fetchError); }; /** * Calls API method to get data based on nutrient codes. * * @param page */ self.getReportByNutrientCode = function (page) { scaleManagementApi.queryForNutrientStatementByNutrientCode({ nutrientCodes: self.searchSelection, page: page, pageSize: self.PAGE_SIZE, includeCounts: self.includeCounts }, self.loadData, self.fetchError); // Commented out per PM-985 //scaleManagementApi.queryForMissingNutrientCodesByNutrientStatements({nutrientCodes: self.searchSelection}, // self.showMissingData, self.fetchError); }; /** * Calls PI method to get dat a based on statement id. * * @param page */ self.getReportByStatementId = function (page) { scaleManagementApi.queryForNutrientStatementByStatementId({ nutrientStatementId: self.searchSelection, page: page, pageSize: self.PAGE_SIZE, includeCounts: self.includeCounts }, self.loadData, self.fetchError); // Commented out per PM-985 //scaleManagementApi.queryForMissingNutrientStatementsByNutrientStatements({ // nutrientStatements: self.searchSelection}, self.showMissingData, self.fetchError); }; /** * Changes the edit mode of a nutrient detail object to the opposite of what it currently is. * * @param nutrientDetail The nutrient detail object to flip the edit mode of. */ self.flipEditMode = function(nutrientDetail) { nutrientDetail.inAlternateEditMode = !nutrientDetail.inAlternateEditMode; }; /** * Returns whether or not to not show nutrient measure at all for a nutrient detail object. * * @param nutrientDetail The nutrient detail object to not show the measure of. * @returns {boolean} True if the UI should not show nutrient measure and false otherwise. */ self.showBlankNutrientMeasure = function(nutrientDetail) { // Never show it if there is no defined recommendedDailyAmount. They have to edit the measure. if (nutrientDetail.nutrient.recommendedDailyAmount == 0) { return false; } // If they are in alternate edit mode, then, by definition, you'd never see a blank one here. if (nutrientDetail.inAlternateEditMode) { return false; } // So basically, show blank if we usePercentDailyValue and are not in alternate edit mode. return nutrientDetail.nutrient.usePercentDailyValue; }; /** * Returns whether or not to show a read-only version of the nutrient measure for a nutirent detail object. * * @param nutrientDetail The nutrient detail object to show a read-only nutrient measure for. * @returns {boolean} True if the UI should show read-only nutrient measure and false otherwise. */ self.showReadOnlyNutrientMeasure = function(nutrientDetail) { // If there is no recommended daily value, you always have to edit that way, so never show the empty box. if (nutrientDetail.nutrient.recommendedDailyAmount == 0) { return false; } if (nutrientDetail.inAlternateEditMode) { return !nutrientDetail.nutrient.usePercentDailyValue; } else { nutrientDetail.nutrient.usePercentDailyValue; } }; /** * Returns whether or not a user should be able to edit a nutrient detail's regular measure quantity. * * @param nutrientDetail The nutrient detail object to look at. * @returns {boolean} True if the user can edit the measure quantity and false otherwise. */ self.isEditableNutrientMeasure = function(nutrientDetail) { // If there is no recommended daily value, you always have to edit this way. if (nutrientDetail.nutrient.recommendedDailyAmount == 0) { return true; } if (nutrientDetail.inAlternateEditMode) { return nutrientDetail.nutrient.usePercentDailyValue; } else { return !nutrientDetail.nutrient.usePercentDailyValue; } }; /** * Returns whether or not a percent daily value is editable for a nutrient detail. * * @param nutrientDetail The nutrient detail object to look at. * @returns {boolean} True if the user can edit the percent daily value and false otherwise. */ self.isEditablePercentDailyValue = function(nutrientDetail) { // If there is no recommended daily value, you can never edit. if (nutrientDetail.nutrient.recommendedDailyAmount == 0.0) { return false; } /// If there is a recommended daily value, you should defer to usePercentDailyValue unless // the user has specifically said they want to do the opposite. if (nutrientDetail.inAlternateEditMode) { return !nutrientDetail.nutrient.usePercentDailyValue; } else { return nutrientDetail.nutrient.usePercentDailyValue; } }; /** * Constructs the table that shows the report. */ self.buildTable = function() { return new ngTableParams( { // set defaults for ng-table page: 1, count: self.PAGE_SIZE }, { // hide page size counts: [], /** * Called by ngTable to load data. * * @param $defer The object that will be waiting for data. * @param params The parameters from the table helping the function determine what data to get. */ getData: function ($defer, params) { self.defer = $defer; if(self.isCurrentStateNull()) { self.defer = $defer; return; } self.isWaiting = true; self.data = null; self.isWaitingForRoundRules = false; self.roundingRulesSuccess = null; self.roundingRulesData = null; // Save off these parameters as they are needed by the callback when data comes back from // the back-end. self.defer = $defer; self.dataResolvingParams = params; // If this is the first time the user is running this search (clicked the search button, // not the next arrow), pull the counts and the first page. Every other time, it does // not need to search for the counts. if(self.firstSearch){ self.includeCounts = true; self.firstSearch = false; } else { self.includeCounts = false; } // Issue calls to the backend to get the data. self.getReportByTab(params.page() - 1); } } ); }; /** * The parameters that define the table showing the report. */ self.tableParams = self.buildTable(); /** * Checks whether searchSelection is null and if the find all option is not selected. * * @returns {boolean} return true */ self.isCurrentStateNull = function(){ return (!self.findAll && self.searchSelection == null); }; /** * Edit current row of nutrition statement data. * * @param statement * @param index */ self.editNutritionStatement = function(statement, index){ self.deleteMessage = null; self.isEditing = true; self.nutrientStatement = angular.copy(statement); self.updateServingLabelComponents(); self.updateShowVariesLabelComponents(); self.setDateForDatePicker(self.nutrientStatement); self.previousEditingIndex = index; self.getAvailableMandatedNutrients(statement); }; /** * Gets available mandated nutrients... if there are any available. * * @param statement */ self.getAvailableMandatedNutrients = function(statement) { self.isMandatedWaiting = true; self.currentNonZeroNutrientList = []; if (!self.isAddingNutrientStatement){ self.isCheckExistNLEA2016Waiting = true; scaleManagementApi.isNLEA16NutrientStatementExists({ nutrientStatementNumber: statement.nutrientStatementNumber }, function (result) { self.isExistNLEA2016 = angular.copy(result.data); self.isCheckExistNLEA2016Waiting = false; }, self.fetchError); } scaleManagementApi.getMandatedNutrientsByStatementId({ statementNumber: statement.nutrientStatementNumber }, //success function (results) { self.currentNonZeroNutrientList = results; self.isMandatedWaiting = false; }, //error function (results) { self.currentNonZeroNutrientList = []; self.isMandatedWaiting = false; } ); }; /** * Push updated nutrition statement data to back end to write to database */ self.saveNutritionStatement = function() { var difference = angular.toJson(self.data[self.previousEditingIndex]) != angular.toJson(self.nutrientStatement); if(difference) { var nutrientStatement = angular.copy(self.nutrientStatement); nutrientStatement.effectiveDate = $scope.convertDate(nutrientStatement.effectiveDate); this.isWaiting = true; scaleManagementApi.updateNutritionStatementData(nutrientStatement, self.loadData, self.fetchError); } else { self.error = "No difference detected"; } }; /** * Callback for a successful call to get data from the backend. It requires the class level defer * and dataResolvingParams object is set. * * @param results The data returned by the backend. */ self.loadData = function(results){ self.error = null; self.success = null; self.isWaiting = false; // If this was the fist page, it includes record count and total pages . if (results.complete) { self.totalRecordCount = results.recordCount; self.dataResolvingParams.total(self.totalRecordCount); } if (results.data.length === 0) { self.data = null; self.error = "No records found."; } else if(self.isAddingNutrientStatement){ self.isAddingNutrientStatement = false; self.modifyMessage = results.message; self.resultMessage = null; self.data = []; self.data.push(results.data); self.defer.resolve(self.data); } else if(self.previousEditingIndex != null && self.isEditing){ self.error = null; self.modifyMessage = results.message; self.data[self.previousEditingIndex] = results.data; self.previousEditingIndex = null; self.nutrientStatement = null; self.isEditing = false; } else { self.resultMessage = self.getResultMessage(results.data.length, results.page); self.error = null; self.data = results.data; self.defer.resolve(results.data); } if(self.removedNutrientStatement) { self.removedNutrientStatement = false; } else { self.deleteMessage = null; } // Return the data back to the ngTable. }; /** * Initiates a download of all the records. */ self.export = function() { var encodedUri = self.generateExportUrl(); if(encodedUri !== self.EMPTY_STRING) { self.downloading = true; downloadService.export(encodedUri, 'nutrientStatements.csv', self.WAIT_TIME, function () { self.downloading = false; }); } }; /** * Generates the URL to ask for the export. * * @returns {string} The URL to ask for the export. */ self.generateExportUrl = function() { if(self.selectionType == self.NUTRIENT_CODE && !self.findAll) { return urlBase + '/pm/nutrientsStatement/exportNutrientStatementByNutrientCodesToCsv?nutrientCodes=' + encodeURI(self.searchSelection) + "&totalRecordCount=" + self.totalRecordCount; } else if (self.selectionType == self.STATEMENT_ID && !self.findAll){ return urlBase + '/pm/nutrientsStatement/exportNutrientStatementByIdsToCsv?nutrientStatements=' + encodeURI(self.searchSelection) + "&totalRecordCount=" + self.totalRecordCount; } else if (self.findAll){ return urlBase + '/pm/nutrientsStatement/exportAllNutrientStatementsToCsv?totalRecordCount=' + self.totalRecordCount; } else { return self.EMPTY_STRING; } }; /** * Callback for the request for the number of items found and not found. * * @param results The object returned from the backend with a list of found and not found items. */ self.showMissingData = function(results){ self.missingValues = results; }; /** * Only show match count information for searches by ingredient statement code. * * @returns {boolean} True if the search is by ingredient statement code. */ self.showMatchCount = function(){ return self.selectionType === self.STATEMENT_ID || self.selectionType === self.NUTRIENT_CODE; }; /** * Generates the message that shows how many records and pages there are and what page the user is currently * on. * * @param dataLength The number of records there are. * @param currentPage The current page showing. * @returns {string} The message. */ self.getResultMessage = function(dataLength, currentPage){ return "Result " + (self.PAGE_SIZE * currentPage + 1) + " - " + (self.PAGE_SIZE * currentPage + dataLength) + " of " + self.totalRecordCount.toLocaleString(); }; /** * If there are available mandated nutrients to add or remove. * * @returns {boolean} */ self.isMandated = function () { return self.currentNonZeroNutrientList.length == 0; }; /** * If the current typed in statement ID is available or not. */ self.isStatementCodeAvailable = function () { if (self.nutrientStatement.nutrientStatementNumber != null) { scaleManagementApi.searchForAvailableNutrientStatement({ nutrientStatement: self.nutrientStatement.nutrientStatementNumber }, //success function (results) { self.isNutrientStatementCodeAvailable = results.data; }, //error function(results) { self.isNutrientStatementCodeAvailable = "Not available"; } ); } else { self.isNutrientStatementCodeAvailable = "Not available"; } }; /** * If the current mandated nutrients are still loading. * * @returns {boolean} */ self.isCurrentlyWaiting = function () { return self.isMandatedWaiting; }; /** * Sends nutrient statement to backend to be removed. */ self.removeNutrientStatement = function() { var nutrientStatementNumber = self.data[self.previousEditingIndex].nutrientStatementNumber; var deptList = []; for(var index = 0; index < self.departmentArray.length; index++){ if(self.departmentArray[index].isSelected == true){ deptList.push(self.departmentArray[index].id); } } self.isWaiting = true; scaleManagementApi.deleteNutrientStatement( {nutrientStatementNumber: nutrientStatementNumber, deptList: deptList}, self.reloadRemovedData, self.fetchError); }; /** * Return of back end after a user removes a nutrient statement. Based on the size of totalRecordCount, * this method will either: * --reset view to initial state * --re-issue call to back end to update information displayed * * @param results Results from back end. */ self.reloadRemovedData = function(results){ self.deleteMessage = results.message; self.removedNutrientStatement = true; if(self.totalRecordCount == null || self.totalRecordCount <= 1) { self.searchSelection = null; self.isWaiting = false; self.init(); } else { self.newSearch(self.findAll); } }; /** * Apply the Nutrient round rules to the changed value (if changed). * * @param scope The Angular scope object. We'll use this to pull out whether or not it is valid before * trying to round. * @param index The index of this control. This will be used to pull the form out of the page to chck * for validity. * @param nutrientStatementDetail current nutrient statement detail */ self.applyRoundingRuleToNutrientCode = function(scope, index, nutrientStatementDetail) { // Check to make sure what the user typed in is a valid number. var fieldName = "measure" + index; var field = scope.nutrientForm[fieldName]; if (field.$error['pattern']) { self.fetchRoundingError(nutrientStatementDetail, {data: {message: 'Value must be numeric with no more than one decimal place.'}}); nutrientStatementDetail.nutrientRoundingRequired = true; nutrientStatementDetail.stillNeedsRequired = false; return; } nutrientStatementDetail.roundingError = null; if (nutrientStatementDetail.nutrientStatementQuantity != null) { nutrientStatementDetail.nutrientRoundingRequired = true; nutrientStatementDetail.changedQuantity = true; nutrientStatementDetail.stillNeedsRequired = true; nutrientStatementDetail.isNewElement = undefined; scaleManagementApi.applyRoundingRuleToNutrient(nutrientStatementDetail, //success function (results) { field.$setValidity("rounding", true); nutrientStatementDetail.nutrientStatementQuantity = results.data.nutrientStatementQuantity; nutrientStatementDetail.nutrientDailyValue = results.data.nutrientDailyValue; nutrientStatementDetail.nutrientRoundingRequired = false; nutrientStatementDetail.stillNeedsRequired = false; }, //error function(error) { field.$setValidity("rounding", false); self.fetchRoundingError(nutrientStatementDetail, error); nutrientStatementDetail.stillNeedsRequired = false; } ); } }; /** * Callback for when the backend rounding returns an error. * * @param detail Nutrient statement detail that has error. * @param error The error from the backend. */ self.fetchRoundingError = function(detail, error) { detail.stillNeedsRequired = true; if (error && error.data) { if(error.data.message != null && error.data.message != "") { detail.roundingError = error.data.message; } else { detail.roundingError = error.data.error; } } else { detail.roundingError = self.UNKNOWN_ERROR; } }; /** * Adds all of the departments when th select all button is pressed. * * @param value */ self.addAllDepartments = function(value) { if(value) { for(var index = 0; index < self.departmentArray.length; index++) { self.departmentArray[index].isSelected = true; } } else { for(index = 0; index < self.departmentArray.length; index++) { self.departmentArray[index].isSelected = false; } } }; /** * Updates the select all switch if all of them are selected without pushing the select all checkbox. * * @param value */ self.updateSelectAllSwitch = function(value) { if(!value) { self.selectAll = false; } else { var found = false; for(var index = 0; index < self.departmentArray.length; index++) { if(!self.departmentArray[index].isSelected){ found = true; break; } } if(!found){ self.selectAll = true; } } }; /** * Prompts the department modal to remove nutrient statement. * * @param index */ self.chooseNutrientStatementDepartments = function(index){ self.resetDepartmentList(); self.deleteMessage = null; self.isRemovingNutrientStatement = true; self.previousEditingIndex = index; if(self.data[index].statementMaintenanceSwitch == 'A'){ self.removeNutrientStatement(); } else { $("#nutrientStatementChooseDepartmentModal").modal("show"); } }; /** * If any department is chosen. */ self.isDepartmentChosen = function() { for(var index = 0; index < self.departmentArray.length; index++) { if(self.departmentArray[index].isSelected == true){ return self.departmentArray[index].isSelected == true; } } }; /** * Resets the department list to all empty. */ self.resetDepartmentList = function() { for(var index = 0; index < self.departmentArray.length; index++) { self.departmentArray[index].isSelected = false; } }; /** * Updates all of the information for the serving size label. */ self.updateServingLabelComponents= function () { self.servingLabel=""; var bothPresent = false; if(self.nutrientStatement.measureQuantity !=null && self.nutrientStatement.nutrientCommonUom !=null){ self.parseNumberToText(self.nutrientStatement.measureQuantity); self.servingTextCharacterRemainingCharacterCount -= self.nutrientStatement.nutrientCommonUom.nutrientUomDescription.length; self.servingLabel += " " + self.nutrientStatement.nutrientCommonUom.nutrientUomDescription.trim(); bothPresent = true; } else { self.servingLabel+=""; } if(self.nutrientStatement.metricQuantity !=null && self.nutrientStatement.nutrientMetricUom != null){ var metricPart = ""+ Math.round(self.nutrientStatement.metricQuantity)+ self.nutrientStatement.nutrientMetricUom.nutrientUomDescription.trim(); if(bothPresent){ metricPart = " (" + metricPart + ")"; } self.servingLabel += metricPart; } else { self.servingLabel+=""; } self.colorServingLabel(); }; /** * Breaks up number to whole number and decimal components * The first round for decimal is to correct for binary rounding errors. * * @param number */ self.parseNumberToText = function (number) { var wholeNumber = Math.floor(number); var decimal = Math.round(((number%1)*1000))/1000; self.convertDecimalToFraction(wholeNumber, Math.floor(((decimal)*100))/100); }; /** * This method will determine if the decimal is to be converted into a fraction or not. * * @param wholeNumber whole number component of fraction * @param decimal decimal component to be possibly converted to fraction. */ self.convertDecimalToFraction = function (wholeNumber, decimal) { var decimalPart = ""; var converted = false; switch(decimal){ case(0.0): decimalPart = ""; converted = true; break; case(0.08): decimalPart = "1/12 "; converted = true; break; case(0.10): decimalPart = "1/10"; converted = true; break; case(0.12): decimalPart = "1/8"; converted = true; break; case(0.16): decimalPart = "1/6"; converted = true; break; case(0.20): decimalPart = "1/5"; converted = true; break; case(0.25): decimalPart = "1/4"; converted = true; break; case(0.33): decimalPart = "1/3"; converted = true; break; case(0.50): decimalPart = "1/2"; converted = true; break; case(0.66): decimalPart = "2/3"; converted = true; break; case(0.75): decimalPart = "3/4"; converted = true; break; default: decimalPart = "" + decimal; break; } if(wholeNumber>0) { if(converted){ decimalPart = wholeNumber + " " +decimalPart; } else { decimalPart = wholeNumber + decimalPart.substring(1); } } self.servingLabel += decimalPart; }; /** * This method will determine which characters are in bounds (black) and which ones are out of bounds * (anything over 22, red). */ self.colorServingLabel = function () { var servingLabelTextField = document.getElementById("scaleManagementNutrientStatementLabel"); self.servingTextCharacterRemainingCharacterCount = 22 - self.servingLabel.length; if(self.servingLabel.length > 22){ self.servingLabel = self.servingLabel.substring(0, 22).fontcolor("black") + self.servingLabel.substring(22).fontcolor("red"); } servingLabelTextField.innerHTML = self.servingLabel; }; /** * The method will disable all of the increment/decrement features found int number inputs for HTML5. * * @param inputId */ self.disableNumberInputFeatures = function (inputId) { var input = document.getElementById(inputId); if (input == null) { return; } var ignoreKey = false; var handler = function(e) { if (e.keyCode == 38 || e.keyCode == 40) { e.preventDefault(); } }; input.addEventListener("mousewheel", function(event){ this.blur() }); input.addEventListener('keydown',handler,false); input.addEventListener('keypress',handler,false); } /** * Show varies when Servings Per Container = 999. */ self.updateShowVariesLabelComponents = function () { if(self.isServingSizeVariable()){ self.showVariesLabel= self.VARIES_LABEL; }else{ self.showVariesLabel=""; } }; /** * Check varies when Servings Per Container = 999. * @returns {boolean} */ self.isServingSizeVariable = function () { if (self.nutrientStatement.servingsPerContainer != null && self.nutrientStatement.servingsPerContainer == self.servingPerContainerVariesVary){ return true; }else{ return false; } }; } })();
var response = require('./response'); var samurai = {}; var colors = [0xff2424, 0x33fa86, 0xff7111, 0xbe5ecf]; var hexColors = ['#ff2424', '#33fa86', '#ff7111', '#be5ecf']; const SUITE = { religion: 'religion', politics: 'politics', trade: 'trade', samurai: 'samurai', ronin: 'ronin', boat: 'boat' }; const CITYTYPE = ['religion', 'trade', 'politics' ]; //gameInfo { roomName, ownerName, numPlayers, mapName, password, isPrivate } //mapObject { name, size {x,y}, data } samurai.createGame = function (gameInfo, mapObject, callback) { var gameObject = {}; gameObject.roomName = gameInfo.roomName; gameObject.numPlayers = gameInfo.numPlayers; gameObject.ownerName = gameInfo.ownerName; gameObject.ownerUserId = gameInfo.ownerUserId; gameObject.mapName = gameInfo.mapName; gameObject.map = mapObject; gameObject.players = createPlayers(gameObject.numPlayers); gameObject.players[0].name = gameObject.ownerName; gameObject.players[0]._id = gameObject.ownerUserId; gameObject.state = []; gameObject.players.forEach(function (player, index) { gameObject.state.push({ player: player.name, turn: player.turn, color: hexColors[index], score: { religion: 0, politics: 0, trade: 0 } }); }); gameObject.status = 'waiting for players'; gameObject.turnCounter = 0; gameObject.moveList = []; gameObject.playerTurn = Math.floor((Math.random() * 123456)) % gameInfo.numPlayers; gameObject.gameid = createRandomId(); callback(gameObject); }; function createPlayers(numPlayers) { var players = []; for (var i = 0; i < numPlayers; i += 1) { var player = {}; player.name = 'unassigned'; player.turn = i; player.deck = createDeck(); player.usedCards = []; player.hand = []; player.color = colors[i]; dealHand(player.hand, player.deck); players.push(player); } return players; } function dealHand(hand, deck) { while (hand.length < 6) { var randomNumber = Math.random() * deck.length; if (randomNumber < deck.length && randomNumber >= 0) { var randomIndex = Math.floor(randomNumber); var card = deck.splice(randomIndex, 1); hand.push(card[0]); } } } //Todo What is in a complete deck? function createDeck() { let deck = []; for (let cardSize = 2; cardSize <= 4; cardSize += 1) { deck.push({suite: SUITE.trade, size: cardSize}); deck.push({suite: SUITE.religion, size: cardSize}); deck.push({suite: SUITE.politics, size: cardSize}); } const samurai1 = {suite: SUITE.samurai, size: 1}; const samurai2 = {suite: SUITE.samurai, size: 2}; const samurai3 = {suite: SUITE.samurai, size: 3}; deck.push(samurai1, samurai1, samurai2, samurai2, samurai3); const ronin = {suite: SUITE.ronin, quick: true, size: 1}; const boat1 = {suite: SUITE.boat, quick: true, size: 1}; const boat2 = {suite: SUITE.boat, quick: true, size: 2}; deck.push(ronin, boat1, boat1, boat2); //TODO: MISSING SWAP AND MOVE TILE return deck; } function createRandomId(n) { var randomId = []; const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrtuvwxyz123456789"; const numChars = n || 6; for (var i = 0; i < numChars; i += 1) { const index = Math.floor(Math.random() * possible.length); randomId.push(possible[index]); } return randomId.join(''); } function validPlayerTurn(gameObject, player) { for (let i = 0; i < gameObject.players.length; i += 1) { if (gameObject.players[i]._id == player && gameObject.playerTurn == i) return true; } return false; } function validateHand(playerMoves, playerHand) { let validatedHand = true; playerMoves.every(move => { for (var i = 0; i < playerHand.length; i += 1) { if (move.suite == playerHand[i].suite && move.size == playerHand[i].size) { move.playerCard = playerHand.splice(i, 1); return true; } } validatedHand = false; return false; }); return validatedHand; } function validateMoves(mapObject, playerMoves, turnCount, playerColor, playerName) { let validMapMoves = true; let normalMoveTaken = false; playerMoves.every(move => { var tile = mapObject.data.find(t => { return (move.x == t.x && move.y == t.y); }); if (!tile) { validMapMoves = false; return false; } if (move.suite != SUITE.boat && move.suite != SUITE.ronin) { if (normalMoveTaken) { validMapMoves = false; return false; } normalMoveTaken = true; } if (tile.move !== undefined) { validMapMoves = false; return false; } if (move.suite == SUITE.boat && tile.type != 1) { validMapMoves = false; return false; } if (move.suite != SUITE.boat && tile.type != 2) { validMapMoves = false; return false; } tile.move = { color: playerColor, player: playerName, suite: move.suite, size: move.size, turn: turnCount }; return true; }); return validMapMoves; } const tileOffsets = [{x: 0, y: 1}, {x: 0, y: -1}, {x: 1, y: 0}, {x: -1, y: 0}]; const specialOffsets = [ [{x: 1, y: -1}, {x: -1, y: -1}], //%2 == 0 [{x: 1, y: 1}, {x: -1, y: 1}] //%2 == 1 ]; function findSurroundingTiles(tiles, mapData){ let surroundingTiles = []; tiles.forEach( tile => { function findTilesFor(offset) { let t = mapData.find(maptile => (offset.x + tile.x) == maptile.x && (offset.y + tile.y) == maptile.y ); if( t ) surroundingTiles.push(t); } let specialOffset = specialOffsets[tile.x % 2]; //validate %2? specialOffset.forEach(findTilesFor); tileOffsets.forEach(findTilesFor); }); return surroundingTiles; } const TILE = { CITY: 3, LAND: 2, WATER: 1, VOID: 0 }; function handleScore(gameObject, moves) { let cities = findSurroundingTiles(moves.filter(move => move.suite != SUITE.boat), gameObject.map.data).filter(tile => tile.type == TILE.CITY && tile.occupied === undefined ); let uniqueCities = Array.from( new Set(cities) ); uniqueCities.forEach( cityTile => { let cityTiles = findSurroundingTiles( [cityTile], gameObject.map.data); let unoccupiedLand = cityTiles.filter( tile => tile.type == TILE.LAND && tile.move === undefined ); if( unoccupiedLand.length > 0 ) { console.log('City has unoccupied land', cityTile); return; } const all = [SUITE.samurai, SUITE.boat, SUITE.ronin]; let cityInfluence = {}; for( let cityType in cityTile.city ) cityInfluence[cityType] = {}; let tilesWithMoves = cityTiles.filter( tile => tile.move !== undefined ); tilesWithMoves.forEach( tile => { let suite = tile.move.suite; if( all.find( type => type == suite ) ){ for( let cityType in cityInfluence ){ cityInfluence[cityType][tile.move.player] = cityInfluence[cityType][tile.move.player] || 0; cityInfluence[cityType][tile.move.player] += tile.move.size; } } else if( cityInfluence[suite] ) { cityInfluence[suite][tile.move.player] = cityInfluence[suite][tile.move.player] || 0; cityInfluence[suite][tile.move.player] += tile.move.size; } }); console.log( cityTile, cityInfluence ); for( let cityType in cityInfluence ){ let kv = []; for( let player in cityInfluence[cityType] ) kv.push({player: player, influence: cityInfluence[cityType][player]}); kv.sort( (v0, v1) => v1.influence - v0.influence ); if( kv.length == 0 ) { moves.resolve = moves.resolve || []; moves.resolve.push( {type: cityType, player: 'Tie'} ); } else if( kv.length == 1 && kv[0].influence > 0 ){ console.log('Score', kv[0].player, cityType, kv[0]); let playerState = gameObject.state.find( stateObject => stateObject.player == kv[0].player ); playerState.score[cityType] += 1; moves.resolve = moves.resolve || []; moves.resolve.push( {type: cityType, player: playerState.player} ); } else if( kv[0].influence == kv[1].influence ) { console.log( 'Tied', cityTile, cityType, kv); moves.resolve = moves.resolve || []; moves.resolve.push( {type: cityType, player: 'Tie'} ); } else { console.log('Score', kv[0].player, cityType, kv[0]); let playerState = gameObject.state.find( stateObject => stateObject.player == kv[0].player ); playerState.score[cityType] += 1; moves.resolve = moves.resolve || []; moves.resolve.push( {type: cityType, player: playerState.player} ); } } gameObject.map.data.find( tile => cityTile.x == tile.x && cityTile.y == tile.y ).occupied = true; }); return true; } function countFreeTiles(mapObject){ let freeTiles = 0; mapObject.data.forEach( tile => { if( tile.type === 2 && tile.move === undefined ) freeTiles+=1; }); return freeTiles; } function finishGame(gameObject){ let endGameObject = { cityState: {}, playerState: [] }; gameObject.players.forEach(() => endGameObject.playerState.push({ casteSupport: 0, castes: [] })); CITYTYPE.forEach( city => { let high = -1; let player = -1; gameObject.state.forEach( (playerState, playerIndex) => { let playerScore = playerState.score[city]; if( playerScore > high ){ high = playerScore; player = playerIndex; } else if( playerScore === high ){ player = -1; } }); if( player !== -1 ) { endGameObject.playerState[player].casteSupport += 1; endGameObject.playerState[player].castes.push(city); } endGameObject.cityState[city] = { winner: player, score: high }; }); let highestCasteSupport = 0; endGameObject.playerState.forEach( ps => { highestCasteSupport = Math.max(highestCasteSupport, ps.casteSupport); }); let highestCastePlayers = []; endGameObject.playerState.forEach( (ps, index) => { if( ps.casteSupport != highestCasteSupport ) return; highestCastePlayers.push(index); }); // A Player Won if caste support >= 2 or is the only one with caste support if( highestCasteSupport >= 2 || highestCastePlayers.length === 1){ endGameObject.winner = highestCastePlayers[0]; endGameObject.winCondition = "Caste Support"; return endGameObject; } highestCastePlayers.forEach( playerIndex => { const playerState = gameObject.state[playerIndex]; let totalSupport = 0; let balanceSupport = 0; CITYTYPE.forEach( city => { totalSupport += playerState.score[city]; if( endGameObject.playerState[playerIndex].castes[0] !== city ) balanceSupport += playerState.score[city]; }); endGameObject.playerState[playerIndex].totalSupport = totalSupport; endGameObject.playerState[playerIndex].balanceSupport = balanceSupport; }); let highestBalance = -1; highestCastePlayers.forEach( playerIndex => highestBalance = Math.max(endGameObject.playerState[playerIndex].balanceSupport, highestBalance) ); let highestBalancePlayers = []; highestCastePlayers.forEach( playerIndex => { if( endGameObject.playerState[playerIndex].balanceSupport !== highestBalance ) return; highestBalancePlayers.push(playerIndex); }); //A Player wins with highest balance sum if( highestBalancePlayers.length === 1 ){ endGameObject.winner = highestBalancePlayers[0]; endGameObject.winCondition = "Balance Support"; return endGameObject; } let highestTotal = -1; highestCastePlayers.forEach( playerIndex => highestTotal = Math.max(endGameObject.playerState[playerIndex].totalSupport, highestTotal) ); let highestTotalPlayers = []; highestCastePlayers.forEach( playerIndex => { if( endGameObject.playerState[playerIndex].totalSupport !== highestTotal ) return; highestTotalPlayers.push(playerIndex); }); //A Player wins with highest total support if( highestTotalPlayers.length === 1 ){ endGameObject.winner = highestTotalPlayers[0]; endGameObject.winCondition = "Total Support"; return; } endGameObject.winner = highestTotalPlayers; endGameObject.winCondition = "Tied"; return endGameObject; } samurai.processTurn = function (gameObject, userId, moves, callback) { const freeTilesPreTurn = countFreeTiles(gameObject.map); console.log("Free Tiles", freeTilesPreTurn); if( freeTilesPreTurn === 0 || gameObject.status === "game over"){ callback(response.fail("Game is finished")); return; } if( moves.length == 0 ){ callback(response.fail('Skipping turns not allowed')); return; } if (!validPlayerTurn(gameObject, userId)) { callback(response.fail('Not your turn')); return; } //TODO: Investigate '==' let playerObject = gameObject.players.find( p => p._id == userId ); if (playerObject === undefined) { callback({success: false, error: 'player not found in gameobj'}); return; } if (!validateHand(moves, playerObject.hand)) { callback(response.fail('Failed hand validation')); return; } if (!validateMoves(gameObject.map, moves, gameObject.turnCounter, playerObject.color, playerObject.name)) { callback(response.fail('Failed map validation')); return; } if( !handleScore(gameObject, moves) ){ callback(response.fail('Failed score handling')); return; } //Add cards to the spent pile moves.forEach(move => playerObject.usedCards.push(move) ); //Draw new cards while (playerObject.hand.length < 6 && playerObject.deck.length != 0) { var cardIndex = Math.floor(playerObject.deck.length * Math.random()); var draw = playerObject.deck.splice(cardIndex, 1); playerObject.hand.push(draw[0]); } //TODO: Mark who made the move let moveObject = {player: playerObject.name, moves: moves}; if( moves.resolve ) moveObject.resolve = moves.resolve; gameObject.moveList.push(moveObject); gameObject.turnCounter++; gameObject.playerTurn = (gameObject.playerTurn + 1) % gameObject.numPlayers; if( countFreeTiles(gameObject.map) === 0 || playerObject.hand.length === 0 ){ gameObject.status = "game over"; gameObject.endGameState = finishGame(gameObject); console.log(gameObject.endGameState); } callback({success: true, game: gameObject}); }; module.exports = samurai;
import React, { Component } from 'react' import { connect } from 'react-redux'; import { checkisauth } from '../actions'; import './layout.css'; export default function(ComposedClass, isallowed){ class Authcheck extends Component{ state = { loading : true } componentWillMount(){ this.props.checkisauth() } componentWillReceiveProps(nextProps){ if(!nextProps.user.login.loginauth){ this.setState({loading : false}) if(isallowed){ this.props.history.push('/signin') } }else{ this.setState({loading : false}) if(isallowed===false){ this.props.history.push('/userprofile') } } } render(){ if(this.state.loading === true){ return ( <div className='loadingpage'> <h1 className='loadingtxt'>Loading...</h1> </div> ) } return( <ComposedClass user={this.props.user} sectionnname={ComposedClass}/> ) } } const mapStateToProps = (state) =>{ return { user : state.user_reducer } } return connect(mapStateToProps,{checkisauth})(Authcheck) }
export class CalculatorView { constructor (handlerClick) { this._result = document.querySelector('[data-js="result"]') this._historic = document.querySelector('[data-js="historic"]') this.createEvents(handlerClick) } createEvents (handlerClick) { document .querySelectorAll('[data-js="button"]') .forEach(button => button.addEventListener('click', () => handlerClick(button), false)) } get result () { return this._result.innerText } set result (value) { this._result.innerText = value } get historic () { return this._historic.innerText } set historic (value) { this._historic.innerText = value } }
Polymer({ is: "iron-form", properties: { allowRedirect: { type: Boolean, value: !1 }, headers: { type: Object, value: function() { return {} } }, withCredentials: { type: Boolean, value: !1 } }, attached: function() { this._nodeObserver = Polymer.dom(this).observeNodes(function(e) { for (var t = 0; t < e.addedNodes.length; t++) "FORM" !== e.addedNodes[t].tagName || this._alreadyCalledInit || (this._alreadyCalledInit = !0, this._form = e.addedNodes[t], this._init()) }.bind(this)) }, detached: function() { this._nodeObserver && (Polymer.dom(this).unobserveNodes(this._nodeObserver), this._nodeObserver = null) }, _init: function() { this._form.addEventListener("submit", this.submit.bind(this)), this._form.addEventListener("reset", this.reset.bind(this)), this._defaults = this._defaults || new WeakMap; for (var e = this._getSubmittableElements(), t = 0; t < e.length; t++) { var i = e[t]; this._defaults.has(i) || this._defaults.set(i, { checked: i.checked, value: i.value }) } }, validate: function() { if ("" === this._form.getAttribute("novalidate")) return !0; for (var e, t = this._form.checkValidity(), i = this._getValidatableElements(), r = 0; e = i[r], r < i.length; r++) { var s = e; s.validate && (t = !!s.validate() && t) } return t }, submit: function(e) { if (e && e.preventDefault(), this._form) { if (!this.validate()) return void this.fire("iron-form-invalid"); this.$.helper.textContent = ""; var t = this.serializeForm(); if (this.allowRedirect) { for (var i in t) this.$.helper.appendChild(this._createHiddenElement(i, t[i])); this.$.helper.action = this._form.getAttribute("action"), this.$.helper.method = this._form.getAttribute("method") || "GET", this.$.helper.contentType = this._form.getAttribute("enctype") || "application/x-www-form-urlencoded", this.$.helper.submit(), this.fire("iron-form-submit") } else this._makeAjaxRequest(t) } }, reset: function(e) { if (e && e.preventDefault(), this._form) for (var t = this._getSubmittableElements(), i = 0; i < t.length; i++) { var r = t[i]; if (this._defaults.has(r)) { var s = this._defaults.get(r); r.value = s.value, r.checked = s.checked } } }, serializeForm: function() { for (var e = this._getSubmittableElements(), t = {}, i = 0; i < e.length; i++) for (var r = this._serializeElementValues(e[i]), s = 0; s < r.length; s++) this._addSerializedElement(t, e[i].name, r[s]); return t }, _handleFormResponse: function(e) { this.fire("iron-form-response", e.detail) }, _handleFormError: function(e) { this.fire("iron-form-error", e.detail) }, _makeAjaxRequest: function(e) { this.request || (this.request = document.createElement("iron-ajax"), this.request.addEventListener("response", this._handleFormResponse.bind(this)), this.request.addEventListener("error", this._handleFormError.bind(this))), this.request.url = this._form.getAttribute("action"), this.request.method = this._form.getAttribute("method") || "GET", this.request.contentType = this._form.getAttribute("enctype") || "application/x-www-form-urlencoded", this.request.withCredentials = this.withCredentials, this.request.headers = this.headers, "POST" === this._form.method.toUpperCase() ? this.request.body = e : this.request.params = e; var t = this.fire("iron-form-presubmit", {}, { cancelable: !0 }); t.defaultPrevented || (this.request.generateRequest(), this.fire("iron-form-submit", e)) }, _getValidatableElements: function() { return this._findElements(this._form, !0) }, _getSubmittableElements: function() { return this._findElements(this._form, !1) }, _findElements: function(e, t) { for (var i = Polymer.dom(e).querySelectorAll("*"), r = [], s = 0; s < i.length; s++) { var n = i[s]; n.disabled || !t && !n.name ? n.root && Array.prototype.push.apply(r, this._findElements(n.root, t)) : r.push(n) } return r }, _serializeElementValues: function(e) { var t = e.tagName.toLowerCase(); return "button" === t || "input" === t && ("submit" === e.type || "reset" === e.type) ? [] : "select" === t ? this._serializeSelectValues(e) : "input" === t ? this._serializeInputValues(e) : e._hasIronCheckedElementBehavior && !e.checked ? [] : [e.value] }, _serializeSelectValues: function(e) { for (var t = [], i = 0; i < e.options.length; i++) e.options[i].selected && t.push(e.options[i].value); return t }, _serializeInputValues: function(e) { var t = e.type.toLowerCase(); return ("checkbox" !== t && "radio" !== t || e.checked) && "file" !== t ? [e.value] : [] }, _createHiddenElement: function(e, t) { var i = document.createElement("input"); return i.setAttribute("type", "hidden"), i.setAttribute("name", e), i.setAttribute("value", t), i }, _addSerializedElement: function(e, t, i) { void 0 === e[t] ? e[t] = i : (Array.isArray(e[t]) || (e[t] = [e[t]]), e[t].push(i)) } });
import React from "react"; import { View, Panel, PanelHeader, Header, Group, Cell } from '@vkontakte/vkui'; import Carousel from './Components/Carousel' class App extends React.Component { render() { return ( <> <View activePanel="main"> <Panel id="main"> <PanelHeader>Radio Flow</PanelHeader> <Group header={<Header mode="secondary">Items</Header>}> <Carousel /> </Group> </Panel> </View> </> ); } } export default App;
alert('Welcome dear\'s'); /*var pictureType = prompt('what type of pirctures do u like, Wild Animals, Toursim Area, Football Staduim, or Rain Forset '); var pictureType = prompt('what type of pirctures do u like, Wild Animals, Toursim Area, Football Staduim, or Rain Forset '); if(pictureType == 'Wild Animals'){ document.write('<img src="https://images.theconversation.com/files/134652/original/image-20160818-12312-4dyz0u.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=926&fit=clip">'); }else if(pictureType == "Toursim Area"){ document.write('<img src="https://www.overseaspropertyalert.com/wp-content/uploads/2019/08/tourist-town.jpg">'); }else if(pictureType == "Football Staduim"){ document.write('<img src="football.png">'); }else if(pictureType == "Rain Forset"){ document.write('<img src="rainForest.jpg" width="250px">'); }else { document.write("<p> u need to identify one of the 4 type's i mention before please " ); }*/ function viewFavouriteOne(){ var favouritePicture = prompt('What do u love more, Wild Animals, Toursim Area, Football Staduim, Rain Forset .. ? '); while(favouritePicture != 'Wild Animals' && favouritePicture != 'Toursim Area' && favouritePicture != 'Football Staduim' && favouritePicture != 'Rain Forset'){ favouritePicture = prompt('Please Choose One of the 4 type i have mentioned'); } var selected =''; if( favouritePicture == 'Wild Animals'){ selected ='<img src="https://images.theconversation.com/files/134652/original/image-20160818-12312-4dyz0u.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=926&fit=clip" width="100px">'; }else if(favouritePicture == "Toursim Area"){ selected ='<img src="https://www.overseaspropertyalert.com/wp-content/uploads/2019/08/tourist-town.jpg" width ="50px" >'; }else if(favouritePicture == "Football Staduim"){ selected = '<img src="football.png" width ="50px">'; }else if(favouritePicture == "Rain Forset"){ selected ='<img src="rainForest.jpg" width="50px">'; } return selected; } //viewFavouriteOne(); /*else { document.write("<p> u need to identify one of the 4 type's i mention before please " ); }*/ var loveRating = prompt('How Much u Love My Gallery Pictuers From 10 ?' ); var love = Number(loveRating); console.log(typeof love); for( var i=0; i<love; i++){ document.write('<img src="https://image.shutterstock.com/image-vector/heart-love-emoji-icon-object-260nw-1578259714.jpg" width="30px">'); } var name = prompt('hey, i want to know your name '); alert('My name is : ' + name);
import Letter from '../../../models/letter'; import { ForbiddenError, UserInputError } from 'apollo-server-micro'; import transporter from '../../../utils/email/sendEmail'; import fieldsCannotBeEmpty from '../../../utils/user-input/fieldsCannotBeEmpty'; import User from '../../../models/user'; export default async (root, { letterId, message }, { user, authenticationRequired }) => { authenticationRequired(); fieldsCannotBeEmpty({ message }); const letter = await Letter.findById(letterId); if (!letter) { throw new UserInputError("There's no letter with that id"); } if (letter.toEmail !== user.email) { throw new ForbiddenError("You're not allowed to leave a thank you message on that letter"); } if (!letter.thankYouMessage && letter.fromEmail) { const letterRecipient = await User.findOne({ email: letter.toEmail }); await transporter.sendMail({ to: letter.fromEmail, subject: letterRecipient.firstName + ' left you a thank you message | StuySU Valentines', html: ` <html> <body style=" padding: 1rem; text-align: center; font-family: Georgia, serif; background: #fc6c8540; " > <div style="min-height: 60vh; background: rgba(255, 255, 255, 0.5); padding: 2rem 1rem" > <img src="https://res.cloudinary.com/hoxqr9glj/image/upload/v1613323569/urban-876_nktnkh.png" style="width: 500px; max-width: 80vw" /> <h1>${letterRecipient.firstName} sent you a thank you message!</h1> <p> Sign on to <a href="https://valentines.stuysu.org">valentines.stuysu.org</a> in order to see it! </p> </div> </body> </html>`, text: `${user.firstName} sent you a thank you message!. Sign on to valentines.stuysu.org in order to see it!`, }); } letter.thankYouMessage = message; await letter.save(); return letter; };
import { createLocalVue, shallowMount } from '@vue/test-utils' import Footer from '@/components/structure/Footer.vue' describe('Footer', () => { const localVue = createLocalVue() let wrapper const stubs = {} beforeEach(() => { wrapper = mountWrapper(localVue, stubs) }) describe('Components', () => { describe('when component is loaded', () => { it('should have a tui-footer', () => { expect(wrapper.find('.tui-footer').exists()).toBeTruthy() }) it('should have a tui-footer__link', () => { expect(wrapper.find('.tui-footer__link').exists()).toBeTruthy() }) }) }) }) function mountWrapper(localVue, stubs) { return shallowMount(Footer, { localVue, stubs, mocks: { $t: jest.fn().mockImplementation((x) => x), }, }) }
export * from './authorizeActions' export * from './commentActions' // export * from './fileActions' export * from './globalActions' export * from './imageGalleryActions' // export * from './imageUploaderActions' export * from './postActions' export * from './voteActions' export * from './notifyActions' export * from './circleActions' export * from './friendActions'
var cfg = require("../../utils/cfg.js"); const qiniuUploader = require("../../utils/qiniuUploader"); var app = getApp(); var taskid = "" Page({ data: { objectType: [{ value: app.language('camera1.carpet'), checked: false }, { value: app.language('camera1.pet_dung'), checked: false }, { value: app.language('camera1.waterlogging'), checked: false }, { value: app.language('camera1.wire'), checked: false }, { value: app.language('camera1.pet'), checked: false }, { value: app.language('camera1.character'), checked: false } ], objectPhoto: [ { imgsrc: '../../images/add.png', key: '' }, { imgsrc: '../../images/add.png', key: '' } ], curid: 0, selectid: [], sop: {}, uuid: "", taskid: "", progress: "" }, onLoad: function (options) { console.log(options) var that = this getUUID(that) this.setData({ taskid: options.taskid, objectType: [{ value: app.language('camera1.carpet') }, { value: app.language('camera1.pet_dung') }, { value: app.language('camera1.waterlogging') }, { value: app.language('camera1.wire') }, { value: app.language('camera1.pet') }, { value: app.language('camera1.character') } ], }) wx.setNavigationBarTitle({ title: options.taskid }) this.setLang(); }, setLang(){ const set=wx.T._ this.setData({ camera1:set('camera1'), }) }, submit: function () { if (this.data.progress !== "") { cfg.titleToast(app.language('validator.uploading')) return } var res = [] var res0 = {} res0["key"] = this.data.objectPhoto[0].key res0["filename"] = this.data.objectPhoto[0].imgsrc res0["tags"] = this.data.selectid.join(",") res[0] = JSON.stringify(res0) var res1 = {} res1["key"] = this.data.objectPhoto[1].key res1["filename"] = this.data.objectPhoto[1].imgsrc res1["tags"] = this.data.selectid.join(",") res[1] = JSON.stringify(res1) if (res0["key"]===""||res1["key"] ===""){ cfg.titleToast(app.language('validator.picmust')) return } cfg.wxPromise(wx.request)({ url:cfg.getAPIURL() + "/api/projects/" + that.data.taskid + "/task", header : app.globalData.header, method: "POST", data: { id: that.data.taskid, uuid: that.data.uuid, result: JSON.stringify(res), }, }) .then(res=>{ cfg.titleToast(app.language('validator.submission_success')) getUUID(that) // 重新获取任务 that.setData({ // seapub [{ imgsrc: '' }, { imgsrc: '' }] objectPhoto: [{ imgsrc: '../../images/add.png' }, { imgsrc: '../../images/add.png' }], }) }) .catch(error=>{ cfg.titleToast("error") }) }, choiceObject: function (e) { var objectType = this.data.objectType var checkArr = e.detail.value for (var i = 0; i < objectType.length; i++) { objectType[i].checked = false for (var j = 0; j < checkArr.length; j++) { if (objectType[i].value == checkArr[j]) { objectType[i].checked = true break } } } this.setData({ objectType: objectType, selectid: checkArr }) }, chooseImage: function (e) { if (this.data.progress !== "") { cfg.titleToast(app.language('validator.uploading')) wx.showToast({ title: app.language('validator.uploading'), icon: "loading", duration: 2000 }); return } let _this = this; var id = e.currentTarget.dataset.id; _this.data.curid = id; wx.showActionSheet({ itemList: [app.language('validator.album'), app.language('validator.camera')], itemColor: "#f7982a", success: function(res) { if (!res.cancel) { if (res.tapIndex == 0) { _this.chooseWxImage('album') } else if (res.tapIndex == 1) { _this.chooseWxImage('camera') } } } }) }, chooseWxImage: function (type) { let that = this; wx.chooseImage({ count: 1, sizeType: ['original'], sourceType: [type], success: function(res) { var imgsrc = res.tempFilePaths[0]; var newImgs = that.data.objectPhoto; newImgs[that.data.curid].imgsrc = imgsrc that.setData({ objectPhoto: newImgs }) // 获取上传token getUploadToken(that, imgsrc); }, fail:function(){ } }) }, delcont: function (e) { var _this = this; var index = e.currentTarget.dataset.index; var list = _this.data.objectPhoto; list[index].imgsrc = "" this.setData({ objectPhoto: list }); }, previewImage: function (e) { var index = e.currentTarget.dataset.index var imgArr = []; var objkeys = Object.keys(this.data.objectPhoto) // console.log(objkeys) for (var i = 0; i < objkeys.length; i++) { imgArr.push(this.data.objectPhoto[i].imgsrc) } wx.previewImage({ current: imgArr[index], urls: imgArr, }) }, }) function getUUID(that) { cfg.wxPromise(wx.request)({ url:cfg.getAPIURL() + "/api/projects/" + that.data.taskid + "/task", header : app.globalData.header, }) .then(res=>{ that.setData({ uuid: response.data.questions[0].uuid, }); }) .catch(error=>{ cfg.titleToast("error") }) } function uploadPhoto(that, filePath, key, token) { // 交给七牛上传 qiniuUploader.upload( filePath, res => { console.log("uploadPhoto res"); that.setData({ imageObject: res, progress: '', }); }, error => { console.error("error: " + JSON.stringify(error)); }, { // hard coding seapub_todo region: "ECN", // ECN, SCN, NCN, NA, ASG : 华东 华南 华北 北美 新加坡 uptoken: token, key: key, shouldUseQiniuFileName: false, domain: "https://s301.fanhantech.com" }, progress => { that.setData({ progress: progress.progress }); if (that.data.progress === 100) { setTimeout(() => { that.setData({ progress: '' }) }, 1000) } console.log("上传进度", progress.progress); // console.log("已经上传的数据长度", progress.totalBytesSent); // console.log( // "预期需要上传的数据总长度", // progress.totalBytesExpectedToSend // ); }, cancelTask => that.setData({ cancelTask }) ); } function getUploadToken(that, filename) { cfg.wxPromise(wx.request)({ url:cfg.getAPIURL() + "/api/projects/" + that.data.taskid + "/token", header : { "Content-Type": "application/x-www-form-urlencoded", "Cookie": app.getCookie() }, method: "POST", data: { taskid: that.data.taskid, filename: filename, }, }) .then(res=>{ if (res.data.key !== "" && res.data.token !== "") { console.log(filename, res.data.key, res.data.token) uploadPhoto(that, filename, res.data.key, res.data.token) var newImgs = that.data.objectPhoto; newImgs[that.data.curid].key = res.data.key that.setData({ objectPhoto: newImgs, }) console.log(that.data.objectPhoto) } else { cfg.titleToast(app.language('validator.uploadfail')) } }) .catch(error=>{ cfg.titleToast("error") }) }
/* @flow weak */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2016 */ import React from 'react'; import PropTypes from 'prop-types'; import { StyleSheet, View, ViewPropTypes, Dimensions } from 'react-native'; import { RecyclerListView, LayoutProvider } from 'recyclerlistview'; export class DataTable extends React.Component { constructor(props) { super(props); this.shouldComponentUpdate = this.shouldComponentUpdate.bind(this); } shouldComponentUpdate(props) { return this.props.dataSource !== props.dataSource || this.props.width !== props.width; } render() { const { style, listViewStyle, width, dataSource, refCallback, renderRow, ...listViewProps } = this.props; const layoutProvider = this._getLayoutProvider(); const { height } = Dimensions.get('window'); return dataSource.getSize() > 0 && width > 0 ? <RecyclerListView renderAheadOffset={height} layoutProvider={layoutProvider} dataProvider={dataSource} rowRenderer={(type, data, index) => this._rowRenderer(type, data, index)} /> : null; } _getLayoutProvider() { return new LayoutProvider( (_index) => 0, (_type, dim) => { dim.width = this.props.width; dim.height = this.props.cellHeight; } ); } _rowRenderer(_type, data, index) { return this.props.renderRow(data, index); } } DataTable.propTypes = { style: ViewPropTypes.style, listViewStyle: PropTypes.object, refCallback: PropTypes.func, dataSource: PropTypes.object.isRequired, renderRow: PropTypes.func.isRequired, width: PropTypes.number, cellHeight: PropTypes.number, }; DataTable.defaultProps = { showsVerticalScrollIndicator: true, scrollRenderAheadDistance: 5000, width: 1, cellHeight: 35, }; const defaultStyles = StyleSheet.create({ verticalContainer: { flex: 1, }, listView: { flex: 1, }, });
'use strict'; /** * [APP Core] * Author: Marco Paulo * @return {[false]} * * This pattern is a experience * I tried to create a simple module pattern that works with DI (Dependency Injection) * Enjoy =D */ var mpAPP = mpAPP || {}; //Initialize mpAPP = function() { var i = 0; for (i in arguments) { var type = (typeof Object.getPrototypeOf(this).exports[arguments[i]]), module = Object.getPrototypeOf(this).exports[arguments[i]]; //If arguments is a function if (type === 'function') { this[arguments[i]] = module(this); } //If argument is a object if (type === 'object') { this[arguments[i]] = module; } //Show a warning if the module does not exist. if (type !== 'function' && type !== 'object') console.warn(arguments[i] + ': was required, but does not exist a module associated.'); } return false; } // Expose exports method // This is just a wrapper for expose exports method. mpAPP.prototype.exports = function() { return false; }
import React from "react"; import { connect } from 'react-redux' import ShakingError from "./ShakingError"; import Table from "./Table"; import { lotteryFetchData } from "../actions/lottery"; import { lotteryWipeData } from "../actions/lottery"; class InteractiveBlock extends React.Component { constructor() { super(); this.state = {}; this.handleSubmit = this.handleSubmit.bind(this); this.lotteryWipeData = this.handleSubmit.bind(this); this.handleReset = this.handleReset.bind(this); } handleSubmit(event) { event.preventDefault(); const form = event.target; const data = new FormData(form); const result = this.getCheckedNames(data); const selectedNames = Object.keys(result); this.props.checkLotteryCard(selectedNames); this.setState({ formData: JSON.stringify(selectedNames), invalid: false, displayErrors: false, }); } handleReset(event){ event.preventDefault(); this.props.lotteryWipeDataAction(); } getCheckedNames(fd) { const data = {}; for (let key of fd.keys()) { data[key] = fd.get(key); } return data; } render(){ const { formData, invalid } = this.state; const { cardCountError, lotteryIsLoading, lotteryHasErrored, generatedNumbers, guessedNumbers } = this.props; return ( <section className="lottery"> <div className="container maxWidth"> <div className="lottery__heading"> <h3>Smashed the phone?</h3> <h3>No problem!</h3> <h1>Win the lottery and buy a new one!</h1> </div> <form className="lottery__form" onSubmit={this.handleSubmit}> {/* Generate table */} <Table /> {(!generatedNumbers.length>0) ? <button key="1" type="submit" className={lotteryIsLoading ? "disabled lottery__sendBtn": "lottery__sendBtn" } disabled={cardCountError}> {lotteryIsLoading? <div className="loader"></div> : "Send data!" } </button> : <button key="2" type="button" className="lottery__sendBtn" onClick={this.handleReset}> Reset </button> } </form> <div className="resultBlock"> {cardCountError && ( <ShakingError text="You cannot select more than five numbers in one card." /> )} {!lotteryHasErrored && generatedNumbers.length>0 &&( <div> <h3>You guessed {JSON.stringify(guessedNumbers.length)} out of 25 numbers, want to try again? Than press "RESET"!</h3> </div> )} </div> </div> </section> ) } } const mapStateToProps = (state) => { return { cardCountError: state.cardCountError, lotteryIsLoading: state.lotteryIsLoading, lotteryHasErrored: state.lotteryHasErrored, generatedNumbers: state.generatedNumbers, guessedNumbers: state.guessedNumbers, } } const mapDispatchToProps = dispatch => { return { checkLotteryCard: (selectedNames) => dispatch(lotteryFetchData(selectedNames)), lotteryWipeDataAction: () => dispatch(lotteryWipeData()), } } export default connect( mapStateToProps, mapDispatchToProps )(InteractiveBlock);
application.factory('$validateAdmin', ['$rootScope', '$state','$http', '$socket', function(rootscope, state, http){ var header = '[$validateAdmin]'; var validateAdmin = {}; validateAdmin.validate = function(callback) { if(rootscope.adminToken){ http.post(address+'admin/validate', {"adminToken":rootscope.adminToken}) .then(function(res){ if(res.status == 200){ console.log(header,'token validated'); return callback(true); state.go('adminDash'); }else { console.log(header,'Bad token'); return callback(false); state.go('adminConsoleLogin'); } }) .catch(function(err){ console.log(header,'post error'); console.log(header,err); return callback(false); state.go('adminConsoleLogin'); }); }else{ console.log('Has no admin token redirect to admin login'); return callback(false); state.go('adminConsoleLogin'); } } validateAdmin.stay = function(callback){ validateAdmin.validate(function(result){ console.log(header,'ValidateAdmin.validate retured '+ result); if(result){ //change this to result state.go('adminDash'); }else{ state.go('adminConsoleLogin'); } callback(result); //change this to result }); } return validateAdmin; }]); application.controller('dashController', ['$rootScope', '$scope', '$http','$validateAdmin','$mdExpansionPanel','$socket', '$registration', '$mdDialog', '$mdToast' , function(rootscope, scope, http, validateAdmin, mdExpansionPanel, socketService, registration, mdDialog, mdToast){ var header = "[dashController]"; var socket; /*New Registration*/ scope.newUser = {}; scope.postList = ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'Faculty']; scope.departmentList = ['Applied Electronics' , 'Civil', 'Computer' , 'Electrical', 'Electronics' , 'Industrial' , 'Mechanical' ]; rootscope.new_user_response = true; /***************** */ scope.showUI = function () { registration.showUI(scope); } scope.channelList = []; scope.channelCount = 0; scope.registeredCount = 0; scope.openRegistration = true; scope.onlineList = []; scope.onlineCount = 0; scope.waiting = false; scope.batch = ""; scope.channelAddWaiting = false; scope.channelPayload = {}; rootscope.rootscope_channelListWait = true; validateAdmin.stay(function(result){ if(result){ socket = socketService.getSocket(); socketService.dataListeners(scope); mdExpansionPanel('Users').expand(); mdExpansionPanel('Channels').expand(); mdExpansionPanel('Extra').expand(); } }); scope.registrationChange = function(status){ console.log(header,'Registration change'); socket.emit('registrationStatusChange', {status:status}); } /* User console */ scope.addUser = function () { registration.addUser(scope, scope.newUser); } /*Delete User UI */ scope.showDeleteUser = function () { mdDialog.show({ templateUrl: 'html/deleteUser/del.html', parent: angular.element(document.body), clickOutsideToClose:true, controller:'delUser', preserveScope:true, }) .then(function(answer) { },function() { console.log("cancelled dialog"); }); } scope.batchDelete = function(batch){ scope.waiting = true; var payload = { adminToken : rootscope.adminToken, batch : batch } console.log(header,payload); http.post(address+'admin/batchDelete', {payload:payload} ) .then(function(res){ mdToast.show(mdToast.simple().textContent(res.data.message)); scope.waiting = false; }) .catch(function(err){ scope.waiting = false; console.log(header,err); mdToast.show(mdToast.simple().textContent('Server unreachable')); }); } /* ************************* */ /* Channel Console */ scope.addChannel = function() { var header = '[addchannelRequest]'; scope.channelAddWaiting = true; scope.channelPayload.adminToken = rootscope.adminToken; http.post(address+'admin/addChannel',{payload: scope.channelPayload}) .then(function(res){ console.log(header,'Response ' + res.status); scope.channelAddWaiting = false; mdToast.show(mdToast.simple().textContent(res.data.message)); if(res.status == 200){ scope.channelPayload.channelName = ""; scope.channelPayload.admin = ""; socketService.getChannelList(); } }) .catch(function(err){ scope.channelAddWaiting = false; mdToast.show(mdToast.simple().textContent('Something went wrong.')); }); } scope.channelDetail = function(channelName){ console.log(header,'Opening dialog for channel '+ channelName); mdDialog.show({ locals:{channelName: channelName }, clickOutsideToClose: true, templateUrl: 'html/channelDetail/channelDetailDialog.html', controller: 'channelInfo', }); } /* *********************************** */ /*change password************************/ scope.password_wait = false; scope.passwordPayload = { userId: rootscope.adminId, adminToken: rootscope.adminToken } scope.changePassword = function() { if( (scope.passwordPayload.newPassword == scope.passwordPayload.confirm) && (scope.passwordPayload.confirm.length > 3) ){ scope.password_wait = true; var header = '[changePassword]'; http.post(address+'admin/changePassword',{payload:scope.passwordPayload}) .then(function(res){ mdToast.show(mdToast.simple().textContent(res.data.message)); scope.password_wait = false; if(res.status==200){ scope.passwordPayload.oldPassword =""; scope.passwordPayload.newPassword = ""; scope.passwordPayload.confirm =""; } }) .catch(function(err){ mdToast.show(mdToast.simple().textContent("Something went wrong")); scope.password_wait = false; }); }else{ mdToast.show(mdToast.simple().textContent('Make sure the new password is same in the confirm field or length is greater than 3 character')); } } /*************************************** */ /* STATS *********************************/ scope.stat_wait = true; /**************************************** */ }]); application.controller('delUser', ['$rootScope' , '$socketConnect', '$http', '$scope', '$mdToast', function(rootscope, socketconnect, http, scope, mdToast){ var header = '[delUser]'; var socket = socketconnect.getSocket(); scope.data = {}; scope.data.user = {}; scope.data.showList = true; scope.data.user_data_returned = false; scope.data.user.name = "Akhil"; scope.data.user.post="s8"; scope.data.user.department = "CSE"; scope.data.user.batch = "2013"; scope.data.waiting = false; scope.showIdUI = function () { scope.data.showList = false; } scope.find = function () { scope.data.waiting = true; scope.data.user_data_returned=false; http.post(address+'admin/findUser', {userId: scope.data.userId, adminToken: rootscope.adminToken}) .then(function(res){ scope.data.waiting = false; mdToast.show(mdToast.simple().textContent(res.data.message)); if(res.status == 200) { console.log(header,res.data); scope.data.user_data_returned = true; scope.data.user.name = res.data.user.name; scope.data.user.post = res.data.user.post; scope.data.user.department = res.data.user.department; scope.data.user.batch = res.data.user.batch; scope.data.user.user_token = res.data.user.user_token; } }) .catch(function(err){ console.log(header,err); scope.data.waiting=false; mdToast.show(mdToast.simple().textContent('Server Error')); }); } scope.deleteUser = function () { scope.data.waiting = true; var payload = { adminToken : rootscope.adminToken, user_token : scope.data.user.user_token } console.log(header,payload); http.post(address+'admin/deleteUser',{payload:payload}) .then(function(res){ scope.data.waiting = false; mdToast.show(mdToast.simple().textContent(res.data.message)); if(res.status == 200){ scope.data.user_data_returned = false; scope.data.user.name = null; scope.data.user.post = null scope.data.user.department = null ; scope.data.user.user_token = null; scope.data.user.batch = null; } }) .catch(function(err){ scope.data.waiting = false; console.log(header,err); mdToast.show(mdToast.simple().textContent('Server error')); }) } }]);
// @flow import * as React from 'react'; import { StackNavigator, StackNavigatorOptions, } from '@kiwicom/mobile-navigation'; import { createSwitchNavigator } from 'react-navigation'; import { withMappedNavigationAndConfigProps as withMappedProps } from 'react-navigation-props-mapper'; import { defaultTokens } from '@kiwicom/mobile-orbit'; import { NewHotelsStandAlonePackage } from '@kiwicom/react-native-app-hotels'; import DetailScreen, { MenuComponents } from './DetailScreen'; import ListScreen from './ListScreen'; import FillTravelDocumentScreen from './FillTravelDocumentScreen'; import TravelDocumentModalScreen from './TravelDocumentModalScreen'; import AppleWalletScreen from './AppleWalletScreen'; import AddressPickerScreen from './AddressPickerScreen'; import TransportationMap from '../scenes/tripServices/transportation/TransportationMap'; import GuaranteeScreen from './GuaranteeScreen'; import InsuranceStack from '../scenes/tripServices/insurance/navigation/InsuranceStack'; // THIS IS ONLY FOR MOBILE DEVICES! const Screens = {}; Object.entries(MenuComponents).forEach( // $FlowIssue: https://github.com/facebook/flow/issues/2221 ([routeName, { screen, headerTitle, headerRight, headerStyle }]) => { Screens[routeName] = { screen: withMappedProps(screen), navigationOptions: (props: Object) => ({ headerTitle, headerRight: headerRight == null ? null : React.cloneElement(headerRight, props), headerStyle: { ...headerStyle, backgroundColor: defaultTokens.paletteWhite, }, }), }; }, ); const MainStack = StackNavigator( { ListScreen: { screen: withMappedProps(ListScreen), }, DetailScreen: { screen: withMappedProps(DetailScreen), }, AppleWalletScreen: { screen: withMappedProps(AppleWalletScreen), }, TravelDocumentScreen: { screen: withMappedProps(FillTravelDocumentScreen), }, ...Screens, }, { ...StackNavigatorOptions, initialRouteName: 'ListScreen', }, ); const TravelDocumentModalStack = StackNavigator( { TravelDocumentModalScreen: { screen: withMappedProps(TravelDocumentModalScreen), }, }, { ...StackNavigatorOptions, initialRouteName: 'TravelDocumentModalScreen', }, ); const SwitchStack = createSwitchNavigator( { MMBMainSwitchStack: { screen: MainStack, }, MMBHotelsStack: { screen: withMappedProps(NewHotelsStandAlonePackage), }, }, { ...StackNavigatorOptions, initialRouteName: 'MMBMainSwitchStack', backBehavior: 'initialRoute', resetOnBlur: false, }, ); const TransportationStack = StackNavigator( { AddressPickerScreen: withMappedProps(AddressPickerScreen), TransportationMap: withMappedProps(TransportationMap), // TODO add another webview screen to this stack as navigation behaviour looks weird otherwise. }, { ...StackNavigatorOptions, initialRouteName: 'TransportationMap', mode: 'modal', }, ); const GuaranteeStack = StackNavigator( { GuaranteeScreen: withMappedProps(GuaranteeScreen), }, { ...StackNavigatorOptions, initialRouteName: 'GuaranteeScreen', mode: 'modal', }, ); export default StackNavigator( { MMBMainStack: { screen: SwitchStack, }, TravelDocumentModalStack: { screen: TravelDocumentModalStack, }, TransportationMap: { screen: TransportationStack, }, GuaranteeStack: { screen: GuaranteeStack, }, InsuranceStack: { screen: InsuranceStack, }, }, { ...StackNavigatorOptions, initialRouteName: 'MMBMainStack', headerMode: 'none', mode: 'modal', }, );
import InputCard from './src/index.vue' InputCard.install = (vue) => { vue.component(InputCard.name, InputCard) } export default InputCard
Ext.define('AM.view.analysis.OS', { extend: 'AM.view.analysis.Browser', alias: 'widget.analysis_os', config: { serviceName: 'osUsage' }, initialize: function () { this.callParent(); } });
//Especificamos el tipo de dato que nos va a devolver la funcion function multiplicar(numero1, numero2) { var total = numero1 * numero2; return total; } console.log('El resultado es ' + multiplicar(2, 3));
const init = () => { const tableId = createHtmlObject('table', 'div'); //생성된 table.Id let table = document.getElementById(tableId); setTableByObject(table, getData()); table.classList.add('.table'); return true; }; const createHtmlObject = (element, containerdiv) => { let div = document.getElementById(containerdiv); let createHtmlElement = document.createElement(element); createHtmlElement.id = `${containerdiv}_${createHtmlElement}`; div.appendChild(createHtmlElement); return createHtmlElement.id; }; const getTagName = (name, innerText) => `<${name}>${innerText}</${name}>`; const getTotalPrice = (q, p) => q * p; const getCurrencyUnit = input => input === '' ? '' : Number(input).toLocaleString('en'); const setTableByObject = (table, ary = []) => { let combineBody = []; let combineHead = []; let headIdx = 0; for (let [key] of Object.entries(ary[0].product)) { combineHead[headIdx] = getTagName('th', key); headIdx += 1; } combineHead[headIdx + 1] = getTagName('th', 'Total Price'); ary.forEach((v, i) => { const { name, price, quntity } = v.product; let res = ''; res = [ getTagName('td', name), getTagName('td', quntity), getTagName('td', getCurrencyUnit(price)), getTagName('td', getCurrencyUnit(getTotalPrice(quntity, price))) ].join(''); combineBody[i] = getTagName('tr', res); }); table.innerHTML = getTagName('thead', combineHead.reduce((av, cv) => av + cv)) + getTagName('tbody', combineBody.reduce((av, cv) => av + cv)); }; let getData = () => { return [ { product: { name: 'apple', price: 1000, quntity: 200 } }, { product: { name: 'strawbery', price: 150, quntity: 300 } }, { product: { name: 'banana', price: 500, quntity: 300 } }, { product: { name: 'kiwi', price: 800, quntity: 400 } }, { product: { name: 'orange', price: 1000, quntity: 300 } }, { product: { name: 'watermelon', price: 10000, quntity: 20 } }, { product: { name: 'tomato', price: 600, quntity: 250 } } ]; }; init();
import React, { useState, useEffect } from 'react'; import Fab from '@material-ui/core/Fab'; import SendIcon from '@material-ui/icons/Send'; import Grid from '@material-ui/core/Grid'; import TextField from '@material-ui/core/TextField'; function SendMessageForm (props) { const [message, setMessage] = useState(''); let handleSubmit = (e) => { e.preventDefault() props.sendMessage(message) setMessage('') } let handleChange = (e) => setMessage(e.target.value) return ( <Grid container style={{padding: '20px'}}> <Grid item xs={11}> <TextField id="outlined-basic-email" onChange={handleChange} value={message} label="Type Something" fullWidth/> </Grid> <Grid xs={1} align="right"> <Fab color="primary" aria-label="add" onClick={handleSubmit}><SendIcon /></Fab> </Grid> </Grid> ) } export default SendMessageForm;
/* eslint-env node, mocha */ const assert = require('assert'); //const Client = require('../../mocks/client'); //const client = Client.mockClient; //client.config.storeLimit = 1; const { Client } = require('../../../src/index.js'); const generateClient = require('../../seed/generated/generateRlayClient.js'); const client = generateClient(new Client()); const check = require('check-types'); const defaultPayload = { "annotations": [], "class_assertions": [], "negative_class_assertions": [], "object_property_assertions": [], "negative_object_property_assertions": [], "data_property_assertions": [], "negative_data_property_assertions": [], "type": "Individual" } const clone = x => JSON.parse(JSON.stringify(x)) describe('Rlay_Individual', () => { describe('.create', () => { context('same property payload', () => { it('produces same CID', async () => { const objIndi1 = client.getEntityFromPayload(defaultPayload); const objIndi2 = client.Rlay_Individual.from(defaultPayload); const indi1 = await client.Rlay_Individual.create({ httpConnectionClass: true, httpStatusCodeValueDataProperty: 200, httpRequestsObjectProperty: objIndi1 }); const indi2 = await client.Rlay_Individual.create({ httpConnectionClass: false, httpStatusCodeValueDataProperty: 200, httpRequestsObjectProperty: objIndi2 }); assert.equal(indi1.cid, indi2.cid); }); }); context('different property payload', () => { it('produces different CIDs', async () => { const indi1 = await client.Rlay_Individual.create({ httpStatusCodeValueDataProperty: 201 }); const indi2 = await client.Rlay_Individual.create({ httpStatusCodeValueDataProperty: 202 }); assert.notEqual(indi1.cid, indi2.cid); }); }); }); describe('.resolve', () => { it('works as expected', async () => { const properties = { httpStatusCodeValueDataProperty: 200 }; const properties1 = { httpStatusCodeValueDataProperty: 400 }; const indi = await client.Rlay_Individual.create(clone(properties)); const objIndi1 = await client.Rlay_Individual.create(clone(properties1)); await indi.assert({ httpConnectionClass: true, httpEntityHeaderClass: true, httpStatusCodeValueDataProperty: 599, httpRequestsObjectProperty: objIndi1 }); await indi.resolve(); await objIndi1.resolve(); assert.deepEqual(indi.properties, properties); assert.deepEqual(objIndi1.properties, properties1); assert.equal(indi.httpRequestsObjectProperty instanceof client.Rlay_Individual, true); assert.equal(indi.httpConnectionClass, true); assert.equal(indi.httpEntityHeaderClass, true); assert.equal(indi.httpStatusCodeValueDataProperty, 599); }); }); describe('.findByAssertion', () => { context('property assertions', () => { context('ClassAssertion', () => { it('works as expected', async () => { const searchResult = await client.Rlay_Individual.findByAssertion({ httpConnectionClass: true }); assert.equal(searchResult.asProperty.length, 1); assert.equal(check.all(searchResult.asProperty.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); context('DataPropertyAssertion', () => { it('works as expected', async () => { const searchResult = await client.Rlay_Individual.findByAssertion({ httpStatusCodeValueDataProperty: 200 }); assert.equal(searchResult.asProperty.length, 2); assert.equal(check.all(searchResult.asProperty.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); context('ObjectPropertyAssertion', () => { it('works as expected', async () => { const indi = client.getEntityFromPayload(defaultPayload); const searchResult = await client.Rlay_Individual.findByAssertion({ httpRequestsObjectProperty: indi }); assert.equal(searchResult.asProperty.length, 1); assert.equal(check.all(searchResult.asProperty.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); }); context('assert assertions', () => { context('ClassAssertion', () => { it('works as expected', async () => { const searchResult = await client.Rlay_Individual.findByAssertion({ httpConnectionClass: true }); assert.equal(searchResult.asAssertion.length, 1); assert.equal(check.all(searchResult.asAssertion.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); context('DataPropertyAssertion', () => { it('works as expected', async () => { const searchResult = await client.Rlay_Individual.findByAssertion({ httpStatusCodeValueDataProperty: 599 }); assert.equal(searchResult.asAssertion.length, 1); assert.equal(check.all(searchResult.asAssertion.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); context('ObjectPropertyAssertion', () => { it('works as expected', async () => { const clonedDefault = clone(defaultPayload); clonedDefault.annotations.push('0x00'); const objIndi = client.getEntityFromPayload(clonedDefault); const indi = await client.Rlay_Individual.create({ httpEntityHeaderClass: true, }); await indi.assert({httpRequestsObjectProperty: objIndi}); const searchResult = await client.Rlay_Individual.findByAssertion({ httpRequestsObjectProperty: objIndi }); assert.equal(searchResult.asAssertion.length, 1); assert.equal(searchResult.asAssertion[0].cid, indi.cid); assert.equal(check.all(searchResult.asAssertion.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); }); context('multiple assertions', () => { it('works as expected', async () => { const objIndi = client.getEntityFromPayload(defaultPayload); const searchResult = await client.Rlay_Individual.findByAssertion({ httpStatusCodeValueDataProperty: 200, httpConnectionClass: true, httpRequestsObjectProperty: objIndi }); assert.equal(searchResult.asProperty.length, 1); assert.equal(check.all(searchResult.asProperty.map(entity => { return entity instanceof client.Rlay_Individual })), true, 'search results are not Individuals'); }); }); }); });
const express = require("express"); const mongoose = require("mongoose"); const app = express(); const productsRouter = require("./routes/product.route"); app.use(express.json()); app.use("/api/products", productsRouter); //connect to db with mongoose mongoose .connect("mongodb://127.0.0.1:27017/e-commerce", { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true, }) .then(() => { console.log("Database connect"); }); app.listen(process.env.PORT || 8000, () => { console.log(`Application start at ${process.env.PORT || 8000}`); });
import React, { useContext } from "react"; import SignInContext from "./SignInContext"; import Profile from "./Profile.jsx"; const Home = () => { const [signInState, setsignInState] = useContext(SignInContext); //return <div>{signInState.status}</div>; if (signInState[0] === "Signed Out") { return ( <div> <h1>PyLot Banner</h1> </div> ); } else { return ( <Profile status={signInState[0]} username={signInState[1]} password={signInState[2]} ></Profile> ); } }; export default Home;
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const ControlButton = styled.button` width: 50px; height: 30px; border-radius: 10px; background-color: #a19fa5; margin: 4px; outline: none !important; `; const ButtonText = styled.div` text-align: center; font-size: 0.75rem; width: 100%; color: #fff; text-shadow: 1px 1px 1px #000; `; const ControlBox = styled.div` margin-top: 8px; `; const ControlSection = ({ callCard, hitCard, standCard, restartRound, playState, isEndRound = false, betsTotal }) => { return ( <ControlBox> {playState === 'call' && ( <ControlButton disabled={betsTotal >= 1 ? false : true} onClick={() => { callCard(); }} > <ButtonText>Call</ButtonText> </ControlButton> )} {playState === 'called' && ( <> <ControlButton onClick={() => { hitCard(); }} > <ButtonText>Hit</ButtonText> </ControlButton> <ControlButton onClick={() => { standCard(); }} > <ButtonText>Stand</ButtonText> </ControlButton> </> )} {isEndRound && ( <ControlButton onClick={() => { restartRound(); }} > <ButtonText>Next</ButtonText> </ControlButton> )} </ControlBox> ); }; ControlSection.propTypes = { callCard: PropTypes.func, hitCard: PropTypes.func, standCard: PropTypes.func, restartRound: PropTypes.func, betsTotal: PropTypes.number, isEndRound: PropTypes.bool, playState: PropTypes.string }; export default ControlSection;
import React, { Component } from 'react'; class MyComponent extends Component { render() { const { data = {} } = this.props; return <div className='mountain'> <img style={{ position: "fixed", left: '0', bottom: '0', width: '100%', objectFit: 'cover' }} src={require('../images/mountain2.png')} /> </div> } } export default MyComponent
define(['api'], function(api, tab) { let tabAll, phone_login, code_login, password_login, pos, btnAll, dowmload_pic, dowmload, login_btn, code; return { init() { tabAll = api.$All('span'); phone_login = api.$('.phone'); code_login = api.$('.code_login'); password_login = api.$('.password'); login_btn = api.$('.log_pas'); pos = api.$('.pos'); btnAll = pos.children; dowmload_pic = api.$('.qr'); dowmload = api.$('.dowmload'); this.event(); }, event() { const self = this; tabAll[0].onclick = function () { this.style.color = '#cc5252'; tabAll[1].style.color = 'gray'; code_login.style.display = 'none'; pos.style.display = 'block' phone_login.style.display = 'none'; password_login.style.display = 'block'; } tabAll[1].onclick = function () { this.style.color = '#cc5252'; tabAll[0].style.color = 'gray'; phone_login.style.display = 'none'; pos.style.display = 'none'; code_login.style.display = 'block'; phone_login.style.display = 'none' password_login.style.display = 'none'; } let onoff = true; btnAll[0].onclick = function () { if(onoff) { onoff = !onoff; phone_login.style.display = 'block'; code_login.style.display = 'none' password_login.style.display = 'none'; btnAll[0].innerHTML =` <a href="javascript:void(0);">账号密码</a>` ; }else { onoff = !onoff; code_login.style.display = 'none' phone_login.style.display = 'none'; password_login.style.display = 'block'; btnAll[0].innerHTML = ` <a href="javascript:void(0);"> 手机动态码登录 <em class="icon_hot"></em> </a>`; } } let flag = true; dowmload.onclick = function () { if(flag) { flag = !flag; dowmload_pic.style.display = 'block'; }else { flag = !flag; dowmload_pic.style.display = 'none'; } } login_btn.onclick = function () { const $from = api.$('.content_box') var obj = { phone: $from['phone'].value, password: $from['password'].value } api.sendAjax('server/login.php', { method: 'POST', data: obj } ) .then((date) => { if(date.code == 200) { console.log(date) localStorage.phone = JSON.stringify(date); location.href = 'http://localhost/wbiao_project/dist/index.html'; }else { alert('用户名或密码错误,请重试') } }) .catch((date) => { alert(date) }); } } } });
"use strict"; /* Copyright [2014] [Diagramo] 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. */ /** * It will group a set of figures * @this {GroupCreateCommand} * @constructor * @param groupId {Numeric} - the id of the group */ function GroupCreateCommand(groupId){ this.groupId = groupId; /**Figures ids that belong to this group*/ this.figuresIds = STACK.figureGetIdsByGroupId(groupId); this.firstExecute = true; this.oType = "GroupCreateCommand"; } GroupCreateCommand.prototype = { /**This method got called every time the Command must execute. *The problem is that is a big difference between first execute and a "redo" execute **/ execute : function(){ if(this.firstExecute){ //first execute STACK.groupGetById(this.groupId).permanent = true; //transform this group into a permanent one this.firstExecute = false; } else{ //a redo (group was previously destroyed) //create group var g = new Group(); g.id = this.groupId; //copy old Id g.permanent = true; //add figures to group for(var i=0; i < this.figuresIds.length; i++){ var f = STACK.figureGetById(this.figuresIds[i]); f.groupId = g.id; } var bounds = g.getBounds(); g.rotationCoords.push(new Point(bounds[0]+(bounds[2]-bounds[0])/2, bounds[1] + (bounds[3] - bounds[1]) / 2)); g.rotationCoords.push(new Point(bounds[0]+(bounds[2]-bounds[0])/2, bounds[1])); //save group to STACK STACK.groups.push(g); } state = STATE_GROUP_SELECTED; selectedGroupId = this.groupId; }, /**This method should be called every time the Command should be undone*/ undo : function(){ STACK.groupDestroy(this.groupId); selectedGroupId = -1; state = STATE_NONE; } }
console.log('modified');
var fs = require('fs'), path = require('path'), async = require('async'), validator = require('validator'), bcrypt = require('bcrypt'), request = require('superagent'), passport = require('passport'); var log = require('../log'); exports.route = function(app) { app.get('/activateuser', function(req, res) { // Call the activation endpoint var email = req.query.email, code = req.query.code; // Redirect back to the login page is the parameters were not included if (!email || !code) { return res.redirect('/login'); } // Build the request request .post('http://54.200.112.228/GroupDirectServices/SignupService.svc/activateusersignuprequest') .send({ email: email, code: code }) // Submit the request .end(function (response) { if (!response.ok) { log.error('We got an invalid response from the backend on activation:', response.body); } return res.redirect('/signin'); }); }); app.get('/reset', function(req, res) { // Call the activation endpoint var token = req.query.token, reset = req.query.reset; // Redirect back to the login page if the parameters were not included if (!token || !reset) { return res.redirect('/signin'); } else { if (reset == 'true'){ //if(isTokenValid) return res.redirect('/confirmpassword?token='+token); //else TODO return res.redirect('/request-expired') } else { request .post('http://54.200.112.228/GroupDirectServices/ApheliaIUserService.svc/DiactivateRestPassowrdToken') .send({ token: token }) .end(function (response) { if (!response.ok) { log.error('We got an invalid response from the backend on activation:', response.body); } console.log('Response for DiactivateRestPassowrdToken', JSON.stringify(response.body)); return res.redirect('/signin'); }); } } }); app.post('/api/register/user', function(req, res) { // If we're already logged in, send a 401 if (req.user) { return res.status(403).send('Cannot register a user while logged in'); } // Validate input var problems = []; if (!validator.matches(req.body.firstName, /[a-zA-Z_\-]{2,}/)) { problems.push({ field: 'firstName', message: 'Must be at least two letters long' }); } if (!validator.matches(req.body.lastName, /[a-zA-Z_\-]{2,}/)) { problems.push({ field: 'lastName', message: 'Must be at least two letters long' }); } if (!validator.matches(req.body.userName, /[a-zA-Z0-9\.]{6,20}/)) { problems.push({ field: 'userName', message: 'Must be between 6 and 18 alphanumeric characters long' }); } if (!validator.matches(req.body.password, /((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})/)) { problems.push({ field: 'password', message: 'Must have one digit, lowercase letter, uppercase letter, special symbol and be between 6 and 20 characters long' }); } if (!validator.isEmail(req.body.email)) { problems.push({ field: 'email', message: 'Must be a correctly formatted email address' }); } // Yell at the requester if ill-formatter if (problems.length > 0) { return res.status(400).json(problems); } // Prepare to talk to the database var responseSent = false; async.waterfall([ function(callback) { // Check if the userName is taken req.models.User.count({ where: { userName: req.body.userName } }).on('success', function(count) { if (count > 0) { res.status(400).json([{ field: 'userName', message: 'This user name has already been taken' }]); responseSent = true; callback('User name already taken'); } else callback(); }).on('error', function(err) { callback(err); }); }, function(callback) { // Check if the email is taken req.models.User.count({ where: { email: req.body.email } }).on('success', function(count) { if (count > 0) { res.status(400).json([{ field: 'email', message: 'This email has already been taken' }]); responseSent = true; callback('Email has already been taken'); } else callback(); }).on('error', function(err) { callback(err); }); }, function(callback) { bcrypt.hash(req.body.password, 10, function(err, hash) { if (err) { res.status(500).json([{ field: 'password', message: 'The password could not be parsed - please check your connection' }]); responseSent = true; callback('Could not hash the password'); } else { callback(null, hash); } }); }, function(hashedPassword, callback) { // Make the database insertion req.models.User.create({ firstName: req.body.firstName, lastName: req.body.lastName, userName: req.body.userName, password: req.body.password, email: req.body.email }) .then(function() { callback(); }) .catch(function(err) { responseSent = true; callback(err); }); } ], function(err) { if (err && !responseSent) { res.status(500).send('Problem putting new user in the database'); } else { res.status(200).send(); } }); }); app.post('/api/auth/login', passport.authenticate('local'), function(req, res) { // Authentication succeeded return res.status(200).json({ id: req.user.id, userName: req.user.userName, firstName: req.user.firstName, lastName: req.user.lastName }); }); };
'use strict'; var isUtils = require('../common-utils/is-utils'); var eventNames = [ 'onStart', 'onRankStart', 'onRankEnd', 'onPiece', 'onEmptySquare', 'onEmptySquaresCount', 'onPiecePlacementEnd', 'onWhiteActiveColor', 'onBlackActiveColor', 'onCastlingAvailability', 'onEnPassantSquare', 'onHalfMoveClock', 'onFullmoveNumber', 'onEnd' ]; function FenParseHandler(listeners) { addEventListeners(this, listeners); } function addEventListeners(handler, listeners) { eventNames.forEach(function (eventName) { var listener = listeners[eventName]; if (isUtils.isUndefined(listener)) { listener = function() {}; } else if (!isUtils.isFunction(listener)) { throw new Error(eventName + ' must be a function'); } handler[eventName] = listener; }); } module.exports = FenParseHandler;
const twitterClient = require('../client/twitter'); const Persistence = require('../persistence/persistence'); const connection = new Persistence(); async function fetchTweets() { try { // Establish database connection await connection.connect(); // Fetch last docuent from mongo let lastTweet = await connection.fetchLatestTweet(); const userId = process.env.TWITTER_USER; let tweets = await twitterClient.getUserData(userId, lastTweet ? lastTweet.id_str : null); console.log("Results: ", tweets.length); if (tweets.length > 0) { let result = await connection.insertTweets(tweets); console.log("Inserted " + result.result.n + " tweets"); } } catch (e) { console.error(e); } finally { connection.disconnect(); } } module.exports = { fetchTweets: fetchTweets };
import React from "react"; import jwt from "jsonwebtoken"; import { Route, useHistory } from "react-router-dom"; import { toast } from "react-toastify"; let isAuth = false; const verifyToken = async () => { let token = localStorage.getItem("token"); if (token) { let state = jwt.verify(localStorage.getItem("token"),"secretkey",(err, decoded) => { if (err) return false; localStorage.setItem( "user", decoded.data.username.toString().toUpperCase() ); localStorage.setItem("userRole", decoded.data.role); localStorage.setItem("userId", decoded.data._id); return true; } ); isAuth = state; } else { isAuth = false; } }; const ProtectedRoute = ({ component: Component, ...rest }) => { let history = useHistory(); //to check the jwt token; verifyToken(); return ( <> <Route {...rest} render={(props) =>{ return isAuth ? <Component {...props} /> : ( toast.info("please login to continue",{autoClose:2000,position:"top-center"}), history.push("/") ) } } /> </> ); }; export default ProtectedRoute;
//copying mail function copyToClipboard(element) { var $temp = $("<input>"); $("body").append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); } // button event $(document).ready(function() { $("#menu-icon").on("click", function() { $("nav ul").toggleClass("showing"); }); $('.slide').on("click", function() { $("nav ul").removeClass("showing"); }); //scroll nav var navHigh = $('nav').outerHeight(); //86.4 $('.slide').click(function(e) { var linkHref = $(this).attr('href'); $('html, body').animate({ scrollTop: $(linkHref).offset().top - 86.4 }, 1000); e.preventDefault(); }); }); //nav color change $(window).on("scroll", function() { if ($(window).scrollTop()) { $('nav').addClass('black'); } else { $('nav').removeClass('black'); } })
import { graphql } from 'react-apollo' import gql from 'graphql-tag' import objFragment from '../fragments/obj' const editObj = gql` mutation editObj($obj: ObjInput!) { editObj(obj: $obj) { ...ObjFragment } } ${objFragment} ` const mutationConfig = { props: ({ mutate, ownProps: { objId } }) => ({ editObj: obj => mutate({ variables: { obj: { ...obj, id: objId } } }) }) } export default graphql(editObj, mutationConfig)
// chat-core.js // Defines the core of the chat simulator var extend = require("extend"); var controller = require("tpp-controller"); var donger = require("./donger.js"); function currTime() { return new Date().getTime(); } /** */ function Chat() { } extend(Chat.prototype, { playerUser: null, _u_list: [], //contains the list of all users _u_hash: {}, //contrains a hash of usernames to users _u_classes: { chatleader: [], }, _initUserlist : function() { var ul = require("./userlist"); for (var i = 0; i < ul.length; i++) { var u = new User(ul[i]); this._u_list.push(u); this._u_hash[u.name] = u; if (!this.playerUser) { //The first user is the player's user this.playerUser = u; } } }, _randomUser : function(time){ time = time || new Date().getTime(); var index; for (var i = 0; i < 20; i++) { //try up to only 20 times index = Math.floor(Math.random() * this._u_list.length); var u = this._u_list[index]; if (u.nextTimeTalk > time) return u; } //If we can't find a user to return, make a new one as a fallback var u = new User({name: "guest"+ (Math.floor(Math.random() * 20000) + 10000) }); this._u_list.push(u); this._u_hash[u.name] = u; return u; }, /////////////////////////////////////////////////// // Note, the chat spawn loop was going to be part of the tick loop, but // using setTimeout ourselves makes things more independant and more // flexible. _currChatMode : null, _timeout_id: 0, initChatSpawnLoop : function() { var self = this; __tick_spawnChats(); return; function __tick_spawnChats() { if (!self._currChatMode) { //TODO remove connecting spinner self._currChatMode = "normal"; } if (self._currChatMode == "normal") { self.spawnChatMessages(); self._timeout_id = setTimeout(__tick_spawnChats, 500); } else { console.error("INVALID CHAT MODE"); } } }, setChatMode: function(chat) { this._currChatMode = chat; if (!self._timeout_id) { this.initChatSpawnLoop(); } }, /////////////////////////////////////////////////////////////////// spawnChatMessages: function() { var numMsgs = Math.floor(Math.random() * 5) + 4; var date = currTime(); for (var i = 0; i < numMsgs; i++) { } }, }); module.exports = new Chat();
/*function generarArray(){*/ var Bombo=[]; for(var i=1;i<=99;i++){ Bombo.push(i); } Bombo.sort(function() {return Math.random() - 0.5}); Bombo.current = 0; Bombo.next = function(){ return this.current===this.length-1 ? null : this[++this.current]; } function mostrar() { document.getElementById("MostrarNumeros").innerHTML = Bombo[Bombo.current]; } window.onload = mostrar; function next() { document.getElementById("MostrarNumeros").innerHTML = Bombo.next(); var voz=document.getElementById("MostrarNumeros").innerHTML = Bombo.next(); var bola = new Audio("sonidoNumero.wav"); bola.play(); reproduccionVoz(voz); } function reproduccionVoz(numero){ switch (numero){ case 1: var num1 =new Audio("1.mp3"); num1.play(); break; case 2: var num2 =new Audio("2.mp3"); num2.play(); break; case 3: var num3 =new Audio("3.mp3"); num3.play(); break; case 4: var num4 =new Audio("4.mp3"); num4.play(); break; case 5: var num5 =new Audio("5.mp3"); num5.play(); break; case 6: var num6 =new Audio("6.mp3"); num6.play(); break; case 7: var num7 =new Audio("7.mp3"); num7.play(); break; case 8: var num8 =new Audio("8.mp3"); num8.play(); break; case 9: var num9 =new Audio("9.mp3"); num9.play(); break; case 10: var num10 =new Audio("10.mp3"); num10.play(); break; case 11: var num11 =new Audio("11.mp3"); num11.play(); break; case 12: var num12 =new Audio("12.mp3"); num12.play(); break; case 13: var num13 =new Audio("13.mp3"); num13.play(); break; case 14: var num14 =new Audio("14.mp3"); num14.play(); break; case 15: var num15 =new Audio("15.mp3"); num15.play(); break; case 16: var num16 =new Audio("16.mp3"); num16.play(); break; case 17: var num17 =new Audio("17.mp3"); num17.play(); break; case 18: var num18 =new Audio("18.mp3"); num18.play(); break; case 19: var num19 =new Audio("19.mp3"); num19.play(); break; case 20: var num20 =new Audio("20.mp3"); num20.play(); break; case 21: var num21 =new Audio("21.mp3"); num21.play(); break; case 22: var num22 =new Audio("22.mp3"); num22.play(); break; case 23: var num23 =new Audio("23.mp3"); num23.play(); break; case 24: var num24 =new Audio("24.mp3"); num24.play(); break; case 25: var num25 =new Audio("25.mp3"); num25.play(); break; case 26: var nu26 =new Audio("26.mp3"); nu26.play(); break; case 27: var num27 =new Audio("27.mp3"); num27.play(); break; case 28: var num28 =new Audio("28.mp3"); num28.play(); break; case 29: var num29 =new Audio("29.mp3"); num29.play(); break; case 30: var num30 =new Audio("30.mp3"); num30.play(); break; case 31: var num31 =new Audio("31.mp3"); num31.play(); break; case 32: var num32 =new Audio("32.mp3"); num32.play(); break; case 33: var num33 =new Audio("33.mp3"); num33.play(); break; case 34: var num34 =new Audio("34.mp3"); num34.play(); break; case 35: var num35 =new Audio("35.mp3"); num35.play(); break; case 36: var nu36 =new Audio("36.mp3"); nu36.play(); break; case 37: var num37 =new Audio("37.mp3"); num37.play(); break; case 38: var num38 =new Audio("38.mp3"); num38.play(); break; case 39: var num39 =new Audio("39.mp3"); num39.play(); break; case 40: var num40 =new Audio("40.mp3"); num40.play(); break; case 41: var num41 =new Audio("41.mp3"); num41.play(); break; case 42: var num42 =new Audio("42.mp3"); num42.play(); break; case 43: var num43 =new Audio("43.mp3"); num43.play(); break; case 44: var num44 =new Audio("44.mp3"); num44.play(); break; case 45: var num45 =new Audio("45.mp3"); num45.play(); break; case 46: var nu46 =new Audio("46.mp3"); nu46.play(); break; case 47: var num47 =new Audio("47.mp3"); num47.play(); break; case 48: var num48 =new Audio("48.mp3"); num48.play(); break; case 49: var num49 =new Audio("49.mp3"); num49.play(); break; case 50: var num50 =new Audio("50.mp3"); num50.play(); break; case 51: var num51 =new Audio("51.mp3"); num51.play(); break; case 52: var num52 =new Audio("52.mp3"); num52.play(); break; case 53: var num53 =new Audio("53.mp3"); num53.play(); break; case 54: var num54 =new Audio("54.mp3"); num54.play(); break; case 55: var num55 =new Audio("55.mp3"); num55.play(); break; case 56: var nu56 =new Audio("56.mp3"); nu56.play(); break; case 57: var num57 =new Audio("57.mp3"); num57.play(); break; case 58: var num58 =new Audio("58.mp3"); num58.play(); break; case 59: var num59 =new Audio("59.mp3"); num59.play(); break; case 60: var num60 =new Audio("60.mp3"); num60.play(); break; case 61: var num61 =new Audio("61.mp3"); num61.play(); break; case 62: var num62 =new Audio("62.mp3"); num62.play(); break; case 63: var num63 =new Audio("63.mp3"); num63.play(); break; case 64: var num64 =new Audio("64.mp3"); num64.play(); break; case 65: var num65 =new Audio("65.mp3"); num65.play(); break; case 66: var nu66 =new Audio("66.mp3"); nu66.play(); break; case 67: var num67 =new Audio("67.mp3"); num67.play(); break; case 68: var num68 =new Audio("68.mp3"); num68.play(); break; case 69: var num69 =new Audio("69.mp3"); num69.play(); break; case 70: var num70 =new Audio("70.mp3"); num70.play(); break; case 71: var num71 =new Audio("71.mp3"); num71.play(); break; case 72: var num72 =new Audio("72.mp3"); num72.play(); break; case 73: var num73 =new Audio("73.mp3"); num73.play(); break; case 74: var num74 =new Audio("74.mp3"); num74.play(); break; case 75: var num75 =new Audio("75.mp3"); num75.play(); break; case 76: var nu76 =new Audio("76.mp3"); nu76.play(); break; case 77: var num77 =new Audio("77.mp3"); num77.play(); break; case 78: var num78 =new Audio("78.mp3"); num78.play(); break; case 79: var num79 =new Audio("79.mp3"); num79.play(); break; case 80: var num80 =new Audio("80.mp3"); num80.play(); break; case 81: var num81 =new Audio("81.mp3"); num81.play(); break; case 82: var num82 =new Audio("82.mp3"); num82.play(); break; case 83: var num83 =new Audio("83.mp3"); num83.play(); break; case 84: var num84 =new Audio("84.mp3"); num84.play(); break; case 85: var num85 =new Audio("85.mp3"); num85.play(); break; case 86: var nu86 =new Audio("86.mp3"); nu86.play(); break; case 87: var num87 =new Audio("87.mp3"); num87.play(); break; case 88: var num88 =new Audio("88.mp3"); num88.play(); break; case 89: var num89 =new Audio("89.mp3"); num89.play(); break; case 90: var num90 =new Audio("90.mp3"); num90.play(); break; case 91: var num91 =new Audio("91.mp3"); num91.play(); break; case 92: var num92 =new Audio("92.mp3"); num92.play(); break; case 93: var num93 =new Audio("93.mp3"); num93.play(); break; case 94: var num94 =new Audio("94.mp3"); num94.play(); break; case 95: var num95 =new Audio("95.mp3"); num95.play(); break; case 96: var nu96 =new Audio("96.mp3"); nu96.play(); break; case 97: var num97 =new Audio("97.mp3"); num97.play(); break; case 98: var num98 =new Audio("98.mp3"); num98.play(); break; case 99: var num99 =new Audio("99.mp3"); num99.play(); break; default :alert("se acabaron los números"); } }
import mongoose from "mongoose"; import shortid from "shortid"; const schema = new mongoose.Schema({ _id: { type: String, "default": shortid.generate }, firstName: { type: String, trim: true }, lastName: { type: String, trim: true }, email: { type: String, min: 6, unique: true, required: true, trim: true }, bio: { type: String, min: 100, trim: true }, skills: [String], organization: String }); class Worker { get fullName() { return `${this.firstName} ${this.lastName}`; } } schema.loadClass(Worker); export default schema;
const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { devtool: 'cheap-module-eval-source-map', module: { rules: [ { test: /\.(pdf|jpg|png|gif|svg|ico)$/, use: [ { loader: 'url-loader', }, ], }, ], }, });
/** * file: asathoor.js **/ // open links as <a href="x" target="_blank"> $('a').attr({ target:'_blank' });
const mongoose = require("mongoose"); // mongodb://127.0.0.1:27017/ const db_uri = 'mongodb://127.0.0.1:27017/TrabajoBd' module.exports = ( )=>{ const connect= () => { mongoose.connect( db_uri,{ keepAlive :true, useNewUrlParser:true, useUnifiedTopology:true }, (err)=>{ if(err){ console.log(err+"error"); console.log("error mongo"); }else{ console.log("conexion correcta mongo") } } ) } connect(); }
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { desginderDetails: { id: null, }, storeDetails: { id: null, }, }, getters: {}, mutations: { SET_userID(state, id) { state.desginderDetails.id = id; }, SET_storeId(state, id) { state.storeDetails.id = id; }, }, actions: { setReviceUserId(context, payload) { context.commit('SET_userID', payload.id); }, setReviceStoreId(context, payload) { context.commit('SET_storeId', payload.id); }, }, modules: {}, });
/** * Created by sylwester on 30.06.17. */ /** * Created by sylwester on 25.06.17. */ if (typeof Src === 'undefined') { var Src = {}; Src.Layout = {}; } if (!Src.hasOwnProperty('Layout')) { Src.Layout = {}; } Src.Layout.Controller = Object.assign(Object.create(Src.Layout), { SideMenuLayout(){ const layout = Layout.getSomeLayout(); return function view(anchor) { layout.render(anchor); App.run('/layout/side/menu', layout.menu); return layout.content; } }, sideMenu(){ const home = Object.create(MenuElement); home .setLabel('home') .setLink('/'); const menu = Object.create(Menu); menu .addElement(home) .build(); return function view(anchor) { anchor.appendChild(menu.domElement); return anchor; } }, preload(){ const template = ` <div class="vertical-center__element"> <span class="preloader preloader--top"></span> <span class="preloader preloader--bottom"></span> </div>`; const div = document.createElement('div'); div.id = 'loader'; div.classList.add('vertical--center'); div.innerHTML = template; return function view(anchor) { anchor.innerHTML = ''; anchor.appendChild(div); return anchor; } } });
import React from 'react'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import { Link } from 'react-router'; import PropTypes from 'prop-types'; const propTypes = { auth: PropTypes.object.isRequired, logout: PropTypes.func.isRequired, }; class BusinessMenu extends React.PureComponent { render() { const { auth, logout } = this.props; return ( <Menu> <Link to="/profile"><MenuItem>Profile</MenuItem></Link> <Link to="/restaurants"><MenuItem>All Restaurants</MenuItem></Link> <Link to={`/restaurant/${auth.user.id}`}><MenuItem>My restaurant</MenuItem></Link> <Link onClick={logout}><MenuItem>Log out</MenuItem></Link> </Menu> ); } } BusinessMenu.propTypes = propTypes; export default BusinessMenu;
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ function CacheJSonService() { this.cacheData = new eXo.core.HashMap() ; } ; if(eXo.core.CacheJSonService == undefined){ eXo.core.CacheJSonService = new CacheJSonService() ; } ; CacheJSonService.prototype.getData = function(url, invalidCache) { if(invalidCache){ this.cacheData.remove(url) ; } else { var value = this.cacheData.get(url) ; if(value != null && value != undefined) return value ; } var responseText = ajaxAsyncGetRequest(url, false) ; if(responseText == null || responseText == '') return null ; // alert("Response Text1: " + responseText); var response ; try { if(request.responseText != '') { eval("response = "+responseText) ; } } catch(err) { /**Created: Comment by Le Bien Thuy**/ //TODO. alert(err + " : "+responseText); return null ; } if(response == null || response == undefined) return null ; this.cacheData.put(url, response) ; return response ; } ;
use codeclan; db.students.insert([ { name: "Fred", favouriteFood: "Pizza" }, { name: "Jeff", favouriteFood: "Haggis" } ]); db.students.find(); db.instructers.insert([ { name: "John", favouriteFood: "Pasta" }, { name: "Jarrod", favouriteFood: "Burgers" } ]); db.instructers.find(); show collections; db.dropDatabase();
var mutt__lua_8h = [ [ "mutt_lua_parse", "mutt__lua_8h.html#a91c41afa7a2a63d5a43885d9cc59790b", null ], [ "mutt_lua_source_file", "mutt__lua_8h.html#a70cdff4a76452475cb756f4f3386a3eb", null ], [ "mutt_lua_init", "mutt__lua_8h.html#a388809bb42b3e97c7af207cd5e86857f", null ] ];
/// <reference path="_references.js" /> /* * GLOBAL VARIABLES/OBJECTS * ======================================================================== */ var __rootUrl = window.location.protocol + '//' + window.location.hostname, // Avoids hardcoded urls in script GlobalSessionObjectStore = GlobalSessionObjectStore || []; // Creates global array object for cleanup GlobalSessionObjectStore.Remove = function (noteid, checkForToolType) { if (!isNaN(noteid)) { var objectsToRemove = this.filter(function (object) { if (typeof checkForToolType !== 'undefined' && typeof checkForToolType === 'Boolean' && checkForToolType) { if (typeof object.NoteID !== 'undefined') return object.NoteID == noteid && object.ToolType == "guideStepTool"; } else if (typeof object.NoteID !== 'undefined') { return object.NoteID == noteid; } else { return false; } }); objectsToRemove.forEach(function (object) { var index = $.inArray(object, GlobalSessionObjectStore); // IE8 fix GlobalSessionObjectStore.splice(index, 1); object = undefined; }); objectsToRemove = undefined; } }; GlobalSessionObjectStore.Dispose = function () { this.forEach(function (object) { var index = $.inArray(object, GlobalSessionObjectStore); // IE8 fix GlobalSessionObjectStore.splice(index, 1); object = undefined; }); this.Destroy(); }; GlobalSessionObjectStore.Destroy = function () { this = undefined; }; /* ======================================================================== * GLOBAL METHODS * ======================================================================== */ PerformAjaxAsynchronousPostback = function (jsondata, sender, successCallback, failureCallback) { $.ajax({ url: __rootUrl + '/_layouts/tpcip.web/ws/ActionHandler.asmx/HandleUserAction', type: 'POST', data: JSON.stringify(jsondata), dataType: 'json', contentType: 'application/json' }).success(function (data, status) { if (status == 'success') { if (typeof successCallback === 'function') { successCallback(sender, data.d, true); } } }).fail(function (jqHXR, status, errorThrown) { if (typeof failureCallback === 'function') { failureCallback(sender, status + ': ' + errorThrown + '<p>StackTrace: ' + jqHXR.responseText + "</p>", true); } }); }; OnAjaxAsynchronousPostback = function (jsondata) { return $.ajax({ url: __rootUrl + '/_layouts/tpcip.web/ws/ActionHandler.asmx/HandleUserAction', type: 'POST', data: JSON.stringify(jsondata), dataType: 'json', contentType: 'application/json' }); }; /* ======================================================================== * GLOBAL BASE TYPE * ======================================================================== */ var TdcBaseObject = function () { this.NoteID = 0; this.ToolType = null; };
/* eslint-env node */ const Hapi = require('hapi'); const {connection} = require('./config'); const routes = require('./routes'); const server = new Hapi.Server(); server.connection({ port: connection.port, host: connection.host, routes: { cors: true } }); server.route(routes); server.start((err) => { if (err) { console.error( err ); // eslint-disable-line } console.log(`Server started at ${server.info.uri}`) // eslint-disable-line });
import { Math } from "phaser"; class Bullet extends Phaser.Physics.Arcade.Image { constructor(scene) { super(scene, 0, 0, 'bullet'); this.scene = scene; scene.add.existing(this); scene.physics.world.enableBody(this); this.speed = 500; this.setCollideWorldBounds(true); this.body.onWorldBounds = true; this.setBounce(1); this.MAXBOUNCES = 6; this.bounces = this.MAXBOUNCES; scene.physics.world.on('worldbounds', this.reduceBounce, this); } fire(source, target, power) { this.enableBody(true, source.x, source.y, true, true); this.scene.physics.moveTo(this, target.x, target.y, this.speed); this.bounces = Math.RoundTo(power*this.bounces); } reduceBounce() { this.bounces -= 1; if (this.bounces < 0) { this.reset(); } } reset() { this.setVelocity(0); //reset the body this.enableBody(true, -32, -32, false, false); this.disableBody(); this.setVisible(false); this.emit('bulletDead', this); this.bounces = this.MAXBOUNCES; } } export default Bullet;
(function () { 'use strict'; angular .module('generalApp') .controller('CustomersController', CustomersController); function CustomersController($scope, CustomerService){ initController(); function initController(){ CustomerService.GetCustomers() .then(function(customers) { $scope.customers = customers; }); } } })();
/** * Created by zhengHu on 16-10-8. * 商品详情展示 */ import React from 'react'; class SettlementProdDetail extends React.Component { constructor(props) { super(props); } handleClick(message){//单击弹框处理 alert(message); } specialProd(){ let tips='',message='',dataS=this.props.data.commonCartItems[0];// 此特例品不参与会员折扣活动 此特例品不参与优惠券和会员折扣活动 if(dataS.isSpecialProductAsTicket || dataS.isSpecificForUserDiscount){ tips='特殊商品'; if(dataS.isSpecialProductAsTicket){ if(dataS.isSpecificForUserDiscount){ message='此特例品不参与优惠券和会员折扣活动'; }else{ message='此特例品不参与优惠券活动'; } }else{ message='此特例品不参与会员折扣活动'; } } return {'tips':tips,'message':message} } render() { let dataS=this.props.data.commonCartItems[0]; return ( <div className="pro-section clell_border link-page-view" name="pro-page-view"> <div className="pro-info-first"> <div className='info-icon'><img src={dataS.image} /></div> <div className='info-box'> <div> <div className='info-title'>{dataS.name}</div> <div className='info-mixin'>数量:x{dataS.quantity}{dataS.spec}</div> </div> <div className='info-wrap'> <div className='info-special' onClick={() => this.handleClick(this.specialProd().message)}>{this.specialProd().tips}<span className={this.specialProd().tips?'secoo_icon_Artboard-3':''}></span></div> <div className='info-amount'>{dataS.nowPrice}</div> </div> </div> </div> <div className="pro-info-second hide"> <div className="info-gift">[赠品] Michael Kors/迈克·科尔斯 纯皮女款笑脸包提包黑色手提色手提手提包黑色手提</div> <div className="info-count">x1</div> </div> </div> ); } } SettlementProdDetail.defaultProps = { }; export default SettlementProdDetail;
const router = require("express").Router(); const checkAuth = require("./check-auth"); const { getProfile, setVideoSeen } = require("../controller/profile") router.get("/:id", checkAuth, getProfile); router.post("/videoSeen", checkAuth, setVideoSeen); module.exports = router;