text
stringlengths
7
3.69M
import React, {Fragment, useRef, useState} from 'react'; let accessedProperties = []; const derivationGraph = {}; const observable = (targetObject) => { const ObservableObject = {}; const keys = Object.keys(targetObject); const id = Math.random(); function getId(key) { return `Observable(${id}:${key})`; } keys.forEach(key => { const id = getId(key); ObservableObject[key] = targetObject[key]; if (typeof targetObject[key] !== 'function') { Object.defineProperty(ObservableObject, key, { get() { accessedProperties.push(id); return targetObject[key]; }, set(value) { targetObject[key] = value; if (derivationGraph[id]) { derivationGraph[id].forEach(fn => fn()); } } }); } }); return ObservableObject; }; const createReaction = (whatShouldWeRunOnChange) => { return { track(fnWhereWeUseObservables) { accessedProperties = []; fnWhereWeUseObservables(); console.log(derivationGraph); console.log(accessedProperties); accessedProperties.forEach(id => { derivationGraph[id] = derivationGraph[id] || []; if (derivationGraph[id].indexOf(whatShouldWeRunOnChange) < 0) { derivationGraph[id].push(whatShouldWeRunOnChange); } }); } } }; const autorun = (cb) => { const reaction = createReaction(cb); reaction.track(cb); }; const useForceUpdate = () => { const [, set] = useState(0); return () => set(val => val + 1); }; const observer = (baseComponent) => { const Wrapper = () => { const forceUpdate = useForceUpdate(); const reaction = useRef(null); if (!reaction.current) { reaction.current = createReaction(forceUpdate); } let result; reaction.current.track(() => { result = baseComponent(); }); return result; }; return Wrapper; }; const store = observable({ count: 0, name: 'Unnamed', increment() { this.count += 1; } }); autorun(() => { console.log('autorun count', store.count); }); const App = () => { return ( <Fragment> <h1>Counter {store.count}</h1> <button onClick={() => store.increment()}>Increment</button> </Fragment> ); }; export const ObserverApp = observer(App);
// creating a menger-sponge // https://en.wikipedia.org/wiki/Menger_sponge class MengerSponge { constructor(size, cx=0, cy=0, cz=0) { this.sponges = []; this.size = size; this.cx = cx; this.cy = cy; this.cz = cz; } draw() { if (this.sponges.length == 0) { //noStroke(); push(); translate(this.cx,this.cy,this.cz); box(this.size); // translate back to origin //translate(-this.cx,-this.cy,-this.cz); pop(); } else { for (var i = 0; i < this.sponges.length; i++) { this.sponges[i].draw(); } } } split(){ if (this.sponges.length == 0) { // split into 3x3x3 smaller sponges var nSize = this.size / 3; for(var x = -1; x<2 ; x++){ var ncx = this.cx + (nSize*x); for(var y = -1; y<2; y++){ var ncy = this.cy + (nSize*y); for(var z = -1; z<2 ; z++){ //var f = abs(x)^abs(y)^abs(z); //if( f != 1) var f = abs(x)+abs(y)+abs(z); //if( f == 2) if( f < 2) continue; var ncz = this.cz + (nSize*z); var s = new MengerSponge(nSize,ncx,ncy,ncz); this.sponges.push(s); } } } console.log(this.sponges); } else { for (var i = 0; i < this.sponges.length; i++) { this.sponges[i].split(); } } } } var angle; var canvasSize; var spongeSize; var center; var angle_change_rate; var mengerSponge; function setup() { angle = 0; angle_change_rate = 0.01; canvasSize = 800; center = 0; spongeSize = 300; createCanvas(canvasSize, canvasSize, WEBGL); mengerSponge = new MengerSponge(spongeSize); } function increaseAngle() { angle += angle_change_rate; rotateX(angle); rotateY(angle); } function doubleClicked() { mengerSponge.split(); return false; } function draw() { background(000); lights(); mengerSponge.draw(); orbitControl(); }
var express = require("express"); // use npm install express var http = require("http"); const dao = require("./src/dao"); const bodyParser = require("body-parser"); module.exports = dao; var app = express(); app.use(bodyParser.urlencoded({ extended: true })); // parse application/json app.use(bodyParser.json()); var cors = require("cors"); app.use(cors()); app.get("/playlists", function(req, res) { //connect db dao.connect(); //query data from database dao.query("SELECT * FROM playlist ", [], result => { console.log(result.rows); // var json_users = JSON.stringify(result.rows); // console.log(json_users); res.status(200).json({ data: result.rows }); dao.disconnect(); }); }); app.get("/tracks/:playListID", function(req, res) { //connect db dao.connect(); //query data from database dao.query( "SELECT * FROM track where playlist_id=$1 ", [req.params.playListID], result => { console.log(result.rows); // var json_users = JSON.stringify(result.rows); // console.log(json_users); res.status(200).json({ data: result.rows }); dao.disconnect(); } ); }); app.get("/tracks", function(req, res) { //connect db dao.connect(); //query data from database dao.query("SELECT * FROM track ", [], result => { console.log(result.rows); // var json_users = JSON.stringify(result.rows); // console.log(json_users); res.status(200).json({ data: result.rows }); dao.disconnect(); }); }); 2; app.post("/track", function(req, res) { dao.connect(); dao.query( "insert into track (playlist_id,title,uri,master_id)values($1,$2,$3,$4)", [req.body.playListID, req.body.title, req.body.uri, req.body.masterID], result => { console.log(result.rowCount); if (result.rowCount > 0) { res .status(200) .json({ data: "Track details Added successfully to playlist" }); } else { res.status(500).send("something went wrong"); } dao.disconnect(); } ); }); app.delete("/tracks/:trackId", function(req, res) { dao.connect(); //query data from database console.log(req.params.id); dao.query("delete from track where id = $1", [req.params.trackId], result => { console.log(result); if (result.rowCount > 0) { res.status(200).json({ data: "Track Deleted SuccessFully!" }); } dao.disconnect(); }); }); app.listen(8000, function() { console.log("Example app listening on port 3000!"); });
import React from 'react' import {HashRouter , Route} from 'react-router-dom' import App from '../App' import Detail from '../views/detail' import Home from '../views/home' import PictureSelect from '../views/PictureSelect' const router = <HashRouter> <App> <Route path="/detail" component={Detail}/> <Route path="/home" component={Home}/> <Route path="/aaa" component={PictureSelect}/> </App> </HashRouter> export default router;
angular.module('ngApp.baseRateCard').controller('BaseRateCardLimitController', function ($scope, $uibModalInstance,OperationZone, RateLimit, $filter, $state, toaster, $translate, $uibModal, ZoneBaseRateCardService, $window) { //Set Multilingual for Modal Popup var setModalOptions = function () { $translate(['FrayteError', 'FrayteInformation', 'FrayteValidation', 'ErrorSavingRecord', 'PleaseCorrectValidationErrors', 'SuccessfullySavedInformation', 'records', 'ErrorGetting', 'Success', 'FrayteWarning_Validation', 'UpdateRecord_Validation', 'PleaseCorrectValidationErrors', 'RateCardSaveLimit_Validation']).then(function (translations) { $scope.TitleFrayteError = translations.FrayteError; $scope.TitleFrayteInformation = translations.FrayteInformation; $scope.TitleFrayteValidation = translations.FrayteValidation; $scope.TextValidation = translations.PleaseCorrectValidationErrors; $scope.TextErrorSavingRecord = translations.ErrorSavingRecord; $scope.TextSuccessfullySavedInformation = translations.SuccessfullySavedInformation; $scope.RecordGettingError = translations.ErrorGetting + " " + translations.records; $scope.Success = translations.Success; $scope.FrayteWarningValidation = translations.FrayteWarning_Validation; $scope.UpdateRecordValidation = translations.UpdateRecord_Validation; $scope.PleaseCorrectValidationErrors = translations.PleaseCorrectValidationErrors; $scope.RateCardSaveLimitValidation = translations.RateCardSaveLimit_Validation; }); }; $scope.submit = function (IsValid) { if (IsValid) { $scope.BaseRateLimitJson.push($scope.RateLimit); ZoneBaseRateCardService.SaveZoneBaseRateCardLimit($scope.BaseRateLimitJson).then(function (response) { if (response.data.Status) { toaster.pop({ type: 'success', title: $scope.Success, body: $scope.RateCardSaveLimit_Validation, showCloseButton: true }); $uibModalInstance.close($scope.RateLimit); } else { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextErrorSavingRecord, showCloseButton: true }); } }, function () { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextErrorSavingRecord, showCloseButton: true }); }); } else { toaster.pop({ type: 'warning', title: $scope.FrayteWarningValidation, body: $scope.PleaseCorrectValidationErrors, showCloseButton: true }); } }; var getCurrencyCodes = function () { ZoneBaseRateCardService.GetOperationZoneCurrencyCode($scope.OperationZone.OperationZoneId, 'Buy').then(function (response) { if (response.data !== null) { $scope.CurrencyCodes = response.data; } }, function () { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.RecordGettingError, showCloseButton: true }); }); }; function init() { $scope.BaseRateLimitJson = []; $scope.OperationZone = OperationZone; getCurrencyCodes(); $scope.RateLimit = RateLimit; setModalOptions(); } init(); });
const belong = require('../src/algorithms/belong'); describe('belong', () => { it('should throw an error if the first input is not an array', () => { const actual = belong(false, 8); expect(actual).toBe('You need an array and a number'); }); it('should throw an error if the second input is not a number', () => { const actual = belong([1, 2, 3, 4,], true); expect(actual).toBe('You need an array and a number'); }); it('should return the index of where the number fits', () => { const actual = belong([10, 20, 30, 40, 50], 30); expect(actual).toBe(2); }); it('should return the last index if the number does not fit', () => { const actual = belong([10, 20, 30, 40, 50], 60); expect(actual).toBe(5); }); });
var dgram = require('dgram'); var freeport = require('freeport'); var network = require('network'); var http = require('http'); var weather = require('./weather'); var TLcList = config.TLc.list; var allScenes = []; var allChannels = []; var enqTimer = null; var enqBroadcastCb = null; var broadcastAddress; var refreshCompleteCb; var controlState = 'Auto'; exports.init = init; exports.send = send; exports.rqInfo = rqInfo; exports.control = control; exports.trigger = trigger; exports.setChannel = setChannel; exports.showScene = showScene; exports.refresh = refresh; exports.list = list; exports.state = state; exports.checkTLcs = checkTLcs; exports.updateScenes = updateScenes; var udpServervar; function enqTimeoutCb() { console.log("### Tlc enqTimeoutCb"); TLcList.forEach((t) => { // Deal with TLcs going offline if (!t.online) t.ip = null; }); if (enqBroadcastCb) { console.log(`TLcs: ${JSON.stringify(TLcList, null, 2)}`) updateScenes(enqBroadcastCb); // enqBroadcastCb(); enqBroadcastCb = null; } } function udpServerMessageFunc(message, remote) { console.log("### UDP msg") try { var response = JSON.parse(message); /* Should be like: {"TLc":"Hollies-L", "Version":{"Major":0,"Minor":73}, "IPaddress":"192.168.001.081", "snMatches":true, "Errors":[{"Section":1,"Error":1,"Count":32,"Message":"Corrupt SwitchPlate msg 2"},...] } or {"OSC"} */ } catch (ex) { console.error("UDP msg: %j %s", response, ex.message); } if (response.TLc) { var _tlc = getTLc(response.TLc); if (_tlc) { _tlc.IPaddress = response.IPaddress.replace(/\.0/g, '.').replace(/\.0/g, '.');; _tlc.Version = response.Version.Major.toString() + '.' + response.Version.Minor.toString(); _tlc.online = true; _tlc.errors = []; if (response.Errors) { response.Errors.forEach((err) => { _tlc.errors.push(err); }); } if (enqTimer) { clearTimeout(enqTimer); } enqTimer = setTimeout(enqTimeoutCb, 500); console.log("### Reset enqTimer"); } else { console.error(`TLc ${response.TLc} not in TLcList`); addTLc(response.TLc, response.IPaddress, `${response.Version.Major}.${response.Version.Minor}`) } } else if (response.OSC) { console.log(remote.address + ':' + remote.port + ' - ' + message); var parts = response.OSC[0].split('-'); if (parts[1] == 'Fader') { if (refreshCompleteCb) { refreshCompleteCb(parts[0], response.args[0]); } } } else { console.log("udpServerMessageFunc: %j", response); } } function broadcast(address, str) { var bfr = new Buffer.from(str); console.log("tlc:-> %s", str); udpServer.setBroadcast(true); udpServer.send(bfr, 0, bfr.length, config.TLc.udp_port, address, (err, bytes) => { if (err) { console.log("Broadcast error: %j", err); } }); } function init(initDone) { enqBroadcastCb = initDone; udpServer = dgram.createSocket('udp4'); udpServer.on('message', udpServerMessageFunc); udpServer.on('error', (err) => { console.error(`UDP error ${err}`); }); freeport((err, port) => { if (err) console.error(`No free port ${err}`); network.get_interfaces_list((err, list) => { var i; for (i = 0; i < list.length; i++) { console.log(`IFs: ${JSON.stringify(list[i])}`) if (list[i].type == 'Wired') { try { udpServer.bind(port, list[i].ip_address, () => { var address = udpServer.address(); var p = address.address.split('.'); broadcastAddress = `${p[0]}.${p[1]}.${p[2]}.255`; console.log('UDP udpServer listening on ' + address.address + ":" + address.port); broadcast(broadcastAddress, '{"enq":"TLc"}'); console.log("### Start timeout"); enqTimer = setTimeout(enqTimeoutCb, 1000); // Allow longer time for initial response }); } catch (ex) { console.error(`UDP bind error: ${ex}`); } return; } } console.error("No wired interface available"); }); }); } function checkTLcs(cb) { if (enqBroadcastCb) { console.log("checkTLcs, enq in progress"); return; // Already doing it } enqBroadcastCb = cb; TLcList.forEach((t) => { t.online = false }); broadcast(broadcastAddress, '{"enq":"TLc"}'); } function rqInfo(tlcName, info, cb, param) { var options = { timeout: 1000, host: "", port: config.TLc.http_port, }; t = getTLc(tlcName); if (t) { if (t.serNo.length > 6) { options.host = getTLc(tlcName).IPaddress; } else { cb({ error: true, info: `${tlcName} not online` }); } } else { cb({ error: true, info: `${tlcName} not registered in config` }); return; } options.path = '/' + info + '?serialNo=' + getTLc(tlcName).serNo if (param) { options.path += '&' + param; } var req = http.get(options, function (res) { var data = ''; res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { var obj = {}; try { obj.data = JSON.parse(data); // Must be in try/catch if (!obj.data.result) { // NB reponse is EITHER a result code (+info) or the data obj.error = false; } else { obj.error = true; obj.info = `Rq ${info} returned false, info: ${data}`; } } catch (ex) { obj.error = true; obj.info = "Bad JSON: " + data; } obj.reqInfo = info; obj.tlc = tlcName; cb(obj); }); }); req.on('error', (e) => { console.error("rqInfo error: %j", e); console.log(e.stack); cb({ error: true, info: e.message, reqInfo: info, tlc: tlcName }); if (!enqBroadcastCb) { // No enqBroadcastCb in progress checkTLcs(() => { console.log("Rechecked TLc IP addresses"); }); } else { console.log("rqInfo enqBroadcast in progress"); } }); } exports.test = function (request, response) { updateScenes(() => { response.setHeader('Content-Type', 'application/json'); response.end(allScenes); }); } function getChannel(tlcName, channelID) { var chnl = allChannels.find(channel => { return channel.tlcName == tlcName && channel.id == channelID; }); return chnl; } function updateScenes(cb) { let tlcCount = TLcList.length; allChannels = []; TLcList.forEach(function (_tlc) { // e.g. channels {"ID":5,"AreaID":0,"Name":"Bay green"}, // e.g. areas {"ID":1,"Name":"Hall","LastScene":19}, // e.g. channelvalues [255,0,0,0,0,0,0,0,0,0,255,255,255,0,0,0,255,255,0,255,255,0,255,0,0,0,0,0,255,255,255] const MAXAREAS = 20; const MAXCHANNELS = 50; let areaNames = []; let channels = []; let channelValues = []; for (let i = 0; i < MAXAREAS; i++) areaNames.push('-'); const getTLcData = function (url) { return new Promise((resolve, reject) => { rqInfo(_tlc.Name, url, (result) => { if (result.error) reject(result); else { resolve(result.data); } }); }); } if (_tlc.online) { getTLcData('areas') .then(_areas => { _areas.forEach(a => { areaNames[a.ID] = a.Name; }); return getTLcData('channelValues'); }) .then(_values => { channelValues = _values; return getTLcData('channels'); }) .then(_channels => { _channels.forEach((c) => { channels.push({ id: c.ID, name: c.Name, tlcName: _tlc.Name, areaName: areaNames[c.AreaID], currentValue: channelValues[c.ID] }); }); Array.prototype.push.apply(allChannels, channels); return getTLcData('scenes'); }) .then(tlcScenes => { if (tlcScenes.length > 0) { tlcScenes.forEach((scene) => { updateScene(_tlc.Name, scene); }); } else { console.log(`No scenes from ${_tlc.Name}`); } return getTLcData('sceneChannels'); }) .then(tlcSceneChannels => { tlcSceneChannels.forEach(sc => { updateSceneChannels(_tlc.Name, sc); }); console.log(allScenes.length); if (--tlcCount == 0) { if (cb) cb(); } }) .catch(e => console.log(e)); } else { console.log(`TLc ${_tlc.Name} is offline`); if (cb) cb(); } // e.g. allScenes {"ID":1, "Name": "Reading", "FadeIn":20, "Duration":0, "FadeOut":0, "FadePrev":false, "NextScene":255, "StartTime":"42:30"}, function updateScene(tlcName, scene) { let idx = allScenes.findIndex((sc) => { return sc.tlcName == tlcName && scene.ID == sc.ID }); if (idx >= 0) { allScenes[idx].Name = scene.Name; // That's all that might have changed that we want } else { allScenes.push({ tlcName: tlcName, ID: scene.ID, Name: scene.Name, channels: [] }); } } // e.g. sceneChannels {"SceneID":1,"Channel":{"ID":2,"Max":2,"value":250}} function updateSceneChannels(tlcName, sceneChannel) { try { let sceneIdx = allScenes.findIndex(scene => { return scene.tlcName == tlcName && scene.ID == sceneChannel.SceneID }); if (sceneIdx >= 0) { // console.log(`updateSceneChannels: %d %j`, sceneIdx, sceneChannel); // Add to scene.channels[] => {ID, targetValue, currentValue, areaName, channelName} let scene = allScenes[sceneIdx]; // Note sceneChannel has range of channels ID->Max for (let channelID = sceneChannel.Channel.ID; channelID <= sceneChannel.Channel.Max; channelID++) { let sceneChannelIdx = scene.channels.findIndex(channel => { return channel.ID == channelID; }); let channelObj = getChannel(scene.tlcName, channelID); if (channelObj) { if (sceneChannelIdx >= 0) { // Found exisiting scene.channels[sceneChannelIdx].targetValue = sceneChannel.Channel.value; scene.channels[sceneChannelIdx].currentValue = channelObj.value; } else { // New scene.channels.push({ ID: channelID, targetValue: sceneChannel.Channel.value, currentValue: channelObj.value, areaName: channelObj.areaName, channelName: channelObj.name }); } } else { // console.log(`No channelObj for ${JSON.stringify(scene)}, ${channelID} in ${JSON.stringify(sceneChannel)}`); } } } else { console.log(`(${sceneIdx}) Scene inconsistancy tcl: ${tlcName} no scene for ${JSON.stringify(sceneChannel)}`); } } catch (ex) { console.log('Error in updateSceneChannels: ', ex.message) } } }); } exports.getSceneAreaChannels = function (areaName, sceneName, cb) { const getTLcData = function (tlcName, url) { return new Promise((resolve, reject) => { rqInfo(tlcName, url, (result) => { if (result.error) reject(result); else { resolve(result); } }); }); } function findValue(channelValues, tlcName, channelID) { channelValues.forEach((tlcValues) => { if (tlcName == tlcValues.tlc) return tlcValues.data[channelID]; }); return 0; } var allTLcPromises = []; var channelInfo = []; TLcList.forEach((_tlc) => { allTLcPromises.push(getTLcData(_tlc.Name, 'channelvalues')); }); Promise.all(allTLcPromises) .then((results) => { console.log(results); allScenes.forEach((scene) => { if (scene.Name == sceneName || sceneName == null) { scene.channels.forEach((channel) => { if (channel.areaName == areaName || areaName == null) { channelInfo.push({ tlc: scene.tlcName, area: areaName, scene: scene.Name, channel: channel.channelName, id: channel.ID, value: findValue(results, scene.tlcName, channel.ID), target: channel.targetValue }); } }); } }); cb(channelInfo); }) .catch(reason => { console.log(reason) cb(reason); }); } exports.getAreaChannels = function (areaName, cb) { const getTLcData = function (tlcName, url) { return new Promise((resolve, reject) => { rqInfo(tlcName, url, (result) => { if (result.error) reject(result); else { resolve(result); } }); }); } function findValue(channelValues, tlcName, channelID) { var retVal = -1; channelValues.forEach((tlcValues) => { if (tlcName == tlcValues.tlc) retVal = tlcValues.data[channelID]; }); if (channelID == 18) console.log(tlcName, channelID); return (retVal < 0) ? 0 : retVal; } var allTLcPromises = []; var channelInfo = []; // Set up for parallel getting all (3) tlc info TLcList.forEach((_tlc) => { allTLcPromises.push(getTLcData(_tlc.Name, 'channelvalues')); }); Promise.all(allTLcPromises) .then((results) => { allChannels.forEach((channel) => { if (channel != {}) { channel.currentValue = findValue(results, channel.tlcName, channel.id); } }); let result = allChannels.filter((chanl) => chanl.areaName == areaName); cb(result); }) .catch(reason => { console.log(reason); cb(reason); }); } function control(state) { switch (state) { case "Auto": case "Dark": case "Light": controlState = state; } } function state() { return controlState; } exports.isLight = isLight; // for testing function isLight(now, cloudCover) { switch (controlState) { case "Auto": let cloudAdjustment = 0.5 + cloudCover / 100; // Up to 1.5 hours before/after sunset/sunrise let times = sunCalc.getTimes(now, config.latitude, config.longitude); let start = moment(times.sunrise).add(cloudAdjustment, 'hours'); let end = moment(times.sunset).subtract(cloudAdjustment, 'hours'); console.log(`Light: ${start.format('HH:mm')} - ${end.format('HH:mm')} cloud: ${cloudAdjustment}`); return now.isBetween(start, end); case "Dark": return false; case "Light": return true; } return true; } function trigger(tlcName, area, channel, state, filter) { if (filter && state == 'on') { // NB always turn OFF; conditional turn ON if (isLight(moment(), weather.getCloud().c[0])) return; } send(tlcName, `{"OSC":["${area}-Fader","${channel}"],"args":[${(state == 'on') ? 255 : 0}]}`); } function setChannel(tlcName, area, channel, val) { if (val < 0) val = 0; if (val > 255) val = 255; send(tlcName, `{"OSC":["${area}-Fader","${channel}"],"args":[${val}]}`); } function showScene(tlcName, scene) { send(tlcName, `{"OSC":["Area-Scene","${scene}"],"args":[1]}`); }; function refresh(tlcName, area, channel, cb) { console.log("refresh: %j %s-%s", tlcName, area, channel); refreshCompleteCb = cb; send(tlcName, `{"OSC":["Refresh Fader-${area}","${channel}"],"args":[1]}`); }; function send(tlcName, str) { var bfr = new Buffer.from(str); console.log("Send %j ===> %s", tlcName, str); var tlcObj = getTLc(tlcName) if (tlcObj) { var ip = tlcObj.IPaddress.replace(/\.0/g, '.').replace(/\.0/g, '.'); console.log("%s=>%s %s", tlcName, str, ip); udpServer.send(bfr, 0, bfr.length, config.TLc.udp_port, ip, function (err, bytes) { if (err) { console.log("tlc send error: %j", err); } }); } else { console.log("TLc %j is not online", tlcName); } } function getTLc(tlcName) { _tlc = TLcList.find((t) => { return t.Name == tlcName }); if (_tlc) return _tlc; console.error(`*** tlcName "${tlcName}" is not defined`); return undefined; } function addTLc(tlcName, ipAddress, version) { var newTLc = { Name: tlcName, serNo: '', online: false, IPaddress: ipAddress, Version: version, Location: 'Not registered' }; TLcList.push(newTLc); return newTLc; } function list() { return TLcList; }
var searchData= [ ['ctrl_5falgorithm_2ejava',['Ctrl_Algorithm.java',['../Ctrl__Algorithm_8java.html',1,'']]], ['ctrl_5fbrowser_2ejava',['Ctrl_Browser.java',['../Ctrl__Browser_8java.html',1,'']]], ['ctrl_5ffolderfile_2ejava',['Ctrl_FolderFile.java',['../Ctrl__FolderFile_8java.html',1,'']]], ['ctrl_5finput_2ejava',['Ctrl_Input.java',['../Ctrl__Input_8java.html',1,'']]], ['ctrl_5finput_5fencoded_2ejava',['Ctrl_Input_Encoded.java',['../Ctrl__Input__Encoded_8java.html',1,'']]], ['ctrl_5finput_5fimg_2ejava',['Ctrl_Input_Img.java',['../Ctrl__Input__Img_8java.html',1,'']]], ['ctrl_5finput_5fjpeg_2ejava',['Ctrl_Input_JPEG.java',['../Ctrl__Input__JPEG_8java.html',1,'']]], ['ctrl_5finput_5flz78_2ejava',['Ctrl_Input_LZ78.java',['../Ctrl__Input__LZ78_8java.html',1,'']]], ['ctrl_5finput_5flzss_2ejava',['Ctrl_Input_LZSS.java',['../Ctrl__Input__LZSS_8java.html',1,'']]], ['ctrl_5finput_5flzw_2ejava',['Ctrl_Input_LZW.java',['../Ctrl__Input__LZW_8java.html',1,'']]], ['ctrl_5finput_5ftext_2ejava',['Ctrl_Input_Text.java',['../Ctrl__Input__Text_8java.html',1,'']]], ['ctrl_5foutput_2ejava',['Ctrl_Output.java',['../Ctrl__Output_8java.html',1,'']]], ['ctrl_5foutput_5fencoded_2ejava',['Ctrl_Output_Encoded.java',['../Ctrl__Output__Encoded_8java.html',1,'']]], ['ctrl_5foutput_5fimg_2ejava',['Ctrl_Output_Img.java',['../Ctrl__Output__Img_8java.html',1,'']]], ['ctrl_5fpresentacio_2ejava',['Ctrl_Presentacio.java',['../Ctrl__Presentacio_8java.html',1,'']]] ];
import React from "react"; import { getBg } from "../getColor"; export const Pure = () => { return <div style={getBg()}>pure</div>; };
'use strict'; const pagination = require('hexo-pagination'); module.exports = function(locals) { const config = this.config; const perPage = config.tag_generator.per_page; const paginationDir = config.pagination_dir || 'page'; const orderBy = config.tag_generator.order_by || '-date'; let authorsDir = config.hexo_authors_generator.authors_dir || "authors/"; if (authorsDir[authorsDir.length - 1] !== '/') authorsDir += '/'; let authors = []; // console.log(posts); const Query = this.model('Post').Query; locals.posts.each(function(post,index){ if(!post.author) return; //console.log(post.title) var authorName = post.author.name //console.log(authorName); if(authorName == undefined && authorName != "") return; var found = false; authors.forEach((author,index)=>{ if(authorName == author.name){ authors[index].posts.push(post); found = true; } }); if(!found){ var newAuthor = { name: "", posts: [] } newAuthor.name = post.author.name; // console.log("author:"+newAuthor.name); newAuthor.posts.push(post); authors.push(newAuthor); // console.log(newAuthor); } }); const pages = authors.reduce((result, author) => { if (!author.posts.length) return result; var posts = author.posts; var postObj = new Query(posts) const data = pagination(authorsDir + author.name, postObj.sort(orderBy), { perPage: perPage, layout: ['archive', 'index'], format: paginationDir + '/%d/', data: { author: author.name } }); return result.concat(data); }, []); if(config.hexo_authors_generator.create_root) { var allPosts = locals.posts.sort(orderBy) pages.push({ path: authorsDir, layout: ['archive','index'], posts: allPosts, data: { base: authorsDir, total: 1, current: 1, current_url: authorsDir, posts: allPosts, prev: 0, prev_link: '', next: 0, next_link: '' } }); } return pages; };
const mongoose = require('mongoose') const Schema = mongoose.Schema const model = mongoose.model const messageSchema = new Schema({ content:{type:String, require:true}, activityId:{type:String, require:true}, createTime:{type:String}, wxname:{type:String}, sno:{type:String} }) const Message = model('Message',messageSchema) module.exports = Message
import { GET_REPOS, ERROR_MSG, LOADER } from "./actions"; const initialData = { loader: false, errorMsg: "", repos: [], }; const repoReducer = (state = initialData, action) => { switch (action.type) { case LOADER: return {...state, loader:action.payload} case GET_REPOS: return { ...state, repos: action.payload, errorMsg: ""}; case ERROR_MSG: return { ...state, errorMsg: action.payload }; default: return state; } }; export default repoReducer;
/** * */ $(document).ready(function() {menu.getMenu(7); menu.getListBody();}); var font = "微博媒体管理"; var valids = ["所属地区", "微博认证", "微博网站", "头像", "昵称", "粉丝数量(万)", "直发市场价", "直发锁定价", "转发市场价", "转发锁定价", "直发成本价", "转发成本价", "媒体QQ", "备注", "最后修改时间", "最后修改人"]; var sizes = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]; var contents = ["所属地区", "微博认证", "微博网站", "头像", "昵称", "粉丝数量(万)", "直发市场价", "直发锁定价", "转发市场价", "转发锁定价", "直发成本价", "转发成本价", "媒体QQ", "备注", "最后修改时间", "最后修改人"]; var keys = ["area_did", "weibo_auth", "weibo_websit_did", "head_pic", "nickname", "fan", "straight_market_price", "straight_lock_price", "redirect_market_price", "redirect_lock_price", "straight_cost", "redirect_cost", "qqnumber", "commont", "quantity", "last_update_time", "last_update_by"];
var path = require('path') var config = require('../config') var ExtractTextPlugin = require('extract-text-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') var fs = require('fs') exports.assetsPath = function (_path) { var assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } exports.cssLoaders = function (options) { options = options || {} var cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { var loaders = [cssLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' }) } else { return ['vue-style-loader'].concat(loaders) } } // https://vue-loader.vuejs.org/en/configurations/extract-css.html return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), sass: generateLoaders('sass', { indentedSyntax: true }), scss: generateLoaders('sass'), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') } } // Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function (options) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] output.push({ test: new RegExp('\\.' + extension + '$'), use: loader }) } return output } //根据命令行参数获取当前编译目录 exports.getEntries = function(postfix) { var curShopDir = path.join(__dirname, '../src/'); var self = this; var entries = fs.readdirSync(curShopDir).filter(function(file) { return self.filterFiles(file, postfix); }) return entries } //获取指定后缀文件 exports.filterFiles = function(str, postfix) { var postfix = postfix || 'js'; var fileRe = new RegExp('\.(' + postfix + ')'); return fileRe.test(str); } //动态产生页面 exports.gerHtmlWebpackPlugin = function() { var htmlPlugins = [] var entries = this.getEntries() var pages = this.getEntries('html'); var curDir = path.join(__dirname, '../src/'); entries.map(function(file){ var name = file.split('.')[0] var pl = new HtmlWebpackPlugin({ filename: name + '.html', template: pages.indexOf(name+'.html')>-1 ? curDir + '/' + name + '.html': (pages.indexOf(name + '.htm')>-1 ? name + '/' + '.htm' : 'index.html'), chunks: [name, 'vendor', 'manifest'], inject: true }) htmlPlugins.push(pl) }); return htmlPlugins }
import React, { useEffect, useState } from 'react'; import ErrorMessage from '../components/ErrorMessage'; import { Link } from 'react-router-dom'; import './CartScreen.css'; const CartScreen = (props) => { // const productId=props.match.params.id; // const qty=props.location.search?Number(props.location.search.split('=')[1]):0; // accessing the second element to get the quantity const {cart}=props; const {setcart}=props; const deleteHandler=(props)=>{ setcart({...cart,cartItems: cart.cartItems.filter(el=>el.product!==props)}); localStorage.setItem("cart",JSON.stringify({...cart,cartItems: cart.cartItems.filter(el=>el.product!==props)})); } const checkoutHandler=()=>{ props.history.push('/signin?redirect=shipping'); } return ( <div className="container"> <div className="items"> <h3 className="heading">Shopping Cart</h3> { cart.cartItems.length===0?<ErrorMessage>Cart is empty <Link to="/">Go Shopping</Link></ErrorMessage> : <div> { cart.cartItems.map(item=>( <div key={item.product} className="item-container"> <div className="item"><img className="image" src={item.image} /></div> <div className="item"> <Link to={`/product/${item.product}`}>{item.name}</Link> </div> <div className="item"> <select value={item.qty} onChange={(e)=>{ const newQty=e.target.value; const tempcart={...cart}; const idx=tempcart.cartItems.findIndex(el=>el.product===item.product) const temp1={...tempcart.cartItems[idx]} temp1.qty=newQty; tempcart.cartItems[idx]=temp1; setcart({ ...tempcart }); localStorage.setItem("cart",JSON.stringify({ ...tempcart })); }}> { [...Array(item.countInStock).keys()].map(idx=>( <option key={idx+1} value={idx+1}> {idx+1} </option> )) } </select> </div> <div className="item">${item.price}</div> <div className="item"> <button className="btn btn-danger" onClick={()=>deleteHandler(item.product)}>Delete</button> </div> </div> )) } </div> } </div> {cart.cartItems.length!==0 && <div className="checkout"> <div className="subtotal"> <h5> Subtotal ({cart.cartItems.reduce((a,c)=>Number(a)+Number(c.qty),0)}) items: ${cart.cartItems.reduce((a,c)=>a+c.price*c.qty,0)} </h5> <button className="btn checkoutbtn" onClick={checkoutHandler}>Proceed to Checkout</button> </div> </div> } </div> ); } export default CartScreen;
function myFunc() { let count = 0; //using clousure return function() { count++; return count; }; } console.log(myFunc()); const instanceOne = myFunc(); //function invocation stored const instanceTwo = myFunc(); console.log('instanceOne: ', instanceOne()); console.log('instanceOne: ', instanceOne()); console.log('instanceOne: ', instanceOne()); console.log('instanceTwo: ', instanceTwo()); console.log('instanceTwo: ', instanceTwo()); console.log('instanceOne: ', instanceOne()); //Create function that will tell how many times it is running
import React from 'react'; import Fade from 'react-reveal/Fade'; import { useTranslation } from 'react-i18next'; import data from '../mydata'; const Contact = () => { const { t } = useTranslation(); return( <div> <h1><Fade bottom cascade> {t('Contact.title')} </Fade></h1> <Fade bottom> <div className="contact-content"> <h2 className="amazing-color"> {t('Contact.message')}<br></br> </h2> <ul> {data.social.map((link, index)=>{ if (link.name==="Email"){return <li key={index}><a href={`mailto:${link.name}`}>{t(link.name)}</a></li>} else{ return <li key={index}><a target='_blank' rel="noopener noreferrer" href={link.url}>{t(link.name)}</a></li> } })} </ul> </div> </Fade> </div> ) } export default Contact;
({ getServiceInfo : function(component, event, helper) { var navEvt = $A.get("e.force:navigateToSObject"); navEvt.setParams({ "recordId": component.get("v.ServiceDetails.ServiceData.Id") }); navEvt.fire(); }, gotomembertask : function(component, event, helper){ component.getEvent('sendtoParent').setParams({ sequence:'BAMMemberService' }).fire(); }, gotoprevious : function(component, event, helper){ component.getEvent('gotoPrevious').setParams({ }).fire(); } })
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Field, reduxForm } from 'redux-form'; import Checkbox from '../../../form-fields/checkbox'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import Grid from 'material-ui/Grid'; class CarThirdStep extends Component { render() { const { previousPage, invalid, submitting, handleSubmit } = this.props; return ( <form onSubmit={handleSubmit} className="quotation-form"> <Grid container gutter={24}> <Grid item xs={12}> <Typography type="title" color="inherit" style={{ marginBottom: 20 }}> Categoria </Typography> </Grid> <Grid container gutter={0} item xs={12}> <Grid item xs={6}> <Field name="categorias_carro[economico]" component={Checkbox} label="Econômico" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[luxo]" component={Checkbox} label="Luxo" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[compacto]" component={Checkbox} label="Compacto" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[premium]" component={Checkbox} label="Premium" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[intermediario]" component={Checkbox} label="Intermediário" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[minivan]" component={Checkbox} label="Minivan" /> </Grid> <Grid item xs={6}> <Field name="categorias_carro[suv]" component={Checkbox} label="SUV" /> </Grid> </Grid> <Grid gutter={0} item xs={12} container style={{ marginTop: 20}}> <Grid gutter={0} container item xs={6} justify="flex-start"> <Button raised color="primary" type="button" onClick={previousPage}> Anterior </Button> </Grid> <Grid gutter={0} container item xs={6} justify="flex-end"> <Button raised color="primary" type="submit" disabled={invalid || submitting}> Próximo </Button> </Grid> </Grid> </Grid> </form> ); } } CarThirdStep.propTypes = { handleSubmit: PropTypes.func.isRequired }; export default reduxForm({ form: 'carForm', destroyOnUnmount: false, forceUnregisterOnUnmount: true, enableReinitialize: true, keepDirtyOnReinitialize: true, initialValues: { qnt_adultos: 0, qnt_criancas: 0, qnt_bebes: 0 } })(CarThirdStep);
function _a2c(id, qty, calc) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: "WebServices/WebService.asmx/add2cart", data: "{'ajax_Id':'" + id + "', 'qty':'" + qty + "'}", success: function (res) { $('#cartholder').html(res.d); var val = (parseInt($('#cartqty' + id).text()) + parseInt(qty)); if (val >= 0) { $('#cartqty' + id).text(val) } if (calc) { _ccp(); } } }); } function _delc(id) { var ret = confirm("Please confirm again for delete."); if (ret) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: "WebServices/WebService.asmx/del2cart", data: "{'ajax_Id':'" + id + "'}", success: function (res) { $('#cartholder').html(res.d); $('#cartr' + id).remove(); _ccp(); } }); } } function _ccp(drpship) { subt = 0; var table = document.getElementById('carttable'); if (table) { for (var i = 0; i < table.rows.length; i += 1) { var dt = $(table.rows[i]).find('input').val(); if (dt != undefined) { var qty = $('#cartqty' + dt).text(); var prc = $('#cartprc' + dt).text(); var tot = parseFloat(qty) * parseFloat(prc); subt += tot; $('#carttot' + dt).text(tot.toFixed(2)); } } $('#subtotal').text(subt.toFixed(2)); var vat = ((subt * parseFloat($('#vatper').val())) / 100); var ship = 0; if (drpship) { ship = parseFloat($(drpship).val()); if (drpship.selectedIndex == 0) { $('#trOutlet').hide(); $('#trDealer').hide(); } else if (drpship.selectedIndex == 1) { $('#trOutlet').show(); $('#trDealer').hide(); } else { $('#trOutlet').hide(); $('#trDealer').show(); } } $('#shiptotal').text(ship.toFixed(2)); $('#vattotal').text(vat.toFixed(2)); $('#grdtotal').text((subt + vat + ship).toFixed(2)); } } $(document).ready(function () { _ccp(); $('#trOutlet').hide(); $('#trDealer').hide(); });
import React from 'react'; import { connect } from 'react-redux'; import OrderItem from './OrderItem'; const mapStateToProps = state => { return ( {order: state.orderReducer.currentOrder} ) } export default connect(mapStateToProps)(OrderItem)
export const spec = (data) => ({ $schema: "https://vega.github.io/schema/vega-lite/v5.json", width: 1000, height: 600, data, encoding: { x: { field: "date", type: "temporal", }, tooltip: [ { field: "-", type: "quantitative" }, { field: "EXPIRED", type: "quantitative" }, { field: "HIT", type: "quantitative" }, { field: "MISS", type: "quantitative" }, { field: "REVALIDATED", type: "quantitative" }, { field: "STALE", type: "quantitative" }, { field: "UPDATING", type: "quantitative" }, { field: "total", type: "quantitative" }, ], }, layer: [ { params: [ { name: "legendclick", select: { type: "point", fields: ["symbol"], }, bind: "legend", }, ], mark: { type: "area", line: true, }, encoding: { y: { aggregate: "sum", field: "value", stack: false, axis: { format: "s", }, }, color: { field: "symbol", scale: { scheme: "category10" }, }, strokeWidth: { value: 1, }, fillOpacity: { condition: { param: "legendclick", value: 0.5 }, value: 0.2, }, opacity: { condition: { param: "legendclick", value: 0.5, }, value: 0.2, }, }, }, { transform: [{ pivot: "symbol", value: "value", groupby: ["date"] }], params: [ { name: "hover", select: { type: "point", fields: ["date"], on: "mouseover", clear: "mouseout", nearest: true, }, }, { name: "range", select: { type: "interval", }, }, ], mark: "rule", encoding: { opacity: { condition: { param: "hover", value: 0.5, empty: false, }, value: 0, }, }, }, // { // mark: "rule", // encoding: { // y: { // datum: 990000000, // }, // color: { value: "red" }, // size: { value: 1 }, // }, // }, ], }); export const specPie = (data) => ({ $schema: "https://vega.github.io/schema/vega-lite/v5.json", data, layer: [ { mark: "arc", encoding: { theta: { field: "value", type: "quantitative" }, color: { field: "symbol", type: "nominal", scale: { scheme: "sinebow" }, }, tooltip: [{ field: "value", type: "quantitative" }], }, }, ], view: { stroke: null }, });
/* React Libraries */ import React, {Component} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import toastr from 'toastr'; import Spinner from 'react-spinner'; /*constants*/ import { IMG_CONSTANT } from '../constants/application.constants'; var serialize = require('form-serialize'); /*Actions*/ import { userSignIn, contactUs, fbSignIn } from '../actions/loginAction'; import { isvalidLogin } from '../utils/Validation'; /*Functions*/ import { getFormSerializedData } from '../utils/functions'; import { APP_URL } from '../constants/applicationUrl'; /*Components*/ import App from '../containers/App'; import {isValidEmail} from '../utils/Validation'; import FacebookLogin from 'react-facebook-login'; let ImgPath = IMG_CONSTANT.BASE_PATH; class Login extends Component { constructor(props, context) { super(props, context); this.onSubmit=this.onSubmit.bind(this); this.onSignup=this.onSignup.bind(this); this.state={ buttonDisabled : true, name : "", email : "", msg : "", errName : "", errEmail : "", errMsg: "", ajaxCallInProgress:false, } } responseFacebook(response){ this.setState({ajaxCallInProgress:true}); this.props.fbSignIn(response).then(() => { if(this.props.userDetails!=undefined && this.props.userDetails!=null && this.props.userDetails.exists == false){ this.context.router.push(APP_URL.RREGISTER); } else{ this.context.router.push(APP_URL.HOME); this.setState({ajaxCallInProgress:false}); } }).catch((error) => { this.setState({ajaxCallInProgress:false}); }); } onSubmit(e) { this.setState({ajaxCallInProgress:true}); let formData = getFormSerializedData('login_form'); let errors = isvalidLogin(formData) if (_.size(errors) == 0) { this.props.userSignIn(formData).then(() => { this.setState({ajaxCallInProgress:false}); this.context.router.push(APP_URL.HOME); }).catch((error) => { this.setState({ajaxCallInProgress:false}); toastr.error("Please Enter Valid EmailId/Password"); }); } else { this.setState({ajaxCallInProgress:false}); toastr.warning("Email id /password are required fields"); } } onSendClick(){ let form = document.querySelector('#contactForm'); let formData = serialize(form, { hash: true }); this.props.contactUs(formData).then(()=>{ $('#name').val(''); $("#email").val(''); $('#message').val(''); $('#contactMessage').val(''); $("#myModal").modal('hide'); }).catch((error)=>{ }); } ForgotPassword(){ this.context.router.push('/enterEmail'); } onSignup() { this.context.router.push(APP_URL.RREGISTER); } /*****/ onRequired(e){ if(e.target.name == "name"){ if(e.target.value == ""){ this.setState({ name : "", errName : (<span className="err-msg1">Please Enter theName </span>), buttonDisabled : true }); } else{ this.setState({ name : e.target.value, errName :"", buttonDisabled : false }); } } if(e.target.name == "email"){ let errors = isValidEmail(e.target.value); if(errors == false){ this.setState({ errEmail : (<span className="err-msg1"> Invalid Email</span>), email : "", buttonDisabled: true }); } else{ this.setState({ errEmail : "", email : e.target.value, buttonDisabled: false }); } } if(e.target.name == "message"){ if(e.target.value == ""){ this.setState({ msg : "", errMsg : (<span className="err-msg1">Please Enter Something to Send </span>), buttonDisabled : true }); } else{ this.setState({ msg : e.target.value, errMsg:"", buttonDisabled : false }); } } } /*****/ enterCapture(e){ if((e.target.value != "") && (e.keyCode == 13)){ this.onSubmit(); } } render() { return( <div><div className="bgLoginReg "> <div className="BgadminDashboard"></div> </div> <div className="login-page "> <div className="navigation"> <div className="logo_login"> <img src={ImgPath+"Golf_CNX_Logo.png"} /> </div> <div className="menu-right"> <a onClick={this.onSignup} className="txtwhite">Sign Up</a> <a data-toggle="modal" data-target="#myModal" className="txtwhite"> Contact Us</a> <div className="modal fade addInvite" id="myModal" role="dialog" data-backdrop="static"> <form action="" method="post" id="contactForm" name="contactForm" ref="contactForm"> <div className="modal-dialog modal-sm mt15pc"> <div className="modal-content"> <div className="modal-header col-sm-12 modalHeader"><h4 className="m0px">CONTACT ADMIN</h4></div> <div className="modal-body col-sm-12 bgwhite mb0px"> <div className="col-sm-12"> <label>Name:</label><input type="text" placeholder="John Doe" id="name" name="name" className="form-control" onChange={this.onRequired.bind(this)}/> {this.state.errName} </div> <div className="col-sm-12"> <label>Email:</label><input type="email" placeholder="abc@gmail.com" id="email" name="email" className="form-control" onChange={this.onRequired.bind(this)}/> {this.state.errEmail} </div> <div className="col-sm-12"> <label>Message</label> <textarea className="txtarea form-control invtTxtArea" id="contactMessage" name="message" onChange={this.onRequired.bind(this)}/> {this.state.errMsg} </div> </div> <div className="modal-footer col-sm-12 bgwhite"> <button type="button" className="btn btnSend" id="btnSend" onClick={this.onSendClick.bind(this)} disabled={this.state.buttonDisabled || !this.state.name || !this.state.email || !this.state.msg}>Send</button> <button type="button" className="btnCncl" data-dismiss="modal">Cancel</button> </div> </div> </div> </form> </div> </div> </div> <div className="middlealign"> <div className="logoLoginPage"> <img src={ImgPath+"Golf_login_Logo.png"} /> </div> {(this.state.ajaxCallInProgress)?(<div className=""><Spinner /></div>):(<form action="" method="post" ref="login_form" id="login_form" name="login_form"> <div className="formElements"> <div className="form-group"> <input name="userEmailId" key="userEmailId" type="email" className="form-control" id="userEmailId" placeholder="Email:"/> </div> <div className="form-group"> <input name="userPassword" id="userPassword" key="userPassword" type="password" className="form-control" placeholder="Password:" onKeyDown={this.enterCapture.bind(this)}/> </div> <div className="LoginButton"> <button onClick={this.onSubmit} type="button"> <img src={ImgPath+"Login_button.png"}/> </button> </div> <div className="form-group"> <center className="txtwhite fnt20px">-or-</center> </div> <div className="LoginButton text-align pdlftryt15pc"> <img src={ImgPath+"FB_Login_button.png"} className=" fbImg"/> <div className="fbLoginbtn"><FacebookLogin appId="194085854431251" autoLoad={false} fields="name,email,picture" callback={this.responseFacebook.bind(this)} > </FacebookLogin> </div> </div> <div className="signup_text_main"> <div className="forget_txt cursor-pointer" onClick={this.ForgotPassword.bind(this)}>Forgot Password?</div> <div onClick={this.onSignup} className="signup_text cursor-pointer">Sign Up</div> </div> </div> </form>)} </div> </div> </div> ); } } Login.contextTypes = { router: React.PropTypes.object }; function mapStateToProps(state) { return { userDetails: (state.activeUser!=null)?(state.activeUser):(JSON.parse(sessionStorage.getItem('userDetails'))), }; } function matchDispatchToProps(dispatch){ return bindActionCreators({userSignIn, contactUs, fbSignIn}, dispatch); } export default connect(mapStateToProps, matchDispatchToProps)(Login);
$(function(){ var chats, nodeChat, socket; _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g }; // //models // var ChatEntry = Backbone.Model.extend({ initialize: function(model){ this.whom = model.whom; this.content = model.content; }, url: '/new' }); var ChatCount = Backbone.Model.extend({ initialize: function(){ this.number = 0; } }); // //collections // var Chats = Backbone.Collection.extend({ model: ChatEntry, url: '/nodechat.json', initialize: function(){ this.fetch(); } }); // //views // var ChatCountView = Backbone.View.extend({ el: $('#client_count'), initialize: function(){ _.bindAll(this, 'render'); }, render: function(activeClients){ $(this.el).html(activeClients); } }); var ChatEntryView = Backbone.View.extend({ tagName: 'li', template: _.template("<li class='chat_entry'><p class='whom'>{{whom}}:</p><p class='content'>{{content}}</p></li>"), initialize: function(){ _.bindAll(this, 'render'); this.render(); }, render: function(){ $(this.el).html(this.template({ whom: this.model.whom, content: this.model.content })); return this; } }); var ChatList = Backbone.View.extend({ el: $('#chat_list'), initialize: function(){ _.bindAll(this, 'render'); chats.bind('all', this.render); this.render(); }, render: function(){ $(this.el).html(''); for (var i = 0; i < chats.length; i++){ var model = chats.at(i); model = {whom: model.whom, content: model.content}; var chatEntryView = new ChatEntryView({model: model}); $(this.el).append(chatEntryView.el); } } }); var ChatForm = Backbone.View.extend({ el: $('#chat_form'), events: { 'submit': 'submitForm' }, submitForm: function(e){ e.preventDefault(); var whom = $(this.el).find('input[name="whom"]').val(), content = $(this.el).find('textarea').val(), model = {whom: whom, content: content}; //var chatEntry = new ChatEntry(model); //chatEntry.save(); if (model = chats.create(model)){ chats.add(model); this.clear(); } }, clear: function(){ var textarea = this.$('textarea'); textarea.val(''); } }); var NodeChat = Backbone.View.extend({ el: $('#context'), initialize: function(){ //this.chats = new Chats(); this.chatList = new ChatList(); this.chatForm = new ChatForm(); this.chatCountView = new ChatCountView(); } }); // //controllers // function init(){ socket = new io.Socket(null, {port: 3000}); socket.on('message', function(msg){ if (msg.event == 'refresh'){ chats.fetch(); }else if (msg.event == 'update' && typeof msg.activeClients === 'number'){ console.log(msg.activeClients); nodeChat.chatCountView.render(msg.activeClients); } }); socket.connect(); window.chats = chats = new Chats(); window.nodeChat = nodeChat = new NodeChat(); } init(); });
const express = require('express'); const app = express(); const { ROLE, users } = require('./data.js') const { authUser, authRole } = require('./basicAuth.js') const projectRouter = require('./routes/projects') app.use(express.json()); app.use(setUser); app.use('/projects',projectRouter); app.get('/', (req, res) => { res.send("home page welcome"); }) app.get('/dashboard', authUser, (req, res) => { res.send("dasboard page"); }) app.get('/Admin', authUser, authRole(ROLE.ADMIN),(req, res) => { res.send("Admin Page"); }) function setUser (req, res , next){ const userId = req.body.userId console.log(userId) if(userId){ req.user = users.find(user => user.id === userId); console.log("tambien aca") } next() } app.listen("3000", (req,res)=>{ console.log("me conecte"); })
var ProductRedeem= function() { this.tips1 = $("#buyProduct"); this.ok_pay = $("#ok_pay") this.param = GHutils.parseUrlParam(window.location.href) this.isOpenRemeed = ''; this.previousCur = {}; this.protocalMessage=""; return this; } ProductRedeem.prototype = { init: function() { this.maxRedeemMoney = 0; GHutils.isLogin() this.pageInit(); this.bindEvent(); }, pageInit: function() { var _this = this // _this.getUserInfo(); _this.getRedeemMoney(); _this.getToDetail(); }, bindEvent: function() { var _this = this //密码框 GHutils.inputPwd("#inputPayPwd"); //输入框 GHutils.checkInput($("#redeemMoney"),3); GHutils.checkInput($("#inputPayPwd"),5); //协议复选框 GHutils.protocolCheck('#redeem-protocolcheck'); setTimeout(function(){ $("#redeemMoney").val('') },50) //点击确认支付 _this.ok_pay.on('click',function(){ $("#buyProduct").html("&nbsp;") if($(this).hasClass("btn_loading")){ return } if(GHutils.validate('deposit-box')){ if(!$('#redeem-protocolcheck').hasClass('active')){ _this.tips1.html('提示:'+_this.protocalMessage) return false } //1.isOpenRemeed为"YES"可赎回 if(_this.isOpenRemeed == "NO"){//1.不可超过单笔最大赎回金额 _this.tips1.html('提示:不可赎回') return false; } var money = parseFloat($("#redeemMoney").val()) if(_this.previousCur != {} && money >_this.previousCur.previousCurVolume){ _this.tips1.html('提示:今日累计赎回已超出产品单日可赎回上限,请在下一交易日再发起赎回') return } _this.ok_pay.addClass("btn_loading") //继续校验 _this.myt0detail(); } }) //点击全部赎回 $('#redeemAll').on('click',function(){ //应该是获取全部的金额,放到框中 var uraParam = GHutils.parseUrlParam(window.location.href) GHutils.load({ url: GHutils.API.ACCOUNT.prot0detail+'?productOid='+uraParam.productOid, data:{}, type: "post", callback: function(result) { if(GHutils.checkErrorCode(result,_this.tips1 )){ _this.maxRedeemMoney = result.redeemableHoldVolume; if(result.maxRredeem){ if(_this.maxRedeemMoney > result.maxRredeem){ _this.maxRedeemMoney = result.maxRredeem; } } $('#redeemMoney').val(_this.maxRedeemMoney) } } }) }) }, // getUserInfo:function(){ // var _this = this; // GHutils.load({ // url: GHutils.API.ACCOUNT.userinfo, // data: {}, // type: "post", // callback: function(result) { // GHutils.log(result,"用户======="); // if(GHutils.checkErrorCode(result,_this.tips1)){ //// $('#hasPayPwd').hide() //// $('#noPayPwd').hide() // GHutils.userinfo = result //// if(result.paypwd){ // _this.ok_pay.addClass("active") //// $('#hasPayPwd').show() //// $('#noPayPwd').hide() //// }else{ //// $('#noPayPwd').show() //// $('#hasPayPwd').hide() //// _this.ok_pay.removeClass("active").off(); //// } // } // } // }) // }, getRedeemMoney:function(){ var _this = this; //获取可赎回金额 GHutils.load({ url: GHutils.API.ACCOUNT.prot0detail+'?productOid='+_this.param.productOid, data:{}, type: "post", callback: function(result) { GHutils.log(result,"可赎回金额====="); if(GHutils.checkErrorCode(result,_this.tips1 )){ $('.redeem_money').html(GHutils.formatCurrency(result.redeemableHoldVolume)) $("#redeemMoney").attr("placeholder",result.minRredeem+"元,"+result.additionalRredeem+"元递增") _this.maxRedeemMoney = result.redeemableHoldVolume; if(result.maxRredeem){ if(_this.maxRedeemMoney > result.maxRredeem){ _this.maxRedeemMoney = result.maxRredeem; } $("#pc_maxRredeem").html(GHutils.formatCurrency(result.maxRredeem)+'元') }else{ $("#pc_maxRredeem").html('无限制') } $("#redeemMoney").keyup(function(){ var _val = $(this).val(); if(_val && Number(_val) > Number(_this.maxRedeemMoney)){ _val = _this.maxRedeemMoney; $(this).blur().next().hide(); } $(this).val(_val) }) } } }); }, getToDetail:function(){ var _this = this; GHutils.load({ url: GHutils.API.PRODUCT.gett0detail+'?oid='+_this.param.productOid, data:{}, type: "post", callback: function(result) { GHutils.log(result,"产品详情========"); if(GHutils.checkErrorCode(result,_this.tips1 )){ GHutils.product = result $(".redeem_name").html(result.productName); _this.isOpenRemeed =result.isOpenRemeed if(result.isPreviousCurVolume == "YES"){ _this.previousCur ={"previousCurVolume":result.previousCurVolume} } if(result.isOpenRemeed == "NO"){//1.不可超过单笔最大赎回金额 _this.tips1.html('提示:不可赎回') _this.ok_pay.removeClass("btn_loading").removeClass("gh_btn_orange").addClass("gh_btn_disabled").off(); return false; } //动态展示协议 if(result.investFiles && result.investFiles.length > 0){ $("#investFiles").parent().removeClass("gh_none") _this.protocalMessage="《投资协议》"; } if(result.files && result.files.length > 0){ $("#files").parent().removeClass("gh_none") if(_this.protocalMessage){ _this.protocalMessage+="、《投资说明书》" } } if(result.serviceFiles && result.serviceFiles.length > 0){ $("#serviceFiles").parent().removeClass("gh_none") if(_this.protocalMessage){ _this.protocalMessage+="和《风险提示书及平台免责声明》" } } if( _this.protocalMessage.indexOf("、") == 0 || _this.protocalMessage.indexOf("和") == 0){ _this.protocalMessage = _this.protocalMessage.substr(1) } } }, errcallback: function(){ _this.tips1.html("提示: 数据加载失败,刷新页面") } }); }, myt0detail:function(){ var _this = this; GHutils.load({ url: GHutils.API.ACCOUNT.prot0detail+'?productOid='+_this.param.productOid, data:{}, type: "post", callback: function(result) { GHutils.log(result,"产品可赎回金额============") if(GHutils.checkErrorCode(result,_this.tips1)){ var redeemMoney = Number($('#redeemMoney').val()) if(result.singleDayRedeemCount && result.dayRedeemCount >= result.singleDayRedeemCount){//7.不可超过单人单数赎回次数上限 _this.tips1.html("提示:产品已达当日最高赎回限制"+result.singleDayRedeemCount+"笔") _this.ok_pay.removeClass("btn_loading") return false }else if(!redeemMoney){ _this.tips1.html("提示:请输入赎回金额") _this.ok_pay.removeClass("btn_loading") return false }else if(result.maxRredeem && redeemMoney > result.maxRredeem){//1.不可超过单笔最大赎回金额 _this.tips1.html('提示:赎回金额不可超过单笔最大赎回金额'+result.maxRredeem+"元") _this.ok_pay.removeClass("btn_loading") return false; }else if(redeemMoney > result.redeemableHoldVolume){//2.不可超过剩余可赎回金额 _this.tips1.html('提示:输入金额不可大于赎回限额'+result.redeemableHoldVolume+'元') _this.ok_pay.removeClass("btn_loading") return false; }else if(redeemMoney < result.minRredeem){//3.不可小于最低可赎回金额 _this.tips1.html('提示:赎回金额不可小于起赎金额'+result.minRredeem+'元') _this.ok_pay.removeClass("btn_loading") return false; }else if(GHutils.Fdiv(GHutils.Fsub(redeemMoney, result.minRredeem), result.additionalRredeem).toString().indexOf('.') > 0){//4.赎回金额必须为最低金额+递增金额的整数倍 _this.tips1.html('提示:赎回金额不可小于起赎金额'+result.minRredeem+'元,且以'+result.additionalRredeem+'元的整数倍递增') _this.ok_pay.removeClass("btn_loading") return false; }else if(result.singleDailyMaxRedeem && redeemMoney > GHutils.Fsub(result.singleDailyMaxRedeem, result.dayRedeemVolume)){//5.不可超过单人单日赎回上限 _this.tips1.html('提示:赎回金额不可超过您的当日剩余可赎回金额 '+GHutils.Fsub(result.singleDailyMaxRedeem, result.dayRedeemVolume)+"元") _this.ok_pay.removeClass("btn_loading") return false; }else if(result.netMaxRredeemDay && redeemMoney > result.dailyNetMaxRredeem){//6.不可超过产品单日赎回上限 _this.tips1.html('提示:不可超过产品单日赎回上限') _this.ok_pay.removeClass("btn_loading") return false; } _this.checkpaypwd() } } }); }, checkpaypwd:function() { var _this = this; GHutils.load({ url: GHutils.API.USER.checkpaypwd, data:{ payPwd:$('#inputPayPwd').val() }, type: "post", callback: function(result) { if(GHutils.checkErrorCode(result,_this.tips1)){ _this.redeemProduct() } } }); }, redeemProduct:function(){//赎回 var _this = this; var productOid = _this.param.productOid, orderAmount = Number($('#redeemMoney').val()); GHutils.load({ url: GHutils.API.PRODUCT.performredeem, data:{ productOid:productOid, orderAmount:orderAmount, cid:cid, ckey:ckey, }, type: "post", callback: function(result) { if(GHutils.checkErrorCode(result,_this.tips1)){ _this.ok_pay.removeClass("btn_loading") //赎回成功 window.location.href = 'product-result.html?action=redeem&moneyVolume='+orderAmount+'&tradeOrderOid='+result.tradeOrderOid+"&productOid="+_this.param.productOid _this.ok_pay.removeClass("btn_loading") } } }) }, callBackFun:function(){ var _this = this _this.pageInit(); } } $(function() { new ProductRedeem().init(); window.pageFun = new ProductRedeem(); })
//验证整个表单的输入值外加IP正则 <script type="text/javascript"> function checkip(ipaddr) { var ipaddr = document.all.IP.value; var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; if (re.test(ipaddr)) { var parts = ipaddr.split("."); if (parseInt(parseFloat(parts[0])) == 0) { alert("输入错误,请重新填写"); return false; } if (parseInt(parseFloat(parts[3])) == 0) { alert("输入错误,请重新填写"); return false; } for (var i=0; i<parts.length; i++) { if (parseInt(parseFloat(parts[i])) > 254) { alert("输入错误,请重新填写"); return false; } } var form=document.getElementById('form'); var inputArray=form.getElementsByTagName("input"); var inputArrayLength=inputArray.length; for(var int=0;int<inputArrayLength;int++) { if( inputArray[int].value==null || inputArray[int].value=='') { alert('第'+(int+1)+'个输入值为空.'); return false; } } return true; }else{ alert("输入错误,请重新填写"); return false; } } </script> ---------------------------------------------------------------------------------------------------------------------------- <form onSubmit="return checkip();" action="/host_link" method="post" id="form"> <!--返回true时则post到server 否则不post--> <ul class="list"> <li>IP : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="IP" name="IP" type="text" onclick=""></li> <li>端口: &nbsp;&nbsp;&nbsp;<input id="port" name="port" type="text"></li> <li>帐号:&nbsp;&nbsp;&nbsp;&nbsp;<input id="user" name="user" type="text"></li> <li>密码:&nbsp;&nbsp;&nbsp;&nbsp;<input id="passwd" name="passwd" type="password" ></li> </ul> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button> <button id="" type="submit" class="btn btn-primary" onclick="">添加</button> </div> </form> ---------------------------------------------------------------------------------------------------------------------------- //ajax 提交数据 <script type="text/javascript"> function Delete(event){ var value = event.value //表单value的值 if (!confirm("确认要删除该主机吗?")) { window.event.returnValue = false; } $.ajax({ type: "POST", url: "/host_del", data: {id: value}, }).done(function(data,status,jqXHR){ if(jqXHR.status == 200){ if(data.status == 1){ alert("删除成功") } alert("删除成功") } }).fail(function(){ alert("删除失败") }).always(function(){ location.href="/host_list"; }) } </script> <li><button id="del" type="submit" value="{{b[u'host_id']}}" onclick="Delete(this)"><i class="icon-trash"></i>删除</button></li> ------------------------------------------------------------------------------------------------------------------------ //ajax 一个按钮,两个事件的功能,传文件,说多了都是泪啊,前端太渣了,吃了不少苦 <script type="text/javascript"> function check() { var file_value = document.getElementById("file").value; var formData = new FormData($( "#fileup" )[0]); if(file_value == ""){ alert('请选择文件!') return false; }else{ $.ajax({ url: '/file_up' , type: 'POST', data: formData, async: true, cache: false, contentType: false, processData: false, success: function (returndata) { alert("上传成功,正在传输到远端服务器"); }, error: function (returndata) { alert(returndata); } }); } } </script> <button style="float:right" class="btn btn-info btn-srm " type="button" onclick="check();" >点击上传</button> http://stackoverflow.com/questions/27736186/jquery-has-deprecated-synchronous-xmlhttprequest http://blog.csdn.net/willspace/article/details/49021481 —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— //ajax download <script type="text/javascript"> function check() { var remote = document.getElementById("remote").value;//都是id var local = document.getElementById("local").value; var ip = document.getElementById("IP").value; var formData = new FormData($( "#filedw" )[0]); //表单ID if(remote == "请选择远程文件路径") { alert("请选择远程文件路径"); }else if(local == "请选择到本地路径"){ alert("请选择到本地路径"); }else if(ip == "请选择主机") { alert("请选择主机"); }else{ $.ajax({ url: '/file_dw' , type: 'POST', data: formData, async: true, cache: false, contentType: false, processData: false, success:function (data,status) { if(data == "0"){ alert("下载成功") }else{ alert("主机没有录入信息") } }, error: function (returndata) { alert("上传失败"); } }); } } </script>
import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import { Typography } from "@material-ui/core"; const useStyles = makeStyles(() => ({ message: { width: "50%", padding: "1em", alignSelf: "center" } })); const Message = ({ children }) => { const classes = useStyles(); return ( <Paper className={classes.message}> <Typography variant="body2">{children}</Typography> </Paper> ); }; export default Message;
import default_image from '../../images/default_image.png'; export const map = [ ["userimage","userimage",default_image], ["realname_checkbox","username.show"], ["realname","username.data"], ["nickname_checkbox","nickname.show"], ["nickname","nickname.data"], ["shortintro","profile.data"], ["email_checkbox","profile.show"], ["email","publicEmail.data"], ["phone_company_checkbox","office.show"], ["phone_company","office.data"], ["phone_home_checkbox","homephone.show"], ['phone_home','homephone.data'], ['mobile_checkbox','cellphone.show'], ['mobile','cellphone.data'], ['address_checkbox','CC.show'], ['address','CC.data'], ['personal_website_checkbox','web.show'], ['personal_website','web.data'], ['facebook_checkbox','facebook.show'], ['facebook','facebook.data'], ['Linkedin_checkbox','Linkedin.show'], ['Linkedin','Linkedin.data'], ['major_checkbox','education.major.show'], ['diploma_bachelor_major','education.major.SD'], ['diploma_bachelor_double_major','education.double_major.SD'], ['diploma_bachelor_minor','education.minor.SD'], ['dm_checkbox','education.double_major.show'], ['diploma_master','education.master.SD'], ['master_checkbox','education.master.show'], ['diploma_doctor','education.doctor.SD'], ['doctor_checkbox','education.doctor.show'] ]
var http = require('http'); var url = process.argv[2]; http.get(url,function(response, err){ if (!err){ response.on("data",(data)=>{ console.log(data.toString()); }); }else{ console.log(err.stack); } });
import styleProps from '../config/props' import { inputProps } from '../Input/input.props' import Input from '../Input' import { forwardProps } from '../utils' const Textarea = { name: 'Textarea', model: { prop: 'inputValue', event: 'change' }, props: { ...styleProps, ...inputProps, inputValue: String }, render (h) { return h(Input, { props: { ...forwardProps(this.$props), as: 'textarea', py: '8px', minHeight: '80px', fontFamily: 'body', lineHeight: 'shorter' }, on: { input: (value, $e) => this.$emit('change', value, $e) } }, this.$slots.default) } } export default Textarea
Shortly.LoginView = Backbone.View.extend({ className: 'login', template: Templates['login'], events: { 'submit': 'login' }, initialize: function(router) { this.router = router; }, render: function() { this.$el.html( this.template() ); return this; }, login: function(e) { e.preventDefault(); var $username = this.$el.find('form #username'); var $password = this.$el.find('form #password'); var log = new Shortly.Login({ username: $username.val(), password: $password.val() }); log.save({}) .always(data => this.always.call(this, data)); $username.val(''); $password.val(''); }, always: function(data) { if (data.status === 200) { this.success(); } else { this.failure(); } }, success: function() { this.$el.find('.message') .html('') .removeClass('error'); this.router.navigate('/', { trigger: true }); }, failure: function(model, res) { this.$el.find('.message') .html('Invalid credentials') .addClass('error'); this.router.navigate('/login', { trigger: true }); return this; }, });
import React from 'react'; import ReduxToastr from 'react-redux-toastr'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware } from 'redux'; import { configure, addDecorator } from '@storybook/react'; import { withKnobs } from '@storybook/addon-knobs'; import rootReducer from '../src/reducers'; import history from '../src/history'; import App from '../src/components/App'; import initialState from '../src/store/initialState.json5'; const req = require.context('../src', true, /\.story\.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } const middleware = [thunk.withExtraArgument({ history })]; const enhancer = applyMiddleware(...middleware); const context = { insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, store: createStore(rootReducer, initialState, enhancer), }; addDecorator(story => ( <App context={context}> <div> <ReduxToastr timeOut={4000} newestOnTop={false} position="top-right" transitionIn="fadeIn" transitionOut="fadeOut" progressBar closeOnToastrClick /> {story()} </div> </App> )); addDecorator(withKnobs); configure(loadStories, module);
import React from "react"; function ContactDetails() { return ( <div> <div class="contactMainDiv"> <div style={{textAlign: 'center'}}> <img src="./images/contact.png"/> </div> <div style={{padding: '2% 15%'}}> <form method="POST" class="contact-form"> <div class="row"> <div class="col-md-6"> Full name: <input type="text" aria-required="true" aria-invalid="false" placeholder="Full name" required></input> </div> <div class="col-md-6"> Email: <input type="email" aria-required="true" aria-invalid="false" placeholder="Email address" required></input> </div> <div class="col-md-6"> For: <select required> <option>---</option> <option>Html 5</option> <option>CSS 3</option> <option>JS</option> </select> </div> <div class="col-md-6"> Purpose: <select required> <option>---</option> <option>Query</option> <option>Suggestion</option> </select> </div> <div class="col-md-12"> Your Answer: <textarea aria-required="true" cols="40" rows="7" aria-invalid="false" placeholder="Answer" required></textarea> </div> <div class="col-md-12"> <div class="g-recaptcha" data-sitekey="6LdVc7gbAAAAAFgrXGPDUafhq1RhtlXoGdXyk5Kc"></div> </div> <div class="col-md-12" style={{paddingTop: '2%'}}> <button type="button" class="btn btn-secondary">Submit</button> </div> </div> </form> </div> </div> </div> ) } export default ContactDetails;
var express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const bodyParser = require('body-parser'); const app = express(); require('dotenv/config'); const jwt = require('jsonwebtoken'); app.use(bodyParser.json()); const userRoute = require('./routes/user'); app.use('/user', userRoute); const bookRoute = require('./routes/book'); app.use('/book', bookRoute); app.get('/', (req,res)=> { res.send('Bonjour je suis un Youcodeur'); }); mongoose.connect( process.env.DB_CONNECTION, console.log('connected') ); app.listen(3000);
//Objects Array For Questions const questions = [ { id: 1, question: "Inside which HTML element do we put the JavaScript?", }, { id: 2, question: "What is the correct JavaScript syntax to change the content of the HTML element below? <p id=\"demo\">This is a demonstration.</p>", }, { id: 3, question: "Where is the correct place to insert a JavaScript?", }, { id: 4, question: "What is the correct syntax for referring to an external script called \"xxx.js\"?", }, { id: 5, question: "The external JavaScript file must contain the <script> tag.", }, { id: 6, question: "How do you write \"Hello World\" in an alert box?", }, { id: 7, question: "How do you create a function in JavaScript?", }, { id: 8, question: "How do you call a function named \"myFunction\"?", }, ] //Objects Array For Questions Answers const possibleAnswers = [ { id: "1", answer: "<script>", questionid: 1, correct:"true", }, { id: "2", answer: "<scripting>", questionid: 1, correct:"false", }, { id: "3", answer: "<js>", questionid: 1, correct:"false", }, { id: "4", answer: "document.getElementByName(\"p\").innerHTML = \"Hello World!\";", questionid: 2, correct:"false", }, { id: "5", answer: "document.getElementById(\"demo\").innerHTML = \"Hello World!\";", questionid: 2, correct:"true", }, { id: "6", answer: "document.getElement(\"p\").innerHTML = \"Hello World!\";", questionid: 2, correct:"false", }, { id: "7", answer: "#demo.innerHTML = \"Hello World!\";", questionid: 2, correct:"false", }, { id: "8", answer: "The <head> section", questionid: 3, correct:"false", }, { id: "9", answer: "The <body> section", questionid: 3, correct:"true", }, { id: "10", answer: "Both the <head> section and the <body> section are correct", questionid: 3, correct:"false", }, { id: "11", answer: "<script src=\"xxx.js\">", questionid: 4, correct:"true", }, { id: "12", answer: "<script name=\"xxx.js\">", questionid: 4, correct:"false", }, { id: "12", answer: "<script href=\"xxx.js\">", questionid: 4, correct:"false", }, { id: "13", answer: "False", questionid: 5, correct:"true", }, { id: "14", answer: "True", questionid: 5, correct:"false", }, { id: "15", answer: "alertBox(\"Hello World\");", questionid: 6, correct:"false", }, { id: "16", answer: "alert(\"Hello World\");", questionid: 6, correct:"true", }, { id: "17", answer: "msgBox(\"Hello World\");", questionid: 6, correct:"false", }, { id: "18", answer: "msg(\"Hello World\");", questionid: 6, correct:"false", }, { id: "19", answer: "function = myFunction()", questionid: 7, correct:"false", }, { id: "20", answer: "function:myFunction()", questionid: 7, correct:"false", }, { id: "21", answer: "function myFunction()", questionid: 7, correct:"true", }, { id: "22", answer: "call myFunction()", questionid: 8, correct:"false", }, { id: "23", answer: "call function myFunction()", questionid: 8, correct:"false", }, { id: "24", answer: "myFunction()", questionid: 8, correct:"true", }, ] var timerCount=90; var questionNumber=1; var startSection = document.querySelector(".start-section") var quizSection = document.querySelector(".quiz-section") var timerElement = document.querySelector(".timer-count"); var answersSection = document.querySelector(".answers-section") var questionsHeading = document.querySelector(".questions-heading") questionsHeading.setAttribute("style","width: 80%;") var resultsSection = document.querySelector(".results-section") var answerResult = document.createElement("p") var hr=document.createElement("hr") resultsSection.appendChild(hr) resultsSection.appendChild(answerResult) var score=0 var numberOfQuestions=questions.length; var areAllAnswered = false; timerElement.textContent="Timer: "+timerCount //Main Function For Starting Quiz function init(){ startSection.style.display = "none" quizSection.style.display = "block" startQuiz(); fillAnswersSection(); } //Adding Event Listener To Start Button document.querySelector("#start-button").addEventListener("click", function () { init() }) //Function For Filling Answers Section Depending On Question function fillAnswersSection(){ clearAnswersSection(); //Code For Getting Next Question And Create Possible Answers if (questionNumber<=questions.length){ var question = questions.find(getQuestion) var answers=getAnswers() questionsHeading.textContent = question.question createAnswers(answers) addAnswersEventListeners(); questionNumber++ } else{ areAllAnswered=true createfinalScore(); } } //Function For Creating Answers Buttons Depending On Question function createAnswers(answers){ var length = answers.length for (i = 0; i < length; i++) { var answerButton = document.createElement("input") answersSection.appendChild(answerButton) answerButton.setAttribute("data-correct", answers[i].correct) answerButton.setAttribute("class", "answer") answerButton.setAttribute("style", "margin: 5px;") answerButton.setAttribute("type", "button") answerButton.setAttribute("style", "margin: 5px; padding: 5px; background-color: rgb(168, 104, 241); width: 80%;") answerButton.value = i+1+". "+answers[i].answer } } //Function For Add Events Listeners To Every Answer Button function addAnswersEventListeners(){ document.querySelectorAll('.answer').forEach(item => { item.addEventListener('click', event => { checkAnswer(item); fillAnswersSection(); }) }) } //Function For Checking Answers function checkAnswer(e){ resultsSection.setAttribute("style","opacity: 1; visibility: visible; -webkit-transition: none; -moz-transition: none; -o-transition: none;") if (e.getAttribute("data-correct")==="true"){ answerResult.textContent="Correct!" score++; } else{ timerCount-=10; answerResult.textContent="Wrong!" } var waitTransition=1; wait = setInterval(function() { waitTransition--; if (waitTransition >= 0) { resultsSection.setAttribute("style","opacity: 0; visibility: hidden; -webkit-transition: visibility 2s linear, opacity 2s linear; -moz-transition: visibility 2s linear, opacity 2s linear; -o-transition: visibility 2s linear, opacity 2s linear;") } // Tests if time has run out if (timerCount === 0) { // Clears interval clearInterval(timer); } }, 0); } //Function For Clearing Answers Section function clearAnswersSection(){ if (answersSection.children.length>0){ while (answersSection.firstChild) { answersSection.removeChild(answersSection.firstChild); } } } //Function For Initializing Timer function startQuiz() { areAllAnswered = false; startTimer() } //Function For Timer function startTimer() { // Sets timer timer = setInterval(function() { timerCount--; timerElement.textContent = "Timer: "+timerCount; if (timerCount >= 0) { if (areAllAnswered && timerCount > 0) { // Clears interval and stops timer clearInterval(timer); createfinalScore(); } } // Tests if time has run out if (timerCount === 0) { // Clears interval clearInterval(timer); createfinalScore(); } }, 1000); } //Function For Showing Final Score And Form For Submitting It function createfinalScore(){ questionsHeading.textContent="All Done!" clearAnswersSection(); var finalScore = document.createElement("p") finalScore.setAttribute("style","margin:10px 0 10px 0;") var submitScore = document.createElement("form"); submitScore.setAttribute("style","margin:10px 0 10px 0;") submitScore.setAttribute('id',"submit-form"); var label = document.createElement("Label"); label.htmlFor = "score"; label.innerHTML="Enter Initials:"; var initials = document.createElement("input"); initials.setAttribute('type',"text"); initials.setAttribute('name',"initials"); var submit = document.createElement("input"); submit.setAttribute('type',"submit"); submit.setAttribute('value',"Submit"); submit.setAttribute("style", "margin: 5px; padding: 5px; background-color: rgb(168, 104, 241);") submitScore.appendChild(label); submitScore.appendChild(initials); submitScore.appendChild(submit); answersSection.appendChild(finalScore) finalScore.textContent="Your final score is: "+score+"/"+numberOfQuestions answersSection.appendChild(submitScore) addFormEventListener(); questionNumber=1; } //Function For Obtaining Each Question function getQuestion(obj) { return obj.id === questionNumber; } //Function For Obtaining Possible Question Answers function getAnswers(){ var filteredAnswers = possibleAnswers.filter(function (obj) { return obj.questionid === questionNumber; }) .map(function (obj) { return obj }) return filteredAnswers; } //Function For Showing Highscores In Descending Order And Restart Quiz function createHighScores(){ questionsHeading.textContent="Highscores" clearAnswersSection(); // var highScore = document.createElement("input"); var highScore = document.createElement("div"); var goBack = document.createElement("button"); var clearHighScores = document.createElement("button"); highScore.setAttribute('id',"high-scores"); highScore.setAttribute('style',"color: red;"); var arrayOfKeys = Object.keys(localStorage); var arrayOfValues = Object.values(localStorage); var localstorage = {}; for (var i = 0; i < localStorage.length; i++){ localstorage[arrayOfKeys[i]] = arrayOfValues[i] } var orderedLocalStorage = []; for (var item in localstorage) { orderedLocalStorage.push([item, localstorage[item]]); } orderedLocalStorage.sort(function(a, b) { return b[1] - a[1]; }); var scorePosition=1 for (var i = 0; i < orderedLocalStorage.length; i++){ var parr=document.createElement("p"); highScore.appendChild(parr) parr.textContent=scorePosition+". "+orderedLocalStorage[i][0]+" - "+orderedLocalStorage[i][1] scorePosition++ } goBack.setAttribute('type',"button"); goBack.setAttribute('name',"go-back"); goBack.setAttribute('id',"goback"); goBack.setAttribute("style","margin:15px 0 15px 0;") goBack.textContent="Go Back"; clearHighScores.setAttribute('type',"button"); clearHighScores.setAttribute('name',"clear-high-scores"); clearHighScores.setAttribute('id',"clearhighscores"); clearHighScores.setAttribute("style","margin:15px 0 15px 0;") clearHighScores.textContent="Clear Highscores"; answersSection.appendChild(highScore) answersSection.appendChild(goBack) answersSection.appendChild(clearHighScores) addGobackEventListener() addClearHighScoresEventListener(highScore) } //Function For Adding Event Listener To The Final Score Submit Form function addFormEventListener(){ document.querySelectorAll('#submit-form').forEach(item => { item.addEventListener('submit', event => { handleFormSubmit(event,item); }) }) } //Function For Adding Event Listener To Go Back Button function addGobackEventListener(){ document.querySelectorAll('#goback').forEach(item => { item.addEventListener('click', event => { location.reload(); }) }) } //Function For Clearing Local Storage Highscores function addClearHighScoresEventListener(highScore){ document.querySelectorAll('#clearhighscores').forEach(item => { item.addEventListener('click', event => { localStorage.clear(); clearScores(highScore); }) }) } //Function For Controlling Submit In Form function handleFormSubmit(event,item) { // Prevent the default behavior event.preventDefault(); localStorage.setItem(item.initials.value, score); createHighScores() } //Function For Cleaning Highscore Area function clearScores(highScore){ if (highScore.children.length>0){ while (highScore.firstChild) { highScore.removeChild(highScore.firstChild); } } } //Function For Add Event Listener To View Highscore Button document.querySelector(".view-hihgscores").addEventListener("click", function(){ startSection.style.display = "none" quizSection.style.display = "block" createHighScores() });
import React, { Component } from 'react'; import './Track.css'; class Track extends Component { render() { return ( <div className="Track"> <div className="rank"> {this.props.track.rank}. </div> <div className="album"> <img src={this.props.track.image} alt="Album Art"/> </div> <div className="info text-left"> <div className="track-name">{this.props.track.name}</div> <div className="track-artist">{this.props.track.artist}</div> </div> <div className="listenerInfo"> <div className="track-listeners-label">Listeners</div> <div className="track-listeners">{this.props.track.listeners}</div> </div> </div> ); } } export default Track;
// server.js // BASE SETUP // ============================================================================= // call the packages we need var express = require('express'); // call express var app = express(); // define our app using express var bodyParser = require('body-parser'); var shell = require('node-cmd'); var tcp = require('tcp-proxy'); var server = tcp.createServer({ target: { host: '127.0.0.1', port: 8080 } }); server.listen(8081); // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var port = process.env.PORT || 8080; // set our port // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // get an instance of the express Router router.use(function(req, res, next) { // do logging shell.run('avconv -f video4linux2 -s 640x480 -i /dev/video0 -ss 0:0:2 -frames 1 /foo/out.jpg') console.log('Something is happening.'); shell.run('/root/openface/demos/classifier.py infer generated-embeddings/classifier.pkl out.jpg') next(); // make sure we go to the next routes and don't stop here }); // more routes for our API will happen here // REGISTER OUR ROUTES ------------------------------- // all of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); console.log('Magic happens on port ' + port);
sap.ui.define([], function () { "use strict"; return { currencyValue: function (sValue) { if (!sValue) { return ""; } var sParts = parseFloat(sValue).toFixed(2).toString().split("."); sParts[0] = sParts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " "); return sParts.join(","); }, formatInteractiveMap: function (sStreet, sBuilding, sCity, sPostalCode, sCountry) { var vHTML1 = "<iframe height='99%' width='100%' marginheight='0' marginwidth='0' frameborder='0' src='", vHTML2 = "'>HERE maps not available!</iframe>", sParam1 = (sStreet === null) ? "" : jQuery.sap.encodeURL(sStreet), sParam2 = (sBuilding === null) ? "" : jQuery.sap.encodeURL(sBuilding), sParam3 = (sCity === null) ? "" : jQuery.sap.encodeURL(sCity), sParam4 = (sPostalCode === null) ? "" : jQuery.sap.encodeURL(sPostalCode), sParam5 = (sCountry === null) ? "" : jQuery.sap.encodeURL(sCountry), vURL = this.getView().getController().getRootPath("html/map.html"), sFullPath; if (sParam2 !== "") { sParam1 = jQuery.sap.encodeURL(sStreet + " " + sBuilding); } if (sParam4 !== "") { sParam3 = jQuery.sap.encodeURL(sPostalCode + " " + sCity); } sFullPath = vHTML1 + vURL + "?Street=" + sParam1 + "&City=" + sParam3 + "&Country=" + sParam5 + vHTML2; return sFullPath; }, salesOrderNumber: function (sValue) { return parseInt(sValue, 10); }, numberUnit: function (sValue) { if (!sValue) { return ""; } return parseFloat(sValue).toFixed(2); }, businessPartnerOrdersCount: function (sPartnerID) { var oMasterModel = this.getModel("masterView"), currentPath = "/BusinessPartnerSet(BusinessPartnerID='" + sPartnerID + "')", listBindingContextPath = "/BusinessPartnerSet('" + sPartnerID + "')"; if (oMasterModel) { var sServiceUrl = this.getOwnerComponent().getModel().sServiceUrl, oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl), countPath = currentPath + "/ToSalesOrders/$count"; oModel.read(countPath, { success: function (oData, oResponse) { var listItems = oMasterModel.getProperty("/list").getItems(); if (listItems) { var foundListItem = listItems.find(function (oListItem) { return oListItem.getBindingContextPath() === listBindingContextPath; }); if (foundListItem) { var number = parseInt(oData, 10); if (number > 0) { foundListItem.setCounter(number); foundListItem.setUnread(true); } else { foundListItem.setCounter(0); foundListItem.setUnread(false); } } } } }); } return sPartnerID; }, countryName: function (sCountry) { var oVHCountrySetModel = this.getModel("appView").getProperty("/oVHCountrySetModel"), sResult; sResult = sCountry; if (oVHCountrySetModel) { var countries = oVHCountrySetModel.getData().results; if (countries) { var foundCountry = countries.find(function (country) { return country.Land1 === sCountry; }); if (foundCountry) { sResult = foundCountry.Landx; } } } return sResult; }, currencyName: function (sCurrency) { var oVHCurrencySetModel = this.getModel("appView").getProperty("/oVHCurrencySetModel"), sResult; sResult = sCurrency; if (oVHCurrencySetModel) { var currList = oVHCurrencySetModel.getData().results; if (currList) { var foundCurrency = currList.find(function (currency) { return currency.Waers === sCurrency; }); if (foundCurrency) { sResult = foundCurrency.Ltext; } } } return sResult; }, unitQuantityName: function (sUnit) { var oVHUnitQuantitySetModel = this.getModel("appView").getProperty("/oVHUnitQuantitySetModel"), sResult; sResult = sUnit; if (oVHUnitQuantitySetModel) { var unitList = oVHUnitQuantitySetModel.getData().results; if (unitList) { var foundUnit = unitList.find(function (unit) { return unit.Msehi === sUnit; }); if (foundUnit) { sResult = foundUnit.Msehl; } } } return sResult; }, unitWeightName: function (sUnit) { var oVHUnitWeightSetModel = this.getModel("appView").getProperty("/oVHUnitWeightSetModel"), sResult; sResult = sUnit; if (oVHUnitWeightSetModel) { var unitList = oVHUnitWeightSetModel.getData().results; if (unitList) { var foundUnit = unitList.find(function (unit) { return unit.Msehi === sUnit; }); if (foundUnit) { sResult = foundUnit.Msehl; } } } return sResult; }, unitLengthName: function (sUnit) { var oVHUnitLengthSetModel = this.getModel("appView").getProperty("/oVHUnitLengthSetModel"), sResult; sResult = sUnit; if (oVHUnitLengthSetModel) { var unitList = oVHUnitLengthSetModel.getData().results; if (unitList) { var foundUnit = unitList.find(function (unit) { return unit.Msehi === sUnit; }); if (foundUnit) { sResult = foundUnit.Msehl; } } } return sResult; }, messageIsNotEmpty: function (sMessage) { if (sMessage) { return true; } else { return false; } } }; });
// // fetch resolves the promise triggering the .then as soon as it receives // // the headers back from the api // fetch('https://api.cryptonator.com/api/ticker/btc-usd') // .then(res => { // // this does not guarantee that I have all of the data // console.log("RESPONSE, WAITING TO PARSE...", res) // // use this .json method to resolve the promise when all of the data // // is recieved and it is parsed as json // return res.json() // }) // .then(data => { // console.log("DATA PARSED...", data) // console.log(data.ticker.price) // }) // .catch(e => { // console.log("OH NO! ERROR", e) // }) const fetchBitcoinPrice = async () => { try{ const res = await fetch('https://api.cryptonator.com/api/ticker/btc-usd') const data = await res.json(); console.log(data.ticker.price) } catch (e) { console.log("SOMETHING WENT WRONG!", e) } }
const debug = require('debug')('snowboy') const path = require ('path') debug('Loading in SNOWBOY') const record = require('node-record-lpcm16') debug('Loaded in record') const Detector = require('snowboy').Detector; debug('Loaded in detector') const Models = require('snowboy').Models; debug('Loaded in snowboy') debug('PATH: ', __dirname) const models = new Models(); models.add({ file: path.join(__dirname, 'resources/snowboy.umdl'), sensitivity: '0.5', hotwords : 'snowboy' }); const detector = new Detector({ resource: path.join(__dirname, 'resources/common.res'), models: models, audioGain: 2.0 }); detector.on('silence', function () { console.log('silence'); }); detector.on('sound', function () { console.log('sound'); }); detector.on('error', function () { console.log('error'); }); detector.on('hotword', function (index, hotword) { console.log('hotword', index, hotword); }); const mic = record.start({ threshold: 0, verbose: true, recordProgram: 'arecord' }); mic.pipe(detector);
import { test } from 'qunit'; import moduleForAcceptance from 'travel-eve/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | events'); test('visiting /events', function(assert) { server.createList('events', 1); visit('/events'); andThen(function() { assert.equal(currentURL(), '/events'); }); }); test('Events are loaded into the main page', function(assert) { let events = server.createList('event', 20); visit('/events'); andThen(function() { assert.equal(find('.list-event').length, 20); assert.equal(find('.event-title:first').text(), events[0].title); }); });
import { USER_LOGIN_FAILURE, USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS } from "./constants"; export function loginRequest (data) { return { type: USER_LOGIN_REQUEST, payload: data, }; } export function loginSuccess (data) { return { type: USER_LOGIN_SUCCESS, payload: data, }; } export function loginFailure () { return { type: USER_LOGIN_FAILURE, }; }
import React from 'react'; import './CartSummary.css'; import Button from '../../../SharedComponents/UIElements/Buttons/Buttons'; import { useStateValue } from '../../../StateProvider/StateProvider'; import ForwardIcon from '@material-ui/icons/Forward'; import ShoppingCartIcon from '@material-ui/icons/ShoppingCart'; import { motion } from 'framer-motion'; import { Link } from 'react-router-dom'; const CartSummary = () => { const [state, dispatch] = useStateValue(); const subtotal = state.cart.reduce((accumulator, product) => { return (accumulator = accumulator + parseInt(product.price)); }, 0); const shipping = state.cart.length * 2; const tax = 0.1 * subtotal; const total = tax + subtotal + shipping; const forward = <ForwardIcon />; const keepCartSummary = () => { dispatch({ type: 'KEEP_CART_SUMMARY', cartSummary: { total: total, items: state.cart.length, }, }); }; return ( <motion.div animate={{ y: 480, opacity: 1 }} transition={{ duration: 0.3 }} className='cartSummary'> <div className='cartSummary__container'> <div className='cartSummary__title'> <ShoppingCartIcon /> <div className='cartSummary__titleText'>Summary</div> </div> <div className='cartSummary__promoCodeAd'> Do you have a promo code? Use a promo code and get free shipping! </div> <div className='cartSummary__items'> <div className='cartSummary__subtotalTitle'>Items:</div> <div className='cartSummary__subtotalCost'>x{state.cart.length}</div> </div> <div className='cartSummary__subtotal'> <div className='cartSummary__subtotalTitle'>Subtotal:</div> <div className='cartSummary__subtotalCost'>${subtotal}</div> </div> <div className='cartSummary__shipping'> <div className='cartSummary__shippingTitle'>Shipping:</div> <div className='cartSummary__shippingCost'>${shipping}</div> </div> <div className='cartSummary__tax'> <div className='cartSummary__taxTitle'>Tax:</div> <div className='cartSummary__taxCost'>${tax}</div> </div> <div className='cartSummary__total'> <div className='cartSummary__totalTitle'>Total:</div> <div className='cartSummary__totalCost'>${total}</div> </div> {state.currentUser[0] ? ( <Link to='/checkout' className='cartSummary__button'> <Button type='danger' icon={forward} onClick={keepCartSummary} message='Proceed Checkout' /> </Link> ) : ( <Button type='danger' icon={forward} message='Sign in to proceed checkout' /> )} </div> </motion.div> ); }; export default CartSummary;
import React from "react" import LayoutPublic from "../../components/Layout/LayoutPublic/LayoutPublic"; import Starter from "../../components/PageProfile/BannerProfile/BannerProfile"; import {WhyChoose} from "../../components/PageProfile/WhyChoose/WhyChoose"; import Knowus from "../../components/knowus/knowus"; import Jobs from "../../components/PageProfile/JobsProfile/JobsProfile"; const Profile = () => { return ( <LayoutPublic> <Starter/> <Jobs/> <WhyChoose/> <Knowus/> </LayoutPublic> ) } export default Profile
// functionality for home route module.exports = { showHome: function(req,res) { res.render('pages/home', { title: 'Dogify'}); } };
import {PolarArea} from 'vue-chartjs' export default { extends: PolarArea, mounted() { this.renderChart({ datasets: [{ data: [ 11, 16, 7, 3, 14 ], backgroundColor: [ '#8dace7', '#4BC0C0', '#ef869e', '#E7E9ED', '#71deb9' ], label: 'My dataset' // for legend }], labels: [ 'Red', 'Green', 'Yellow', 'Grey', 'Blue' ] }, {responsive: true, maintainAspectRatio: false}) } }
//@flow import React from 'react'; import { GLView } from 'expo-gl'; import { PanResponder, PixelRatio } from 'react-native'; import { vec2 } from 'gl-matrix'; import PIXI from '../Pixi'; import { takeSnapshotAsync } from '../utils'; import { BezierPath, BezierProvider } from '../core/signature'; global.__ExpoSignatureId = global.__ExpoSignatureId || 0; type Props = { strokeColor: number | string, strokeAlpha: number, onChange: () => PIXI.Renderer, onReady: () => WebGLRenderingContext, }; const scale = PixelRatio.get(); function scaled(nativeEvent) { const out = vec2.fromValues(nativeEvent.locationX, nativeEvent.locationY); vec2.scale(out, out, scale); return out; } export default class Signature extends React.Component<Props> { stage: PIXI.Stage; graphics; graphicsTmp; panResponder: PanResponder; renderer: PIXI.Renderer; constructor(props, context) { super(props, context); this.provider = new BezierProvider(); this._setupPanResponder(); } componentWillMount() { global.__ExpoSignatureId++; } componentDidMount() { this._drawSub = this.provider.addListener(BezierProvider.EVENT_DRAW_PATH, this._drawPath); } componentWillUnmount() { this._drawSub.remove(); } _setupPanResponder = () => { const onEnd = nativeEvent => { this.provider.addPointToSignature(scaled(nativeEvent), true); this.provider.reset(); setTimeout(() => this.props.onChange && this.props.onChange(this.renderer), 1); }; this.panResponder = PanResponder.create({ onStartShouldSetResponder: () => true, onStartShouldSetPanResponderCapture: () => true, onMoveShouldSetPanResponder: (evt, gestureState) => true, onPanResponderGrant: ({ nativeEvent }) => { this._beginNewLine(); this.provider.reset(); this.provider.addPointToSignature(scaled(nativeEvent)); }, onPanResponderMove: ({ nativeEvent }) => { this.provider.addPointToSignature(scaled(nativeEvent)); }, onPanResponderRelease: ({ nativeEvent }) => onEnd(nativeEvent), onPanResponderTerminate: ({ nativeEvent }) => onEnd(nativeEvent), }); }; _beginNewLine = () => { this.graphics = new PIXI.Graphics(); this.stage.addChild(this.graphics); }; _drawPath = (type, points, finalized) => { this.graphicsTmp.clear(); const graphics = finalized ? this.graphics : this.graphicsTmp; graphics.beginFill(this.props.strokeColor); graphics.lineStyle(1, this.props.strokeColor, this.props.strokeAlpha); BezierPath[type](points, graphics); graphics.endFill(); this.renderer._update(); }; shouldComponentUpdate = () => false; undo = () => { if (!this.renderer) { return null; } const { children } = this.stage; if (children.length > 0) { const child = children[children.length - 1]; this.stage.removeChild(child); this.renderer._update(); // TODO: This doesn't really work :/ setTimeout(() => this.props.onChange && this.props.onChange(this.renderer), 2); return child; } }; clear = () => { this.provider.reset(); if (!this.renderer) { return null; } if (this.stage.children.length > 0) { this.stage.removeChildren(); this.renderer._update(); } return null; }; takeSnapshotAsync = (...args) => { return takeSnapshotAsync(this.glView, ...args); }; onContextCreate = async (context: WebGLRenderingContext) => { this.context = context; this.graphicsTmp = new PIXI.Graphics(); this.stage = new PIXI.Container(); this.stage.addChild(this.graphicsTmp); const getAttributes = context.getContextAttributes || (() => ({})); context.getContextAttributes = () => { const contextAttributes = getAttributes(); return { ...contextAttributes, stencil: true, }; }; this.renderer = PIXI.autoDetectRenderer( context.drawingBufferWidth, context.drawingBufferHeight, { context, antialias: true, backgroundColor: 0xffffff, transparent: false, autoStart: false, } ); this.renderer._update = () => { this.renderer.render(this.stage); context.endFrameEXP(); }; this.props.onReady && this.props.onReady(context); }; onLayout = ({ nativeEvent: { layout: { width, height }, }, }) => { if (this.renderer) { const scale = PixelRatio.get(); this.renderer.resize(width * scale, height * scale); this.renderer._update(); } }; setRef = ref => { this.glView = ref; }; render() { return ( <GLView {...this.panResponder.panHandlers} onLayout={this.onLayout} key={'Expo.Signature-' + global.__ExpoSignatureId} ref={this.setRef} {...this.props} onContextCreate={this.onContextCreate} /> ); } }
define({ "passwordError":"Przynajmniej 4 znaki.", "usernameError":"Przynajmniej 3 znaki, dozwolone tylko litery.", "emailError":"Niepoprawny adres mailowy.", "rangeError":'"%VALUE%" nie jest w zakresie %MIN%-%MAX% %FORMAT%', "invalidNumber":'"%VALUE%" nie jest poprawną liczbą', "passwordsNotEqual":"Powtórzone hasło jest niepoprawne", "invalidTokenError":"Link resetujący hasło jest niepoprawny lub nieważny", "wrongPasswordError":"Podane dotychczasowe hasło jest niepoprawne" });
(function(){ fs = require('fs'); fs.readFile('dist/index.html', 'utf-8', function (err, data){ var OpenCC = require('opencc'); var opencc = new OpenCC('hk2s.json'); var simplifiedText = opencc.convertSync(data); simplifiedText = simplifiedText.replace('zh-hant', 'zh-hans'); fs.writeFile("dist/index_hans.html", simplifiedText, function(err) { if(err) { return console.log(err); } console.log("index_hans.html created."); }); }); }());
var findMissingConsecutive = require('../05_missing_consecutive').findMissingConsecutive; var expect = require('chai').expect; describe('Finding a missing integer from a list of consecutive integer', function() { describe('the list is ranged from 1 to N', function() { describe('input: [1, 3]', function() { it('should output: 2', function() { expect(findMissingConsecutive([1, 3])).to.eq(2); }); }); describe('input: [4, 2, 3, 1, 7, 6]', function() { it('should output: 5', function() { var nums = [4, 2, 3, 1, 7, 6]; expect(findMissingConsecutive(nums)).to.eq(5); }); }); describe('input: [2, 3, 1, 5, 6]', function() { it('should output: 4', function() { var nums = [2, 3, 1, 5, 6]; expect(findMissingConsecutive(nums)).to.eq(4); }); }); }); });
// if(x%2==0){ // isEven = true // }else{ // isEven = false // } var x = 2 // var isEven = true var isEven = (x % 2 == 0) ? true : false alert(isEven) console.log(isEven) var dayOfWeek = 2 switch(dayOfWeek) // { // case 1: // alert('Monday') // break // case 2: // alert('Tuesday') // break // default: // alert('This is not a day of week') // } { case 1: case 2: case 3: case 4: case 5: alert("This is a Working Day") break case 6: case 7: alert("This is a Weekend") default: alert("This is not a day of week") } function test(id, name, age){ var id = id || 0, name = name || 'no value' age = age || 0 return id+" "+name+" "+age } var a = test(45) alert(a) function divide(x,y){ if(y===0){ alert("you can't divide by 0") return } return x / y } var result = divide(1,0) alert(result)
// Root view. prDemo.views.DefaultView = Ext.extend(Ext.Container, { fullscreen: true, layout: { type: 'card' }, init: function(views) { // Add each view to our card layout. for (var i=0; i<views.length; i++) { this.add(views[i]); } }, loadView: function(viewIndex) { this.layout.setActiveItem(viewIndex); this.doLayout(); } });
function Camera(canvasId) { this.target = [-8, 164, 0]; this.fieldOfView = 72; this.angle = -99; this.eyeY = 144; this.eye = [300 * Math.sin(this.angle * 0.01 * Math.PI), this.eyeY, 300 * Math.cos(this.angle * 0.01 * Math.PI)]; let canvas = document.getElementById(canvasId); this.keysdown = {}; canvas.addEventListener("keydown", ((e) => { this.keysdown[event.keyCode] = true; e.stopPropagation(); }), false); canvas.addEventListener("keyup", ((e) => { delete this.keysdown[event.keyCode]; e.stopPropagation(); }), false); canvas.addEventListener("mousewheel", ((e) => { if(e.wheelDelta < 0) { this.fieldOfView += 1; this.calculateEye(); } else if(e.wheelDelta >= 0) { this.fieldOfView -= 2; this.calculateEye(); } return false; }), false); canvas.addEventListener("mousedown", ((e) => { canvas.addEventListener("mousemove", UpdateViewAngle, false); }), false); canvas.addEventListener("mouseup", ((e) => { canvas.removeEventListener("mousemove", UpdateViewAngle, false); this.lastLocation = []; }), false); canvas.addEventListener("mouseleave", ((e) => { canvas.removeEventListener("mousemove", UpdateViewAngle, false); this.lastLocation = []; }), false); let UpdateViewAngle = ((e) => { if(this.hasOwnProperty("lastLocation") == false) { this.lastLocation = [e.screenX, e.screenY]; return; } if(this.lastLocation[1] > e.screenY) { this.eyeY -= 2; } else { this.eyeY += 2; } this.lastLocation = [e.screenX, e.screenY]; this.calculateEye(); }); this.calculateEye = ((e) => { this.eye = [300 * Math.sin(this.angle * 0.01 * Math.PI), this.eyeY, 300 * Math.cos(this.angle * 0.01 * Math.PI)]; }); } Camera.prototype.GetCameraTransform = function() { if (this.keysdown[65]) { this.target[0] += 2; this.calculateEye(); } else if (this.keysdown[68]) { this.target[0] -= 2; this.calculateEye(); } if(this.keysdown[87]) { this.target[1] += 2; this.eyeY += 2; this.calculateEye(); } else if(this.keysdown[83]) { this.target[1] -= 2; this.eyeY -= 2; this.calculateEye(); } if(this.keysdown[81]) { this.angle -= .5; this.calculateEye(); } else if(this.keysdown[69]) { this.angle += .5; this.calculateEye(); } return m4.inverse(m4.lookAt(this.eye, this.target, [0, 1, 0])); } Camera.prototype.GetProjectionTransform = function() { return m4.perspective(DegreesToRadians(this.fieldOfView), 1, 10, 100000); } Camera.prototype.ResetView = function() { this.target = [-8, 164, 0]; this.fieldOfView = 72; this.angle = -99; this.eyeY = 144; this.calculateEye(); }
import { connect } from 'react-redux' import { storeNumberToArray, add, substract, multiply, division, equal } from '../Actions/actions' import SpecialButtonGroup from '../Components/SpecialButtonGroup' const mapStateToProps = state => { return { } }; const mapDispatchToProps = dispatch => { return { storeNumberToArray: function(){ dispatch(storeNumberToArray()) }, onAddButtonClick: function(){ dispatch(add()) }, onSubstractButtonClick: function(){ dispatch(substract()) }, onMultiplyButtonClick: function(){ dispatch(multiply()) }, onDivisionButtonClick: function(){ dispatch(division()) }, onEqualButtonClick: function(){ dispatch(equal()) } } } const specialButtonContainer = connect(mapStateToProps, mapDispatchToProps)(SpecialButtonGroup); export default specialButtonContainer
var keyNum = 20, currentKeyNum = 0, cl = console.log; var mySwiper; $(function () { lockerLayoutFn(); activateDragFn(); $(".droppable").droppable({ accept: ".draggable", drop: dropElement, hoverClass: 'drop-hover', tolerance: "touch", /*activate: function () { $('drop-key-inner').show(); console.log("active") }, deactivate: function () { $('drop-key-inner').hide(); console.log("deactive") }*/ }); $('#drop-key-inner').show(); mySwiper = new Swiper('.swiper-container', { // Optional parameters direction: 'horizontal', loop: true, // If we need pagination pagination: { el: '.swiper-pagination', }, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, // And if we need scrollbar scrollbar: { el: '.swiper-scrollbar', }, }) }); $(window).resize(lockerLayoutFn); $('#start-btn').mouseup(function () { document.getElementById('clickSound').play() $(this).css('background-image', 'linear-gradient(#80c7ba, #1a8a6d)'); console.log("up"); $("#info-container").hide(); $(".popup-win-container").hide(); }); $('.continue-btn').mouseup(function () { document.getElementById('clickSound').play() // $(this).css('background-image', 'linear-gradient(#80c7ba, #1a8a6d)'); setTimeout(function () { window.location.href = "IKnow.html"; }, 500); }); $('#close-btn').mousedown(function () { document.getElementById('clickSound').play(); $(this).css('background-image', 'linear-gradient(#bd262a, #cf6063)'); console.log("down") }); $('#close-btn').mouseup(function () { clickSd.play(); $(this).css('background-image', 'linear-gradient(#cf6063, #bd262a)'); console.log("up"); $("#instruct-container").hide(); $(".popup-win-container").hide(); }); function activateDragFn() { $(".draggable").draggable({ //axis: "x", /*containment: "#game-container",*/ revert: true, drag: onDragFn, stop: stopDragFn }); } ///////////////////////reham function lockerLayoutFn() { if (window.innerHeight > window.innerWidth && window.innerWidth <= 400) { //$('.alert-win-container').show(); $('.flag_container').each(function (i, obj) { $(".draggable").css('z-index', '1000'); //$(".empty_drag_square span img").css('width', '50px'); }); } else { //$('.alert-win-container').hide(); $('.flag_container').each(function (i, obj) { $(".draggable").css('z-index', '999999'); //$(".empty_drag_square span img").css('width', 'inherit'); }); } //////////////////reham $("#locker-keys-img, #lockerHandel-img, #lockerFront-img").hide(); $("#lockerHandel-img").css('top', "-" + $("#lockerBack-img").height() + "px"); $("#locker-keys-img").css('top', "-" + $("#lockerBack-img").height() * 2 + "px"); $("#lockerFront-img").css('top', "-" + $("#lockerBack-img").height() * 3 + "px"); $("#lockerOpen-img").css('top', "-" + $("#lockerBack-img").height() * 4 + "px"); $("#lockerOpen-img").css('left', $("#lockerBack-img").width() - $("#lockerBack-img").width() / 4 + "px"); $("#locker-keys-img, #lockerHandel-img, #lockerFront-img").show(); $('#word-holder-div').css('width', $("#lockerBack-img").css('width')); $('#word-holder-div').css('height', $("#lockerBack-img").css('height')); $("#word-holder-div").css('top', "-" + $("#lockerBack-img").height() * 5 + "px"); for (var i = 1, m = 6; i <= keyNum; i++, m++) { $("#k" + i + '-ok').css('top', "-" + $("#lockerBack-img").height() * m + "px"); } $('#drop-key-div').css('width', $("#lockerBack-img").css('width')); $('#drop-key-div').css('height', $("#lockerBack-img").css('height')); $("#drop-key-div").css('top', "-" + $("#lockerBack-img").height() * (6 + keyNum) + "px"); $("#finalTxt-div").css('top', "-" + $("#lockerBack-img").height() * (6 + keyNum) + "px"); } $('#instruct-btn').mousedown(function () { stopAllSounds(); clickSd.play(); $(this).css('-webkit-transform', 'scale(0.8)'); $(this).css('-moz-transform', 'scale(0.8)'); $(this).css('transform', 'scale(0.8)'); }); $('#instruct-btn').mouseup(function () { //$('#instruct-btn').css('width', parseFloat($('#instruct-btn').css('width')) + 20 + "px"); //setTimeout(function () { $("#instruct-container").show(); $(".popup-win-container").show(); $(this).css('-webkit-transform', 'scale(1)'); $(this).css('-moz-transform', 'scale(1)'); $(this).css('transform', 'scale(1)'); //}, 100); }); function onDragFn(event, ui) { var keyId = $(this).attr('id').replace(/^\D+/g, ''); $(this).css('cursor', 'grabbing'); if (window.innerHeight > window.innerWidth && window.innerWidth <= 400) { //$('.flag_container').css('overflow', ''); } else { //$('.flag_container').css('overflow', 'visible'); } /*$(document).on('swipeleft swiperight swipedown swipeup',function(event, data){ event.stopImmediatePropagation(); console.log('(document).Stop prop: You just ' + event.type + 'ed!'); });*/ //mySwiper = null; } function stopDragFn(event, ui) { /*ui.position.left = Math.min( ui.position.left, ui.helper.next().offset().left + ui.helper.next().width()-dragDistance); ui.position.left = Math.max(ui.position.left, ui.helper.prev().offset().left + dragDistance);*/ if (window.innerHeight > window.innerWidth && window.innerWidth <= 400) { } else { } /*resize();*/ $(this).css('-webkit-transform', 'scale(1)'); $(this).css('-moz-transform', 'scale(1)'); $(this).css('transform', 'scale(1)'); $(this).css('cursor', 'grab') /*$(document).on('swipeleft swiperight swipedown swipeup',function(event, data){ event.stopImmediatePropagation(); console.log('(document).Stop prop: You just ' + event.type + 'ed!'); });*/ } function dropElement(event, ui) { // var keyCor = ui.draggable.attr('cor'); var keyId = ui.draggable.attr('id').replace(/^\D+/g, ''); var dropId = $(this).attr('id').replace(/^\D+/g, ''); // var dropDeg = rotateKeys * (keyId - 1); // cl("deg " + dropDeg) if (dropId == keyId) { stopAllSounds(); good.play(); currentKeyNum++; $(".draggable").draggable("destroy"); //$(".draggable").css('opacity', '0.5'); ui.draggable.removeClass('draggable'); $(this).droppable("destroy"); if ($(ui.draggable).parent().hasClass('swiper-slide')) { $(ui.draggable).parent().remove(); } $(ui.draggable).css('opacity', '0'); $('#letter' + keyId ).show(); //$('#locker-keys-img').attr('src', 'img/game/lockerBack-' + currentKeyNum + '.png'); $('#img' + keyId ).css('opacity', '1'); //$('#h' + keyId ).css('opacity', '1'); $(".drag_box span img").css('width', '100px'); //$(".droppable").css('width', 'auto'); setTimeout(function () { if (currentKeyNum ==3) { sfx_showRoad.play(); $("#beforeDone").hide(); $(".final_step_message").show();; // $("#click").show();; // if (window.innerHeight > window.innerWidth && //window.innerWidth <= 400) { // $('.alert-win-container').show(); // $('.flag_selected_box').each(function (i, obj) { // $(".empty_drag_square span img").css('width', '50px'); // }); // } else { // $('.alert-win-container').hide(); // $('.flag_selected_box').each(function (i, obj) { // $(".empty_drag_square span img").css('width', 'inherit'); // }); // } // finalFbFn(); finalFbFn(); } else { /*$('#locker-keys-img').removeClass('rotate' + -1 * (rotateKeys)); // rotateKeys += plusRotate; // $('#locker-keys-img').addClass('rotate' + -1 * (rotateKeys)); $('#drop-key-inner').show();*/ activateDragFn(); } }, 500); } else { stopAllSounds(); error.play(); } } ////////////reham $('.modal').on('shown.bs.modal', function (e) { setTimeout(sfx_popUp.play(), 500); }); $(".modal").on("hidden.bs.modal", function () { sfx_popDown.play(); }); $('#staticBackdrop').on('shown.bs.modal', function (e) { $('.flag_container').each(function (i, obj) { $(".draggable").css('z-index', '1000'); $(this).css('z-index', '1000'); }); }); $("#staticBackdrop").on("hidden.bs.modal", function () { $('.flag_container').each(function (i, obj) { $(".draggable").css('z-index', '999999'); $(this).css('z-index', '999999'); }); }); $("#click").mouseup(function (e) { e.preventDefault(); clickSd.play(); window.location.href = "Iknow.html"; }); $("#repeat").on("click", function (e) { e.preventDefault(); clickSd.play(); window.location.href = "index.html"; }); /////////////reham //Close_Instruc_modal function finalFbFn() { // stopAllSounds(); // sfx_safe_2.play(); // $('#lockerFront-img').animate({ // borderSpacing: 360 // }, { // step: function (now, fx) { // $(this).css('-webkit-transform', 'rotate(' + now + 'deg)'); // $(this).css('-moz-transform', 'rotate(' + now + 'deg)'); // $(this).css('transform', 'rotate(' + now + 'deg)'); // }, // duration: 500 // }, 'linear'); // setTimeout(function () { // $('#lockerFront-img').css('-webkit-transform', 'rotate(0deg)'); // $('#lockerFront-img').css('-moz-transform', 'rotate(0deg)'); // $('#lockerFront-img').css('transform', 'rotate(0deg)'); // $('#lockerFront-img').animate({ // borderSpacing: 360 // }, { // step: function (now, fx) { // $(this).css('-webkit-transform', 'rotate(' + now + 'deg)'); // $(this).css('-moz-transform', 'rotate(' + now + 'deg)'); // $(this).css('transform', 'rotate(' + now + 'deg)'); // }, // duration: 500 // }, 'linear'); // setTimeout(function () { // // stopAllSounds(); // // sfx_showRoad.play(); // $('#lockerFront-img, #locker-keys-img').css('opacity', '0'); // $("#logo-div img").addClass('logo-img-smaller'); // $('#lockerOpen-img').css('opacity', '1'); // $('#word-holder-div img').animate({ // width: '100%', // height: '100%', // margin: '0px' // }); // /*if (window.innerHeight > 417 || // (window.innerHeight > 417 && window.innerWidth <= 750) || // (window.innerHeight > 417 && window.innerWidth <= 750)) { // setTimeout(function () { // $('#finalTxt-div').show(); // }, 500); // } else {*/ // setTimeout(function () { // $("#final-container").show(); // $(".popup-win-container").show(); // }, sfx_showRoad._duration * 1000); // //} // }, 1000 + 1); // }, 500 + 1); /*$('.word-div-holder h2').animate({ opacity: '1' }, 1000, function () { window.location.href = "final.html"; });*/ }
// Copyright (c) 2019 - 2020, FHNW, Switzerland. All rights reserved. // Licensed under MIT License, see LICENSE for details. import React from 'react' import _ from 'lodash' import {Table} from 'react-bootstrap' import DeviceTableElement from "./deviceTableElement" const DeviceTable = ({devices, configurations, onUpdate, onRemove, onApproveDevice}) => { console.log("rendered Device table with devices: ", devices.length, " and configs: ", configurations.length); return ( <Table hover> <thead> <tr> <th>ID</th> <th>Name</th> <th>MAC</th> <th>Configuration</th> <th>Description</th> <th>Approved</th> <th>Actions</th> </tr> </thead> <tbody> { _.map(devices, device => <DeviceTableElement key={device.id} device={device} onUpdate={onUpdate} onRemove={onRemove} configurations={configurations} onApproveDevice={onApproveDevice} /> ) } </tbody> </Table> ) }; export default DeviceTable
function updateLineStatus(lineStatusElement, locationName) { lineStatusElement.classList.remove(lineStatusElement.classList.item(1)); switch (Math.floor((Math.random() * 3) + 1)) { case 1: lineStatusElement.classList.add('goodservice'); lineStatusElement.textContent = locationName + ": Unusually good service"; break; case 2: lineStatusElement.classList.add('badservice'); lineStatusElement.textContent = locationName + ": Bad service"; break; case 3: lineStatusElement.classList.add('terribleservice'); lineStatusElement.textContent = locationName + ": All services cancelled"; break; } } var timer = setInterval(function() { switch (Math.floor((Math.random() * 3) + 1)) { case 1: updateLineStatus(document.getElementById('colchester'), 'Colchester'); break; case 2: updateLineStatus(document.getElementById('rochford'), 'Rochford'); break; case 3: updateLineStatus(document.getElementById('stratford'), 'Stratford'); break; } }, 1000);
import app from './app'; const ExtensionPopup = () => import('@/layouts/ExtensionPopup'); const ExtensionWeb3Popup = () => import('@/layouts/ExtensionWeb3Popup'); const Web3DetectedContainer = () => import('@/layouts/ExtensionWeb3Popup/containers/Web3DetectedContainer'); const AccountAccessContainer = () => import('@/layouts/ExtensionWeb3Popup/containers/AccountAccessContainer'); const SignTxContainer = () => import('@/layouts/ExtensionWeb3Popup/containers/SignTxContainer'); const SignMsgContainer = () => import('@/layouts/ExtensionWeb3Popup/containers/SignMsgContainer'); const ExtensionBrowserAction = () => import('@/layouts/ExtensionBrowserAction'); const ExtensionAddWalletContainer = () => import( '@/layouts/ExtensionBrowserAction/containers/ExtensionAddWalletContainer' ); const ExtensionWalletContainer = () => import( '@/layouts/ExtensionBrowserAction/containers/ExtensionWalletContainer' ); const MyWalletsContainer = () => import('@/layouts/ExtensionBrowserAction/containers/MyWalletsContainer'); const WatchOnlyWalletsContainer = () => import( '@/layouts/ExtensionBrowserAction/containers/WatchOnlyWalletsContainer' ); const ExtensionDappsContainer = () => import('@/layouts/ExtensionBrowserAction/containers/ExtensionDappsContainer'); const ExtensionDappsItemContainer = () => import( '@/layouts/ExtensionBrowserAction/containers/ExtensionDappsItemContainer' ); const ExtensionDappContainer = () => import('@/layouts/ExtensionBrowserAction/containers/ExtensionDappContainer'); const cxRoutes = [ { path: '/extension-popups', name: 'Web3 Detected', component: ExtensionWeb3Popup, meta: { requiresAuth: false }, children: [ { path: 'web3-detected', component: Web3DetectedContainer, meta: { requiresAuth: false } }, { path: 'account-access', component: AccountAccessContainer, meta: { requiresAuth: false } }, { path: 'sign-tx', component: SignTxContainer, meta: { requiresAuth: false } }, { path: 'sign-msg', component: SignMsgContainer, meta: { requiresAuth: false } } ] }, { path: '/popup', name: 'Popup', component: ExtensionPopup, meta: { requiresAuth: false } }, { path: '/', component: ExtensionBrowserAction, children: [ { path: '', component: ExtensionWalletContainer, meta: { requiresAuth: false }, children: [ { path: '', meta: { requiresAuth: false }, component: MyWalletsContainer }, { path: 'wallets', name: 'myWallets', meta: { requiresAuth: false }, component: MyWalletsContainer }, { path: 'watch-only', name: '', meta: { requiresAuth: false }, component: WatchOnlyWalletsContainer }, { path: 'dapps', meta: { requiresAuth: false }, component: ExtensionDappsContainer, children: [ { path: '', meta: { requiresAuth: false }, component: ExtensionDappsItemContainer }, { path: '/dapps/:slug', meta: { requiresAuth: false }, component: ExtensionDappContainer } ] } ] }, { path: '/access-my-wallet', name: 'AccessWalletLayout', component: ExtensionAddWalletContainer, meta: { requiresAuth: false } } ] } ]; const configRoutes = routes => { const interfaceIdx = routes.findIndex(item => { return item.path === '/interface'; }); const newArr = []; routes[interfaceIdx].children.forEach(item => { if (item.path !== 'send-offline') { newArr.push(item); } }); routes[interfaceIdx].children = newArr; return routes.concat(cxRoutes); }; export { app, configRoutes };
require("dotenv").config({ path: __dirname + "/../.env" }); const pd = require("paralleldots"); pd.apiKey = process.env.PARALLELDOTS_API_KEY; pd.emotion("Уебищный день, уебищный ты!", "ru") .then(response => { console.log(response); }) .catch(error => { console.log(error); });
var searchData= [ ['id',['id',['../struct_s_f___c_h_u_n_k___i_n_f_o.html#afedf0986b689c3962843160d15acdad6',1,'SF_CHUNK_INFO']]], ['id_5fsize',['id_size',['../struct_s_f___c_h_u_n_k___i_n_f_o.html#afa2490bdb8ac85fc207ef938a8c4a03d',1,'SF_CHUNK_INFO']]], ['indx',['indx',['../struct_s_f___c_u_e___p_o_i_n_t.html#a346aebc992e886ce24654d2190842d05',1,'SF_CUE_POINT']]], ['initialize_5faudio_5fstream',['initialize_audio_stream',['../classclient_1_1_client.html#a3b9a4e393333a884eae6783f272e6d64',1,'client::Client']]] ];
/*global ODSA */ // Written by Jieun Chon //Array-Based list introduction // var it2_midblue1, // it2_midblue2, // it2_midblue3, // it2_consoleLabels, // it2_consoleY, // it2_consoleGap, // it2_printprice; $(document).ready(function() { "use strict"; //BlueStepAnim :This should come before JSAV Initialize JSAV.ext.blueStepAnim = JSAV.anim(function doBlueStep(delay, time, consoleIndex, priceValue) { if (this._shouldAnimate()) { setTimeout(function() { // midblue 1 start it2_midblue1.addClass("blueboxh", {record: false}); setTimeout(function() { it2_midblue1.removeClass("blueboxh", {record: false}); // midblue 2 animation start ----------------- setTimeout(function() { it2_midblue2.addClass("blueboxh", {record: false}); setTimeout(function(){ it2_printprice.value(priceValue); for(var i = 0; i <= consoleIndex; i++){ it2_consoleLabels[i].css({top: it2_consoleY + (it2_consoleGap * i)}); it2_consoleLabels[i].show(); } it2_consoleY -= 30; setTimeout(function(){ it2_midblue2.removeClass("blueboxh", {record: false}); it2_printprice.value(""); // midblue 3 animation start ----------------- setTimeout(function() { it2_midblue3.addClass("blueboxh", {record: false}); setTimeout(function() { it2_midblue3.removeClass("blueboxh", {record: false}); }, time); }, time); // midblue 3 animation close --------------------- }, time + 600); }, time); }, time); // midblue 2 animation close }, time); }, delay); } }, function undoBlueStep(elemSet) {}); // BlueStepAnim END -----------------------------------------------zz //Animation :This should come before JSAV Initialize JSAV.ext.animation = JSAV.anim(function doBlueStep(item, time, effectName) { if (this._shouldAnimate()) { item.addClass(effectName, {record: false}); setTimeout(function() { item.removeClass(effectName, {record: false}); }, time); } }, function () {}); // BlueStepAnim END ----------------------------------------------- var arrValues = [4, 13, 6, 9, 11]; var av_name = "iteration2CON"; var interpret = ODSA.UTILS.loadConfig({av_name: av_name}).interpreter; var av = new JSAV(av_name); var left = 120, rect0_top = 0, rect_top = 40, topMargin = rect_top + 20; var nodegap = 40; // blue boxes, floor 1, last floor var topblue = av.g.rect(left, rect0_top, 280, 35, 10).addClass("bluebox"); var botblue = av.g.rect(left, rect0_top + 295, 280, 35, 10).addClass("bluebox"); // var rect_set = []; // floor 2 av.g.rect(left, rect_top, 250, 35.5, 10).addClass("purplebox"); av.g.rect(left, rect_top + 20, 50, 15).addClass("purplebox"); // for no-roung on the corner //floor 3 rects and array list JSAV contains arrValues' elements av.g.rect(left, rect_top + 5, 30, 90, 10).addClass("purplebox").css({opacity: 0.7}); av.g.rect(left + 73, rect_top + 25, 30, 70, 10).addClass("purplebox").css({opacity: 0.9}); var arr = av.ds.array(arrValues, {indexed: false, left: left + 150, top: topMargin, position: "absolute"}); //floor 4, long purple av.g.rect(left, rect_top + 76, 300, 30, 10).addClass("purplebox"); //floor 5, left big purple box and 3 blue boxes av.g.rect(left, rect_top + 80, 110, 170, 10).addClass("purplebox"); av.g.rect(left, rect_top + 76, 50, 15).addClass("purplebox"); // for no-roung on the corner //blue boxes and the the sets of it for the iterations later it2_midblue1 = av.g.rect(left + 130, rect_top + 110, 180, 25, 10).addClass("bluebox"); it2_midblue2 = av.g.rect(left + 130, rect_top + 140, 180, 25, 10).addClass("bluebox"); it2_midblue3 = av.g.rect(left + 130, rect_top + 170, 180, 25, 10).addClass("bluebox"); // last purple box. av.g.rect(left + 90, rect_top + 200, 240, 50, 10).addClass("purplebox"); // ---------------loop -labels----------------------- av.label("for each item", {left: left + 10, top: rect_top - 30}).addClass("loopLabels"); av.label("price", {left: left + 19, top: rect_top + 45}).addClass("loopLabels"); av.label("do", {left: left + 35, top: rect_top + 100}).addClass("loopLabels"); av.label("print (price)", {left: left + 160, top: rect_top + 112}).addClass("loopLabels").addClass("midlabel"); var valuelabel = av.label("", {left: left + 240, top: rect_top + 112}); valuelabel.addClass("loopLabels"); valuelabel.addClass("priceBoxLable"); it2_printprice = av.label("", {left: left + 240, top: rect_top + 85}); it2_printprice.addClass("loopLabels"); it2_printprice.addClass("valuelabelpb"); // <<--------------- STATE BOX ----------------->> var stateX = 530; var stateY = 40; // STATE label and maroon color box av.label("STATE", {left: stateX, top: stateY + 30}).addClass("statelabellarge"); var stateBox = av.g.rect(stateX - 25, stateY + 80, 110, 150).addClass("statebox"); // price box and label av.label("price", {left: stateX + 11, top: stateY + 90}).addClass("statelabel"); var priceBox = av.g.rect(stateX - 5, stateY + 135, 70, 70).addClass("bluebox"); var pricelabelX = stateX + 23; var priceBoxLabel = av.label("", {left: pricelabelX, top: stateY + 130}); priceBoxLabel.addClass("loopLabels"); priceBoxLabel.addClass("midlabel"); var totalBoxLabel = av.label("", {left: stateX + 23, top: stateY + 215}); // <<--------------- CONSOLE BOX ----------------->> it2_consoleGap = 30; var consoleX = 655; var consoleY = 45; // create CONSOLE label av.label("CONSOLE", {left: consoleX + 35, top: consoleY}).addClass("statelabellarge");; // create console box. var consoleBox = av.g.rect(consoleX, consoleY + 50, 170, 180).addClass("consolebox"); // create console labels will pop up later in the slides var consoleLabelX = consoleX + 20; it2_consoleY = consoleY + 184; var label1 = av.label("4", {left: consoleLabelX, top: it2_consoleY}); var label2 = av.label("13", {left: consoleLabelX, top: it2_consoleY}); var label3 = av.label("6", {left: consoleLabelX, top: it2_consoleY}); var label4 = av.label("9", {left: consoleLabelX, top: it2_consoleY});; var label5 = av.label("11", {left: consoleLabelX, top: it2_consoleY}); it2_consoleLabels = [label1, label2, label3, label4, label5]; // ------------------------console box line ----------------------- var consoleLineY = consoleY + 270; for (var i = consoleY + 200; i > consoleY + 60; i -= 30){ var consoleline = av.g.line(consoleX, i, consoleX + 170, i); consoleline.addClass("consoleline"); } for(var i = 0; i < it2_consoleLabels.length; i++){ it2_consoleLabels[i].addClass("consolelabels"); it2_consoleLabels[i].addClass("smalllabel"); it2_consoleLabels[i].hide(); } // --------------------- start slide shows // Slide 1 av.umsg(interpret("sc1")); var nextleft = left + 50; av.displayInit(); // Slide 2 av.umsg(interpret("sc2")); av.step(); // Slide 3 av.umsg(interpret("sc3")); av.bluehigh(topblue); av.step(); // Slide 4 av.umsg(interpret("sc4")); arr.css({left: nextleft}); nextleft -= nodegap; priceBoxLabel.value("4"); priceBoxLabel.css({left: pricelabelX}); av.step(); // Slide 5 av.umsg(interpret("sc5")); av.blueStepAnim(0, 100, 0, "4"); av.step(); // Slide 6 av.umsg(interpret("sc6")); arr.css({left: nextleft}); nextleft -= nodegap; it2_printprice.value(""); priceBoxLabel.value("13"); priceBoxLabel.css({left: pricelabelX - 6}); av.step(); // Slide 7 av.umsg(interpret("sc7")); av.blueStepAnim(0, 100, 1, "13"); av.step(); // Slide 8 av.umsg(interpret("sc8")); arr.css({left: nextleft}); nextleft -= nodegap; it2_printprice.value(""); priceBoxLabel.value("6"); priceBoxLabel.css({left: pricelabelX}); av.step(); // Slide 9 av.umsg(interpret("sc9")); av.blueStepAnim(0, 100, 2, "6"); av.step(); // slide 10 av.step(); // Slide 11 av.umsg(interpret("sc11")); arr.css({left: nextleft}); nextleft -= nodegap; it2_printprice.value(""); priceBoxLabel.value("9"); priceBoxLabel.css({left: pricelabelX}); av.step(); // Slide 12 av.umsg(interpret("sc12")); av.blueStepAnim(0, 100, 3, "9"); av.step(); // Slide 13 av.umsg(interpret("sc13")); arr.css({left: nextleft}); nextleft -= (nodegap + 50); it2_printprice.value(""); priceBoxLabel.value("11"); priceBoxLabel.css({left: pricelabelX - 6}); av.step(); // Slide 14 av.umsg(interpret("sc14")); av.blueStepAnim(0, 100, 4, "11"); av.step(); // Slide 15 av.umsg(interpret("sc15")); arr.css({left: nextleft}); it2_printprice.value(""); nextleft -= (nodegap + 100); av.step(); // Slide 16 av.umsg(interpret("sc16")); av.bluehigh(botblue); av.recorded(); });
import { Avatar } from '@material-ui/core'; import React, { useState } from 'react' import db from './firebase'; import "./PostHere.css"; import { useStateValue } from './StateProvider'; import firebase from "firebase"; function PostHere() { const [{ user }] = useStateValue(); const [input, setInput] = useState(""); const [imageUrl, setImageUrl] = useState(""); const handleSubmit = (e) => { e.preventDefault(); db.collection("posts").add({ message: input.trim(), timestamp: firebase.firestore.FieldValue.serverTimestamp(), profilePic: user.photoURL.trim(), username: user.displayName.trim(), image: imageUrl.trim(), likeCount: 0, }); setInput(""); setImageUrl(""); }; return ( <div className="postHere"> <div className="postHere__top"> <Avatar src={user.photoURL} /> <form> <input value={input} onChange={(e) => setInput(e.target.value)} className="postHere__input" placeholder={`Whats on your mind , ${user.displayName}`} type="text" /> <input value={imageUrl} onChange={(e) => setImageUrl(e.target.value)} placeholder="image url (Optional)" /> <button onClick={handleSubmit} type="submit">Post</button> </form> </div> </div> ) } export default PostHere
import React from 'react' import propTypes from 'prop-types' const Card = ({ cards }) => { return ( <div className="Card"> <h1>{cards.title}</h1> <ul> {cards.items.map(cardItem => ( <li>{cardItem.item}</li> ))} </ul> </div> ) } Card.propTypes = { cards: propTypes.object.isRequired } export default Card
import React from 'react' import styled from 'styled-components'; const Main = styled.main` width: 100vw; height: 100vh; `; const Div = styled.div` margin: 0 auto; padding: .8rem; `; function FullWidthSlide({ children }) { return ( <Main> <Div> {children} </Div> </Main> ) } export default FullWidthSlide;
import caseNucleaire3HTML from "./caseNucleaire3.html"; export const caseNucleaire3 = { template: caseNucleaire3HTML };
import React, { Component } from 'react'; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import classNames from 'classnames' import { Button, Card, CardBody, Col, Container, Form, Input, Row, FormGroup, Label, FormFeedback } from 'reactstrap'; import { Formik, Field } from 'formik'; import MaskedInput from "react-text-mask"; import 'react-select/dist/react-select.min.css'; import Select from 'react-select'; import 'react-select/dist/react-select.min.css'; import * as Yup from 'yup' import './Register.scss' import logo from './images/logo.png' import RegisterSubmitModal from './RegisterSubmitModal' import { fetchStates } from "../../../modules/States"; import { fetchBrands } from "../../../modules/Brands"; import axios from 'axios'; const phoneNumberMask = [ "(", /[1-9]/, /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/ ]; const validationSchema = function (values) { return Yup.object().shape({ email: Yup.string() .email('Invalid email address') .required('Email is required!'), firstName: Yup.string() .min(2, `First name has to be at least 2 characters`) .required('First name is required'), lastName: Yup.string() .min(1, `Last name has to be at least 1 character`) .required('Last name is required'), phonenumber: Yup.string() .required('Store phone number is required'), companyName: Yup.string() .required('Company name is required'), website: Yup.string() .min(2, `Website URL has to be at least 2 characters`) .required('Website URL is required'), mohawkAccount: Yup.string() .test('len', 'Must be exactly 6 characters', val => val.length === 6) .required('Mohawk Account is required'), Address: Yup.string() .min(5, `Address has to be at least 5 characters`) .required('Address is required'), Address2: Yup.string() .min(5, `Address2 has to be at least 5 characters`), city: Yup.string() .min(5, `City has to be at least 5 characters`) .required('City is required'), zipCode: Yup.string() .length(5, `Zip Code has to be at 5 characters`) .required('Zip Code is required'), }) } const validate = (getValidationSchema) => { return (values) => { const validationSchema = getValidationSchema(values) try { validationSchema.validateSync(values, { abortEarly: false }) return {} } catch (error) { return getErrorsFromValidationError(error) } } } const getErrorsFromValidationError = (validationError) => { const FIRST_ERROR = 0 return validationError.inner.reduce((errors, error) => { return { ...errors, [error.path]: error.errors[FIRST_ERROR], } }, {}) } const initialValues = { email: '', firstName: '', lastName: '', phonenumber: '', website: '', companyName: '', mohawkAccount: '', Address: '', city: '', zipCode: '', us_state: '', mohawkBrands: '', } class Register extends Component { states_ = {}; constructor(props) { super(props) this.props.fetchStateData(); this.props.fetchBrandsData(); this.touchAll = this.touchAll.bind(this) this.state = { submitSuccess: false, email: '', firstName: '', lastname: '', us_state: '', mohawkBrands: '', companyName: '', us_state_error: false, mohawk_error: false, modal: false } this.form = React.createRef(); this.saveMohawkChanges = this.saveMohawkChanges.bind(this); } componentDidMount = () => { this.form.current.validateForm(); } findFirstError(formName, hasError) { const form = document.forms[formName] for (let i = 0; i < form.length; i++) { if (hasError(form[i].name)) { form[i].focus() break } } } validateForm(errors) { this.findFirstError('referralForm', (fieldName) => { return Boolean(errors[fieldName]) }) } touchAll(setTouched, errors) { setTouched({ email: true }) this.validateForm(errors) } onSubmit = (values, { setSubmitting, setErrors }) => { /* this.setState({ firstName: values.firstName, lastName: values.lastName, email: values.email }); */ const appBaseURL = process.env.REACT_APP_API_URL; axios.post(appBaseURL + 'dealers', { ownerfirstname: values.firstName, ownerlastname: values.lastName, companyname: values.companyName, mohawkaccountid: values.mohawkAccount, email: values.email, website: values.website, companyphone: values.phonenumber, storeaddress: values.Address, storeaddress2: values.Address2, storecity: values.city, storestate: this.state.us_state.value, storezip: values.zipcode, brands: this.state.mohawkBrands.value }) .then((result) => { this.setState({ submitSuccess: true }); setSubmitting(false); //access the results here.... }); /* setTimeout(() => { this.setState({ submitSuccess: true }) setSubmitting(false) }, 5000)*/ } //, modal: true saveChanges = (value) => { this.setState({ us_state: value, us_state_error: false }); } handleBlur = () => { if (this.state.us_state === null) { this.setState({ us_state_error: true }) } else { if (this.state.us_state.length > 0 || this.state.us_state.length === undefined) { this.setState({ us_state_error: false }) } else { this.setState({ us_state_error: true }) } } } /* saveMohawkChanges = (value) => { this.setState({ mohawkBrands: value, mohawk_error: false }); } */ saveMohawkChanges = (value) => { this.setState(state => { return { mohawkBrands: value }; }); } handleMohawkBlur = () => { if (this.state.mohawkBrands === null) { this.setState({ mohawk_error: true }) } else { if (this.state.mohawkBrands.length > 0 || this.state.mohawkBrands.length === undefined) { this.setState({ mohawk_error: false }) } else { this.setState({ mohawk_error: true }) } } } toggleModal = () => { this.setState({modal: false}) } render() { const { stateData, brandData } = this.props; return ( <div className="app Register"> <RegisterSubmitModal modal={this.state.modal} toggleModal={this.toggleModal} submitSuccess={this.state.submitSuccess} /> <Container> <Row> <Col md="12" lg="7" xl="12"> <Card className="mt-5 mb-5"> <CardBody className="p-4"> <div className="text-center"><img src={logo} alt="logo" /></div> <h6 className="mt-3 text-center text-muted font-weight-normal"> To become a Soniclean dealer, you will need to register your company first using the form below. Please note that this program is only available for authorized Mohawk retailers. Once you've submitted this registration form, please allow up to 24 to 48 hours for your account to be approved. When your account is approved and activated, you will receive a welcome email with your Soniclean account login instructions. </h6> <Formik enableReinitialize initialValues={initialValues} validate={validate(validationSchema)} onSubmit={this.onSubmit} ref={this.form} render={ ({ values, errors, touched, status, dirty, handleChange, handleBlur, handleSubmit, isSubmitting, isValid, handleReset, setTouched }) => ( <Form onSubmit={handleSubmit} noValidate name='referralForm'> <Row> <Col> <Row className="mt-3"> <Col md={6}> <FormGroup> <Label for="firstName" className="text-muted">First Name</Label> <div> <Input type="firstName" name="firstName" id="firstName" autoComplete="firstName" valid={!errors.firstName} invalid={touched.firstName && !!errors.firstName} required onChange={handleChange} onBlur={handleBlur} value={values.firstName} /> <FormFeedback>{errors.firstName}</FormFeedback> </div> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="lastName" className="text-muted">Last Name</Label> <div> <Input type="lastName" name="lastName" id="lastName" autoComplete="lastName" valid={!errors.lastName} invalid={touched.lastName && !!errors.lastName} required onChange={handleChange} onBlur={handleBlur} value={values.lastName} /> <FormFeedback>{errors.lastName}</FormFeedback> </div> </FormGroup> </Col> </Row> <Row> <Col md={6} > <FormGroup> <Label for="email" className="text-muted">Email Address</Label> <div> <Input type="email" name="email" id="email" autoComplete="email" valid={!errors.email} invalid={touched.email && !!errors.email} required onChange={handleChange} onBlur={handleBlur} value={values.email} /> <FormFeedback>{errors.email}</FormFeedback> </div> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="phonenumber" className="text-muted">Phone Number</Label> <Field name="phonenumber" render={({ field }) => ( <MaskedInput {...field} mask={phoneNumberMask} id="phonenumber" type="text" onChange={handleChange} onBlur={handleBlur} required className={ errors.phonenumber && touched.phonenumber ? "is-invalid form-control" : "form-control" } /> )} /> <FormFeedback>{errors.phonenumber}</FormFeedback> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="companyName" className="text-muted">Company Name</Label> <div> <Input type="companyName" name="companyName" id="companyName" autoComplete="companyName" valid={!errors.companyName} invalid={touched.companyName && !!errors.companyName} required onChange={handleChange} onBlur={handleBlur} value={values.companyName} /> <FormFeedback>{errors.companyName}</FormFeedback> </div> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="website" className="text-muted">Website URL</Label> <div> <Input type="website" name="website" id="website" autoComplete="website" valid={!errors.website} invalid={touched.website && !!errors.website} required onChange={handleChange} onBlur={handleBlur} value={values.website} /> <FormFeedback>{errors.website}</FormFeedback> </div> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="mohawkAccount" className="text-muted">Mohawk Account #</Label> <div> <Input type="number" name="mohawkAccount" id="mohawkAccount" autoComplete="mohawkAccount" valid={!errors.mohawkAccount} invalid={touched.mohawkAccount && !!errors.mohawkAccount} required onChange={handleChange} onBlur={handleBlur} value={values.mohawkAccount} /> <FormFeedback>{errors.mohawkAccount}</FormFeedback> </div> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="mohawkBrands">Which products Mohawk brands do you sell?</Label> <Field name="mohawkBrands" render={({ field }) => ( <Select {...field} name="mohawkBrands" id="mohawkBrands" value={this.state.mohawkBrands} options={brandData} valid={!errors.mohawkBrands} invalid={touched.mohawkBrands && !!errors.mohawkBrands} onChange={this.saveMohawkChanges} onBlur={() => this.handleMohawkBlur()} className={classNames(this.state.mohawk_error ? 'error-select' : '')} /> )} /> {this.state.mohawk_error ? <div className="error">Mohawk brands is required</div> : ''} </FormGroup> </Col> </Row> <Row className="mt-3"> <Col md={12}> <h4 className="text-center">Shipping Address (Main Store Location)</h4> </Col> </Row> <Row className="mt-1"> <Col md={12}> <h6 className="text-center text-muted font-weight-normal">You can add additional store locations once your account has been activated</h6> </Col> </Row> <FormGroup> <Label for="Address">Address 1</Label> <Input type="text" name="Address" id="Address" placeholder="e.g. 123 Main St." autoComplete="address" valid={!errors.Address} invalid={touched.Address && !!errors.Address} required onChange={handleChange} onBlur={handleBlur} value={values.Address} /> <FormFeedback>{errors.Address}</FormFeedback> </FormGroup> <FormGroup> <Label for="Address">Address 2</Label> <Input type="text" name="Address2" id="Address2" autoComplete="address2" placeholder="e.g. Unit, Ste, Apt...." onChange={handleChange} onBlur={handleBlur} value={values.Address2} /> </FormGroup> <Row> <Col md={6}> <FormGroup> <Label for="email">City</Label> <Input type="city" name="city" id="city" autoComplete="city" valid={!errors.city} invalid={touched.city && !!errors.city} required onChange={handleChange} onBlur={handleBlur} value={values.city} /> <FormFeedback>{errors.city}</FormFeedback> </FormGroup> </Col> <Col md={3}> <FormGroup> <Label for="confirmPassword">State</Label> <Field name="us_state" render={({ field }) => ( <Select {...field} name="us_state" id="us_state" value={this.state.us_state} options={stateData} valid={!errors.us_state} invalid={touched.us_state && !!errors.us_state} onChange={this.saveChanges} onBlur={() => this.handleBlur()} className={classNames(this.state.us_state_error ? 'error-select' : '')} />)} /> {this.state.us_state_error ? <div className="error">State is required</div> : ''} </FormGroup> </Col> <Col md={3}> <FormGroup> <Label for="zipCode">Zip Code</Label> <Input type="number" name="zipCode" id="zipCode" autoComplete="zipCode" valid={!errors.zipCode} invalid={touched.zipCode && !!errors.zipCode} required maxLength="200" onChange={handleChange} onBlur={handleBlur} value={values.zipCode} /> <FormFeedback>{errors.zipCode}</FormFeedback> </FormGroup> </Col> </Row> <Row> <Col md={12} className="mt-3"> <Button type="submit" color="success" className="mr-1 btn-block" disabled={isSubmitting || !isValid}>{isSubmitting ? 'Wait...' : 'Submit'}</Button> </Col> </Row> </Col> </Row> </Form> )} /> </CardBody> </Card> </Col> </Row> </Container> </div> ); } } //export default Register; const mapStateToProps = ({ states, brands }) => { const { stateData } = states; const { brandData } = brands; return { stateData,brandData }; } const mapDispatchToProps = (dispatch) => { return { fetchStateData: () => { dispatch(fetchStates()); }, fetchBrandsData: () => { dispatch(fetchBrands()); }, } } export default withRouter(connect( mapStateToProps, mapDispatchToProps, null )(Register));
// ********************************************************************************* // COMMENT ROUTES FOR POST, GET, AND DELETE COMMENTS FROM THE DATABASE // ********************************************************************************* // ============================================================= var mongoose = require("mongoose"); var cheerio = require("cheerio"); var request = require('request'); var path = require('path'); // Require all models var db = require("../models"); module.exports = function(app) { /*========================================================================================== ROUTE TO INSERT A COMMENT INTO THE DB ===========================================================================================*/ app.post("/addComment", function(req, res) { console.log('This is the req.body: ', req.body); // Insert the note into the comments collection var comment = new db.Comment(req.body); comment.save(function(error, saved) { // Log any errors if (error) { console.log('This is the insert error: ' + error); } // Otherwise, send the note back to the browser // This will fire off the success function of the ajax request else { db.Article.findById(req.body.article, function(err, article){ if(err){ console.log(err); } article.comments.push(saved._id); article.save(function(err, article){ if (err){ console.log(err); } res.json(saved); }); }); } }); }); /*========================================================================================== ROUTE TO GET ALL COMMENTS FROM THE DB ===========================================================================================*/ app.get("/all", function(req, res) { // Find all comments in the comments collection db.Comment.find({}, function(error, comments) { // Log any errors if (error) { console.log("THIS IS THE ERROR FOR THE FIND FUNCTION: ", error); } // Otherwise, send json of the comments back to user // This will fire off the success function of the ajax request else { res.json(comments); } }); }); /*========================================================================================== Need to completely change this delete--- do the reverse of addComment ===========================================================================================*/ app.delete("/delete/:id", function(req, res) { // Remove a note using the objectID db.Comment.findByIdAndRemove(req.params.id, function(error, removed) { // Log any errors if (error) { console.log(error); res.send(error); } // This will fire off the success function of the ajax request else { // var t = db.Article.update({}, {$pull:{comments:req.params.id}}, false, function(error, docs){ // if (error){ // console.log(error); // }else { // console.log(docs); // } // }); res.send(removed); } }); }); }
import React, { useEffect, useState } from 'react' import { Layout, Table, Switch, Form, Typography } from 'antd' import { useSelector } from 'react-redux' import Module from '../../../Components/Module' const { Title } = Typography const TradesPage = () => { const OpenTrades = useSelector(state => state.OpenTrades) const Trades = useSelector(state => state.Trades.monthly.all) const [filters, setFilters] = useState({ open: true }) const [data, setData] = useState([]) const filter = () => { let x = filters.open ? OpenTrades : Trades setData(x) } useEffect(filter, [filters, OpenTrades, Trades]) const columns = [ { title: 'Status', dataIndex: filters.open ? 'trade_status' : 'status', key: filters.open ? 'trade_status' : 'status' }, { title: 'Started at', dataIndex: 'started_at', key: 'started_at', sorter: (a, b) => new Date(a.started_at) < new Date(b.started_at) ? 1 : -1 }, { title: 'Trade hash', dataIndex: 'trade_hash', key: 'trade_hash' }, { title: 'Amount requested', dataIndex: 'fiat_amount_requested', key: 'fiat_amount_requested', defaultSortOrder: 'ascend', sorter: (a, b) => Number.parseFloat(a.fiat_amount_requested) < Number.parseFloat(b.fiat_amount_requested) ? -1 : 1, }, { title: 'Margin', dataIndex: 'margin', key: 'margin', defaultSortOrder: 'ascend', sorter: (a, b) => Number.parseFloat(a.margin) < Number.parseFloat(b.margin) ? -1 : 1, }, { title: 'Fee percentage', dataIndex: 'fee_percentage', key: 'fee_percentage', defaultSortOrder: 'ascend', sorter: (a, b) => Number.parseFloat(a.fee_percentage) < Number.parseFloat(b.fee_percentage) ? -1 : 1, } ] if (!filters.open) columns.push({ title: 'Profit', dataIndex: 'profit', key: 'profit', defaultSortOrder: 'ascend', sorter: (a, b) => Number.parseFloat(a.profit) < Number.parseFloat(b.profit) ? -1 : 1, }) return ( <Layout> <Module title={<Title level={4}>Filters</Title>}> <Form layout='inline'> <Form.Item> <Switch checked={!filters.open} size='default' onChange={open => setFilters({...filters, open: !open})} checkedChildren='Completed trades' unCheckedChildren='Open trades' /> </Form.Item> </Form> </Module> <Module title={<Title level={4}>Trades</Title>}> <Table bodyStyle={{backgroundColor: '#ececec'}} columns={columns} dataSource={data} /> </Module> </Layout> ) } export default TradesPage
/** @jsxImportSource @emotion/react */ import { css, jsx } from '@emotion/react'; import { Router } from '@reach/router'; import Navbar from './components/Navbar'; import Landing from './screens/landing/Landing'; import Projects from './screens/projects/Projects'; import ProjectShow from './screens/project-show/ProjectShow'; import Resume from './screens/resume/Resume'; import NoMatch from './components/NoMatch'; import Clearfix from './components/Clearfix' const App = () => ( <Router> <Navbar path="/" > <Landing path="/" /> <Projects path="/projects" /> <ProjectShow path="/projects/:id" /> <Resume path="/resume" /> <NoMatch default /> </Navbar > </Router> ) export default App;
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: allg/table/edit // ================================================================================ { var i; var str = ""; weblet.loadview(); weblet.findIO(); weblet.obj.enablebuttons = {}; weblet.showValue = function(weblet,param) { var i = null; if ( weblet != this ) { var tablenameweblet = this.parent.subweblets[this.initpar.tablenameweblet]; if ( typeof tablenameweblet.act_values.schema == 'undefined' || typeof tablenameweblet.act_values.table == 'undefined' ) { alert(this.txtGetText('#mne_lang#Bitte erst Tabellen auswählen')); return false; } this.initpar.schema = tablenameweblet.act_values.schema; this.initpar.table = tablenameweblet.act_values.table; this.initpar.title = this.initpar.schema + '.' + this.initpar.table; this.titleString.add = this.txtGetText("#mne_lang#Spalte hinzufügen" + ": " + this.initpar.schema + "." + this.initpar.table); this.titleString.mod = this.txtGetText("#mne_lang#Spalte bearbeiten" + ": " + this.initpar.schema + "." + this.initpar.table); var p = { schema : this.initpar.schema, table : this.initpar.table, no_vals : "true", sqlend : 1 }; MneAjaxData.prototype.read.call(this, "/db/utils/table/data.xml", p ); this.obj.tables.content.clearBody(); this.obj.tables.content.plain = false; this.obj.inputs = {}; this.obj.unique = false; this.showids = new Array(); delete this.initpar.scols; for ( i in this.ids ) { if ( tablenameweblet.act_values.haveusertimecolumn && ( i == 'createdate' || i == 'createuser' || i == "modifydate" || i == 'modifyuser' )) continue; var r; r = this.obj.tables.content.add(this.names[this.ids[i]], '####' + 'text' + '####' + i + 'Input####'); this.obj.inputs[i] = this.obj.tables.content.body.rows[r].cells[1].datafield; this.obj.inputs[i].style.width = "40em"; switch(this.typs[this.ids[i]]) { case "1000": case "1001": this.obj.inputs[i].inputtyp = 'date'; this.obj.inputs[i].mne_timevalue = 0; this.obj.inputs[i].onkeyup = MneMisc.prototype.inOndate; break; case "1002": case "1003": this.obj.inputs[i].inputtyp = 'time'; this.obj.inputs[i].mne_timevalue = 0; this.obj.inputs[i].onkeyup = MneMisc.prototype.inOntime; break; } this.create_checkpopup(this.obj.inputs[i], this.regexps[this.ids[i]]); } this.clearModify(); p = { schema : 'mne_application', query : 'table_pkey', cols : 'column', wcol : 'schema,table', wop : '=,=', wval : this.initpar.schema + ',' + this.initpar.table, scol : 'position', sqlend : 1 }; MneAjaxData.prototype.read.call(this, "/db/utils/query/data.xml", p ); if ( this.values.length > 0 ) { var i; for ( i =0; i<this.values.length; i++ ) this.showids[i] = this.values[i][0]; MneAjaxWeblet.prototype.showValue.call(this,weblet,{ignore_notdefined : true, ignore_notfound : true } ); if ( this.values.length == 0 ) this.add(); this.obj.buttons.ok.disabled = false; this.obj.buttons.cancel.disabled = false; this.obj.buttons.add.disabled = false; this.obj.buttons.del.disabled = false; } else { this.obj.title.innerHTML = this.txtGetText('#mne_lang#editieren nicht möglich') + ": " + this.initpar.schema + "." + this.initpar.table; this.obj.buttons.ok.disabled = true; this.obj.buttons.cancel.disabled = true; this.obj.buttons.add.disabled = true; this.obj.buttons.del.disabled = true; } { var popup = this.popup; var timeout = function() { popup.resize.call(popup, true, false); }; window.setTimeout(timeout, 0); } return true; } return MneAjaxWeblet.prototype.showValue.call(this,weblet,param); }; weblet.getParam = function(p) { return MneAjaxWeblet.prototype.getParam.call(this,p); }; weblet.add = function() { this.okaction = 'add'; this.obj.title.innerHTML = this.titleString.add; }; weblet.ok = function() { return MneAjaxWeblet.prototype.ok.call(this); }; weblet.del = function() { return MneAjaxWeblet.prototype.del.call(this); }; }
export let getNewPasswordFields = () => [ { inputType: "textField", floatingLabelText: "Email", hintText: "Ingresa el email", id: "email", type: "text", className: "obligatoryField TextField", errorText: "", defaultValue: "" } ]
import React, { Component } from 'react'; import { SafeAreaView, View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { saveSearchTextInput, changeFouce } from '../actions/navMoreAction'; import { combineActions } from 'redux-actions'; import { fetchMovie, movieListAction } from '../actions/movie'; class SearchTextInput extends Component{ render = () => { const {saveSearchTextInput, isSearch, changeFouce, movieListAction} = this.props return ( <View> {isSearch ? <TextInput style={styles.container} editable = {true} placeholder='搜索番号' underlineColorAndroid='#fff' selectionColor='#fff' placeholderTextColor='#fff' // onBlur={e => changeFouce()} onSubmitEditing = {e => { console.log(e.nativeEvent.text) saveSearchTextInput({searchText:e.nativeEvent.text}) changeFouce() fetchMovie({fanhao:e.nativeEvent.text,limit:30,offset:0},movieListAction) }} /> : <Text onPress={() => changeFouce()} style={styles.text}>点我搜索</Text>} </View> ) } } const mapStateToProps = state => ({ isSearch: state.navMore.isSearch }); const mapDispatchToProps = { saveSearchTextInput, changeFouce, fetchMovie, movieListAction }; const styles = StyleSheet.create({ container: { width:100, color:'#fff' }, text: { color:'#fff' } }) export default connect(mapStateToProps, mapDispatchToProps)(SearchTextInput);
//查找要修改的对象 var id = GetQueryString("id"); var Class = GetQueryString("class"); $.post("../../Handle.ashx", { "parameter": "CheckOne", "id": id }, function (data) { var data1 = JSON.parse(data);//将json 转换成 对象 var dat = data1.Data; $(".Title").val(dat[0].Title);//标题 Abstract 1 $(".Pseudonym").val(dat[0].Author);//作者 2 这个不能绑上去 后端绑个唯一识别码 $(".Abstract").val(dat[0].Abstract);//简介 后期加的 4 $(".Tsize").val(dat[0].Tsize);//大小 后期加的 5 NStatistics $(".NStatistics").val(dat[0].NStatistics);//下载数 后期加的 6 $(".Download").val(dat[0].Download);//下载地址 后期加的 7 $(".ViewCount").val(dat[0].lrNumber);//浏览数 8 $("#news_content").val(dat[0].IsContents);//内容 var s = dat[0].ReleaseTime;//乱码的时间 var istimes = s.substring(6, 16)//截取 var tiems = getLocalTime(istimes)//转换 function getLocalTime(nS) {//时间转换函数 return new Date(parseInt(nS) * 1000).toLocaleString().substr(0, 17) } $(".CreatedTime").val(tiems)//发布时间 $(".Thumbnail").val(dat[0].Thumbnail);//缩略图 11 这个要等后面来 }); function GetQueryString(name) {//获取URL上的参数 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }
import React,{useContext} from 'react'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import Icon from '@material-ui/core/Icon'; import { Switch } from '@material-ui/core'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import clsx from 'clsx'; import { loadCSS } from 'fg-loadcss'; import { UserContext } from '../../contexts/UserContext'; const useStyles = makeStyles(theme => ({ container: { display: 'flex', flexWrap: 'wrap', }, button: { margin: theme.spacing(1), }, root: { padding: theme.spacing(3, 2), }, textField: { marginLeft: theme.spacing(1), marginRight: theme.spacing(1), }, dense: { marginTop: theme.spacing(2), }, menu: { width: 200, }, })); const AddUser=(props)=>{ const{usdata,dispatch}= useContext(UserContext); const [open, setOpen] = React.useState(false); const [values, setValues] = React.useState({ first_name: '', last_name: '', email: '', password: '', role:'', salary:'', assets_pack: '' }); const currencies = [ { value: 'admin', label: 'admin', }, { value: 'regular', label: 'regular', }, ]; const currenciesSal = [ { value: '1000', label: '1000', }, { value: '2000', label: '2000', }, ]; const classes = useStyles(); const handleChangeFirstName = first_name => event => { setValues({ ...values, [first_name]: event.target.value }); }; const handleChangeLastName = last_name => event => { setValues({ ...values, [last_name]: event.target.value }); }; const handleChangeEmail = email => event => { setValues({ ...values, [email]: event.target.value }); }; const handleChangePassword = password => event => { setValues({ ...values, [password]: event.target.value }); }; const handleChangeSalary = salary => event => { setValues({ ...values, [salary]: event.target.value }); }; const handleChangeRole = role => event => { setValues({ ...values, [role]: event.target.value }); }; function handleClickOpen() { setOpen(true); } function handleClose() { setOpen(false); } React.useEffect(() => { loadCSS( 'https://use.fontawesome.com/releases/v5.1.0/css/all.css', document.querySelector('#font-awesome-css'), ); }, []); const onSaveChanges=()=>{ ( async function UpdateCompanyIncome (){ //first const settingsC = { method: 'POST', body: JSON.stringify({ first_name: values.first_name, last_name: values.last_name, email: values.email, password: values.password, role:values.role, salary:values.salary, assets_pack: 0 }), headers: { Accept: 'application/json', 'Content-Type': 'application/json', } }; try{ const cdata= await fetch('/api/users/',settingsC); let cjdata =await cdata.json(); console.log("From PUt"+cjdata); dispatch({type:"ADD_USER", payload: cdata}) setOpen(false); }catch(err){ console.log("Error"+err); } // //second try{ const response = await fetch("/api/users"); const data = await response.json(); console.log("Users as"+ data); dispatch({type:"UPDATE_DATA_USERS", payload: data}) }catch(err){ console.log(err); } })() setValues( values.first_name= " ", values.last_name= " ",values.email="",values.password===""); setOpen(false); } return ( <div className="add_block"> <Icon className={clsx(classes.icon, 'fa fa-plus-circle')} color="action" onClick={handleClickOpen} /> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">Додати нового користувача</DialogTitle> <DialogContent> <form className={classes.container} noValidate autoComplete="off"> <TextField id="first-name" label="Ім'я" className={classes.textField} value={values.first_name} onChange={handleChangeFirstName('first_name')} margin="normal" /> <TextField id="last-name" label="Прізвище" className={classes.textField} value={values.last_name} onChange={handleChangeLastName('last_name')} margin="normal" /> <TextField id="email" label="email" className={classes.textField} value={values.email} onChange={handleChangeEmail('email')} margin="normal" /> <TextField id="password" label="password" className={classes.textField} value={values.password} onChange={handleChangePassword('password')} margin="normal" /> <TextField id="salary" select label=" " className={classes.textField} value={values.currency} onChange={handleChangeSalary('salary')} SelectProps={{ native: true, MenuProps: { className: classes.menu, }, }} helperText="Встановити ставку" margin="normal" > {currenciesSal.map(option => ( <option key={option.value} value={option.value}> {option.label} </option> ))} </TextField> <TextField id="role" select label=" " className={classes.textField} value={values.currency} onChange={handleChangeRole('role')} SelectProps={{ native: true, MenuProps: { className: classes.menu, }, }} helperText="Встановити доступ" margin="normal" > {currencies.map(option => ( <option key={option.value} value={option.value}> {option.label} </option> ))} </TextField> </form> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Вийти </Button> <Button disabled={values.first_name===''||values.last_name===''|| values.email===''|| values.password===''||values.role===''|| values.salary===''} onClick={onSaveChanges} color="primary"> Зберегти </Button> </DialogActions> </Dialog> </div> ); } export default AddUser
import Vue from 'vue' import App from './App.vue' import store from './store' import VueRouter from 'vue-router' import Home from './components/Home.vue' import Education from './components/Education.vue' import Experience from './components/Experience.vue' import ProjectJson from './components/ProjectJson.vue' import Personal from './components/Personal.vue' import Reference from './components/Reference.vue' import Contact from './components/Contact.vue' import Skill from './components/Skills.vue' import { library } from '@fortawesome/fontawesome-svg-core' import { fas } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import Axios from 'axios' import VueAxios from 'vue-axios' import VModal from 'vue-js-modal' import{ init } from 'emailjs-com'; init("user_59CZDqvxkwhM4iH8qaK7y"); library.add(fas) Vue.component('font-awesome-icon', FontAwesomeIcon) import Toaster from 'v-toaster' // You need a specific loader for CSS files like https://github.com/webpack/css-loader import 'v-toaster/dist/v-toaster.css' // optional set default imeout, the default is 10000 (10 seconds). Vue.use(Toaster, {timeout: 5000}) Vue.use(VueRouter) Vue.use(VueAxios, Axios) Vue.use(VModal) Vue.config.productionTip = false const router = new VueRouter({ routes: [ { path:'/', component: Home }, { path:'/education', component: Education }, { path:'/experience', component: Experience }, { path:'/projects', component: ProjectJson }, { path:'/personal', component: Personal }, { path:'/reference', component: Reference }, { path:'/contact', component: Contact }, { path:'/skills', component: Skill }, ], mode: 'history' }); new Vue({ store, router, render: h => h(App) }).$mount('#app')
$(document).ready(function(){ $("#submit").click(function() { if($("#name").val()=="") { alert("enter your name"); $("#name").focus(); return false; } if($("#password").val()=="") { alert("enter your password"); $("#password").focus(); return false; } var a=/^[0-9]+$/; if(!$("#age").val().match(a)) { alert("enter your age"); $("#age").focus(); return false; } if($("#gender").val()=="0") //if(document.s.log.selectedIndex==0) { alert("Select Gender"); $("#gender").focus(); return false; } }); });
"use strict"; var React = require("react"); var ReactDOM = require("react-dom"); var ReactPropTypes = React.PropTypes; var $ = require("jquery"); var Bloodhound = require("Bloodhound"); var SearchBox = React.createClass({ propTypes: { value: ReactPropTypes.string.isRequired, onChange: ReactPropTypes.func.isRequired, onOptionSelected: ReactPropTypes.func.isRequired }, componentDidMount: function(){ var foodCatalogue = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: "api/foods?q=%QUERY", wildcard: "%QUERY" } }); var element = ReactDOM.findDOMNode(this); $(element).typeahead({ minLength: 1, highlight: true, classNames: { menu: "dropdown-menu" } }, { name: "foods", display: "description", source: foodCatalogue }); var that = this; $(element).on("typeahead:selected", function(jquery, option){ that.props.onOptionSelected(option); }); }, componentWillUnmount: function(){ var element = ReactDOM.findDOMNode(this); $(element).typeahead("destroy"); }, render: function(){ return ( <input type="search" value={this.props.value} name="search" ref="input" className="form-control" onChange={this.props.onChange} placeholder="Food" /> ); } }); module.exports = SearchBox;
var variables________________0________8js____8js__8js_8js = [ [ "variables________0____8js__8js_8js", "variables________________0________8js____8js__8js_8js.html#a52ec7e9c6686a7ba3138bd3da848cd6e", null ] ];
require('dotenv').config(); var exports = module.exports = {}; var sql = require("mssql"); const request = require('request'); var format = require('pg-format'); const authentication = require('../utils/access_token') const credentials = require('../utils/Credentials') const resourcesList = require('./GetAllResources') var jwtDecode = require('jwt-decode'); const { resolve, reject } = require('promise'); exports.getAllResourcesAtLogin = async(req,res)=>{ try{ var globalAdmin; await credentials.getcredentials(req.header('id')).then(async(cred)=>{//get credentials on basis of A3SId globalAdmin = cred.globalAdmin await authentication.clientCredAuthenticationForMsManagementApi(cred).then(async(authToken)=>{ decodedToken = jwtDecode(req.header('Authorization')) //decode the access token to get pid console.log("decodedToken-->",decodedToken) await resourcesList.subscriptionOrchestration(authToken["access_token"],decodedToken.oid,req.header('Authorization'),decodedToken.name).then((resourcesList)=>{ //list of resources formatResoucesList(resourcesList,decodedToken.unique_name) resourcesList['GlobalAdmin'] = globalAdmin res.send(resourcesList) }).catch(err=>{ res.status(400).send(err) }) }).catch(err=>{ console.log(err) res.status(400).send(err) }) }).catch(err=>{ // Error in fetching Credentials res.status(400).send(err) }) }catch(err){ console.log('Please Try Again!',err) res.status(404).send(err) } } async function decodeAuthToken(userAuthToken){ return new Promise((resolve,reject)=>{ try{ var decoded = jwt_decode(userAuthToken) resolve(decoded) }catch(error){ reject(error) } }) } async function formatResoucesList(resourcesList,userName){ try{ formattedResourcesList = [] if(resourcesList.Subscription_RGList){ Promise.all(resourcesList.Subscription_RGList.map( eachSubscription => { eachSubscription.ResourceGroups.forEach(eachRG =>{ element=[] element.push(userName) element.push(eachSubscription.SubscriptionID) element.push(eachSubscription.SubscriptionName) element.push(eachRG.Name) formattedResourcesList.push(element) }) return eachSubscription })).then(async(results)=>{ //console.log(formattedResourcesList) console.log("query processing-->") await insertIntoDatabase(formattedResourcesList).then(response=>{ return(response) }).catch(err=>{ console.log(err) }) }) }else{ console.log('No resources for this user') } }catch(err){ console.log(err) } } async function insertIntoDatabase(formattedResourcesList){ return new Promise((resolve,reject)=>{ var request = new sql.Request(); console.log("length",formattedResourcesList.length) for(let i=0;i< formattedResourcesList.length;i+=1000){ query = format('INSERT INTO [PowerBI].[Requestbuffer] (email,subscriptionId,subscriptionName,resourceGroup) VALUES %L' ,formattedResourcesList.slice(i,i+1000)); console.log(query) request.query(query, async function (err, recordset){ if(err){ console.log(err) reject(err) }else { //alterTableColumnType(process.env.alterFloatForecastSubs).then(response=>{ console.log("data inserted---->") resolve({"status":"success"}) // }).catch(err=>{ // console.log(err) // reject(err) // }) } }) } }) } async function deleteUserDetails(){ return new Promise((resolve,reject)=>{ var request = new sql.Request(); request.query(``,async function (err, recordset){ }) }) } exports.getCredentialsFromDatabase = async(req,res)=>{ try{ cred = await credentials.getcredentials(req.header('id')).then(async(cred)=>{ res.send({"ClientID":cred.clientId,"TenantID":cred.tenantId}) }).catch(err=>{ res.status(400).send(err) }) }catch(err){ res.status(404).send({"Error":"Can't get the credentials. Try Again!!"}) } }
import { attributeBindings, classNameBindings, tagName } from '@ember-decorators/component'; import { computed } from '@ember/object'; import BaseFormElementLabel from 'ember-bootstrap/components/base/bs-form/element/label'; import { isBlank } from '@ember/utils'; import defaultValue from 'ember-bootstrap/utils/default-decorator'; @tagName('label') @classNameBindings( 'invisibleLabel:sr-only', 'isHorizontalAndNotCheckbox:col-form-label', 'isCheckbox:form-check-label', 'labelClass', 'sizeClass' ) @attributeBindings('formElementId:for') export default class FormElementLabel extends BaseFormElementLabel { @computed('isHorizontal', 'isCheckbox') get isHorizontalAndNotCheckbox() { return this.get('isHorizontal') && !this.get('isCheckbox'); } @computed('size', 'isHorizontal') get sizeClass() { if (!this.get('isHorizontal')) { return undefined; } let size = this.get('size'); return isBlank(size) ? null : `col-form-label-${size}`; } /** * Property for size styling, set to 'lg', 'sm' * * @property size * @type String * @public */ @defaultValue size = null; }
const SimpleAccountStorage = require('../../src/SimpleAccountStorage'); const ipfsHelper = require('../../src/ipfsHelper'); const JsIpfsService = require('../../src/JsIpfsService'); const FluenceService = require('../../src/fluenceService'); const { testNet } = require('@fluencelabs/fluence-network-environment'); const { FluencePeer, KeyPair } = require("@fluencelabs/fluence"); const accStorage = new SimpleAccountStorage(); const peerIdHelper = require('../../src/peerIdHelper'); module.exports = { async ipfs(options) { const createNode = () => { return ipfsHelper.createDaemonNode({ test: true, disposable: true, }, { pass: options.pass, EXPERIMENTAL: {ipnsPubsub: true} }); }; const _nodeA = new JsIpfsService(await createNode()); const _nodeB = new JsIpfsService(await createNode()); const idB = await _nodeB.id(); const idA = await _nodeA.id(); await _nodeA.swarmConnect(idB.addresses[0]); await _nodeA.addBootNode(idB.addresses[0]); await _nodeB.swarmConnect(idA.addresses[0]); await _nodeB.addBootNode(idA.addresses[0]); return [_nodeA, _nodeB]; }, async fluence() { const createNode = async () => { const peer = new FluencePeer(); const peerId = await peerIdHelper.createPeerId(); await peer.start({ connectTo: testNet[1], KeyPair: new KeyPair(peerId) }); // console.log("connected"); return new FluenceService(accStorage, peer); }; const _nodeA = await createNode(); const _nodeB = await createNode(); return [_nodeA, _nodeB]; } };
import Expo from 'expo'; import React from 'react'; import { PixelRatio, View } from 'react-native'; import TouchableView from './TouchableView'; const scale = PixelRatio.get(); function scaled({ x, y }) { return { x: x * scale, y: y * scale }; } export default ({ app }) => ( <TouchableView id="pixi-view" style={{ flex: 1 }} onTouchesBegan={({ locationX: x, locationY: y }) => this.began && this.began(scaled({ x, y }))} onTouchesMoved={({ locationX: x, locationY: y }) => this.moved && this.moved(scaled({ x, y }))} onTouchesEnded={({ locationX: x, locationY: y }) => this.ended && this.ended(scaled({ x, y }))} onTouchesCancelled={({ locationX: x, locationY: y }) => this.cancelled ? this.cancelled(scaled({ x, y })) : this.ended && this.ended(scaled({ x, y })) }> <View style={{ flex: 1 }}> <Expo.GLView style={{ flex: 1 }} onContextCreate={async context => { const events = (await app(context)) || {}; const { began, moved, ended, cancelled } = events; this.began = began; this.moved = moved; this.ended = ended; this.cancelled = cancelled; }} /> </View> </TouchableView> );
import { useEffect, useState } from 'react' import { motion, useTransform, animate, useMotionValue } from 'framer-motion' import { gradients } from '@/utils/gradients' import { useInView } from 'react-intersection-observer' const colors = { lightblue: [gradients.lightblue[0], 'text-cyan-100', 'bg-cyan-100'], purple: [gradients.purple[0], 'text-fuchsia-100', 'bg-fuchsia-100'], orange: [gradients.orange[0], 'text-orange-100', 'bg-orange-100'], teal: [gradients.teal[0], 'text-green-100', 'bg-green-100'], violet: [gradients.violet[0], 'text-purple-100', 'bg-purple-100'], amber: [gradients.amber[0], 'text-orange-100', 'bg-orange-100'], pink: [gradients.pink[0], 'text-rose-100', 'bg-rose-100'], blue: [gradients.blue[0], 'text-light-blue-100', 'bg-light-blue-100'], } const rotation = [-2, 1, -1, 2, -1, 1] function Testimonial({ testimonial, base, index, total }) { const x = useTransform( base, [0, (100 / total) * (index + 1), (100 / total) * (index + 1), 100], ['0%', `${(index + 1) * -100}%`, `${total * 100 - (index + 1) * 100}%`, '0%'] ) const [straight, setStraight] = useState(false) const color = colors[Object.keys(colors)[index % Object.keys(colors).length]] return ( <motion.li className="px-3 md:px-4 flex-none" onMouseEnter={() => setStraight(true)} onMouseLeave={() => setStraight(false)} style={{ x }} > <motion.figure className="shadow-lg rounded-xl flex-none w-80 md:w-xl" initial={false} animate={straight ? { rotate: 0 } : { rotate: rotation[index % rotation.length] }} > <blockquote className="rounded-t-xl bg-white px-6 py-8 md:p-10 text-lg md:text-xl leading-8 md:leading-8 font-semibold text-gray-900"> <svg width="45" height="36" className={`mb-5 fill-current ${color[1]}`}> <path d="M13.415.001C6.07 5.185.887 13.681.887 23.041c0 7.632 4.608 12.096 9.936 12.096 5.04 0 8.784-4.032 8.784-8.784 0-4.752-3.312-8.208-7.632-8.208-.864 0-2.016.144-2.304.288.72-4.896 5.328-10.656 9.936-13.536L13.415.001zm24.768 0c-7.2 5.184-12.384 13.68-12.384 23.04 0 7.632 4.608 12.096 9.936 12.096 4.896 0 8.784-4.032 8.784-8.784 0-4.752-3.456-8.208-7.776-8.208-.864 0-1.872.144-2.16.288.72-4.896 5.184-10.656 9.792-13.536L38.183.001z" /> </svg> {typeof testimonial.content === 'string' ? ( <p>{testimonial.content}</p> ) : ( testimonial.content )} </blockquote> <figcaption className={`flex items-center space-x-4 p-6 md:px-10 md:py-6 bg-gradient-to-br rounded-b-xl leading-6 font-semibold text-white ${color[0]}`} > <div className="flex-none w-14 h-14 bg-white rounded-full flex items-center justify-center"> <img src={testimonial.author.avatar} alt="" className={`w-12 h-12 rounded-full ${color[2]}`} loading="lazy" /> </div> <div className="flex-auto"> {testimonial.author.name} {testimonial.author.role && ( <> <br /> <span className={color[1]}>{testimonial.author.role}</span> </> )} </div> {testimonial.tweetUrl && ( <cite className="flex"> <a href={testimonial.tweetUrl} className="opacity-50 hover:opacity-75 transition-opacity duration-200" > <span className="sr-only">Original tweet by {testimonial.author.name}</span> <svg width="33" height="32" fill="currentColor"> <path d="M32.411 6.584c-1.113.493-2.309.826-3.566.977a6.228 6.228 0 002.73-3.437 12.4 12.4 0 01-3.944 1.506 6.212 6.212 0 00-10.744 4.253c0 .486.056.958.16 1.414a17.638 17.638 0 01-12.802-6.49 6.208 6.208 0 00-.84 3.122 6.212 6.212 0 002.762 5.17 6.197 6.197 0 01-2.813-.777v.08c0 3.01 2.14 5.52 4.983 6.091a6.258 6.258 0 01-2.806.107 6.215 6.215 0 005.803 4.312 12.464 12.464 0 01-7.715 2.66c-.501 0-.996-.03-1.482-.087a17.566 17.566 0 009.52 2.79c11.426 0 17.673-9.463 17.673-17.671 0-.267-.007-.536-.019-.803a12.627 12.627 0 003.098-3.213l.002-.004z" /> </svg> </a> </cite> )} </figcaption> </motion.figure> </motion.li> ) } export function Testimonials({isChinese} = props) { const testimonials = [ { content: isChinese===true ? `虽然我没有编程经验,但是使用Datav我依然能够轻松地创建想要的图表` : `I have no coding skills and with Datav I can actually make good looking dashboards with ease and it's everything I ever wanted`, author: { name: 'Sara Vieira', role: 'Data Engineer', avatar: require('@/img/avatars/sara-vieira.jpg').default, }, }, { content: isChinese===true ? '如果让我推荐现在的监控平台怎么搭建,我会推荐jaeger + prometheus + datav' :'If I had to recommend a way of getting into apm today, it would be jaeger + prometheus + datav', tweetUrl: '', author: { name: 'Guillermo Rauch', role: 'APM Developer', avatar: require('@/img/avatars/guillermo-rauch.jpg').default, }, }, { content: isChinese===true ? '当我第一次看到datav项目时,就立刻看到了它的潜力,联系Michal Sopor加入Datav团队,并成为核心贡献者' :'When I first saw datav, I instantly contact Michal Sopor to join datav team, and finally become a core contributor of datav', tweetUrl: '', author: { name: 'Sunface', role: 'Datav Core Contributor', avatar: require('@/img/avatars/sunface.jpg').default, }, }, { content: isChinese===true ? `我刚开始用Datav不久,但是很快就爱上了它的漂亮的设计、完善的文档以及简单好用的仪表盘` :`I started using datav. I instantly fell in love with their beautiful design, thorough documentation, and how easy it was customizing my dashboards.`, tweetUrl: '', author: { name: 'Dacey Nolan', role: 'Software Engineer', avatar: require('@/img/avatars/dacey-nolan.jpg').default, }, }, { content: isChinese===true ? '使用Datav的每时每刻我都很享受' :'Loved it the very moment I used it.', author: { name: 'Gilbert Rabut Tsurwa', role: 'Devops Engineer', avatar: require('@/img/avatars/gilbert-rabut-tsurwa.jpg').default, }, }, { content: isChinese===true ? '我一直在寻找企业级的图形可视化解决访问,Datav就是我最终的答案' :"I'm looking for a more enterprise-ready data visualization solutions, I find it now", tweetUrl: '', author: { name: 'Madeline Campbell', role: 'Full-Stack Developer', avatar: require('@/img/avatars/madeline-campbell.jpg').default, }, }, { content: isChinese===true ? 'Datav有一点真的很讨厌 - 一旦你用了它,就再也无法离开' :'There’s one thing that sucks about datav - once you’ve used it you cant leave it', tweetUrl: '', author: { name: 'Graeme Houston', role: 'Devops Engineer', avatar: require('@/img/avatars/graeme-houston.jpg').default, }, }, ] const x = useMotionValue(0) const { inView, ref: inViewRef } = useInView({ threshold: 0, rootMargin: '100px' }) const [duration, setDuration] = useState(150) useEffect(() => { if (!inView) return const controls = animate(x, 100, { type: 'tween', duration, ease: 'linear', loop: Infinity, }) return controls.stop }, [inView, x, duration]) return ( <div ref={inViewRef} className="relative" onMouseEnter={() => setDuration(250)} onMouseLeave={() => setDuration(150)} style={{marginTop:"80px"}} > <div className="absolute right-0 bottom-1/2 left-0 bg-gradient-to-t from-gray-100 pointer-events-none" style={{ height: 607, maxHeight: '50vh' }} /> <div className="flex overflow-hidden -my-8"> <ul className="flex items-center w-full py-8"> {testimonials.map((testimonial, i) => ( <Testimonial key={i} testimonial={testimonial} base={x} index={i} total={testimonials.length} /> ))} </ul> </div> </div> ) }
import test from './modules/test.js' export default {test}
define(function(require, exports, module) { "use strict"; // External dependencies. var Backbone = require("backbone"); var Issue = require("issue"); var Issues = require("issues"); var _ = require("underscore"); // Defining the application router. var Router = Backbone.Router.extend({ routes: { "": "welcome", "app": "app" }, welcome: function() { require(["template!templates/welcome"], function(template) { var contents = template(); $("#main").html(contents); }); }, app: function() { $.getJSON("https://api.github.com/repos/mechiland/stompc/issues", function(issues) { require(["template!templates/card"], function(template) { _.each(issues, function(iss) { var issue = new Issue(iss); console.log(issue); var contents = template(issue.attributes); $("#main").append(contents); }); }); }); // console.log("Welcome to your / route."); } }); module.exports = Router; });
describe("Spec of GaTrackingErrorEvent", function() { 'use strict'; describe("Test for #makeMessage", function() { it("return the text which made the arguments were combined", function() { var msg = 'a', url = 'b', line = 0, result = GaTrackingErrorEvent.makeMessage(msg, url, line); expect(result).to.eql('b : a : 0'); }); }); describe('Test for #tracking', function () { xit("don't call a method of ga if ga does not exist", function () { }); it('call a method of ga', function () { var ga = sinon.spy(), msg = 'a', url = 'b', line = 0, message = 'b : a : 0'; window.ga = ga; GaTrackingErrorEvent.tracking(msg, url, line); expect(ga.calledWith('send', 'event', 'debug', 'error', message)) .to.be.ok(); }); }); });
//var url = require('url'); var casper = require('casper').create({ verbose: true }); //var require = patchRequire(require); //var url = require('url'); casper.options.onResourceReceived = function(arg, response){ if (response.stage === 'end' && (response.url.indexOf('google-analytics') > -1)) { //console.log(JSON.stringify(response, null, 2)); console.log(response.status + " = " + response.url); //var parsedURL = url.parse(response.url); //console.log(JSON.stringify(parsedURL, null, 2)); } }; casper.start('http://www.cowboytoyota.com/', function() { this.echo(this.getTitle()); }); casper.run();
import React from 'react'; import {View, Text, Button, StyleSheet, FlatList} from 'react-native'; import {data} from '../Model/data'; import Card from '../Component/Card'; const CardListScreen = ({navigation}) => { const renderItem = ({item}) => { return ( <Card itemData={item} onPress={() => navigation.navigate('CardItemDetails', {itemData: item})} /> ); }; return ( <View style={styles.container}> <FlatList data={data} renderItem={renderItem} keyExtractor={(item) => item.id} /> </View> ); }; export default CardListScreen; const styles = StyleSheet.create({ container: { flex: 1, width: '90%', alignSelf: 'center', // backgroundColor: '#00a2ff', }, }); // import React, {Component} from 'react'; // import { // StyleSheet, // ScrollView, // Text, // Button, // StatusBar, // View, // TouchableOpacity, // } from 'react-native'; // import {createStackNavigator} from '@react-navigation/stack'; // import Icon from 'react-native-vector-icons/Ionicons'; // import {Avatar} from 'react-native-paper'; // const CardListStack = createStackNavigator(); // const HomeStack = createStackNavigator(); // const CardListScreen = ({navigation}) => { // return ( // <View // style={{ // flex: 1, // color: '#f59042', // alignContent: 'center', // justifyContent: 'center', // alignItems: 'center', // }}> // <Text>Your Card Here</Text> // <Button // title="Go to Details Screen.. Again" // onPress={() => navigation.push('Details')} // /> // </View> // ); // }; // const CardListStackScreen = ({navigation}) => ( // <CardListStack.Navigator // screenOptions={{ // headerStyle: { // backgroundColor: '#000', // shadowColor: '#000', // elevation: 0, // }, // headerTintColor: '#fff', // headerTitleStyle: {fontWeight: 'bold'}, // }}> // <CardListStack.Screen // name="CardListScreen" // component={CardListScreen} // options={{ // title: 'CardListScreen', // headerLeft: () => ( // <View style={{marginLeft: 10}}> // <Icon.Button // name="md-menu" // size={25} // color="#333" // backgroundColor="#fff" // onPress={() => { // navigation.openDrawer(); // }}></Icon.Button> // </View> // ), // headerTintColor: '#333', // headerTitleStyle: {fontWeight: 'bold'}, // headerRight: () => ( // <View style={{flexDirection: 'row', marginRight: 7}}> // <Icon.Button // name="search-sharp" // size={25} // color="#333" // backgroundColor="#fff" // onPress={() => { // { // } // }}></Icon.Button> // <TouchableOpacity // style={{paddingHorizontal: 4, marginTop: 5}} // onPress={() => { // navigation.navigate('Profile'); // }}> // <Avatar.Image source={require('../assets/prof.png')} size={35} /> // </TouchableOpacity> // </View> // ), // }} // /> // </CardListStack.Navigator> // ); // export default CardListStackScreen;
(function(){ angular .module('myApp') .controller('LoginController', ['LoginService', 'ConnectService', '$location', 'Data', LoginController ]); function LoginController(LoginService, ConnectService, $location, Data) { var vm = this; console.log('login please!') // // if (sessionStorage.sessionid != 'undefined' && typeof sessionStorage.sessionid !='undefined') { // $location.path('/dashboard'); // } // vm.showinputs = true; vm.formfields = LoginService.fields(); // console.log(vm.inputfields); vm.formmodel = LoginService.model(); var path = $location.path().slice(1); vm.title = path.charAt(0).toUpperCase() + path.slice(1); //vm.title = LoginService.title; // vm.desc = LoginService.desc; vm.demo = function () { Data.demo = true LoginService.demo() } vm.onsubmit = function () { LoginService.execute(vm.formmodel); } } })();
import isBabel from "./isBabel" // node bin is used to help for windows export default ( isBabel ? "babel-node src/" : "node dist/" ) + "__tests__/utils/"
var tag = document.createElement("script"); tag.src = "https://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName("script")[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player("ytplayer", { height: "480", width: "854", videoId: "NTMNxWtbNwQ", playerVars: { controls: 2, showinfo: 0, start: 5 } }); }
//= require bootstrap //= require custom //= require jquery
const UserSerializer = { serialize({ id, firstName, lastName, middleName, email, password, isDeleted, createdBy, updatedBy, createdAt, updatedAt, roles }) { return { id, firstName, lastName, middleName, email, password, isDeleted, createdBy, updatedBy, createdAt, updatedAt, roles }; } }; module.exports = UserSerializer;
// https://www.freecodecamp.org/challenges/pairwise function pairwise(arr, arg){ var pair = 0; for (var i = 0; i < arr.length; i++){ for (var j = i + 1; j < arr.length; j++){ if (arr[i] + arr[j] == arg){ pair += i + j; arr[i] = NaN; arr[j] = NaN; break; } } } return pair; } pairwise([1,4,2,3,0,5], 7);
import { nanoid } from "@reduxjs/toolkit"; import React from "react"; import { useState } from "react"; import { useDispatch } from "react-redux"; import { addContact } from "../../redux/contactSlice"; // import { addContact } from "../../redux/contactSlice"; const Form = () => { const dispatch = useDispatch(); const [name, setName] = useState(""); const [number, setNumber] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!name || !number) return false; // coklu isim eklemek icin asagidaki kod satirlari kullanilabilir // const names = name.split(","); // const data = names.map((name) => ({id: nanoid(), name: name})); data asagidaki dispatch isleminde addContact'e parametre olarak verilmeli dispatch(addContact({ id: nanoid(), name: name, phone_number: number })); setName(""); setNumber(""); }; return ( <div> <form onSubmit={handleSubmit}> <div className="userbox"> <input className='mainLoginInput' placeholder="name" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="userbox"> <input className='mainLoginInput' placeholder="phone number" value={number} onChange={(e) => setNumber(e.target.value)} /> </div> <div className="btn"> <button type="submit">Add</button> </div> </form> </div> ); }; export default Form;
import React from 'react' const Jumbotron = ({title, description}) => { return ( <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4">{title}</h1> {description} </div> </div> ) } export default Jumbotron
var pageSize = 25; Ext.define('gigade.BrandLogoSort', { extend: 'Ext.data.Model', fields: [ { name: "blo_id", type: "int" }, { name: "brand_id", type: "int" }, { name: "brand_name", type: "string" }, { name: "brand_logo", type: "string" }, { name: "blo_sort", type: "int" }, { name: "category_id", type: "int" }, { name: "category_name", type: "string" }, { name: "user_username", type: "string" }, { name: "blo_mdate", type: "string" }, ] }); BrandLogoSortStore = Ext.create('Ext.data.Store', { autoDestroy: true, pageSize: pageSize, model: 'gigade.BrandLogoSort', proxy: { type: 'ajax', url: '/BrandLogoSort/GetBLSList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); BrandLogoSortStore.on('beforeload', function () { Ext.apply(BrandLogoSortStore.proxy.extraParams, { category_id: Ext.getCmp('category_id_ser').getValue(), brand_id: Ext.getCmp('brand_id_ser').getValue(), }); }); var comType = false; Ext.define('gigade.CategoryStore2', { extend: 'Ext.data.Model', fields: [ { name: 'category_id', type: 'int' }, { name: 'category_name', type: 'string' } ] }); var CategoryStore2 = Ext.create("Ext.data.Store", { autoLoad: true, model: 'gigade.CategoryStore2', proxy: { type: 'ajax', url: '/BrandLogoSort/GetCategoryStore', reader: { type: 'json', root: 'data' } } }); Ext.define('gigade.BrandStore2', { extend: 'Ext.data.Model', fields: [ { name: 'brand_id', type: 'int' }, { name: 'brand_name', type: 'string' } ] }); var BrandStore2 = Ext.create("Ext.data.Store", { model: 'gigade.BrandStore2', proxy: { type: 'ajax', url: '/BrandLogoSort/GetBrandStore', reader: { type: 'json', root: 'data' } } }); BrandStore2.on('beforeload', function () { Ext.apply(BrandStore2.proxy.extraParams, { category_id: Ext.getCmp('category_id_ser').getValue(), }); }); var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { Ext.getCmp("BrandLogoSort").down('#edit').setDisabled(selections.length == 0); Ext.getCmp("BrandLogoSort").down('#delete').setDisabled(selections.length == 0); } } }); Ext.onReady(function () { var BrandLogoSort = Ext.create('Ext.grid.Panel', { id: 'BrandLogoSort', store: BrandLogoSortStore, flex: '8.9', width: document.documentElement.clientWidth, columnLines: true, frame: true, columns: [ { header: "編號", dataIndex: 'blo_id', width: 60, align: 'center' }, { header: "品牌名稱", dataIndex: 'brand_name', width: 150, align: 'center' }, { header: "品牌logo", dataIndex: 'brand_logo', width: 80, align: 'center', xtype: 'templatecolumn', tpl: '<a target="_blank" href="{brand_logo}" ><img width=50 name="tplImg" height=50 src="{brand_logo}" /></a>' }, { header: "排序", dataIndex: 'blo_sort', width: 150, align: 'center' }, { header: "品牌館分類", dataIndex: 'category_name', width: 150, align: 'center' }, { header: "異動人員", dataIndex: 'user_username', width: 150, align: 'center' }, { header: "異動時間", dataIndex: 'blo_mdate', width: 150, align: 'center' }, ], tbar: [ { xtype: 'button', text: '新增', id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick }, { xtype: 'button', text: '編輯', id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }, { xtype: 'button', text: '刪除', id: 'delete', hidden: false, iconCls: 'ui-icon ui-icon-user-delete', disabled: true, handler: onDeleteClick }, '->', { xtype: 'combobox', fieldLabel: '品牌館分類', id: 'category_id_ser', displayField: 'category_name', valueField: 'category_id', labelWidth: 70, editable: false, emptyText: "請選擇...", store: CategoryStore2, listeners: { select: function (combo, record) { var m = Ext.getCmp("brand_id_ser"); m.clearValue(); BrandStore2.removeAll(); BrandStore2.load({ params: { category_id: Ext.getCmp('category_id_ser').getValue(), } }); comType = true; } }, }, { xtype: 'combobox', fieldLabel: '品牌名稱', id: 'brand_id_ser', store: BrandStore2, labelWidth: 70, width: 245, margin: '0 0 0 15', emptyText: "請選擇...", displayField: 'brand_name', valueField: 'brand_id', queryMode: 'local', typeAhead: true, listeners: { beforequery: function (qe) { if (comType) { delete qe.combo.lastQuery; BrandStore2.load({ params: { category_id: Ext.getCmp('category_id_ser').getValue(), } }); comType = false; } } } }, { xtype: 'button', text: '查詢', handler: Search }, { xtype: 'button', text: '重置', handler: function () { Ext.getCmp('category_id_ser').setValue(); Ext.getCmp('brand_id_ser').setValue(); } }, ], bbar: Ext.create('Ext.PagingToolbar', { store: BrandLogoSortStore, pageSize: pageSize, displayInfo: true, displayMsg: "當前顯示記錄" + ': {0} - {1}' + "共計" + ': {2}', emptyMsg: "沒有記錄可以顯示" }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, selModel: sm }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [BrandLogoSort], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { BrandLogoSort.width = document.documentElement.clientWidth; this.doLayout(); } } }); ToolAuthority(); //EdmContentStore.load({ params: { start: 0, limit: 25 } }); }); /*************************************************************************************新增*************************************************************************************************/ onAddClick = function () { editFunction(null, BrandLogoSortStore); } /*************************************************************************************編輯*************************************************************************************************/ onEditClick = function () { var row = Ext.getCmp("BrandLogoSort").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert("提示信息", "沒有選擇一行"); } else if (row.length > 1) { Ext.Msg.alert("提示信息", "只能選擇一行"); } else if (row.length == 1) { editFunction(row[0], BrandLogoSortStore); } } onDeleteClick = function () { var row = Ext.getCmp("BrandLogoSort").getSelectionModel().getSelection(); if (row.length < 0) { Ext.Msg.alert("提示信息", "沒有選擇一行!"); } else { Ext.Msg.confirm("確認信息", Ext.String.format("刪除選中 {0} 條數據?", row.length), function (btn) { if (btn == 'yes') { var myMask = new Ext.LoadMask(Ext.getBody(), { msg: "Please wait..." }); myMask.show(); var rowIDs = ''; for (var i = 0; i < row.length; i++) { rowIDs += row[i].data.blo_id + "∑"; } Ext.Ajax.request({ url: '/BrandLogoSort/DeleteBLS', method: 'post', params: { rowID: rowIDs }, success: function (form, action) { myMask.hide(); var result = Ext.decode(form.responseText); if (result.success) { Ext.Msg.alert("提示信息", "刪除成功!"); } else { Ext.Msg.alert("提示信息", "刪除失敗!"); } BrandLogoSortStore.load(); }, failure: function () { myMask.hide(); Ext.Msg.alert("提示信息", "刪除失敗!"); BrandLogoSortStore.load(); } }); } }); } } function Search() { BrandLogoSortStore.removeAll(); var category_id = Ext.getCmp('category_id_ser').getValue(); var brand_id = Ext.getCmp('brand_id_ser').getValue(); if (category_id == null && brand_id == null) { Ext.Msg.alert("提示信息", "請選擇查詢條件"); return; } else if (category_id == null) { Ext.Msg.alert("提示信息", "請先選擇品牌館分類"); //Ext.getCmp('brand_id_ser').setValue(); return; } else { Ext.getCmp("BrandLogoSort").store.loadPage(1, { params: { category_id: Ext.getCmp('category_id_ser').getValue(), brand_id: Ext.getCmp('brand_id_ser').getValue(), } }); } }
var buttonColours=["red","yellow","green","pink"]; var gamePattern=[]; var userClickedPattern=[]; var level=0; var started=false; $("body").keypress(function(){ if(started===false) { $("h1").text("Level "+level); level+=1; nextSequence(); started=true; } }); $("button").on("click", function(){ var userChosenColour =$(this).attr("id"); animatePress(userChosenColour); userClickedPattern.push(userChosenColour); playSound(userChosenColour); var len=userClickedPattern.length; checkAnswer(len-1); }); function nextSequence() { $("h1").text("Level "+level); level+=1; userClickedPattern=[]; var x=Math.random(); x=x*4; var y=Math.floor(x); var randomChosenColour=buttonColours[y]; gamePattern.push(randomChosenColour); animatePress(randomChosenColour); var audio = new Audio(randomChosenColour+ '.mp3'); audio.play(); playSound(randomChosenColour); } function checkAnswer(currentLevel){ if (gamePattern[currentLevel] != userClickedPattern[currentLevel]) { var header = $('body'); header.addClass('game-over'); setTimeout(function() { header.removeClass('game-over'); }, 200); $("h1").text("Game Over!!!!! Please press a key again"); startOver(); } console.log(userClickedPattern.length); console.log(gamePattern.length) if (userClickedPattern.length === gamePattern.length){ setTimeout(function () { nextSequence(); }, 1000); } } //console.log(userClickedPattern); function startOver() { level=0; started=false; gamePattern=[]; } function playSound( name) { var audio = new Audio(name+ '.mp3'); audio.play(); } function animatePress(currentColour) { $("#"+currentColour).fadeOut(200).fadeIn(200); }
import React from 'react'; import { Link }from 'react-router-dom'; class ProjectAPI extends React.Component { constructor(props) { super(props) this.state = { projects: [], repos: [] }; } // Fetches the GitHub API componentDidMount () { fetch('https://api.github.com/users/msagerup/repos') .then(results => { return results.json(); }).then(data => { let repos = data; this.setState({ repos }); }) } render () { let repos = this.state.repos; return ( <div> {repos.map(item => (item.name == this.props.gitcall) ? ( <ul> <li><a target="_blank" href={item.html_url}>{item.html_url}</a></li> <li>Short description: {item.description}</li> <li>created at: {item.created_at}</li> <li>Pushed at: {item.pushed_at}</li> <li>Updated at: {item.updated_at}</li> </ul> ) : null)} </div> ); } } export default ProjectAPI;