text
stringlengths
7
3.69M
$(document).ready( function() { ;nibbleuser = { name : 'nibbleuser', init : function(){ var acode = nibblemain.getParameterByName('acode'); var rcode = nibblemain.getParameterByName('rcode'); if(acode != null && acode != '') { nibbleactivate.init(); }else if(rcode != null && rcode != ''){ nibblereset.init(); }else{ nibblelogin.init(); } } } nibbleuser.init(); });
TQ.overseaPersonnelShiftTree = function (dfop){ var orgSelector; function closeDialog(){ var selectOrgId=$.getSelectedNode(orgSelector).attributes.id; if (selectOrgId!=null){ $("#shiftOrgId").val(selectOrgId); } } $(document).ready(function(){ var orgPangtId = $("#orgPangtId").val(); var orgId = $("#orgId").val(); orgSelector=$("#organizationTree").initTree({rootId:orgPangtId, loadCom:function(){ $.disableNode(orgSelector,orgId); $.disableNode(orgSelector,orgPangtId); } }); $.addClick(orgSelector,closeDialog); jQuery.validator.addMethod("isGridOrganization", function(value, element){ if(value==null||value==undefined||value==""){return true} $.ajax({ async:false, url: PATH + "/sysadmin/orgManage/isGridOrganization.action", data:{ "organization.id":$("#shiftOrgId").val() }, success:function(responseData){ bol = responseData; } }); return bol; }); jQuery.validator.addMethod("isModernOrg", function(value, element){ if($("#orgId").val()==$("#shiftOrgId").val()){ return false; } return true; }); $("#maintainShiftForm").formValidate({ promptPosition: "bottomLeft", submitHandler: function(form) { $(form).ajaxSubmit({ success: function(data){ if(data){ $.messageBox({message:"数据转移成功!"}); $("#overseaPersonnelList").trigger("reloadGrid"); $("#overseaPersonnelMaintanceDialog").dialog("close"); } }, error: function(data){ $.messageBox({ message:data, level: "error" }); } }); }, rules:{"overseaPersonnel.organization.id":{isGridOrganization:true,isModernOrg:true}}, messages:{"overseaPersonnel.organization.id":{isGridOrganization:"数据只能转移得到网格",isModernOrg:"数据不能转移到当前网格"}} }); }); }
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { AppRegistry, Component, Navigator, StyleSheet, TouchableHighlight, Text, } from 'react-native'; import EmployeesList from './EmployeesList'; import DetailsView from './DetailsView'; import { Toolbar } from 'react-native-material-design'; const styles = StyleSheet.create({ container: { flex: 1, }, title: { fontSize: 20, color: 'white', alignSelf: 'flex-start', }, nav: { height: 60, backgroundColor: '#2196f3', }, leftNavButtonText: { fontSize: 18, marginRight: 13, marginTop: 2, }, }); const NavigationBarRouteMapper = { LeftButton(route, navigator, index, navState) { if (index > 0) { return ( <TouchableHighlight underlayColor="transparent" onPress={() => { if (index > 0) { navigator.pop(); } } } > <Text style={ styles.leftNavButtonText }>Back</Text> </TouchableHighlight>); } else { return null; } }, RightButton(route, navigator, index, navState) { return null; }, Title(route, navigator, index, navState) { return <Text style={ styles.title }>Employees</Text>; }, }; class ResumatorMobile extends Component { renderScene(route, navigator) { console.log('This is '.concat(route.component)); return ( <route.component navigator={navigator} {...route.passProps} /> ); } render() { return ( <Navigator style={styles.container} initialRoute={{ component: EmployeesList }} renderScene={this.renderScene} navigationBar={ <Navigator.NavigationBar style={ styles.nav } routeMapper={ NavigationBarRouteMapper } /> } /> ); } } AppRegistry.registerComponent('ResumatorMobile', () => ResumatorMobile);
var map = new L.Map('map', { zoom: 8, fullscreenControl: true, center: [39.3, -82.3], minZoom: 7, maxBounds: [[45.84, -90.38],[35.02,-74.73]], }); /* OSM B&W Basemap no longer used NK update 8-9-17 var OpenStreetMap_BlackAndWhite = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>' }); */ var layerx,layery; var cdblight = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', subdomains: 'abcd', minZoom: 0, maxZoom: 22, maxNativeZoom: 18, }).addTo(map); var esrigray = L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ', maxNativeZoom: 16, maxZoom: 19, }); var esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri', /*maxNativeZoom: 14,*/ maxZoom: 22 }); var labels = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', subdomains: 'abcd', maxNativeZoom: 18, maxZoom: 22, opacity: 0.9, }); //Define style & Load Appalachian Counties outline var appalachia = L.geoJson(null, { style: { color: '#D2B48C', weight: 3, opacity: 0.5, fillOpacity: 0.1, interactive: false, dashArray: "5, 8", } }).addTo(map); var appalachiaData = omnivore.geojson("Ohio_Appalachian_Region.geojson",null, appalachia); /*Load with AJAX Plugin*/ /*var appalachiaData2 = new L.geoJSON.ajax("Ohio_Appalachian_Region.geojson", { style: { color: "purple", } }) .addTo(map); */ var x = 0; //GeoJson layer to hold the csv data var muralLayer = new L.geoJson(null, { pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: 8, fillColor:"#DC143C", color: "#000", weight: 1.5, opacity: 1, fillOpacity: 0.8 }); }, onEachFeature: function(feature, layer) { /*feature.properties && feature.properties.Title && feature.properties.Location*/ if (feature.properties.filename) { // feature.properties.id = x; // x = x+1; /*console.log('getting info');*/ var image = feature.properties.filename; var imageUrl = encodeURI(image); /*console.log(imageUrl);*/ var url = "images/compressed/" + imageUrl; /*console.log(url);*/ var thumbUrl = "images/thumbnails/" + imageUrl; var name = feature.properties.Name; var id = feature.properties.fileid; var lat = feature.geometry.coordinates[1]; var lng = feature.geometry.coordinates[0]; var imageLink = feature.properties.Link; /* console.log(id); */ layer.bindPopup('<a href="' + imageLink + '" target="_blank"><img src="' + url + '" style="width:300px;padding:10px 0;"></a><br/><h4>' + name + '</h4>' + feature.properties.Message + '<br /><span id = "directions"><a href="https://www.google.com/maps/dir//?saddr=My+Location' + '&daddr=' + lat + ',' + lng + '" target="_blank">Directions</a></span></a></li>', { minWidth: 310, maxHeight: 280, }); //var id = feature.properties.ID; var title = feature.properties.Name; //console.log(id); $("#content-6").mThumbnailScroller({ type: "click-25", callbacks:{ onScroll:function(){ console.log("scroll completed"); } }, /*change to "y" for vertical scroller*/ }); $("#mTS_1_container").append('<li class="mTSThumbContainer"><a id ="' + id + '" class="mural-img" href="' + '#' + '"><img src="' + thumbUrl + '" title="' + name + '" height=166px class="mTSThumb" />'); } } }); var muralCluster = new L.markerClusterGroup({ disableClusteringAtZoom: 13, zoomToBoundsOnClick: true, spiderfyOnMaxZoom: false, maxClusterRadius: 60 }).addTo(map); /*CSV LOAD- Features via omnivore and add them to the mural layer*/ var muraldata = omnivore.csv('murals.csv', null, muralLayer); /*scroll to image when mural point is clicked*/ muralLayer.on('click', function(e) { console.log(e); $(".mural-img").removeClass('active'); var muralid = e.layer.feature.properties.id; $("#content-6").mThumbnailScroller("scrollTo", "#" + muralid, { easing: "easeInOutStrong", speed: 1000, callbacks: true }); setTimeout(function() { $("#" + muralid).addClass('active'); }, 100); }); /*Wait for the data to be loaded before doing a few other things.*/ muraldata.on('ready', function() { console.log(muraldata); setTimeout(function() { $("#loader").fadeOut(); },2000); //muralLayer.addTo(map); console.log('mural data ready'); /*console.log(muralLayer); console.log(muraldata);*/ /*map.fitBounds(muralLayer.getBounds(), {maxZoom: 8});*/ //muralCluster.addLayer(muralLayer); muralCluster.on('clusterclick', function(e) { console.log(e); map.flyTo(e.layer.getLatLng(), 14, {duration: 2}) }); /*assign a click event to the mural images*/ $(".mural-img").click(function() { $(".mural-img").removeClass('active'); map.closePopup(); var clickID = ""; clickID = $(this).prop('id'); console.log(clickID); muralLayer.eachLayer(function(layer) { if ((layer.feature.properties.fileid) == clickID) { map.flyTo(layer.getLatLng(), 15); var click = 1; map.on('moveend', function() { if (click === 1) { layer.openPopup(); } }); layer.on('popupopen', function() { click = 2 $("#" + clickID).addClass('active'); }); } }); click = 2; }); }); /*clear active from all mural images on map click or popup close*/ map.on('click', function() { $('.mural-img').removeClass('active') }); map.on('popupclose', function() { $('.mural-img').removeClass('active') }); /*change basemap' to aerial beyond certain zoom*/ map.on('zoom',function() { var currentZoom = map.getZoom(); if (currentZoom > 13 ) { map.removeLayer(cdblight); esri.addTo(map); labels.addTo(map); } if (currentZoom < 14) { map.removeLayer(esri); map.removeLayer(labels); cdblight.addTo(map); } }); /*tabletop loader from the google script form*/ var muralPoints = new L.geoJson().addTo(map); buildMap(); function buildMap() { console.log('building map'); muralPoints.clearLayers(); var tabletop = Tabletop.init({ key: '1VGIfezGZ9cOkPpf5ep5ZG8rvKZs8x2xIYCJJWVDP-bE', simpleSheet: true, //parseNumbers: true, callback: function(data, tabletop) { console.log(data); //create a geojson out of the raw data with geojson.min var muralPointData = GeoJSON.parse(data, {Point: ['Latitude', 'Longitude']}); console.log(muralPointData); var points = new L.geoJson(muralPointData, { pointToLayer: function(feature, latlng) { return new L.circleMarker(latlng, { radius: 8, fillColor:"#DC143C", color: "#000", weight: 1.5, opacity: 1, fillOpacity: 0.8 }); }, onEachFeature: function(feature, layer) { var popup = "<iframe src='https://drive.google.com/file/d/" + layer.feature.properties.fileid +"/preview' width='320' height='240' frameborder='0'></iframe> \ <br /><h5>" + layer.feature.properties.Name + "</h5>" + layer.feature.properties.Message; layer.bindPopup(popup, { minWidth:320 }); } }); //muralPoints.addLayer(points); points.on('click', function(e) { console.log(e); $(".mural-img").removeClass('active'); var muralid = e.layer.feature.properties.fileid; $("#content-6").mThumbnailScroller("scrollTo", "#" + muralid, { easing: "easeInOutStrong", speed: 1000, callbacks: true }); setTimeout(function() { $("#" + muralid).addClass('active'); }, 100); }); muralCluster.addLayer(points); $("#fileWarning").html(''); } }); } /*Checks lat/long on map map.on('click',function(e){ alert("Lat:" + e.latlng.lat + "long:" + e.latlng.lng) }); */
export const GET_INITIAL_BEATMAPS = 'get_initial_beatmaps'; export const CHECK_VALID_MAP = 'check_valid_map'; export const GET_NEW_BEATMAPS = 'get_new_beatmaps'; export const CLEAR_BEATMAPS_BEFORE_SEARCH = 'clear_beatmaps_before_search';
import Template from "./template"; import paper from "paper"; import ComponentPort from "../core/componentPort"; export default class DropletGeneratorFlowFocus extends Template { constructor() { super(); } __setupDefinitions() { this.__unique = { position: "Point" }; this.__heritable = { componentSpacing: "Float", oilChannelWidth: "Float", waterChannelWidth: "Float", length: "Float", radius: "Float", angle: "Float", height: "Float", rotation: "Float" }; this.__defaults = { componentSpacing: 1000, oilChannelWidth: 0.4 * 1000, waterChannelWidth: 0.2 * 1000, length: 3 * 1000, radius: 500, angle: 45, height: 250, rotation: 0 }; this.__units = { componentSpacing: "&mu;m", oilChannelWidth: "&mu;m", height: "&mu;m", waterChannelWidth: "&mu;m", radius: "&mu;m", length: "&mu;m", rotation: "&deg;", angle: "&deg;" }; this.__minimum = { componentSpacing: 0, oilChannelWidth: 1, waterChannelWidth: 1, length: 1, radius: 1, angle: 1, rotation: 0 }; this.__maximum = { componentSpacing: 10000, oilChannelWidth: 2000, waterChannelWidth: 2000, length: 20000, angle: 360, height: 1200, radius: 2000, rotation: 360 }; this.__featureParams = { componentSpacing: "componentSpacing", position: "position", oilChannelWidth: "oilChannelWidth", waterChannelWidth: "waterChannelWidth", length: "length", angle: "angle", height: "height", rotation: "rotation", radius: "radius" }; this.__targetParams = { componentSpacing: "componentSpacing", oilChannelWidth: "oilChannelWidth", waterChannelWidth: "waterChannelWidth", length: "length", angle: "angle", height: "height", rotation: "rotation", radius: "radius" }; this.__placementTool = "componentPositionTool"; this.__toolParams = { position: "position" }; this.__renderKeys = ["FLOW"]; this.__mint = "DROPLET GENERATOR FLOW FOCUS"; } getPorts(params) { let ports = []; ports.push(new ComponentPort(0, 0, "1", "FLOW")); //Out return ports; } render2D(params, key) { let pos = params["position"]; let x = pos[0]; let y = pos[1]; let color = params["color"]; let oilChannelWidth = params["oilChannelWidth"]; let waterChannelWidth = params["waterChannelWidth"]; let length = params["length"]; let angle = params["angle"]; let radius = params["radius"]; let rotation = params["rotation"]; let ret = new paper.CompoundPath(); // middle path let topLeft = new paper.Point(x - length / 3 - 2 * length, y - waterChannelWidth / 2); let bottomRight = new paper.Point(x, y + waterChannelWidth / 2); ret.addChild(new paper.Path.Rectangle(topLeft, bottomRight)); let circ = new paper.Path.Circle(new paper.Point(x - length / 3 - 2 * length, y), radius); ret.addChild(circ); // top tilt path let Hlength = length / Math.cos((angle * Math.PI) / 180); topLeft = new paper.Point(x - length / 3 - Hlength, y - oilChannelWidth / 2); bottomRight = new paper.Point(x - length / 3, y + oilChannelWidth / 2); let tiltBlock = new paper.Path.Rectangle(topLeft, bottomRight); tiltBlock.rotate(angle, new paper.Point(x - length / 3, y)); ret.addChild(tiltBlock); // bottom tilt path tiltBlock = new paper.Path.Rectangle(topLeft, bottomRight); tiltBlock.rotate(-angle, new paper.Point(x - length / 3, y)); ret.addChild(tiltBlock); // top part let disFromMid = Hlength * Math.sin((angle * Math.PI) / 180); let angleS = 90 - angle; let seamCover = (oilChannelWidth / 2) * Math.tan((angleS * Math.PI) / 180); topLeft = new paper.Point(x - length / 3 - length - oilChannelWidth / 2, y - disFromMid - (2 * length) / 3 + seamCover); bottomRight = new paper.Point(x - length / 3 - length + oilChannelWidth / 2, y - disFromMid + seamCover); ret.addChild(new paper.Path.Rectangle(topLeft, bottomRight)); topLeft = new paper.Point(x - length / 3 - 2 * length, y - disFromMid - (2 * length) / 3 + seamCover); bottomRight = new paper.Point(x - length / 3 - length - oilChannelWidth / 2, y - disFromMid - (2 * length) / 3 + oilChannelWidth + seamCover); ret.addChild(new paper.Path.Rectangle(topLeft, bottomRight)); circ = paper.Path.Circle(new paper.Point(x - length / 3 - 2 * length, y - disFromMid - (2 * length) / 3 + seamCover + oilChannelWidth / 2), radius); ret.addChild(circ); // bottom part topLeft = new paper.Point(x - length / 3 - length - oilChannelWidth / 2, y + disFromMid + (2 * length) / 3 - seamCover); bottomRight = new paper.Point(x - length / 3 - length + oilChannelWidth / 2, y + disFromMid - seamCover); ret.addChild(new paper.Path.Rectangle(topLeft, bottomRight)); topLeft = new paper.Point(x - length / 3 - 2 * length, y + disFromMid + (2 * length) / 3 - seamCover); bottomRight = new paper.Point(x - length / 3 - length - oilChannelWidth / 2, y + disFromMid + (2 * length) / 3 - oilChannelWidth - seamCover); ret.addChild(new paper.Path.Rectangle(topLeft, bottomRight)); circ = paper.Path.Circle(new paper.Point(x - length / 3 - 2 * length, y + disFromMid + (2 * length) / 3 - seamCover - oilChannelWidth / 2), radius); ret.addChild(circ); //Rotate the geometry ret.rotate(-rotation, new paper.Point(pos[0], pos[1])); ret.closed = true; ret.fillColor = color; return ret; } render2DTarget(key, params) { let render = this.render2D(params, key); render.fillColor.alpha = 0.5; return render; } }
../../../../../shared/src/App/RouterBuilder/getPornstarRoutes.js
define([ 'underscore', 'backbone', 'models/scope' ], function(_, Backbone, Scope){ var ScopesCollection = Backbone.Collection.extend({ // Reference to this collection's model. model: Scope, url: "requests/api/scopes" }); return new ScopesCollection(); });
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var MatchEventSchema = new Schema({ type: String, timestamp: Number, match: {type: Schema.Types.ObjectId, ref: 'Match'}, matchtime: Number, data: Schema.Types.Mixed, active: Boolean }); module.exports = mongoose.model('MatchEvent', MatchEventSchema);
$(function(){ $('.myModal').on('click', function(){ $('.overlay').addClass('active'); $('.modal').css({ display : 'block' }).animate({ top : '50%', opacity : 1 }, 400); }); $('.overlay').on('click', function(){ $('.modal').animate({ top: '30%', opacity: 0 }, 400, function(){ $('.overlay').removeClass('active'); $(this).removeAttr('style'); }); }); });
import React, { useEffect, useReducer } from "react"; import { Grid, List, RadioGroup, Backdrop, Typography, } from "@material-ui/core"; import { getClasses, getStudentsByClassId } from "../providers/classProvider" import { getStudentAttendanceStatus } from "../providers/studentProvider"; import { makeStyles } from "@material-ui/styles" import { updateAttendanceStatus } from "../providers/studentClassProvider"; import style from "./ClassListStyle" import reducer from "../reducers/studyClassReducer"; import StudyClass from "./StudyClass"; import StudentList from "./StudentList"; const useStyles = makeStyles(() => style) const StudentSearch = ({ onFilterChange, filter }) => { const classes = useStyles(); return <> <div className={classes.studentSearch}> <div > <input type="text" onChange={onFilterChange} value={filter} placeholder="Filtrar pelo nome do(a) aluno(a)" /> </div> </div> </> } const ClassList = (props) => { const classes = useStyles(); const [state, dispatch] = useReducer(reducer, { studyClasses: [], currentClass: null, selectedClassId: 0, filteredStudents: [], filter: "", loading: false }) useEffect(() => { dispatch({ type: "START_GET_CLASSES" }); getClasses() .then(res => { dispatch({ type: "FINISH_GET_CLASSES", payload: { studyClasses: res.data } }) }) .catch(err => console.error(err)) }, []) const handleClassChange = (id) => { dispatch({ type: "START_SELECT_CLASS", payload: { id } }); getStudentsByClassId(id) .then(res => { dispatch({ type: "FINISH_SELECT_CLASS", payload: { currentClass: res.data } }); }) .catch(err => console.log(err)); } const handleChangeStudentPresence = async (event, studentId, isPresent) => { let requestPayload = { classId: state.currentClass.classId, studentId: studentId, isPresent: !isPresent } setTimeout(() => { if (state.isPresent === isPresent) { dispatch({ type: "UPDATE_STATUS_START" }); } }, 500) await updateAttendanceStatus(requestPayload).then(() => { getStudentAttendanceStatus(studentId, state.currentClass.classId).then(res => { let studentIndex = state.filteredStudents.findIndex(x => x.id === studentId) if (studentIndex !== -1) { let newFilteredStudents = state.filteredStudents; newFilteredStudents[studentIndex]["isPresent"] = res.data.isPresent; newFilteredStudents = Array.from(newFilteredStudents); //Javascript forgot that the new Array is an actual array. This line JS reminds of it. dispatch({ type: "FINISH_UPDATE_STATUS", payload: newFilteredStudents }) } }) }) .catch(err => console.error(err)) } const handleFilterChange = (event) => { dispatch({ type: "FILTER_STUDENTS", payload: { filter: event.target.value } }) } return <> <div style={{ display: "flex", justifyContent: "center" }}> <Grid container style={{ width: "80vw" }}> <Grid item sm={4} xs={12} > <div style={{ position: "-webkit-sticky", top: 0, backgroundColor: "#ededed" }}> <h3 style={{ padding: 20, fontSize: 25, textAlitn: "center", display: "flex", justifyContent: "center" }}>Aulas</h3> <List style={{ position: "sticky" }}> <RadioGroup> {state.studyClasses ? state.studyClasses.map(currentClass => ( <StudyClass discipline={currentClass.discipline} id={currentClass.id} date={currentClass.date} onSelect={handleClassChange} selectedClassId={state.selectedClassId} /> )) : "loading" } </RadioGroup> </List> </div> </Grid> <Grid item sm={8} xs className={classes.studentsList} > {state.currentClass && <> <Typography align="center" style={{ fontSize: 30 }}>{state.currentClass.discipline} - {new Date(state.currentClass.date).toLocaleDateString()}</Typography> <StudentSearch onFilterChange={handleFilterChange} filter={state.filter} /> </>} <div style={{ overflow: "scroll", height: "60%" }}> <StudentList filteredStudents={state.filteredStudents} onTogglePresence={handleChangeStudentPresence} /> </div> </Grid> </Grid> </div> <Backdrop style={{ zIndex: 10 }} open={state.loading} /> </>; } export default ClassList;
//获取经典图片的ID------------------- var urlStr=decodeURI(window.location.href).split("?")[1]; var picID = urlStr.split("&")[0].split("=")[1]; var Channel=urlStr.split("&")[1].split("=")[1]; console.log(picID); var indexOf=null, sumPic=null, picSum=null, // picUrl='https://dev-api.otosaas.com/menpiao/v1/scenic/', picUrl= locationUrl + '/menpiao/v1/scenic/', num=null, myScroll; //对农行的特别处理---- $('#topTitle_abc').hide(); //根据相对应的景点获取图片----------- $.ajax({ url:picUrl+picID, type:'GET', data:{ channel: Channel }, dataType:'json', success:function(data){ $('.picList').html(''); console.log(data); var picStr=''; var data=data.data, nameTitle=data.name; picSum=data.images.length; $('.picC').html(nameTitle); $('.picR').html(picSum+'张'); // for(var i=0;i<picSum;i++){ // picStr+='<li><img src=" '+data.images[i]+' "></li>' // } //$('.picList').append(picStr); var $wrap = $('.picList') $(data.images).each(function(i, o) { var $child = $('<li><img /></li>') $child.find('img').attr('src', o) $wrap.append($child.show()) var $single=$('<div class="picSlingerWrap"><img /></div>') $single.find('img').attr('src', o) $('.picSlingers').append($single) }) // $('.picSlingers').slick() }, error:function(){ console.log('错误!') } }) //点击回到详情页 ------------------- $('.pic_header .picL').on('click',function(){ window.location.href='details.html?cityID='+picID+"&channel="+Channel; }); //点击图像,切换-------------------- $('.picList').on('click','li',function(){ var index=$(this).index(); indexOf=$(this).index()+1;//console.log(indexOf) $('.picDetails').css({ display:'block' }); var srcUrl=$('.picList li').eq(index).children('img').attr('src');//console.log(srcUrl); $('.picSlingers img').attr('src',srcUrl); num=picSum; sumPic=indexOf+'/'+num; $('.goBack span').html(sumPic); $('.goBack img').click(function(){ $('.picDetails').css({ display:'none' }); }) }); // //点击蒙版大图消失----- $('.picSlingerWrap').on('click',function(){ $('.picDetails').css({ display:'none' }); })
import React, { Component } from 'react'; import { GoogleMap, LoadScript } from '@react-google-maps/api'; export default class HostelMap extends Component { render() { return ( <div> <LoadScript id="script-loader" googleMapsApiKey="AIzaSyCM4v1s2BnFzSf0Kp5lMJRH1Qbvs_Yc74I" > <GoogleMap id='example-map' > ...Your map components </GoogleMap> </LoadScript > </div > ) } }
export { default } from "./useSort";
'use strict'; const express = require('express'); const Multer = require('multer'); const {Storage} = require('@google-cloud/storage'); const path = require('path'); const bodyParser = require('body-parser'); const firebase = require("firebase"); // Add the Firebase products require("firebase/firestore"); const {Firestore} = require('@google-cloud/firestore'); // Load environment variables const dotenv = require('dotenv'); dotenv.config(); // Instantiate a storage client const googleCloudStorage = new Storage({ projectId: process.env.GOOGLE_CLOUD_PROJECT, keyFilename: process.env.GCLOUD_KEY_FILE }); // Create a new firestore client const firestore = new Firestore({ projectId: process.env.GOOGLE_CLOUD_PROJECT, keyFilename: process.env.GCLOUD_KEY_FILE }); // Instantiate an express server const app = express(); app.use(bodyParser.urlencoded({ extended: false })); // Multer is required to process file uploads and make them available via // req.files. const multer = Multer({ storage: Multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed } }); // A bucket is a container for objects (files). const bucket = googleCloudStorage.bucket(process.env.GCLOUD_STORAGE_BUCKET); // Display a form for uploading files. app.get("/", (req, res) => { res.sendFile(path.join(`${__dirname}/index.html`)); }); // Process the file upload and upload to Google Cloud Storage. app.post("/upload", multer.single("file"), (req, res, next) => { // Create a new blob in the bucket and upload the file data. const blob = bucket.file(req.file.originalname); // The public URL can be used to directly access the file via HTTP. const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`; if (!req.file) { res.status(400).send("No file uploaded."); return; } // Make sure to set the contentType metadata for the browser to be able // to render the file instead of downloading the file (default behavior) const blobStream = blob.createWriteStream({ metadata: { contentType: req.file.mimetype } }); blobStream.on("error", err => { next(err); return; }); blobStream.on("finish", () => { // The public URL can be used to directly access the file via HTTP. // const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`; blob.makePublic(); }); blobStream.end(req.file.buffer); var collection; var document; async function writeToFirestore() { // Obtain a document reference. collection = firestore.collection('userdata'); document = collection.doc(); // Enter new data into the document. await document.set({ source_language: req.body.srclang, target_language: req.body.tgtlang, bucket_name: `${bucket.name}`, file_name: req.file.originalname, public_url: `${publicUrl}` }); } writeToFirestore().catch(console.error); var response = { source_language:req.body.srclang, target_language:req.body.tgtlang, bucket_name:`${bucket.name}`, file_name:req.file.originalname, public_url:`${publicUrl}`, document_id: `${document.id}` }; console.log("Source Language: " + response.source_language); console.log("Target Language: " + response.target_language); console.log("Bucket Name: " + response.bucket_name); console.log("File Name: " + response.file_name); console.log("Public Url: " + response.public_url); console.log('Document Id:', response.document_id); response = { source_language:req.body.srclang, target_language:req.body.tgtlang, message:`Success! File uploaded to ${publicUrl} and database updated with ${document.id}` }; res.end(JSON.stringify(response)); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); console.log("Press Ctrl+C to quit."); }); module.exports = app;
var rp = require('request-promise'); try { var CONFIG = require('../config.json'); } catch(e) { console.log('config.json is not available, therefore I will use an environment variable.'); } exports.postToChannel = function(channel, emoji, botName, message) { var body = { channel: channel, icon_emoji: emoji, username: botName, text: message, }; return rp({ method: 'POST', uri: CONFIG.SLACK.WEBHOOK_URL, body: body, json: true }) };
var expect = chai.expect; describe('Test de suma', function(){ it('resultado positivo', function(){ var a = suma(2,3); expect(a).to.be.above(0); }) it('resultado negativo', function(){ var a = suma(-1,-3); expect(0).to.be.above(a); }) }); describe('Test de Resta', function(){ it('resultado positivo',function(){ var a = resta(6,2); console.log(a) expect(a).to.be.above(0); }) it('resultado negativo',function(){ var a = resta(-4,-4); console.log(a) expect(a).to.be.equal(0); }) });
import React from 'react'; import "./App.css" import Counter from "./component/counter" class App extends React.Component { constructor(props) { super(props); this.state = { count1: 0, count2: 0 } }; render() { return ( <div className="text-center text-secondary "> <h1>Counter</h1> <Counter count={this.state.count1} increment={() => { if (this.state.count1 < this.state.count2) this.setState({ count1: this.state.count1 + 1 }) if (this.state.count1 === this.state.count2) this.setState({ count1: this.state.count1 + 1, count2: this.state.count2 + 1 }) }} substract={() => { if (this.state.count1 > 0) this.setState({ count1: this.state.count1 - 1 }) }} /> <Counter count={this.state.count2} increment={() => { if (this.state.count2 <= this.state.count1) this.setState({ count2: this.state.count2 + 1 }) }} substract={() => { if (this.state.count2 > 0) this.setState({ count2: this.state.count2 - 1 }) if (this.state.count2 === this.state.count1) this.setState({ count2: this.state.count2 - 1, count1: this.state.count1 - 1 }) }} /> </div> ); }; }; export default App
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var R = require('./rl.js'); var Master = require('./master.js'); var utils = require('./utils.js'); var mnist = require('mnist'); var graphRep = { cost: 0, loss: 0, total: 0, totalTrained: 0, batches: 0, forward: function(graph, graphMats, batch) { var hiddens = utils.sigmoidLayer(graph, graphMats, batch.inputs, 'W1', 'b1') this.cost = utils.softmaxLayer(graph, graphMats, hiddens, batch.labels, 'W2', 'b2'); this.totalTrained += 10; this.total += this.cost; }, reportCost: function(cost) { this.loss += cost; this.batches += 1; if(this.batches >= 1000) { console.log(this.loss / this.batches); this.loss = 0; this.batches = 0; } }, params: { 'W1': { 'nr': 784, 'nc': 10 }, 'b1': { 'nr': 10, 'nc': 1 }, 'W2': { 'nr': 10, 'nc': 10 }, 'b2': { 'nr': 10, 'nc': 1 } }, startImmediately: true, inputSize: 784 } var hyperparams = { lr: 0.01, initMu: 0, initStd: 1, batchSize: 10, epochs: 100, warmup: 1, } var set = mnist.set(10000, 1); var data = {}; data.labels = []; data.inputs = []; for(var j in set.training) { data.inputs.push(set.training[j].input); data.labels.push(set.training[j].output); } server.listen(80); var test = new Master(io, hyperparams, data, graphRep); test.createGraph(); var time = new Number(new Date()) test.addSocketCallBacks() console.log(new Number(new Date())) app.get('/', function (req, res) { res.send("hello"); });
// Write a program that prints a staircase of size n function staircase(n) { // DO stuff //set pointer for current step count let pointer = n - 1; // loop up to n while (pointer >= 0) { //create string to be printed let level = ''; // loop through printing space for pointer number and hash for n minus pointer for (let i = 0; i < n; i++) { if (i < pointer) { level = level + ' '; } else { level = level + '#'; } } // print level console.log(level); // descrease pointer pointer--; } } staircase(6); // # // ## // ### // #### // ##### // ###### staircase(10); // # // ## // ### // #### // ##### // ###### // ####### // ######## // ######### // ##########
var dir_6ca64b3911715fe1678523df834b8cf4 = [ [ "pdebutton", "dir_de71c7dbf62badf80ed65af81648ff00.html", "dir_de71c7dbf62badf80ed65af81648ff00" ], [ "pdedialogs", "dir_cdba9aa89c628c890673653ae8afb655.html", "dir_cdba9aa89c628c890673653ae8afb655" ], [ "pdeinputfields", "dir_afd0c5eca51dedc083dd02b59d04c57f.html", "dir_afd0c5eca51dedc083dd02b59d04c57f" ], [ "pdelogin", "dir_d31a71db8ca3818226810f342b5af278.html", "dir_d31a71db8ca3818226810f342b5af278" ], [ "pdesectionedbutton", "dir_8d5bd76d716f0b089ca483120ad92966.html", "dir_8d5bd76d716f0b089ca483120ad92966" ], [ "pdeslider", "dir_1174e55fad3e1214d1ffd0cb224daeef.html", "dir_1174e55fad3e1214d1ffd0cb224daeef" ], [ "MetaphorsGenericActivity.java", "_metaphors_generic_activity_8java.html", [ [ "MetaphorsGenericActivity", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1genericstyle_1_1_metaphors_generic_activity.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1genericstyle_1_1_metaphors_generic_activity" ] ] ], [ "StageGenericActivity.java", "_stage_generic_activity_8java.html", [ [ "StageGenericActivity", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1genericstyle_1_1_stage_generic_activity.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1genericstyle_1_1_stage_generic_activity" ] ] ] ];
(function(app) { 'use strict'; app.makePeriodActive = function(id) { console.log(id); app.activatePeriod(id, function() { app.route('selectActivePeriod'); }); } app.populateSelectActivePeriodTableView = function() { var periods = app.db.getBudgetingPeriods(); var activePeriod = app.getActiveBudgetPeriod(); var table = document.getElementById('selectActivePeriodsTable'); periods.forEach(function(period, idx) { var row = document.createElement('tr'); var col1 = document.createElement('td'); var col2 = document.createElement('td'); var col3 = document.createElement('td'); var html; if (activePeriod && activePeriod.startDate.toString() === period.startDate.toString() && activePeriod.endDate.toString() === period.endDate.toString()) { html = 'Active'; } else { html = '<a href="javascript:frugalisApp.route(\'makePeriodActive\', ' + idx + ')">'; html += 'Make&nbsp;active</a>'; } col1.innerHTML = app.formatDate(period.startDate) col2.innerHTML = app.formatDate(period.endDate); col3.innerHTML = html row.appendChild(col1); row.appendChild(col2); row.appendChild(col3); table.appendChild(row); }); } app.showSelectActivePeriodTableView = function() { var url = './views/budgeting-periods/select-active-period.html'; app.getViewHtml(url, function(err, response) { var target = document.getElementById('appView'); if (err) { target.innerHTML = err; } else { target.innerHTML = response; app.zoomIn(target); app.populateSelectActivePeriodTableView(); } }); }; })(frugalisApp);
import { useStaticQuery, graphql } from 'gatsby' export const AllGravityData = () => { const { allGfForm } = useStaticQuery( graphql` query { allGfForm { edges { node { ...GravityFormComponent } } } } ` ) return allGfForm }
import {IWouldLike} from "../global/IWouldLike"; export const Guide = { template: ` <transition name="fade"> <div class="Guide"> <div class="TextPanel"> <div class="TextBlock"> <h1>Introduction</h1> <p> Before I start, it is important to say that this is not a feature list or an explanation of all the features this application has. Here, I will explain how a certain feature works. If you want to know why a certain feature works as it works, check out the <router-link :to="createStaticUrl('features')">Features </router-link> section. And as with all guides, this one will be interesting but also boring in some parts, but it is very important that you read it because it may help you a lot in finding what you want in eBay. </p> <p> Some of you may also think that a guide is not necessary because all of us use Google and we already know how to search for things on the internet. Many websites have their own search feature that allows us to search their website and most of them are pretty simple to use. But this search engine is not the same as most of them. On <i-would-like /> you have the ability to search most of eBay sites (more of them are coming) and, in order to make the search more accessible to as many people as possible, you can only search one eBay site at a time. As explained in the <router-link :to="createStaticUrl('features')">Features </router-link> section, this is not just a copy of eBay search; it's an extension of it. Therefor, I have implemented features that eBay does not have and more of them are coming in the future. </p> <p> Because of that, I advise you to not just skim trough this guide but to read it, try some examples by yourself and maybe find some things that the application can do that even I don't know about. At the end of this guide, you can check out the <router-link :to="createStaticUrl('for-you')">for You</router-link> section to see what new features are awaiting for you in the future. Also, there is a proof of concept and the end of this guide that proves that certain features work as this guide says. </p> </div> <div class="TextBlock"> <h1>Sorting</h1> <div class="DisplayImage"> <img src="/images/application_static/filters.png" /> </div> <p> Sorting allows you to sort the results by price and quality but it does not work the same as on eBay. If you sort by lowest price, the search will try to return only the relevant results that you actually want and not the ones that you don't want. For example, if you search for an <span class="Highlight">iphone 7</span> on eBay and sort it by lowest price, the first results will be iPhone masks or other utilities, and it could also include auction listings which is not everybodies desire. What you actually want is a list of Apple Iphone 7 smartphones. If you sort by lowest price on <i-would-like />, it will try to sort the results and give the lowest price of the actual <span class="Highlight">iphone 7</span> and ignore the rest. It may not always work the way you expect but there are other features that you can use to sort the results even more and get what you want. More on that later in other chapters. </p> <p> Sorting by highest price works the same way as sorting by lowest price. Sorting by fixed price tries to filter out only the items that have a fixed price (items that are not auctions). This feature is also one of the features that is not supported by eBay. The last way you can sort is by high quality. The reason why I putted only one quality sort is that the condition of the item combined with the aspects of the item can be a very powerful way of finding the exact items that you are looking for. For that reason, I will wait for you to tell me your wishes about this and see where I will go from there. </p> </div> <div class="TextBlock"> <h1>Modifying the results</h1> <div class="DisplayImage"> <img src="/images/application_static/modifiers.png" /> </div> <p> While sorting the results allows you to sort them in a certain way, modifying them means that you put in or take out some items from the search result. It is best to explain them one by one to see the big picture behind them. </p> <h2 class="InnerEntry">Duplicated items</h2> <p class="InnerEntry"> When putting an item on eBay, some sellers put more than one entry of the same item. That increases the possibility of placing their item on the top of the search. The problem for the end user, but also for other sellers and resellers is that they have to sim trough a lot of items before they find the one(s) they are looking for. If you click on the <span class="Highlight">Show duplicates</span>, that will turn on the duplicates hiding, the listing will reload and the duplicates will disappear. This is also one of the features that eBay does not provide. </p> <h2 class="InnerEntry">Including eBay site native language items</h2> <p class="InnerEntry"> If you try searching items on eBay Germany, you will see that the site is in german including the item listings. But if you try to search it on english, there are some items that are found. That is because some sellers put items on german language only, some on english only and some on both. Because of that, your search query might not return all the relevant results. If you tick the <span class="Highlight">Only english</span> button, searching both english and the language of the site will be turned on. </p> <p class="InnerEntry"> <i-would-like /> will translate the search query to the language of the eBay site that you wish to search and conduct the search in both english and the eBay sites language. For example, if you search for a <span class="Highlight">pocket watch</span> on eBay Italy, <i-would-like /> will translate that to <span class="Highlight">orologio da tasca</span> under the hood and do two searches; one in english and one in italian. After that, it will filter out the items that are identical and display the search results for you. </p> <p class="InnerEntry"> NOTE: <span class="Highlight">This feature is still experimental and I still haven't decided is it actually useful for you. It also takes a really long time since the application has to do multiple queries for each query translation. Please, don't hesitate to check out the <router-link :to="createStaticUrl('for-you')">For you</router-link> section and tell me what you think. </span> </p> <h2 class="InnerEntry">SQF or Search query filter</h2> <p class="InnerEntry"> If you tried the above example with <span class="Highlight">iphone 7</span> sorted by lowest price, you have noticed that the final search result still has some items that are not an actual iPhone 7 smartphone. The reason for that is of technical nature. When the application asks for every iPhone 7 smartphone, eBay searches their database for all occurrences of a string of<span class="Highlight">iphone 7</span> characters in the title of each item. That means that the final result set will have items like iphone 7 masks, protective cases, earpieces or similar items. </p> <p class="InnerEntry"> Because of that reason, I have a list of common phrases that are not valid for a search for iphone smartphones. One of them is the word <span class="Highlight">mask or masks (plural)</span>. When you search for an iPhone, the title of each found item is searched for that word and excluded from the final search result. Other phrases include <span class="Highlight">screen, shell, adapter, cable</span> and similar words. That means if you use this modifier, you will get the most accurate search results for an iPhone. SQF also includes other smartphone manufacturers like Samsung, Huawei, ZTE and others. </p> <p class="InnerEntry"> But that doesn't mean that you cannot search for an actual <span class="Highlight">iphone 7 mask</span>. If the application determines that there is a word in the search query that has also been excluded, it does not implement SQF on it. </p> </div> <div class="TextBlock"> <h1>Translations</h1> <p> Everything in <i-would-like /> is translated to multiple languages. You can see the list of languages that are supported by clicking on the button in the upper right corner. </p> <div class="DisplayImage"> <img src="/images/application_static/languageBar.png" /> </div> <p> Because of the fact that everything is translated, you can choose any eBay site currently supported and it will translate it for you to the language of your choice. In practice, if you choose your site language to be french and search eBay Germany, the search results will be translated from german to french. This is valid for every language that is supported. </p> <p> There is also one hidden feature that is enabled by default. If you search, for example <span class="Highlight">orologio da tasca</span>, and choose eBay Great Britain, the search query will be translated to english and the search will be made in english. This feature is enabled for every language, not just the supported site languages. </p> </div> <div class="TextBlock"> <h1>Proof of concept</h1> <p> So, how to combine all of these features to find what you are looking for on eBay? In this part, I will try to show you using <i-would-like /> on a practical example Since I have used the <span class="Highlight">iphone 7</span> example throughout this guide, I will use it here because it best describes the power of searching on <i-would-like /> </p> <p> A practical question that someone might ask is: </p> <p> <span class="Highlight">"I would like an iphone 7 with a fixed price sorted by lowest price first."</span> </p> <p> To make the most of <i-would-like />, type in your search in the search bar, choose <span class="Highlight">Lowest price</span> and <span class="Highlight">Fixed price</span> sorting. After that, click on the <span class="Highlight">Show duplicates</span> toggle button which hides duplicated items. After that, click <span class="Highlight">SQF off</span> which will turn SQF on. Click the search button and choose any eBay site that you want. </p> <p> Now try to do the same on the actual eBay site that you searched and you will see that <i-would-like /> has much finer grained result set than the actual eBay. Try to play with it some more and, if there is a feature that you would like me to implement, check out the <router-link :to="createStaticUrl('for-you')">for You</router-link> section and tell me about it. I am always glad to hear from you. </p> </div> </div> </div> </transition> `, methods: { createStaticUrl(path) { return `/${this.$localeInfo.locale}/${path}`; } }, components: { 'i-would-like': IWouldLike, } };
import React from 'react'; const Pagination = ({ currentPage, pageNumbers, setPage }) => { const prevClassName = currentPage === 1 ? 'prev arrow disabled' : 'prev arrow'; const nextClassName = currentPage === pageNumbers.length ? 'next arrow disabled' : 'next arrow'; return ( <div className="pagination"> <div onClick={() => setPage('prev')} className={prevClassName}> {'<'} </div> {pageNumbers.map((el, ind) => { const pageNumberClassName = ind + 1 === currentPage ? 'pageNumbers arrow active' : 'pageNumbers arrow'; return ( <div className={pageNumberClassName} onClick={() => setPage(ind + 1)} key={ind} > {ind + 1} </div> ); })} <div onClick={() => setPage('next')} className={nextClassName}> {'>'} </div> </div> ); }; export default Pagination;
module.exports.GenericEmbed = (title, description, options = {}) => ({ embed: { color: 0x32a0e5, author: { name: title, icon_url: 'https://cdn.discordapp.com/app-assets/593852428626165760/593854065776132097.png' }, description, ...options } }) module.exports.SuccessEmbed = (title, description, options = {}) => ({ embed: { color: 0x32e554, author: { name: title, icon_url: 'https://cdn.discordapp.com/app-assets/593852428626165760/593854065398513706.png' }, description, ...options } }) module.exports.WarningEmbed = (title, description, options = {}) => ({ embed: { color: 0xe5a032, author: { name: title, icon_url: 'https://cdn.discordapp.com/app-assets/593852428626165760/593854065729994762.png' }, description, ...options } }) module.exports.GenericErrorEmbed = (description, title = 'Something went wrong', options = {}) => ({ embed: { color: 0xe84040, author: { name: title, icon_url: 'https://cdn.discordapp.com/app-assets/593852428626165760/593854065239261193.png' }, description, ...options } }) module.exports.SyntaxErrorEmbed = (usage, options = {}) => ({ embed: { color: 0xe84040, author: { name: 'Invalid Syntax', icon_url: 'https://cdn.discordapp.com/app-assets/593852428626165760/593854065239261193.png' }, description: [ '**Example Usage:**', usage ].join('\n'), ...options } })
import {ImmutablePropTypes, PropTypes} from 'src/App/helpers' import { immutableArchiveFilmsModel, immutablePageTextModel, immutableNichesListWithLetterModel, pageRequestParamsModel, immutableTagArchiveListModel, immutableSortListModel, immutableTagArchiveListOlderOrNewerModel, } from 'src/App/models' import {immutableVideoItemModel} from 'src/generic/VideoItem/models' export const model = process.env.NODE_ENV === 'production' ? null : ImmutablePropTypes.exact({ isLoading: PropTypes.bool, isLoaded: PropTypes.bool, isFailed: PropTypes.bool, tagId: PropTypes.number, currentPage: PropTypes.string, currentSubPage: PropTypes.string, lastPageRequestParams: PropTypes.nullable(pageRequestParamsModel), pageNumber: PropTypes.number, pagesCount: PropTypes.number, pageText: PropTypes.nullable(immutablePageTextModel), nichesListWithLetter: immutableNichesListWithLetterModel, tagArchiveList: immutableTagArchiveListModel, archiveFilms: PropTypes.nullable(immutableArchiveFilmsModel), tagArchiveListOlder: immutableTagArchiveListOlderOrNewerModel, tagArchiveListNewer: immutableTagArchiveListOlderOrNewerModel, itemsCount: PropTypes.number, videoList: ImmutablePropTypes.listOf(immutableVideoItemModel), randomWidthList: PropTypes.nullable(ImmutablePropTypes.listOf(PropTypes.number)), sortList: immutableSortListModel, sponsorsList: immutableSortListModel, durationList: immutableSortListModel, })
var express = require('express'); var mongoose = require('mongoose'); var path = require('path'); var db = require('db/config.js'); var dbName = 'banal-conga-line'; var portNum = 8000; // Start Express server var app = express(); // Add middleware require('./middleware.js')(app, express); //TODO: make sure path to middleware is correct // Request handlers // Set app to listen app.listen(portNum); // Export app module.exports = app;
/** * @jsx React.DOM */ /** * Created by Drew 1/6/2015 */ var React = require('react'), RouterMixin = require('react-mini-router').RouterMixin, Home = require('./components/Home.jsx'), ItemList = require('./components/ItemList.jsx'), Private = require('./components/Private.jsx'), Login = require('./components/Login.jsx'), Register = require('./components/Register.jsx'), Base = require('./Base.jsx'), Error = require('./components/Error.jsx'), Fluxxor = require('fluxxor'), FluxMixin = Fluxxor.FluxMixin(React), Auth = require('../clients/Authentication'); var App = React.createClass({ mixins: [ RouterMixin, FluxMixin ], routes: { '/': 'home', '/itemlist': 'itemlist', '/login': 'login', '/register': 'register', '/private': 'private', '/private2': 'private2', '/error': 'error' }, render: function () { return ( <Base routeComponent={this.renderCurrentRoute()} /> ); }, home: function () { return React.createElement(Home); }, itemlist: function () { if (!Auth.isAuthorized()) { window.location.replace('/login'); return; } return React.createElement(ItemList); }, login: function () { return React.createElement(Login); }, register: function () { return React.createElement(Register) }, private: function () { if (!Auth.isAuthorized()) { window.location.replace('/login'); return; } return React.createElement(Private, { name: 'One'}); }, private2: function () { if (!Auth.isAuthorized()) { window.location.replace('/login'); return; } return React.createElement(Private, { name: 'Two'}); }, error: function () { return React.createElement(Error); }, notFound: function (path) { return ( <div>Path not found: {path}</div> ); } }); module.exports = App;
var StartMenu : GUIStyle; function OnGUI() { if(Input.GetKeyUp(KeyCode.Space)) Application.LoadLevel(1); }
import React, { useState } from 'react' import { Quote } from './Quote/Quote' import { Quotes } from './Quotes' import { ButtonsQuote } from '../Buttons/ButtonsQuote/ButtonsQuote' import { Card } from '../Card/Card' export const QuoteCharacter = (props) => { const { quote, quotes, refreshQuote } = props const [showQuotes, setShowQuotes] = useState(false) const handleShowQuotes = () => { setShowQuotes(!showQuotes) } return ( <> {quote && ( <div style={{ display: 'flex', width: '100%', }} > <> {quotes && ( <ButtonsQuote {...props} size="medium" refreshQuote={() => refreshQuote()} getAllQuotes={() => handleShowQuotes()} /> )} <Card name="Quote" size={quotes ? 'small' : 'smallCard'} > <Quote {...props} quote={quote} /> </Card> </> </div> )} {showQuotes && quotes && ( <> <Card name="Quotes" key={quotes.author} isList={true}> <Quotes {...props} quotes={quotes} /> </Card> </> )} </> ) }
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const EmpleadoSchema = Schema({ codigo: String, nombre: String, cedula: String, pApellido: String, sApellido: String, telefono1: String, telefono2: String, puesto: String, nacionalidad: String, restaurante: String, foto: String }); module.exports = mongoose.model("Empleado", EmpleadoSchema);
const redis = require('redis'); const redisHost = process.env.REDIS_HOST || '127.0.0.1'; class Redis { constructor() { this.client = redis.createClient({ host: redisHost }); } async insert(key, value) { const promise = new Promise((resolve, reject) => { this.client.set(key, value, (err, reply) => { if (err) { reject(err); } else { resolve(reply); } }) }); return await promise; } async get(key) { const promise = new Promise((resolve, reject) => { this.client.get(key, (err, reply) => { if (err) { reject(err); } else { resolve(reply); } }) }); return await promise; } } module.exports = new Redis();
import Link from "next/link"; import { blog_data } from "../../../data"; const blogItems = blog_data.filter(b => b.home); const BlogArea = () => { return ( <div className="tp-blog-area pt-130 pb-120 p-relative"> <div className="circle-animation blog-animation"> <span className="tp-circle-3"></span> </div> <div className="container"> <div className="row"> <div className="col-xl-12"> <div className="tp-blog-section-box text-center pb-15"> <h5 className="tp-subtitle">Blog & Article</h5> <h2 className="tp-title">Recent blog post</h2> </div> </div> </div> <div className="row gx-40"> {blogItems.map((item, i) => { const { date, delay, duration, id, img, meta_tag, short_desc, title } = item; return <div key={id} className="col-xl-6 col-lg-6"> <div className="tp-blog-box mb-30 wow tpfadeLeft" data-wow-duration={duration} data-wow-delay={delay}> <div className="tp-blog-item"> <div className="tp-blog-img fix mb-35"> <Link href={`/blog-details/${id}`}> <a> <img className="w-100" src={img} alt="" /></a> </Link> </div> <div className="tp-blog-meta d-flex justify-content-between mb-30"> <a href="#">{meta_tag}</a> <a className="tp-blog-meta-color" href="#">{date}</a> </div> <div className="tp-blog-info"> <h3 className="tp-blog-title"> <Link href={`/blog-details/${id}`}> <a>{title}</a> </Link> </h3> <p>{short_desc}</p> </div> </div> </div> </div> })} </div> <div className="row"> <div className="col-xl-12"> <div className="tp-blog-button text-center mt-30"> <Link href={'/blog'}> <a className="tp-btn">View All Blog</a> </Link> </div> </div> </div> </div> </div> ); }; export default BlogArea;
angular.module('pricing') .directive('chartdirective', function($compile) { return { restrict: 'AE', link: function(scope, element, attrs) { var watchlist = scope.$parent.tickerList.watchlist; var stringWatchlist = watchlist.toString(); stringWatchlist = stringWatchlist.replace(/,/g,'","'); scope.templateHTML = "<div>" + '<script type="text/javascript" src="https://s3.amazonaws.com/tradingview/tv.js"></script>' + '<script type="text/javascript">' + // '// <![CDATA[' + 'new TradingView.widget({' + '"width": 600,' + '"height": 300,' + '"symbol": "' + scope.$parent.symbolID + '",' + '"interval": "D",' + '"toolbar_bg": "#E4E8EB",' + '"hide_side_toolbar": false,' + '"allow_symbol_change": true,' + // '"watchlist": ["EURUSD", "GBPUSD", "USDJPY", "USDCHF", "USDCAD", "AUDUSD", "NZDUSD", "GBPJPY", "EURGBP", "EURJPY", "FX:XAUUSD", "FX:XAGUSD"],' + '"watchlist":["' + stringWatchlist + '"],' + '"details": false,' + '"hideideas": true' + '});' + // '// ]]&gt;' + '</script>' + '</div>' console.log(scope.templateHTML); element.html(scope.templateHTML); } }; });
//Creating the class.. class User{ constructor(firstName, lastName, age, username, password){ this.firstName = firstName; this.lastName = lastName; this.age = age; this.username = username; this.password = password; } setFullName(userOne, userTwo){ this.firstName = userOne; this.lastName = userTwo; } getFullName(){ return `Full Name is ${this.firstName+' '+this.lastName}`; } editName(userMiddleName){ var firstOne = this.firstName; var middleOne = userMiddleName; var lastOne = this.lastName; return `First name is ${firstOne}, Middle name is ${middleOne} and Last Name is ${lastOne}`; } } const UserAccount = new User('Asad', 'Anik', 20, 'asadanik', '@@1211##'); UserAccount.setFullName('Asad', 'Anik'); console.log(UserAccount.getFullName()); console.log(UserAccount.editName('Hossan')); //Inherited Class inner here... class Teacher extends User{ constructor(firstName, lastName, age, username, password, subject, experience){ super(firstName, lastName, age, username, password); this.subject = subject; this.experience = experience; } //Overrided the method... getFullName(){ return `Full Name is ${this.firstName+' '+this.lastName} and I teach ${this.subject}`; } favDrink(name){ console.log(`My Fav. drink is ${name}!`); } } const AnotherUser = new Teacher('Hitesh', 'Chudhory', 33, 'hiteshchudhory', '@#@#@#@#1212', 'python', '10years'); console.log(AnotherUser.getFullName()); AnotherUser.favDrink('CocaChola');
import React, { Component } from 'react'; import StockContainer from './StockContainer' import PortfolioContainer from './PortfolioContainer' import SearchBar from '../components/SearchBar' class MainContainer extends Component { state = { allStocks: [], availableStocks: [], purchasedStocks: [], havePurchase: false } componentDidMount(){ fetch('http://localhost:3000/stocks').then(res => res.json()) .then(data => this.setState({ allStocks: data, availableStocks: data })) } handleStock = (stock) => { const availableStocks = this.state.availableStocks.filter(function(ele){ return ele !== stock }) this.setState({ availableStocks: availableStocks, purchasedStocks: [...this.state.purchasedStocks, stock], havePurchase: true }) } handleFilterChange = (e) =>{ const selectedfilter = e.target.value const filteredStocks = this.state.allStocks.filter(function(ele){ return ele.type === selectedfilter }) console.log(filteredStocks) this.setState({ availableStocks: filteredStocks }) } handleSort = (e) => { if(e.target.value === 'Alphabetically'){ const sortedAlpha = this.state.availableStocks.sort((a, b) => (a.name > b.name) ? 1 : -1) this.setState({ availableStocks: sortedAlpha }) } else if (e.target.value === 'Price'){ const sortedPrice = this.state.availableStocks.sort((a, b )=>(a.price > b.price) ? 1 : -1) this.setState({ availableStocks: sortedPrice }) } } render() { // console.log(this.state) return ( <div> <SearchBar handleFilterChange={this.handleFilterChange} handleSort={this.handleSort}/> <div className="row"> <div className="col-8"> <StockContainer allStocks={this.state.availableStocks} handleStock={this.handleStock}/> </div> <div className="col-4"> <PortfolioContainer purchasedStocks={this.state.purchasedStocks} havePurchase={this.state.havePurchase}/> </div> </div> </div> ); } } export default MainContainer;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class CityOptionItem extends Component { constructor(){ super(); this.state={}; } render(){ return ( <option value={this.props.area.code}>{this.props.area.name}</option> ); } } CityOptionItem.propTypes={ area:PropTypes.object } export default CityOptionItem;
/** * Created by Vadym Yatsyuk on 09/10/2016 */ const graphql = require('graphql'); const sqlite3 = require('sqlite3'); const bluebird = require('bluebird'); const chalk = require('chalk'); let data = require('./data.json'); const db = new sqlite3.Database('storage.db'); db.get = bluebird.promisify(db.get); db.all = bluebird.promisify(db.all); var userType = new graphql.GraphQLObjectType({ name: 'User', fields: { id: { type: graphql.GraphQLInt }, name: { type: graphql.GraphQLString }, phone: { type: graphql.GraphQLString } } }); module.exports = new graphql.GraphQLSchema({ query: new graphql.GraphQLObjectType({ name: 'Query', fields: { user: { type: userType, args: { id: { type: graphql.GraphQLInt } }, resolve: (_, { id }) => db.get('SELECT * FROM users u WHERE u.id = $id', { $id: id }) }, addUser: { type: userType, args: { name: { type: graphql.GraphQLString }, phone: { type: graphql.GraphQLString } }, resolve: (_, { name, phone }) => { const stmt = db.prepare('INSERT INTO users(name, phone) VALUES (?, ?)'); stmt.run([name, phone]); }, }, updateUser: { type: userType, args: { id: { type: graphql.GraphQLInt }, name: { type: graphql.GraphQLString }, phone: { type: graphql.GraphQLString } }, resolve: ( _, { id, name }) => { const stmt = db.prepare('UPDATE users SET name = ?, phone = ? WHERE id = ?'); stmt.run([name, id], logError); } }, users: { type: new graphql.GraphQLList(userType), resolve: () => db.all(`SELECT * FROM users`) }, deleteUser: { type: userType, args: { id: { type: graphql.GraphQLInt } }, resolve: ( _, { id }) => { const stmt = db.prepare('DELETE FROM users WHERE id = ?'); stmt.run([parseInt(id, 10)], logError); } } } }) }); function logError(err) { console.log(chalk.red('Error:')); console.log(chalk.red(err)); }
/*============================================================================== Carl's ODK Authenticator App Version: 1.0.0 ==============================================================================*/ var http = require('http'); var https = require('https'); var md5 = require('md5'); var parseString = require('xml2js').parseString; var fs = require('fs'); /*============================================================================== Customizable settings ==============================================================================*/ var CURRENT_VERSION = "1.0.0"; var SERVER_RUNNING = false; var MODE_SIMPLE = false; //If you want to run a basic request (not working) then set as true var MODE_DIGEST = true; //This will attempt Digest Authentication var DEBUG_LOGGING = false; var validator_user = "test"; var validator_pass = "t3stt3st"; var validator_success = false; var GLOBAL_STATUS_CODE = 0; /*============================================================================== Hard-coded variables ==============================================================================*/ logChecker("========================================================="); logChecker("ODK 1 Form Updater"); logChecker("Version: " + CURRENT_VERSION); logChecker("========================================================="); /*============================================================================== HTTP Requests - The real point of this whole script. ==============================================================================*/ // var digest_request_options = { // host: 'abalobi-fisher.appspot.com', // path: '/formList' // }; function saveLatestForm(sentFormURL, callback) { var sentURL = processURL(sentFormURL); var request_options = { "host": sentURL[0], "path": sentURL[1] } createDigestRequest(request_options, function(success, response, body) { logChecker("VALIDATOR SUCCESS: " + success); //Parses the xml form to a json parseString(body.toString(), function(err, result) { logChecker(body.toString()); //Split the URL to use in the request var processedURL = processURL(result.forms.form[0].$.url); //Set header etc for a second request var thirdRequestOptions = { "host": processedURL[0], "path": processedURL[1] } createDigestRequest(thirdRequestOptions, function(success, response, body) { logChecker("PRINTING FINAL"); logChecker(response.statusCode); logChecker(body.toString()); logChecker(response.headers); // var file = fs.createWriteStream(""); fs.writeFile("./datafiles/form.xml", body.toString(), function(err) { if (err) { return console.log(err); } logChecker("\nForm saved successfully.\n"); callback(); }); }); }); }); } /*============================================================================== HANDLE REQUESTS HERE ==============================================================================*/ //This is used to store the values in www-authenticate, which gets //received from the header of the first response. var jsonHEADERS; function getFormList(options, callback) { logChecker("Creating initial Digest Request..."); //Grab the global variables var username = validator_user; var password = validator_pass; var success = false; var req = https.get(options, function(res) { jsonHEADERS = {}; logChecker(""); logChecker('STATUS CODE:\n ' + res.statusCode); logChecker('HEADERS:\n ' + JSON.stringify(res.headers, null, 4)); // Buffer the body entirely for processing as a whole. var bodyChunks = []; res.on('data', function(chunk) { // You can process streamed parts here... bodyChunks.push(chunk); }).on('end', function() { var body = Buffer.concat(bodyChunks); logChecker( 'BODY: \n' + body.toString() ); // ...and/or process the entire body here. //Now that the request has definitely ended, //Start a second request! logChecker("========================================================="); logChecker("First request completed!\nCreating second request...\n"); var stringFromHeaders; var realm; var nonce; var qop; try { stringFromHeaders = res.headers['www-authenticate']; //Store the WWW-Authenticate into a JSON jsonHEADERS = splitIntoJSON(stringFromHeaders); realm = jsonHEADERS.realm; nonce = jsonHEADERS.nonce + "=="; qop = jsonHEADERS.qop; var cnonce = randomString(48); var nc = ""; logChecker("Some information on the Hashing Process:\n"); logChecker("Realm: " + realm + "\nNonce: " + nonce + "\nUsername: " + username + "\nPassword: " + password + "\nCNonce: " + cnonce + "\nQop: " + qop + "\n"); /* HA1 = MD5(A1) = MD5(username:realm:password) HA2 = MD5(A2) = MD5(method:digestURI) response = MD5(HA1:nonce:HA2) */ //TODO: Generate MD5 hashes here. var beforeHA1 = username + ":" + realm + ":" + password; var beforeHA2 = "GET:" + options.path; var ha1 = md5(beforeHA1); var ha2 = md5(beforeHA2); var actualResponse = md5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2); logChecker("Before 1st Hash: " + beforeHA1 + "\n" + "Before 2nd Hash: " + beforeHA2 + "\n" + "HA1: " + ha1 + "\n" + "HA2: " + ha2 + "\n" + "Response: " + actualResponse + "\n"); digestString = "Digest username=\"" + username + "\", " + "realm=\"abalobi-fisher ODK Aggregate\", " + "nonce=\"" + nonce + "\", " + "uri=\"" + options.path + "\", " + "qop=" + qop + ", " + "nc=" + ", " + "cnonce=\"" + cnonce + "\", " + "response=\"" + actualResponse + "\", " + "opaque=, "; //We have to set up our options now. var options2 = { host: options.host, path: options.path, mode: 'no-cors', headers: { Authorization: digestString } } logChecker("Your options for this request: \n" + JSON.stringify(options2, null, 4)); logChecker("\n\nA nicer view of your digest string: \n"); logChecker(nicerDigest(digestString)); //NOW WE MAKE A SECOND REQUEST createRequest(options2, success, callback); // callback(); } catch (ex) { logChecker("ERROR: \n" + ex); logChecker("BLEH"); } }) }); req.on('error', function(e) { logChecker('ERROR: \n' + e.message); }); } function createDigestRequest(options, callback) { logChecker("Creating initial Digest Request..."); var username = validator_user; var password = validator_pass; var success = false; var req = https.get(options, function(res) { jsonHEADERS = {}; logChecker(""); logChecker('STATUS CODE:\n ' + res.statusCode); logChecker('HEADERS:\n ' + JSON.stringify(res.headers, null, 4)); // Buffer the body entirely for processing as a whole. var bodyChunks = []; res.on('data', function(chunk) { // You can process streamed parts here... bodyChunks.push(chunk); }).on('end', function() { var body = Buffer.concat(bodyChunks); logChecker( // 'BODY: \n' + beautify(body.toString(), { // indent_size: 4 // } 'BODY: \n' + body.toString() ); // ...and/or process the entire body here. //Now that the request has definitely ended, //Start a second request! logChecker("========================================================="); logChecker("First request completed!\nCreating second request...\n"); var stringFromHeaders; var realm; var nonce; var qop; try { stringFromHeaders = res.headers['www-authenticate']; //Store the WWW-Authenticate into a JSON jsonHEADERS = splitIntoJSON(stringFromHeaders); realm = jsonHEADERS.realm; nonce = jsonHEADERS.nonce + "=="; qop = jsonHEADERS.qop; var cnonce = randomString(48); var nc = ""; logChecker("Some information on the Hashing Process:\n"); logChecker("Realm: " + realm + "\nNonce: " + nonce + "\nUsername: " + username + "\nPassword: " + password + "\nCNonce: " + cnonce + "\nQop: " + qop + "\n"); /* HA1 = MD5(A1) = MD5(username:realm:password) HA2 = MD5(A2) = MD5(method:digestURI) response = MD5(HA1:nonce:HA2) */ //TODO: Generate MD5 hashes here. var beforeHA1 = username + ":" + realm + ":" + password; var beforeHA2 = "GET:" + options.path; var ha1 = md5(beforeHA1); var ha2 = md5(beforeHA2); var actualResponse = md5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2); logChecker("Before 1st Hash: " + beforeHA1 + "\n" + "Before 2nd Hash: " + beforeHA2 + "\n" + "HA1: " + ha1 + "\n" + "HA2: " + ha2 + "\n" + "Response: " + actualResponse + "\n"); digestString = "Digest username=\"" + username + "\", " + "realm=\"abalobi-fisher ODK Aggregate\", " + "nonce=\"" + nonce + "\", " + "uri=\"" + options.path + "\", " + "qop=" + qop + ", " + "nc=" + ", " + "cnonce=\"" + cnonce + "\", " + "response=\"" + actualResponse + "\", " + "opaque=, "; //We have to set up our options now. var options2 = { host: options.host, path: options.path, mode: 'no-cors', headers: { Authorization: digestString } } logChecker("Your options for this request: \n" + JSON.stringify(options2, null, 4)); logChecker("\n\nA nicer view of your digest string: \n"); logChecker(nicerDigest(digestString)); //NOW WE MAKE A SECOND REQUEST createRequest(options2, success, callback); // callback(); } catch (ex) { logChecker("ERROR: \n" + ex); logChecker("BLEH"); } }) }); req.on('error', function(e) { logChecker('ERROR: \n' + e.message); }); } /*============================================================================== Utility Methods ==============================================================================*/ function splitIntoJSON(stringToSplit) { var finalObject = {}; //Separate all values into an array var commaSplit = stringToSplit.split(","); for (var i = 0; i < commaSplit.length; i++) { //For each pair of values, split by equals var equalsSplit = commaSplit[i].split("="); //If this is running the first time, remove the 'Digest' text if (i == 0) { equalsSplit[0] = equalsSplit[0].replace(/Digest/g, ''); } //Remove spaces from variable names var spacesRemoved = removeSpaces(equalsSplit[0].toString()); finalObject[spacesRemoved.toString()] = removeEscapes(equalsSplit[1]); } return finalObject; } function removeSpaces(processMe) { return processMe.replace(/\s+/g, ''); } function removeEscapes(processMe) { return processMe.replace(/\"/g, ''); } function createRequest(reqOptions, success, callbackFunction) { var req = https.get(reqOptions, function(res) { logChecker("========================================================="); GLOBAL_STATUS_CODE = res.statusCode; logChecker('STATUS:\n ' + res.statusCode); // logChecker('HEADERS:\n ' + JSON.stringify(res.headers, null, 4)); // Buffer the body entirely for processing as a whole. var bodyChunks = []; res.on('data', function(chunk) { // You can process streamed parts here... bodyChunks.push(chunk); }).on('end', function() { var body = Buffer.concat(bodyChunks); logChecker( // 'BODY: \n' + beautify(body.toString(), { // indent_size: 4 // }) 'BODY: \n' + body.toString() ); // ...and/or process the entire body here. if (res.statusCode == 200) { success = true; } callbackFunction(success, res, body); }) }); req.on('error', function(e) { logChecker("INTERNAL FUNCTION ERROR"); logChecker(e); logChecker('ERROR: \n' + e.message); }); } function processURL(url) { var processedURL = url.replace("https://", ""); processedURL = processedURL.split("/"); processedURL[1] = "/" + processedURL[1]; return processedURL; } var randomString = function(length) { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } var nicerDigest = function(sentDigestString) { var digestArray = sentDigestString.split(","); var escapedString = ""; for (var i = 0; i < digestArray.length; i++) { escapedString += digestArray[i] + "\n"; } return escapedString; } function logChecker(logtext) { if (DEBUG_LOGGING) { console.log(logtext); } } module.exports = { saveLatestForm: saveLatestForm }
import React from 'react' import compose from 'lodash/flowRight' import withMovement from './withMovement' import { move, subtract, scale } from '../utils/geometry' function computeZoom( zoom, modifier ) { return Math.max( 0.1, Math.min( zoom + modifier/300, 3 ) ) } function withPanZoomControls( Component ) { return class PanZoomComponent extends React.Component { _delta = [0, 0] constructor( props ) { super() this.state = { pan: props.pan || [0, 0], zoom: props.zoom || 1 } } componentWillReceiveProps( nextProps ) { if ( nextProps.pan !== this.props.pan || nextProps.zoom !== this.props.zoom ) { this.setState( { pan: nextProps.pan, zoom: nextProps.zoom } ) } } resetPanZoom = () => { this.setState( { pan: [0, 0], zoom: 1 } ) } handlePanZoom = ( onPanZoom ) => ( e, delta=[] ) => { e.preventDefault() e.stopPropagation() const { pan:prevPan, zoom:prevZoom } = this.state const position = [e.clientX, e.clientY] const mouseDelta = subtract( delta, this._delta ) const [deltaX, deltaY] = scale( [ e.deltaX / 3 || mouseDelta[0] || 0, e.deltaY / 3 || mouseDelta[1] || 0 ], 1/prevZoom ) this._delta = delta const zoom = e.ctrlKey ? computeZoom( prevZoom, -deltaY ) : prevZoom const pan = e.ctrlKey ? move( prevPan, subtract( scale( position, 1/zoom ), scale( position, 1/prevZoom ) ) ) : move( prevPan, [deltaX, deltaY] ) onPanZoom( pan, zoom ) this.setState( { pan, zoom } ) } handlePanZoomEnd = ( e ) => { this._delta = [0, 0] } render() { const { pan, zoom } = this.state const { movement, ...props } = this.props return ( <Component { ...props } pan={ pan } zoom={ zoom } panZoom={ this.handlePanZoom } startPanZoom={ onPanZoom => movement( this.handlePanZoom( onPanZoom ), this.handlePanZoomEnd ) } resetPanZoom={ this.resetPanZoom } /> ) } } } export default compose( withMovement, withPanZoomControls )
/** * Created by jonnyLee on 2016/9/27. */ Ext.define('Admin.store.resources.Menu', { extend: 'Ext.data.TreeStore', requires: [ 'Common.Config' ], alias: 'store.resourcesMenu', storeId: 'resources.Menu', autoLoad:false, root: { id: 0, text: '业务管理系统' }, proxy: { type: 'ajax', api: { read: Common.Config.requestPath('System', 'Resources', 'menu'), delete: Common.Config.requestPath('System', 'Resources', 'delete') }, reader: { type: 'json', rootProperty: 'data' } } });
$(document).ready(function () { $('.enable-modify-s').on('click', function(){ var flag = $(this).attr('static'); if (flag != 'static') { var content = $(this).html(); $(this).html('<input type="text" class="enable-modify-d">'); $('.enable-modify-d').val(content); $(this).attr('static','static'); $('.enable-modify-d').focus(); } }); $('.enable-modify-s').on('blur', '.enable-modify-d', function () { var father = $(this).parent(); var flag = father.attr('static'); if (flag == 'static') { var content = $(this).val(); var table = father.attr('v1'); var id = father.attr('v2'); var name = father.attr('v4'); var id_name = father.attr('v3'); if (content){ $.ajax({ method: 'post', url: "/admin/modify/", data:{ table: table, id: id, id_name: id_name, name: name, value: content }, success: function(){ father.html(content); father.attr('static','null'); }, error: function(){ alert('error'); } }); } } }); });
$(document).ready(function(){ var ajaxurl = 'despliegueUsuarios.php', data = {'action': 'user'}; $.post(ajaxurl, data, function (response) { // Response div goes here. $("#bodyTablaUser").html(response); }); }); $(document).on('click', '#save', function(){ var parentRow = $(this).closest('tr'); var rowData = new Array(); rowData ={ "ClvUsuarios" : $(parentRow).find("td:eq(0)").text() , "nombreUsuario" : $(parentRow).find("td:eq(1)").text() , "PreguntaSeguridad" : $(parentRow).find("td:eq(2)").text() , "Respuesta" : $(parentRow).find("td:eq(3) input[type='text']").val() , "Estado": $(parentRow).find("td:eq(4) input[type='checkbox']").is(':checked') }; rowData = $.toJSON(rowData); $.ajax({ type: "POST", url: "despliegueUsuarios.php", data: "update=" + rowData, success: function(msg){ alert(msg); } }); });
exports.handler = function(context, event, callback) { console.log(`test.js running...`); callback(null, 'hello world'); }
import React from 'react' import CreateNoteForm from './CreateNoteForm' import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import * as ActionTypes from "../constants/actionTypes"; import {push } from 'react-router'; class CreateNote extends React.Component { static propTypes = { createNote: PropTypes.func.isRequired, }; submit = (values) => { console.log(values); this.props.createNote(values); // this.props.history.push('/'); }; render() { return ( <CreateNoteForm onSubmit={this.submit} /> ) } } const mapDispatchToProps = dispatch => ({ createNote: (values) => dispatch({ type: ActionTypes.CREATE_NOTE, payload: values}), }); export default connect(undefined, mapDispatchToProps)(CreateNote);
/* Copyright 2012 DesignedByDash.com | License required for use. */ (function($) { var dbdFixedMenu = function(element, options, total) { var $mainElement = $('.fixed-header-container .navbar-inners'); if($mainElement.length == 1) { var startPos = $mainElement.offset().top + $mainElement.outerHeight() + 5; var isiPad = navigator.userAgent.match(/iPad/i) != null; if($(window).width() >= 980 && !isiPad) { jQuery.event.add(window, "scroll", function() { var currentPos = $(window).scrollTop(); var isFixed = false; if(currentPos > startPos && currentPos != 0 && $(window).width() >= 980) { $mainElement.addClass('fixed-header-active'); $mainElement.find('.nav-container-outer').css('margin-top', '70px'); } else { $mainElement.removeClass('fixed-header-active'); $mainElement.find('.nav-container-outer').css('margin-top', '0'); } }); } } } $.fn.dbdfixedmenu = function() { var dbdFm = new dbdFixedMenu(); } })(jQuery); jQuery(document).ready(function(e) { jQuery(document).dbdfixedmenu(); });
"use strict"; var _react = _interopRequireDefault(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var _SortableDIVs = _interopRequireDefault(require("./components/SortableDIVs.jsx")); var _TestData = _interopRequireDefault(require("./TestData.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _reactDom.default.render(_react.default.createElement(_SortableDIVs.default, { data: _TestData.default }), document.getElementById('root'));
const elixir = require('laravel-elixir'), gulp = require('gulp'); require('laravel-elixir-vue-2'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ var node = './node_modules/'; var bower = './bower_components/'; var paths = { 'bootstrap': node + 'bootstrap-sass/assets/', 'fontawesome': node + 'font-awesome/', 'eonasdan_bootstrap_datetimepicker': bower + 'eonasdan-bootstrap-datetimepicker/build/', } // plugin de exibição de escalas gulp.task('basefiles', function() { elixir(mix => { mix .copy(paths.bootstrap + 'fonts/bootstrap/**', 'public/fonts') .copy(paths.bootstrap + 'javascripts/bootstrap.min.js', 'public/js') .copy(paths.fontawesome + 'fonts','public/fonts') .copy(bower + 'moment/min/moment-with-locales.min.js', 'public/js') .copy(paths.eonasdan_bootstrap_datetimepicker + 'js/bootstrap-datetimepicker.min.js', 'public/js') .copy(paths.eonasdan_bootstrap_datetimepicker + 'css/bootstrap-datetimepicker.min.css', 'public/css') }); }); // arquivos principais do sistema gulp.task('mainfiles', function() { elixir(mix => { mix.sass('site.scss'); mix.webpack('site.js'); }); }); // plugin de exibição de escalas gulp.task('timesheet', function() { elixir(mix => { mix.webpack('site/escalas/timesheet.js', 'public/js') .sass('site/escalas/timeline.js.scss', 'public/css') }); }); gulp.task( 'default', [ 'basefiles', 'mainfiles', 'timesheet' ] );
define('PlayerView', [ 'createjs', 'ViewConstants', 'CollisionTester' ], function (createjs, ViewConstants, CollisionTester) { var config; var Player = function() { this.direction = -1; this.container = null; this.actions = { moveRight: false, moveLeft: false }; this.isFalling = false; this.velocity = { x: 0, y: 0 }; this.lastPosition = { x: 0, y: 0 }; this.cryAnmitaions = { monster1: [ { x: -50, y: 30, scaleX: 1, scaleY: 1 }, { x: 170, y: 30, scaleX: -1, scaleY: 1 } ], monster2: [ { x: -50, y: 10, scaleX: 1, scaleY: 2 }, { x: 170, y: 10, scaleX: -1, scaleY: 2 } ], monster3: [ { x: -40, y: 10, scaleX: 1, scaleY: 2.4 }, { x: 145, y: 10, scaleX: -1, scaleY: 2.4 } ] } }; Player.prototype.initialize = function (assets, parent, data) { this.container = new createjs.Container(); this.assets = assets; this.animations = []; this.transformation = null; this.tranforamtionData = null; parent.addChild(this.container); this.bitmap = new createjs.Bitmap(assets[data.monsterId]); this.container.y = data.position.y; this.container.x = data.position.x; this.container.addChild(this.bitmap); this.lastPosition.x = this.container.x; this.lastPosition.y = this.container.y; this.collistionTester = new CollisionTester(); this.monsterId = data.monsterId; this.monsterData = assets['monster_data'][data.monsterId]; this.mapData = assets['map_data']['map1']; this.collisioData = assets['collision']; this.playerData = data; this.cryTicks = 0; config = assets['params'].movement; }; Player.prototype.transform = function (type) { if (type && this.transformation) { this.container.removeChild(this.transformation) delete this.transformation; } if (!type) { this.container.removeChild(this.transformation) delete this.transformation; this.bitmap.visible = true; } else if (typeof this.assets['animations'][type] !== 'undefined' && typeof this.assets['animations'][type][this.monsterId] !== 'undefined') { this.bitmap.visible = false; var data = this.assets['animations'][type][this.monsterId], spriteData = { images: [this.assets[data.image]], frames: data.frames, animations: data.animations }, spriteSheet = new createjs.SpriteSheet(spriteData); this.tranforamtionData = data; this.transformation = new createjs.Sprite(spriteSheet, "default"); this.transformation.y = data.position.y; this.transformation.x = data.position.x; if (this.direction != data.direction) { this.transformation.scaleX *= -1; } this.container.addChild(this.transformation); } else { this.bitmap.visible = true; } }; Player.prototype.cry = function (event) { this.cryTicks = event.event.duration; var data1 = { images: [this.assets['cry']], frames: { width: 73, height: 54, count: 8 }, animations: { default: { frames: [0,1,2,3,4,5,6,7], speed: 0.4 } } }; for (var i in this.cryAnmitaions[this.monsterId]) { var spriteSheet = new createjs.SpriteSheet(data1); var animation = new createjs.Sprite(spriteSheet, "default"); animation.x = this.cryAnmitaions[this.monsterId][i].x; animation.y = this.cryAnmitaions[this.monsterId][i].y; animation.scaleX = this.cryAnmitaions[this.monsterId][i].scaleX; animation.scaleY = this.cryAnmitaions[this.monsterId][i].scaleY; this.animations.push(animation); this.container.addChild(animation); } }; Player.prototype.updateSync = function (player) { this.container.x = player.position.x; this.container.y = player.position.y; }; Player.prototype.update = function(changes) { if (this.cryTicks > 0) { this.cryTicks--; if (this.cryTicks == 0) { for (var i in this.animations) { this.container.removeChild(this.animations[i]); delete this.animations[i]; } } } if (changes) { for (var i in changes) { this.actions[i] = changes[i]; } } if (this.actions.moveLeft && !this.actions.moveRight) { this.velocity.x -= config.acceleration; if (this.velocity.x < -config.max_velocity) this.velocity.x = -config.max_velocity; } else if (this.actions.moveRight && !this.actions.moveLeft) { this.velocity.x += config.acceleration; if (this.velocity.x > config.max_velocity) this.velocity.x = config.max_velocity; } else { if (this.velocity.x < 0) { if (this.velocity.x >= -config.friction) this.velocity.x = 0; else this.velocity.x += config.friction; } else if (this.velocity.x > 0) { if (this.velocity.x <= config.friction) this.velocity.x = 0; else this.velocity.x -= config.friction; } } if (this.cryTicks > 0) { this.velocity.x = 0; } this.container.x += this.velocity.x; if (this.velocity.x > 0 && this.direction === -1 || this.velocity.x < 0 && this.direction === 1) { this.bitmap.x -= this.direction * this.monsterData.width; this.bitmap.scaleX *= -1; this.direction *= -1; if (this.transformation) { this.transformation.scaleX *= -1; this.transformation.x -= this.direction * this.monsterData.width * this.tranforamtionData.direction; } } if (this.actions.jump && !this.isFalling && !this.velocity.y) { this.velocity.y = config.jump_velocity; this.isFalling = true; } else { this.velocity.y -= config.gravity; } this.container.y -= this.velocity.y; var mapWidth = this.mapData['tiles'][0].length* ViewConstants.MAP_TILE_WIDTH; if (this.collistionTester.collide({ position: {x: this.container.x, y: this.container.y}, collision: this.collisioData[this.playerData.monsterId], width: this.monsterData.width, height: this.monsterData.height }, { position: {x: 0, y: this.monsterData.collisionOffset}, collision: this.collisioData['map1'], width: mapWidth, height: this.mapData['tiles'].length * ViewConstants.MAP_TILE_HEIGHT + ViewConstants.MAP_TOP_OFFSET })) { if (this.lastPosition.y < this.container.y) { this.container.y += this.velocity.y; this.velocity.y = 0; this.isFalling = false; } else { this.container.y += this.velocity.y; this.velocity.y = 0; this.isFalling = true; } } if (this.container.y > ViewConstants.CONTENT_HEIGHT - this.monsterData.height + 25) { this.container.y = ViewConstants.CONTENT_HEIGHT - this.monsterData.height + 25; this.velocity.y = 0; this.isFalling = false; } if (this.container.x < 0) { this.container.x = 0; this.velocity.x = 0; } else if (this.container.x + this.monsterData.width > mapWidth) { this.container.x = mapWidth - this.monsterData.width; this.velocity.x = 0; } this.lastPosition.x = this.container.x; this.lastPosition.y = this.container.y; }; return Player; });
let pongLevel = []; function levelCreation() { let string1 = "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"; let string2 = "g g"; let string3 = "g g"; let string4 = "g g"; let string5 = "g g"; let string6 = "g g"; let string7 = "g g"; let string8 = "g g"; let string9 = "g g"; let string10 = "g g"; let string11 = "g g"; let string12 = "g g"; let string13 = "g g"; let string14 = "g g"; let string15 = "g g"; let string16 = "g g"; let string17 = "g g"; let string18 = "g g"; let string19 = "g g"; let string20 = "g g"; let string21 = "g g"; let string22 = "g g"; let string23 = "g g"; let string24 = "g g"; let string25 = "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"; pongLevel.push(string1); pongLevel.push(string2); pongLevel.push(string3); pongLevel.push(string4); pongLevel.push(string5); pongLevel.push(string6); pongLevel.push(string7); pongLevel.push(string8); pongLevel.push(string9); pongLevel.push(string10); pongLevel.push(string11); pongLevel.push(string12); pongLevel.push(string13); pongLevel.push(string14); pongLevel.push(string15); pongLevel.push(string16); pongLevel.push(string17); pongLevel.push(string18); pongLevel.push(string19); pongLevel.push(string20); pongLevel.push(string21); pongLevel.push(string22); pongLevel.push(string23); pongLevel.push(string24); pongLevel.push(string25); } class WorldLoader { /** * Method that takes a level and adds the actors to the world model. * @param {array} levelData - an array of strings from the levelCreator. * @param {WorldModel} - the world model you are loading the level to. */ readData(levelData, w) { levelData.forEach((item, index) => item.split("").forEach((a, x) => { if(a === "g") w.addActor(new Goal(x, index)); else if (a === "w") w.addActor(new Wall(x, index)); })); } } /** Class representing a 2 dimensional point. */ class Point { constructor(x, y) { this.x_ = x; this.y_ = y; } /** * @type {int} */ get posX() { return this.x_; } /** * @type {int} */ get posY() { return this.y_; } equals(p) { if(p.posX == this.posX && p.posY == this.posY) return true; else return false; } } /** Model Class representing a virtual world. */ class WorldModel { constructor(ach, w, h) { this.ach_ = ach; this.width_ = w || 100; this.height_ = h || 50; this.views_ = []; this.actors_ = []; this.score_ = {L: 0, R: 0}; } update(steps) { this.actors_.forEach(x => x.update(steps)); let ballArr = this.actors_.filter(x => x.type === "Ball"); let getIndex = arr => { for(let i = 0; i < arr.length; i++) { if(arr[i].type === "Ball") return i; } } let ballInd = getIndex(this.actors_); let ball = {val: ballArr[0], ind: ballInd}; this.actors_.forEach(a => { if(ball.val.didCollide(a)) { console.log("collision!"); this.ach_.applyCollisionAction(a, ball.val); } }); if(!(ball.val.isActive)) { this.actors_.splice(ball.ind ,1); let pongBall = new Ball(Math.round(this.width_/2), Math.round(this.height_/2), this.height_, new Velocity(Math.pow(-1, Math.round(Math.random())), Math.pow(-1, Math.round(Math.random()))), "white"); this.addActor(pongBall); } this.views_.forEach(x => x.display(this)); } get score() { return this.score_; } /** * @type {tuple} */ get actors() { return new ArrayIterator(this.actors_); } /** * @type {int} */ get width() { return this.width_; } /** * @type {int} */ get height() { return this.height_; } get view() { return this.views_[0]; } addActor(a) { if(a instanceof Actor) { this.actors_.push(a); } else throw new Error("Must be given a valid actor."); } addView(v) { if(v instanceof View) { this.views_.push(v); } else throw new Error("Must be given a valid view."); } reset() { this.views_.forEach(x => x.dispose()); this.views_ = []; this.actors_ = []; } } class PaddleController { constructor(world, paddle) { if(world instanceof WorldModel) { this.paddleWorld_ = world; } else throw new Error("Not given a valid WorldModel"); if(paddle instanceof Paddle) { this.paddle_ = paddle; } else throw new Error("Not given a valid Paddle"); } /** * Turns the paddle up. */ turnPaddleUp() { this.paddle_.turnUp(); } /** * Turns the paddle down. */ turnPaddleDown() { this.paddle_.turnDown(); } /** * @type {tuple} */ get paddlePosition() { return this.paddle_.position; } /** * @type {string} */ get paddleDirection() { return this.paddle_.direction; } /** * @type {int} */ get worldHeight() { return this.paddleWorld_.height; } /** * @type {int} */ get worldWidth() { return this.paddleWorld_.width; } } class Player { constructor(paddleController) { if(!(paddleController instanceof PaddleController)) throw new Error("Not given a valid Paddle Controller."); else this.pc_ = paddleController; if(this.constructor === Player) throw new Error("Cannot instantiate a Player, which is an abstract base class"); } } /** Class representing a Human Player of the snake game. */ class HumanPlayer extends Player { constructor(paddleController, inputHandler) { super(paddleController); this.inputHandler_ = inputHandler; } makeTurn() { if(this.inputHandler_.madeUpMove() == true) { this.pc_.turnPaddleUp(); this.inputHandler_.resetUpMove(); } else if(this.inputHandler_.madeDownMove() == true) { this.pc_.turnPaddleDown(); this.inputHandler_.resetDownMove(); } else { } } } /** Interface class that ensures any type of view has a display method.*/ class View { constructor() { if(this.constructor === View) throw new Error("Cannot instantiate a View, which is an interface"); else if(!(this.display instanceof Function)) throw new Error("View class must implement display method."); else if(!(this.dispose instanceof Function)) throw new Error("View class must implement dispose method."); } } /** Class representing what our player sees on their screen.*/ class CanvasView extends View { constructor(scalingFactor) { super(); this.scalingFactor_ = scalingFactor; this.canvas_ = document.createElement("canvas"); this.canvas_.id = "game"; document.body.appendChild(this.canvas_); this.context_= this.canvas_.getContext("2d"); } display(world) { this.canvas_.width = this.scalingFactor_*world.width; this.canvas_.height = this.scalingFactor_*world.height; this.context_.fillText(world.score.L + " : " + world.score.R, 10, 50, 400); world.actors.forEach(x => { this.context_.fillStyle = x.color || "white"; if(x.type === "Ball") { this.context_.arc(x.position.posX*this.scalingFactor_, x.position.posY*this.scalingFactor_, (this.scalingFactor_/1.5),0,2*Math.PI,); this.context_.stroke(); this.context_.fill(); } else if(x.type === "Paddle") { for(let index = 0; index < x.parts_.length; index++) { this.context_.fillRect(x.parts_[index].posX*this.scalingFactor_, x.parts_[index].posY*this.scalingFactor_, this.scalingFactor_, this.scalingFactor_); } } else this.context_.fillRect(x.position.posX*this.scalingFactor_, x.position.posY*this.scalingFactor_, this.scalingFactor_, this.scalingFactor_); }); } dispose() { document.body.removeChild(this.canvas_); } } class InputHandler { constructor() { if(!(this.madeUpMove instanceof Function)) throw new Error("input handler must have madeUpMove method"); if(!(this.madeDownMove instanceof Function)) throw new Error("input handler must have madeDownMove method"); if(!(this.resetUpMove instanceof Function)) throw new Error("input handler must have resetUpMove method"); if(!(this.resetDownMove instanceof Function)) throw new Error("input handler must have resetDownMove method"); } } class KeyInputHandler extends InputHandler { constructor() { super(); this.wasUpPushed_ = false; this.wasDownPushed_ = false; } madeUpMove() { return this.wasUpPushed_; } madeDownMove() { return this.wasDownPushed_; } resetUpMove() { this.wasUpPushed_ = false; } resetDownMove() { this.wasDownPushed_ = false; } } class UDKeyInputHandler extends KeyInputHandler { constructor() { super(); let eventHandler = event => { if(event.key === "ArrowUp") { this.wasUpPushed_ = true; } else if(event.key === "ArrowDown") { this.wasDownPushed_ = true; } } window.addEventListener("keydown", eventHandler); } } class WSKeyInputHandler extends KeyInputHandler { constructor() { super(); let eventHandler = event => { if(event.code === 'KeyW') { this.wasUpPushed_ = true; } else if(event.code === 'KeyS') { this.wasDownPushed_ = true; } } window.addEventListener("keydown", eventHandler); } } class ActorCollisionHandler { constructor() { this.pairs_ = new Map(); } toKey_(colliderType, collidedType) { return colliderType + ", " + collidedType; } addCollisionAction(colliderType, collidedType, actionApplicator) { this.pairs_.set(this.toKey_(colliderType, collidedType), actionApplicator); } hasCollisionAction(colliderType, collidedType) { return this.pairs_.has(this.toKey_(colliderType, collidedType)); } applyCollisionAction(collider, collided) { console.log(collider.type); console.log(collided.type); if(this.hasCollisionAction(collider.type, collided.type)) { console.log("has collision action!"); this.pairs_.get(this.toKey_(collider.type, collided.type)).applyAction(collider, collided); } } } class GameController { constructor(game, maxScore) { this.game_ = game; this.maxScore_ = maxScore; let Handler = new ActorCollisionHandler; let WBCH = new WallBallCollisionHandler; Handler.addCollisionAction("Wall", "Ball", WBCH); let GBCH = new GoalBallCollisionHandler; Handler.addCollisionAction("Goal", "Ball", GBCH); let PBCH = new PaddleBallCollisionHandler; Handler.addCollisionAction("Paddle", "Ball", PBCH); this.world_ = new WorldModel(Handler, 50, 25); this.players_ = []; } init(data) { let arr = [new UDKeyInputHandler, new WSKeyInputHandler]; let myCols = ["red", "blue"]; let compCols = ["green", "orange"] if((data.numOfHumanPlayers !== 0) && (data.numOfHumanPlayers < 3)) { for(let i=0; i < (data.numOfHumanPlayers); i++) { let value = 20; let p = new Point(value, value); let myPaddle = new Paddle(p, 5, myCols[i]); let pc = new PaddleController(this.world_, myPaddle); let player = new HumanPlayer(pc, arr[i]); this.player = player; this.world_.addActor(myPaddle); } } if(data.numOfHumanPlayers > 2) { } if((data.numOfAIPlayers !== 0) && (data.numOfAIPlayers < 3)) { for(let i=0; i < (data.numOfAIPlayers); i++) { let value = null; let p = new Point(value, value); let myPaddle = new Paddle(p, compCols[i]); let pc = new PaddleController(this.world_, myPaddle); let player = new AIPlayer(pc); this.player = player; this.world_.addActor(myPaddle); } } let loadEmUp = new WorldLoader(); levelCreation(); loadEmUp.readData(pongLevel, this.world_); this.world_.addView(new CanvasView(10)); this.run(); } set player(p) { if(p instanceof Player) { this.players_.push(p); } else throw new Error("Must provide a valid player."); } run() { let randDir = Math.round(Math.random()); let pongBall = new Ball(Math.round(this.world_.width/2), Math.round(this.world_.height/2), this.world_.height, new Velocity(Math.pow(-1, Math.round(Math.random())), Math.pow(-1, Math.round(Math.random()))), "white"); this.world_.addActor(pongBall); let lastTime = 0; let giveTime = milliseconds => { lastTime = milliseconds; requestAnimationFrame(updateFrame); } let updateFrame = milliseconds => { this.players_.forEach(x => x.makeTurn()); if((milliseconds - lastTime) > 200){ this.world_.update(1); lastTime = lastTime + 200; } if(this.world_.score.L === this.maxScore_ || this.world_.score.R === this.maxScore_) { console.log("sorry, I have to reset"); this.players_ = []; this.world_.reset(); this.game_.switchContext(); } else requestAnimationFrame(updateFrame); } if(this.players_.length > 0) { requestAnimationFrame(giveTime); } else { this.players_ = []; this.world_.reset(); this.game_.switchContext(); } } } class Actor { constructor() { if(this.constructor===Actor) throw new Error("Cannot instantiate an Actor which is an interface."); else if(!(this.update instanceof Function)) throw new Error("Actor must have an update method."); } } class Collidable extends Actor { constructor() { super(); if(this.constructor === Collidable) throw new Error("Cannot instantiate a Collidable which is an interface."); else if(!(this.didCollide instanceof Function)) throw new Error("Collidable must have a didCollide method."); } } class Wall extends Actor { constructor(x, y) { super(); this.position_ = new Point(x, y); this.color_ = "rgb(0, 0, 0)" } get position() { return this.position_; } get type() { return "Wall"; } get color() { return this.color_; } update() { } } class Goal extends Actor { constructor(x, y) { super(); this.position_ = new Point(x, y); this.color_ = "rgb(0, 0, 0)"; } get position() { return this.position_; } get type() { return "Goal"; } get color() { return this.color_; } update() { } } class CollisionHandler { constructor() { if(this.constructor === CollisionHandler) throw new Error("Cannot instantiate a CollisionHandler which is an Interface."); else if(!(this.applyAction instanceof Function)) throw new Error("Collision Handler must have an applyAction method."); } } class PaddleBallCollisionHandler extends CollisionHandler { constructor() { super(); } applyAction(paddle, ball) { ball.reflectAngle(); } } class WallBallCollisionHandler extends CollisionHandler { constructor() { super(); } applyAction(wall, ball) { console.log("in the WBCH"); ball.reflectAngle(); } } class GoalBallCollisionHandler extends CollisionHandler { constructor() { super(); } applyAction(goal, ball) { ball.score(); } } class ArrayIterator { constructor(arr) { this.arr_ = arr; this.index_ = 0; } next() { let ind = this.index_++; let done = (ind === this.arr_.length) let value = (done) ? undefined : this.arr_[ind]; return {value: value, done: done}; } forEach(f) { this.arr_.forEach(x => f(x)); } } class MainMenuController { constructor(game) { this.game_ = game; this.twoHumansButton_ = document.createElement("button"); this.oneEachButton_ = document.createElement("button"); this.twoCompsButton_ = document.createElement("button"); this.twoHumansButton_.appendChild(document.createTextNode("Play with 2 Players!")); this.twoHumansButton_.addEventListener("click", this.switchContext_.bind(this, [2, 0])); this.oneEachButton_.appendChild(document.createTextNode("Play against an AI!")); this.oneEachButton_.addEventListener("click", this.switchContext_.bind(this, [1, 1])); this.twoCompsButton_.appendChild(document.createTextNode("Watch 2 AI!")); this.twoCompsButton_.addEventListener("click", this.switchContext_.bind(this, [0, 2])); } init(data) { document.getElementById("game-area").appendChild(this.twoHumansButton_); document.getElementById("game-area").appendChild(this.oneEachButton_); document.getElementById("game-area").appendChild(this.twoCompsButton_); } switchContext_(myPlayers) { document.getElementById("game-area").removeChild(this.twoHumansButton_); document.getElementById("game-area").removeChild(this.oneEachButton_); document.getElementById("game-area").removeChild(this.twoCompsButton_); this.game_.switchContext({numOfHumanPlayers: myPlayers[0], numOfAIPlayers: myPlayers[1]}); } } class Game { constructor () { this.contextSwitches_ = new Map(); this.contextSwitches_.set("Start", "Game"); this.contextSwitches_.set("Game", "Start"); this.controllers_ = new Map(); this.controllers_.set("Start", new MainMenuController(this)); this.controllers_.set("Game", new GameController(this)); this.currentContext_ = "Start"; } switchContext(data) { this.currentContext_ = this.contextSwitches_.get(this.currentContext_); this.controllers_.get(this.currentContext_).init(data); } run(data) { this.controllers_.get(this.currentContext_).init(data); } } let hereWeGo = new Game(); hereWeGo.run(); /*************************/ /** * Need AI class * need scorekeeper class /* */ class Paddle extends Actor { constructor(point, length, color) { super(); if(point instanceof Point) { this.parts_ = [point]; } else throw new Error("Must be given a valid Point."); for(let index=1; index < length; index++) { this.parts_.push(new Point(point.posX, point.posY + index)); } this.color_ = color || "white"; this.currentDirection_ = "none"; } move(steps) { if(this.currentDirection_ === "Up") { this.parts_[0] = new Point(this.position.posX, (this.position.posY - steps)); for(let index = (this.parts_.length - 1); index > 0; index = index - 1) { this.parts_[index] = this.parts_[index-1]; } } else if(this.currentDirection_ === "Down") { this.parts_[0] = new Point(this.position.posX, (this.position.posY + steps)); for(let index = (this.parts_.length - 1); index > 0; index = index - 1) { this.parts_[index] = this.parts_[index-1]; } } else { } } update(steps) { this.move(steps); this.currentDirection_ = "none"; } get position() { return this.parts_[0]; } get parts() { return new ArrayIterator(this.parts_); } get direction() { return this.currentDirection_; } get color() { return this.color_; } get length() { return this.length; } get type() { return "Paddle"; } turnUp() { this.currentDirection_ = "Up"; } turnDown() { this.currentDirection_ = "Down"; } } class Velocity { constructor(x, y) { this.xSpeed_ = x; this.ySpeed_ = y; } get xSpeed() { return this.xSpeed_; } get ySpeed() { return this.ySpeed_; } } class Ball extends Collidable { constructor(x, y, worldHeight, velocity, color) { super(); this.velocity_ = velocity; this.worldHeight_ = worldHeight; this.position_ = new Point(x, y); this.color_ = color || "white"; this.isActive_ = true; } move(steps) { this.position_ = new Point(this.position_.posX + (steps*this.velocity_.xSpeed), this.position_.posY + (steps*this.velocity_.ySpeed)); } update(steps) { this.move(steps); } didCollide(a) { if(a === this) { return false; } else if(a.type === "Paddle") { let it = a.parts; let placeHolder = it.next(); while(!placeHolder.done && !(this.position.equals(placeHolder.value))) { console.log("in while loop"); placeHolder = it.next(); } if(placeHolder.done) { return false; } else return true; } else { return (this.position_.equals(a.position)); } } reflectAngle() { console.log("in reflect angle"); if(this.position_.posY > 1 && this.position_.posy < (this.worldHeight_ - 1)) { this.velocity_ = new Velocity(-this.velocity_.xSpeed, this.velocity_.ySpeed); } else { this.velocity_ = new Velocity(this.velocity_.xSpeed, -this.velocity_.ySpeed_); } } get isActive() { return this.isActive_; } get position() { return this.position_; } get theta() { return this.theta_; } get color() { return this.color_; } get type() { return "Ball"; } score() { this.isActive_ = false; } }
export let inicio = {name: "Inicio", path: "/"}; export let conoceme = {name: "Conóceme", path: "/conoceme/"}; export let menu = [inicio, conoceme];
/** * Created by xuwusheng on 15/12/18. */ define(['../../../app'], function (app) { app.factory('taskMonitor', ['$http','$q','$filter','HOST',function ($http,$q,$filter,HOST) { return { getThead: function () { return [ {name:'序号',type:'pl4GridCount'}, {field:'chuCkName',name:'发货仓库'}, {field:'recCkName',name:'收货仓库'}, {field:'taskId',name:'业务单号'}, {field:'custTaskId',name:'客户单号'}, {field:'thirdWild',name:'第三方单号'}, {field:'taskType',name:'业务类型'}, {field:'customer',name:'客户'}, {field:'receTel',name:'联系电话'}, {field:'receAdd',name:'地址'}, // {field:'boxCount',name:'箱数'}, //{field:'taskState',name:'订单状态'}, {field:'fhTime',name:'发货日期'}, {field:'wlTaskTypeId',name:'配送方式'}, {field:'userName',name:'配送员'}, {field:'licenseNumber',name:'配送车辆'}, // {field:'ckName',name:'所属仓库'}, // {field:'toArea',name:'仓库地域'}, // {field:'wlComp',name:'物流中心'}, // {field:'handelTime',name:'业务时间'}, // {field:'moneyCount',name:'订单金额'}, { field: 'op', name: '操作', type: 'operate', style:'width:50px;', buttons: [{ text: '详情', call: 'getOpenModelData', btnType: 'button', style: 'font-size:10px;', openModal: '#workLogModal' }] }] }, getDetailThead: function () { return [ {name:'序号',type:'pl4GridCount'}, {field:'supliers',name:'供应商'}, {field:'goodName',name:'商品名称'}, {field:'model',name:'规格型号'}, {field:'factoryCode',name:'出厂编码'}, {field:'brand',name:'品牌'}, {field:'origGoodCount',name:'订购数量'}, {field:'acceGoodCount',name:'实发数量'}, {field:'meaUnit',name:'计量单位'}, {field:'orderPrice',name:'单价'}, {field:'money',name:'小计'}, {field:'moneyCount',name:'优惠后金额'}, {field:'remark',name:'备注'} ] }, getLogThead: function () { return [ {name:'序号',type:'pl4GridCount'}, {field:'taskId',name:'业务单号'}, {field:'custTaskId',name:'客户单号'}, {field:'handleDetail',name:'操作描述'}, {field:'handleMan',name:'操作人'}, {field:'handelTime',name:'操作时间'} ] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/workMonitor/getTaskDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function( url, data) { //将param转换成json字符串 data.param = $filter('json')(data.param); //console.log(data) var deferred = $q.defer(); $http.post(HOST + url, data) .success(function(data) { //console.log(data) deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
// Prototypal Inheritance // myPerson --> Person.prototype --> Object.prototype --> null class Person { constructor(firstName, lastName, age, likes = []) { this.firstName = firstName this.lastName = lastName this.age = age this.likes = likes } getBio() { let bio = `${this.firstName} is ${this.age}.` this.likes.forEach((like) => { bio += ` ${this.firstName} likes ${like}.` }) return bio } get fullName() { return `${this.firstName} ${this.lastName}` } set fullName(fullName) { const name = fullName.split(' ') this.firstName = name[0] this.lastName = name[1] } } // Subclass class Employee extends Person { constructor(firstName, lastName, age, position, likes) { super(firstName, lastName, age, likes) // retrieve Person constructor this.position = position } getBio() { return `${this.fullName} is a ${this.position}.` } getYearsLeft() { return 65 - this.age } } const me = new Employee('Jeff', 'Calaway', 28, 'Developer', ['Reading', 'Games']) me.fullName = 'Juan Padilla' console.log( me.getBio() ) console.log( me.getYearsLeft() )
import {fetchUtils} from '../utils'; const getUserInfo = () => { return fetchUtils.get('/Account/ILogin', {id: "12345678"}) }; const login = () => { return fetchUtils.post('/Account/ILogin', {UserName: "12345678", UserPwd: "888888888"}) }; export { getUserInfo, login, }
import React from 'react' import ExerciseCard from './ExerciseCard.js'; import { shallow, mount } from 'enzyme'; const props = { id: 1, name: 'pull-ups', description: 'a workout', fetchImageUrls: jest.fn(), toggleDetail: true, active: true, popularity: 1, statistics: { sets: 1, reps: 1, unit: 1, measure: 'lbs', type: 'Weight', } } describe('ExerciseCard Component', () => { it('should render', () => { const wrapper = shallow(<ExerciseCard {...props} />); expect(wrapper.length).toEqual(1); }); it('should display the name of the exercise', () => { const wrapper = shallow(<ExerciseCard {...props} />); }); it('should display sets, reps and weight when detail is shown', () => { const wrapper = shallow(<ExerciseCard {...props} />); }); it('should hide stats when detail is hidden', () => { const wrapper = shallow(<ExerciseCard {...props} />); }); })
var twitter = require('ntwitter'); //your secret keys go here var twit = new twitter({ consumer_key: 'jAn4JNC1w', consumer_secret: 'dJBlWoUvQK5KokueQKljNSfx35Y', access_token_key: '15182YvrTYnaM1nqLJsSlwqW5l', access_token_secret: '03Vb19tlhA3smNer3E9jxxI' }); twit.stream('statuses/sample', function(stream) { stream.on('data', function (data) { console.log(data); }); });
describe("src.core.Core.prototype - Bootstrap", () =>{ beforeEach(()=>{ require('../bootstrap.js')(); global.define = undefined; }); it("Should instantiate the define.js class",()=>{ require('../../src/core/Core.js')(); chai.expect(define).not.to.be.undefined; }); it("Should allow the customization of the alias used for the 'define' funciton",()=>{ require('../../src/core/Core.js')({ defineFunctionAlias: 'banana' }); chai.expect(define).to.be.undefined; chai.expect(banana).not.to.be.undefined; //cleanup global.banana = undefined; }); });
// test on creating a variable without var keyword i = 50; console.log("i = " + i);
// Part 1 function isNice(str) { let vowelRE = /(a|e|i|o|u)/gi, dupeRE = /([a-zA-Z])\1+/g, forbiddenRE = /(ab|cd|pq|xy)/gi, vowelMatches = str.match(vowelRE); return !!(!str.match(forbiddenRE) && (vowelMatches && vowelMatches.length >= 3) && str.match(dupeRE)); } function getNiceAmount(input) { var total = 0; input.forEach(function(str) { if (isNice(str)) { total += 1; } }); return total; } // Part 2 function isReallyNice(str) { let dupeRE = /([a-zA-Z]{2,3}).*\1/, repeatRE = /([a-zA-Z])((?!\1).)\1/; return !!(str.match(dupeRE) && str.match(repeatRE)); } function getReallyNiceAmount(input) { var total = 0; input.forEach(function(str) { if (isReallyNice(str)) { total += 1; } }); return total; }
import * as types from '../constants/ActionTypes'; export function addFriend(name) { return { type: 'ADD_FRIEND', payload:name }; }
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const Convs = require('../models/conv'); var authenticate = require('../authenticate'); const convRouter = express.Router(); convRouter.use(bodyParser.json()); convRouter.route('/') .get((req, res, next) => { Convs.find({}) .then((convs) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(convs); }, (err) => next(err)) .catch((err) => next(err)); }) .post(authenticate.verifyUser, (req, res, next) => { Convs.create(req.body) .then((conv) => { console.log('Conv Created ', conv); res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(conv); }, (err) => next(err)) .catch((err) => next(err)); }) .put(authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.setHeader('Content-Type', 'text/plain'); res.end('PUT operation not supported on /conv'); }) .delete(authenticate.verifyUser, (req, res, next) => { Convs.remove({}) .then((resp) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); convRouter.route('/:convId') .get((req, res, next) => { Convs.findById(req.params.convId) .then((conv) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(conv); }, (err) => next(err)) .catch((err) => next(err)); }) .post(authenticate.verifyUser,(req, res, next) => { res.statusCode = 403; res.setHeader('Content-Type', 'text/plain'); res.end('POST operation not supported on /conv/' + req.params.convId); }) .put(authenticate.verifyUser, (req, res, next) => { Convs.findByIdAndUpdate(req.params.convId, { $set: req.body }, { new: true }) .then((conv) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(conv); }, (err) => next(err)) .catch((err) => next(err)); }) .delete(authenticate.verifyUser, (req, res, next) => { Convs.findByIdAndRemove(req.params.convId) .then((resp) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); module.exports = convRouter;
(function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name angulartics.naver.analytics * Enables analytics support for Naver Analytics (http://analytics.naver.com) */ angular.module('angulartics.naver.analytics', ['angulartics']) .config(['$analyticsProvider', function ($analyticsProvider) { // Naver Analytics (WCS) doesn't support Buffered Invocation. // So, we wait for script until loaded using `angulartics.waitForVendorApi`. angulartics.waitForVendorApi('wcs', 1000, function(wcs) { // Naver Analytics (WCS) dosen't provide setting user information into analytics session. // So, we doesn't need to set default settings. $analyticsProvider.registerPageTrack(function (path) { var origin = location.protocol + '//' + location.host; wcs.setHref(origin + path); window._nasa ? wcs.pageview(_nasa) : wcs.pageview(); wcs.setRefererHref(origin + path); if (window._nasa && window._nasa.cnv) { delete window._nasa.cnv; } }); $analyticsProvider.registerEventTrack(function (action, properties) { if (!properties) { properties = {}; } wcs.event(action, properties.value); }); }); }]); })(window, window.angular);
const http = require('http'); const path = require('path'); const fs = require('fs'); const util = require('util'); const url = require('url'); const chalk = require('chalk'); const mime = require('mime'); const zlib = require('zlib'); const crypto = require('crypto'); const handlebars = require('handlebars'); const config = require('./config'); const debug = require('debug')('static:app'); const fsStat = util.promisify(fs.stat); const readDir = util.promisify(fs.readdir); class StaticServer{ constructor(argv){ this.config = Object.assign({},config,argv); this.compileTpl = compileTpl(); } startServer(){ let server = http.createServer(); server.on('request',this.request.bind(this)); server.listen(this.config.port,()=>{ let serverUrl = `http://${this.config.host}:${this.config.port}`; debug(`服务已开启,地址为${chalk.green(serverUrl)}`); }) } async request(req,res){ let {pathname} = url.parse(req.url); if(pathname == '/favicon.ico'){ return this.sendError('NOT FOUND',req,res); } //获取需要读的文件目录 let filePath = path.join(this.config.root,pathname); let statObj = await fsStat(filePath); if(statObj.isDirectory()){//如果是一个目录的话 列出目录下面的内容 let files = await readDir(filePath); let isHasIndexHtml = false; files = files.map(file=>{ if(file.indexOf('index.html')>-1){ isHasIndexHtml = true; } return { name:file, url:path.join(pathname,file) } }) if(isHasIndexHtml){ let statObjN = await fsStat(filePath+'/index.html'); return this.sendFile(req,res,filePath+'/index.html',statObjN); } let resHtml = this.compileTpl({ title:filePath, files }) res.setHeader('Content-Type','text/html'); res.end(resHtml); }else{ this.sendFile(req,res,filePath,statObj); } } sendFile(req,res,filePath,statObj){ //判断是否走缓存 if (this.getFileFromCache(req, res, statObj)) return; //如果走缓存,则直接返回 res.setHeader('Content-Type',mime.getType(filePath)+';charset=utf-8'); let encoding = this.getEncoding(req,res); //常见一个可读流 let rs = this.getPartStream(req,res,filePath,statObj); if(encoding){ rs.pipe(encoding).pipe(res); }else{ rs.pipe(res); } } sendError(error,req,res){ if(error=='NOT FOUND'){ res.statusCode = 404 }else{ res.statusCode = 500; } res.end(`${util.inspect(error)}`); } getPartStream(req,res,filePath,statObj){ let start = 0; let end = statObj.size -1; let range = req.headers['range']; if(range){ res.setHeader('Accept-Range','bytes'); res.statusCode = 206; let result = range.match(/bytes=(\d*)-(\d*)/); if(result){ start = isNaN(result[1]) ? start : parseInt(result[1]); end = isNaN(result[2]) ? end : parseInt(result[2]) - 1; } } return fs.createReadStream(filePath,{ start,end }) } getFileFromCache(req,res,statObj){ let ifModifiedSince = req.headers['if-modified-since']; let isNoneMatch = req.headers['if-none-match']; res.setHeader('Cache-Control','private,max-age=60'); res.setHeader('Expires',new Date(Date.now() + 60*1000).toUTCString()); let etag = crypto.createHash('sha1').update(statObj.ctime.toUTCString() + statObj.size).digest('hex'); let lastModified = statObj.ctime.toGMTString(); res.setHeader('ETag', etag); res.setHeader('Last-Modified', lastModified); if (isNoneMatch && isNoneMatch != etag) { return false; } if (ifModifiedSince && ifModifiedSince != lastModified) { return false; } if (isNoneMatch || ifModifiedSince) { res.statusCode = 304; res.end(''); return true; } else { return false; } } getEncoding(req,res){ let acceptEncoding = req.headers['accept-encoding']; if(acceptEncoding.match(/\bgzip\b/)){ res.setHeader('Content-Encoding','gzip'); return zlib.createGzip(); }else if(acceptEncoding.match(/\bdeflate\b/)){ res.setHeader('Conetnt-Encoding','deflate'); return zlib.createDeflate(); }else{ return null; } } } function compileTpl(){ //解析模板 try { let tmpHtml = fs.readFileSync(path.resolve(__dirname,'template','tpl.html'),'utf8'); return handlebars.compile(tmpHtml); } catch (error) { debug(`${util.inspect(error)}`) } } // let stServer = new StaticServer(); // stServer.startServer(); module.exports = StaticServer;
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * State Model * ========== */ var State = new keystone.List('State', { //track: true }); State.add({ name: { type: String, required: true, index: true }, locals: { type: Types.Relationship, ref: 'LocalGovernment', many: true }, }); /** * Registration */ State.defaultSort = 'name'; State.defaultColumns = 'name, locals'; State.register();
// medidas em metros const MIN_WALL_SIZE = 1; const MAX_WALL_SIZE = 15; const maxWallSize = (size) => { if (size < 1) { throw new Error(`O tamanho da parede não pode ser menor que ${MIN_WALL_SIZE} m`); }; if (size > 15) { throw new Error(`O tamanho da parede não pode ultrapassar ${MAX_WALL_SIZE} m`); }; }; const maxSizeOfWindowsAndDoors = (doorArea, WindowArea, wallArea) => { if (doorArea + WindowArea > wallArea / 2) { throw new Error( "O tamanho das portas e janelas não pode ultrapassar 50% do tamanho da parede" ); }; }; const minSizeOfWallWithDoor = (wallHeight, doorHeight) => { if (wallHeight - doorHeight < 0.30) { throw new Error("O espaço de parede acima da porta deve ser no mínimo 30 cm") }; }; module.exports = { maxWallSize, maxSizeOfWindowsAndDoors, minSizeOfWallWithDoor, };
var appConf = { app_id: serverConfig.app.app_id, app_key: serverConfig.app.app_key, app_secret_key: serverConfig.app.app_secret_key, // only for demo usage, real secret key must be hidden group_id: serverConfig.app.group_id, use_extlinks: true, group: { fullScope: [ 'MESSAGES_FROM_GROUP', 'GROUP_BOT_API_TOKEN' ].join(';'), scopeMap: { MESSAGES_FROM_GROUP: 'MESSAGES_FROM_GROUP', GROUP_BOT_API_TOKEN: 'GROUP_BOT_API_TOKEN' } }, /** application permissions * @see https://apiok.ru/ext/oauth/permissions * */ oauth: { scope: [ 'VALUABLE_ACCESS', 'PUBLISH_NOTE', 'PUBLISH_TO_STREAM', 'GROUP_CONTENT', 'PERSONAL_CONTENT', //'APP_INVITE', //'GET_EMAIL', 'PHOTO_CONTENT', 'SETTINGS', 'LIKE' ].join(';') //, layout: "w" }, widget_server: serverConfig.widget_server, api_server: serverConfig.api_server };
'use stict' var results = []; var calc = (num1, num2) => { if (typeof num1 == "number" && typeof num2 == "number") { results.push(num1 + " + " + num2 + " = " + Math.round((num1 + num2) * 1000) / 1000, num1 + " - " + num2 + " = " + Math.round((num1 - num2) * 1000) / 1000, num1 + " x " + num2 + " = " + Math.round((num1 * num2) * 1000) / 1000, num1 + " / " + num2 + " = " + Math.round((num1 / num2) * 1000) / 1000); } else if (num1 == undefined && typeof num2 == "number" || num2 == undefined && typeof num1 == "number") { results.push("The root of " + num1 + " is: " + Math.round(Math.sqrt(num1) * 1000) / 1000); } else if (typeof num1 != "number" || typeof num2 != "number") { results.push("Only numeric characters are valid"); } console.log(results); } console.log("Calculator of a parameter (square root), or two parameters (addition, subtraction, multiply and divide). * Returns an array with max. 3 decimals and only accept numbers."); console.log('Insert function "calc" with 1 or 2 parameters: Ej.: calc(5); // calc(1,2);');
import React, { Component } from 'react'; // import logo from './logo.svg'; import './App.css'; // import jwtDecode from 'jwt-decode'; import NavBar from './components/navBar'; import Movies from './components/movies'; // import NavBar from './components/navBar'; import { ToastContainer } from 'react-toastify'; import Customers from './components/customers'; import NotFound from './components/notFound' import Rentals from './components/rentals'; import { Route, Switch, Redirect } from 'react-router-dom' import MovieForm from './components/movieForm'; import LoginForm from './components/loginForm'; import Register from './components/register'; import MoviesForm from './components/moviesForm'; import ProtectedRoute from './components/common/protectedRoute'; import Logout from './components/logout'; import auth from './services/authService'; import "react-toastify/dist/ReactToastify.css"; // import Register from './components/register'; // import { getCurrentUser } from './services/authService'; // import ProtectedRoute from './components/common/protectedRoute'; console.log("SUPERMAN", process.env.REACT_APP_NAME); class App extends Component { state = {}; componentDidMount() { const user = auth.getCurrentUser(); this.setState({ user }); } render() { const { user } = this.state; return ( < React.Fragment > < ToastContainer / > < NavBar user = { user } / > < main className = "container" > < Switch > < Route path = "/login" component = { LoginForm } /> < Route path = "/logout" component = { Logout } /> < Route path = "/register" component = { Register } /> < Route path = "/moviesForm" component = { MoviesForm } / > < ProtectedRoute path = "/movies/:id" component = { MovieForm } / > < Route path = "/customers" component = { Customers } /> < Route path = "/rentals" component = { Rentals } /> < Route path = "/notFound" component = { NotFound } /> < Route path = "/movies" render = { props => < Movies {...props } user = { this.state.user } />} / > < Redirect from = "/" exact to = "/movies" / > < Redirect to = "/notFound" / > < /Switch > < / main > < /React.Fragment> ); } } export default App;
const API_KEY = ''; let h = document.getElementById("TN"); onload = () => { h.innerHTML = "Principais Notícias"; h.style.background = 'rgba(255, 0, 0, 0.959)'; let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; // https://newsapi.org/v2/everything?q= &apiKey= xhr.open('GET', `https://newsapi.org/v2/top-headlines?country=br&apiKey=${API_KEY}`); xhr.send(); //---------------------|Botões|------------------------ let PN = document.getElementById("PN"); PN.onclick = () => { executaPesquisaPN("top-headlines"); h.innerHTML = "Principais Notícias"; h.style.background = 'rgba(255, 0, 0, 0.959)'; } //--------------------------------------------- let TC = document.getElementById("TC"); TC.onclick = () => { executaPesquisaC("Tecnologia"); h.innerHTML = "Tecnologia"; h.style.background = 'rgb(49, 49, 199)'; } //--------------------------------------------- let EC = document.getElementById("EC"); EC.onclick = () => { executaPesquisaC("Economia"); h.innerHTML = "Economia"; h.style.background = 'rgb(0, 126, 0)'; } //--------------------------------------------- let PL = document.getElementById("PL"); PL.onclick = () => { executaPesquisaC("Política"); h.innerHTML = "Política"; h.style.background = 'orange'; } //--------------------------------------------- let EP = document.getElementById("EP"); EP.onclick = () => { executaPesquisaC("Esporte"); h.innerHTML = "Esporte"; h.style.background = 'rgba(0, 0, 0, 0.959)'; h.style.color = 'white'; } let CD = document.getElementById("CD"); CD.onclick = () => { executaPesquisaC("Covid-19"); h.innerHTML = "Covid-19"; h.style.background = 'rgba(0, 255, 42, 0.959)'; } //----------------------------------------------------------------------------------------------------- //---------------------|Botões 2|------------------------ //------------------------------------------------------------------------------------------------------- let PN2 = document.getElementById("PN2"); PN2.onclick = () => { executaPesquisaPN("top-headlines"); h.innerHTML = "Principais Notícias"; h.style.background = 'rgba(255, 0, 0, 0.959)'; } //--------------------------------------------- let TC2 = document.getElementById("TC2"); TC2.onclick = () => { executaPesquisaC("Tecnologia"); h.innerHTML = "Tecnologia"; h.style.background = 'rgb(49, 49, 199)'; } //--------------------------------------------- let EC2 = document.getElementById("EC2"); EC2.onclick = () => { executaPesquisaC("Economia"); h.innerHTML = "Economia"; h.style.background = 'rgb(0, 126, 0)'; } //--------------------------------------------- let PL2 = document.getElementById("PL2"); PL2.onclick = () => { executaPesquisaC("Política"); h.innerHTML = "Política"; h.style.background = 'orange'; } //--------------------------------------------- let EP2 = document.getElementById("EP2"); EP2.onclick = () => { executaPesquisaC("Esporte"); h.innerHTML = "Esporte"; h.style.background = 'rgba(0, 0, 0, 0.959)'; h.style.color = 'white'; } let CD2 = document.getElementById("CD2"); CD2.onclick = () => { executaPesquisaC("Covid-19"); h.innerHTML = "Covid-19"; h.style.background = 'rgba(0, 255, 42, 0.959)'; } //------------------------------------------------------- // Fontes de Noticia //-------------------------------------------------------- let Globo = document.getElementById("Globo"); Globo.onclick = () => { executaPesquisaF("globo"); h.innerHTML = "Globo"; h.style.background = 'rgb(155, 6, 6)'; } let infomoney = document.getElementById("info-money"); infomoney.onclick = () => { executaPesquisaF("info-money"); h.innerHTML = "InfoMoney"; h.style.background = 'rgba(0, 150, 42, 0.959)'; } let Google = document.getElementById("Google"); Google.onclick = () => { executaPesquisaF("google-news-br"); h.innerHTML = "Google News"; h.style.background = 'rgb(36, 105, 151)'; } let BBC = document.getElementById("BBC"); BBC.onclick = () => { executaPesquisaF("bbc-news"); h.innerHTML = "BBC"; h.style.background = 'rgb(155, 6, 6)'; } //------------------------------------------------------- // Fontes de Noticia //-------------------------------------------------------- let Globo2 = document.getElementById("Globo2"); Globo2.onclick = () => { executaPesquisaF("globo"); h.innerHTML = "Globo"; h.style.background = 'rgb(155, 6, 6)'; } let infomoney2 = document.getElementById("info-money2"); infomoney2.onclick = () => { executaPesquisaF("info-money"); h.innerHTML = "InfoMoney"; h.style.background = 'rgba(0, 150, 42, 0.959)'; } let Google2 = document.getElementById("Google2"); Google2.onclick = () => { executaPesquisaF("google-news-br"); h.innerHTML = "Google News"; h.style.background = 'rgb(36, 105, 151)'; } let BBC2 = document.getElementById("BBC2"); BBC2.onclick = () => { executaPesquisaF("bbc-news"); h.innerHTML = "BBC"; h.style.background = 'rgb(155, 6, 6)'; } }; function exibeNoticias() { let divTela = document.getElementById('tela'); let texto = ''; // Montar texto HTML das noticias let dados = JSON.parse(this.responseText); for (i = 0; i < dados.articles.length; i++) { let noticia = dados.articles[i]; let data = new Date(noticia.publishedAt); if (i % 2 == 0) { texto = texto + ` <div class="card-group"> <div class="card"> <img src="${noticia.urlToImage}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">${noticia.title}</h5> <p class="card-text"> <div class="creditos"> <span>${data.toLocaleDateString()} - ${noticia.source.name} - ${noticia.author}</span><br> </div> <span class="text"> ${noticia.content} <a href="${noticia.url}" target="_blank">Leia mais...</a> </span></p> </div> </div> `; } else { texto = texto + ` <div class="card"> <img src="${noticia.urlToImage}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">${noticia.title}</h5> <p class="card-text"> <div class="creditos"> <span>${data.toLocaleDateString()} - ${noticia.source.name} - ${noticia.author}</span><br> </div> <span class="text"> ${noticia.content} <a href="${noticia.url}" target="_blank">Leia mais...</a> </span></p> </div> </div> </div> `; } }; if (texto.length == 0) { texto = `<div id="mERRO"><p>ERRO: Desculpe, mas não encontramos resultados para essa pesquisa.</p></div>`; } // Preencher a DIV com o texto HTML divTela.innerHTML = texto; } // execultar noticias da barra de pesquisa 1 function executaPesquisa() { let query = document.getElementById('txtPesquisa').value; let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; // https://newsapi.org/v2/everything?q= &apiKey= xhr.open('GET', `https://newsapi.org/v2/everything?q=${query}&language=pt&apiKey=${API_KEY}`); xhr.send(); h.innerHTML = "Pesquisa"; h.style.background = 'darkslategray'; } // execultar noticias da barra de pesquisa 2 function executaPesquisaD() { let query = document.getElementById('txtPesquisa2').value; let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; // https://newsapi.org/v2/everything?q= &apiKey= xhr.open('GET', `https://newsapi.org/v2/everything?q=${query}&language=pt&apiKey=${API_KEY}`); xhr.send(); h.innerHTML = "Pesquisa"; h.style.background = 'darkslategray'; } // execultar pesquisa dos botões function executaPesquisaC(query) { let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; xhr.open('GET', `https://newsapi.org/v2/everything?q=${query}&language=pt&apiKey=${API_KEY}`); xhr.send(); } // executar pesquisa de noticias principais function executaPesquisaPN(query) { let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; xhr.open('GET', `https://newsapi.org/v2/top-headlines?country=br&apiKey=${API_KEY}`); xhr.send(); } function executaPesquisaF(query) { let xhr = new XMLHttpRequest(); xhr.onload = exibeNoticias; xhr.open('GET', `http://newsapi.org/v2/top-headlines?sources=${query}&apiKey=${API_KEY}`); xhr.send(); } // Barra de pesquisa 1 document.getElementById('btnPesquisa').addEventListener('click', executaPesquisa); //Barra de pesquisa 2 document.getElementById('btnPesquisa2').addEventListener('click', executaPesquisaD);
import React, { useState, useEffect } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { AppBar, Toolbar, IconButton, Menu, MenuItem, Link, Typography, Hidden } from '@material-ui/core'; import { Menu as MenuIcon, Person as AccountIcon, Search as SearchIcon, ArrowBack as ArrowBackIcon } from '@material-ui/icons'; import classNames from 'classnames'; import { logout } from '../../actions/authActions'; import { toggleSidebar } from '../../actions/sidebarActions'; // styles import useStyles from './styles'; const Header = ({ auth: { user }, logout, toggleSidebar }) => { const classes = useStyles(); const [sidebarOpen, setSidebarOpen] = useState(0); const [profileMenu, setProfileMenu] = useState(null); const handleSidebarOpen = id => () => { setSidebarOpen(!id); }; return ( <AppBar position="sticky" className={classes.appBar}> <Toolbar className={classes.toolbar}> <Hidden smUp> <IconButton color="inherit" onClick={() => toggleSidebar()}> <MenuIcon /> </IconButton> </Hidden> <IconButton aria-haspopup="true" color="inherit" aria-controls="profile-menu" className={classes.toolbarIcons} onClick={e => setProfileMenu(e.currentTarget)} > <AccountIcon classes={{ root: classes.headerIcon }} ></AccountIcon> </IconButton> <Menu id="profile-menu" anchorEl={profileMenu} classes={{ paper: classes.profileMenu }} className={classes.headerMenu} disableAutoFocusItem open={Boolean(profileMenu)} onClose={() => setProfileMenu(null)} > {user === null ? ( <p>Loading...</p> ) : ( <div className={classes.test}> <div className={classes.profileMenuUser}> <img className={classes.profileMenuUserIcon} src={user.avatar} alt="" /> <Typography variant="h4" weight="medium"> {user.name} </Typography> </div> <MenuItem className={classNames( classes.profileMenuItem, classes.headerMenuItem )} > <AccountIcon classes={{ root: classes.profileUserIcon }} className={classes.profileMenuIcon} ></AccountIcon>{' '} Account </MenuItem> <div className={classes.profileMenuUser}> <Link color="primary" className={classes.profileMenuLink} onClick={() => logout()} > Sign Out </Link> </div> </div> )} </Menu> </Toolbar> </AppBar> ); }; Header.propTypes = { auth: PropTypes.object.isRequired, logout: PropTypes.func.isRequired, toggleSidebar: PropTypes.func.isRequired }; const mapStateToProps = state => ({ auth: state.auth, isSidebarOpen: state.sidebar.isSidebarOpen }); export default connect(mapStateToProps, { logout, toggleSidebar })(Header);
import React, { Fragment } from "react"; import { Table, NavLink, Row, Col, Modal, ModalBody, ModalFooter, Button, Container } from "reactstrap"; import { connect } from "react-redux"; import { getRecord } from "../../actions/blockchainActions"; import Fmedicalrecords from "./fmedicalrecord"; import Fmedicalrecords1 from "./fprint/fmedicalrecord"; import ReactToPrint from "react-to-print"; import uuid from "uuid"; class Records extends React.Component { state = { modal2: false }; toggle2 = () => this.setState({ modal2: !this.state.modal2 }); record = (id) => { this.props.getRecord(id); this.setState({ modal2: !this.state.modal2 }); }; render() { const { records, firstName, middleName, lastName } = this.props.auth.patient; if (records.length === 0) { return ( <Container className="bgDesign"> <Container className="medhis"> <Table striped> <thead> <tr> <th>Record ID</th> <th>Date Added</th> <th>Clinician</th> </tr> </thead> <tbody> <tr> <td> </td> <td className="dataDesign">No Records</td> <td> </td> </tr> </tbody> </Table> </Container> </Container> ); } return ( <Container className="bgDesign"> <Container className="medhis"> <Table striped> <thead> <tr> <th>Record ID</th> <th>Date Updated</th> <th>Clinician</th> </tr> </thead> <tbody> {records.map(({ recordId, dateAdded, clinician }, index) => ( <tr key={index}> <td> <NavLink style={{ padding: "0px", color: "#007BFF" }} onClick={this.record.bind(this, recordId)} > {recordId} </NavLink> </td> <td>{dateAdded}</td> <td>{clinician}</td> </tr> ))} </tbody> </Table> </Container> <Modal centered isOpen={this.state.modal2} modalTransition={{ timeout: 700 }} backdropTransition={{ timeout: 1300 }} toggle2={this.toggle2} size="lg" > <ModalBody> <Fmedicalrecords /> </ModalBody> <ModalFooter> <Button color="secondary" style={{ borderRadius: "20px", width: "120px", fontWeight: "bold" }} onClick={this.toggle2} > Go back </Button> <ReactToPrint pageStyle="@page {margin: 1in .5in;}" trigger={() => ( <Button block color="primary" style={{ borderRadius: "20px", width: "120px", fontWeight: "bold" }} > Print </Button> )} content={() => this.componentRef2} /> <div style={{ display: "none" }}> {this.props.medrec.record !== null ? ( <Fmedicalrecords1 ref={(el) => (this.componentRef2 = el)} records={ <Fragment> <Row className="bordercolor"> <Col className="center1"> <h2>CONSULTATION RECORDS</h2> </Col> </Row> <Row className="bordercolor"> <Col> <h5> <b>Physical Examination Findings</b> </h5> </Col> </Row> <Row> <Col className="bordercolor" xs="2"> <h5> <b>Vital Signs</b> </h5> </Col> <Col className="bordercolor" xs="5"> <Col> Blood Pressure:{" "} {this.props.medrec.record.bloodPressure} </Col> <Col> Pulse Rate: {this.props.medrec.record.pulseRate} </Col> </Col> <Col className="bordercolor" xs="5"> <Col> Respiratory Rate:{" "} {this.props.medrec.record.respiratoryRate} </Col> <Col> Temperature: {this.props.medrec.record.temperature} </Col> </Col> </Row> <Row> <Col className="bordercolor"> <h5> <b>Physical Examination</b> </h5> </Col> <Col className="bordercolor" xs="10"> <Row> <Col className="bordercolor" xs="6"> HEENT </Col> <Col className="bordercolor" xs="6"> Heart </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.heent} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.heart} </div> </Col> <Col className="bordercolor" xs="6"> Lungs </Col> <Col className="bordercolor" xs="6"> Abdomen </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.lungs} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.abdomen} </div> </Col> <Col className="bordercolor" xs="12"> Extremities </Col> <Col className="bordercolor" xs="12"> <div className="divprint1"> {this.props.medrec.record.extremities} </div> </Col> </Row> </Col> </Row> <Row> <Col className="bordercolor"> <h5> <b>Laboratory Workups</b> </h5> </Col> <Col className="bordercolor" xs="10"> <Row> <Col className="bordercolor" xs="6"> Complete Blood Count(CBC) </Col> <Col className="bordercolor" xs="6"> Urinalysis </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.completeBloodCount} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.urinalysis} </div> </Col> <Col className="bordercolor" xs="6"> Fecalysis </Col> <Col className="bordercolor" xs="6"> Chest X-ray(CXR) </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.fecalysis} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.chestXray} </div> </Col> <Col className="bordercolor" xs="6"> Ishihara Test </Col> <Col className="bordercolor" xs="6"> Audio </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.isihiraTest} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.audio} </div> </Col> <Col className="bordercolor" xs="6"> Psychological Exam </Col> <Col className="bordercolor" xs="6"> Drug Test </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.psychologicalExam} </div> </Col> <Col className="bordercolor" xs="6"> <div className="divprint"> {this.props.medrec.record.drugTest} </div> </Col> <Col className="bordercolor" xs="12"> Hepatitis B Test </Col> <Col className="bordercolor" xs="12"> <div className="divprint1"> {this.props.medrec.record.hepatitisBTest} </div> </Col> </Row> </Col> </Row> <Row className="bordercolor"> <Col> <h5> <b>Complaints</b> </h5> </Col> </Row> <Row className="bordercolor"> <div className="divprint"> {this.props.medrec.record.complaints} </div> </Row> <Row className="bordercolor"> <Col> <h5> <b>Diagnosis</b> </h5> </Col> </Row> <Row className="bordercolor"> <div className="divprint"> {this.props.medrec.record.diagnosis} </div> </Row> <Row className="bordercolor"> <Col> <h5> <b>Treatment</b> </h5> </Col> </Row> <Row className="bordercolor"> <div className="divprint"> {this.props.medrec.record.treatment} </div> </Row> <Row className="bordercolor"> <Col> <h5> <b>Remarks</b> </h5> </Col> </Row> <Row className="bordercolor"> <div className="divprint"> {this.props.medrec.record.remarks} </div> </Row> <div class="divFooter"> Medical Record ID: {uuid.v4()} </div> <div class="divFooter"> Generated by: {firstName} {middleName} {lastName} </div> <div class="divFooter"> Date & Time: {new Date().toLocaleString("en-PH")} </div> </Fragment> } /> ) : null} </div> </ModalFooter> </Modal> </Container> ); } } const mapStateToProps = (state) => ({ auth: state.auth, medrec: state.medrec }); export default connect(mapStateToProps, { getRecord })(Records);
P.views.programs.schedule.DayEdit = P.views.Item.extend({ templateId: 'programs.schedule.day_edit', className: 'v-Day', events: { 'click .js-count': 'onSelect' }, clear: function() { var css = 'programSchedule-selection', js = 'js-selected'; this.$('.' + css).removeClass(css); this.$('.' + js).removeClass(js); }, select: function($el) { $el .addClass('programSchedule-selection') .addClass('js-selected'); }, onRender: function() { var count = this.model.get('count'); this.select(this.$('.js-count[data-count="' + count + '"]')); }, onSelect: function(event) { this.clear(); this.select($(event.currentTarget)); }, update: function() { var count = this.$('.js-selected').data('count'); count = parseInt(count, 10) || 0; this.model.set('count', count); } });
const MongoClient = require("mongodb").MongoClient; const bluebird = require("bluebird"); const uuid = require("uuid"); const validator = require("validator"); const dateFormat = require("dateformat"); const assert = require("assert"); const now = new Date(); const bcrypt = require("bcrypt-nodejs"); const salt = bcrypt.genSaltSync(6); var dbUrl = require("../db.js").url; exports.getAllRooms = function(req, res) { MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { db .collection("rooms") .find({}) .toArray((err, result) => { if (err) { res.json({ statusCode: 500, body: err }); } else if (result === null) { res.json({ statusCode: 201, body: "no room found" }); db.close(); } else if (result !== null) { res.json({ statusCode: 400, body: result }); db.close(); } }); } catch (err) { throw err; } }); }; exports.getRoomAvailability = function(req, res) { var newStartTime = parseFloat(req.body.start_time); var newEndTime = parseFloat(req.body.end_time); var booking_date = req.body.booking_date; MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { db .collection("rooms") .find( { booking_date: booking_date, reserved: { $not: { $elemMatch: { $or: [ { $and: [ { $or: [ { $and: [ { start_time: { $lt: newStartTime } }, { end_time: { $gt: newStartTime } } ] }, { $and: [ { start_time: { $lt: newEndTime } }, { end_time: { $gt: newEndTime } } ] }, { $and: [ { start_time: { $gte: newStartTime } }, { end_time: { $lte: newEndTime } } ] } ] }, { $or: [ { start_time: { $ne: newStartTime } }, { end_time: { $ne: newEndTime } } ] } ] }, { $and: [ { start_time: { $eq: newStartTime } }, { end_time: { $eq: newEndTime } } ] } ] } } } }, { room_name: 1, room_id: 1 } ) .toArray((err, result) => { console.log(result); if (err) { res.json({ statusCode: 500, body: err }); } else if (result.length === 0) { res.json({ statusCode: 404, body: { result: result, status: "Room is already booked" } }); db.close(); } else if (result) { console.log(result); res.json({ statusCode: 200, body: { result: result, status: "Room is available for booking" } }); db.close(); } }); } catch (err) { throw err; } }); }; exports.getRoomByDate = function(req, res, next) { const booking_date = req.body.booking_date; const room_id = req.body.room_id; var inputDate = new Date(booking_date); var todaysDate = new Date(); MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { // db.collection('rooms').aggregate({$unwind: "$reserved"},{$match: { "reserved.booking_date": {$gte: new Date(booking_date)}} },function(err, result) { // console.log(result); db .collection("rooms") .aggregate( { $unwind: "$reserved" }, { $match: { "reserved.booking_date": new Date(booking_date) } }, function(err, result) { console.log(result); res.json({ status: 200, result: result }); } ); } catch (err) { throw err; } }); }; exports.cancelBooking = function(req, res, next) { const booking_id = req.body.booking_id; const room_id = req.body.room_id; MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { db .collection("rooms") .findOneAndUpdate( { room_id: room_id }, { $pull: { reserved: { booking_id: booking_id } } }, { new: true }, (error, result) => { if (error) { res.json({ statusCode: 500, body: JSON.stringify(error) }); } else if (result) { res.json({ statusCode: 201, body: result }); } } ); } catch (err) { throw err; } }); }; exports.addBooking = function(req, res, next) { const room_id = req.body.room_id; const booking_date = new Date(req.body.booking_date); const booking_id = uuid.v1(); const booking_title = req.body.booking_title; const start_time = req.body.start_time; const end_time = req.body.end_time; const host_name = req.body.host_name; const host_userId = req.body.host_userId; const createdDateAndTime=Date(); let guest_list = req.body.guest_list; guest_list = JSON.parse(guest_list); const booking_status = true; const data = { booking_id, booking_date, booking_title, start_time, end_time, host_name, host_userId, guest_list, booking_status, createdDateAndTime }; MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { db .collection("rooms") .findOneAndUpdate( { room_id: room_id }, { $addToSet: { reserved: data } }, { new: true }, (err, response) => { if (err) { res.json({ statusCode: 500, body: JSON.stringify(err) }); } else if (response) { res.json({ statusCode: 201, body: response }); } } ); } catch (err) { throw err; } }); }; exports.getRoomList = function(req, res, next) { MongoClient.connect(dbUrl, { native_parser: true }, (err, db) => { assert.equal(null, err); try { if (req.query.type == 1) { db .collection("rooms") .find( {}, { room_id: 1, room_name: 1, company_location: 1, company_name: 1 } ) .toArray((err, result) => { res.json({ status: 200, roomList: result }); }); } if (req.query.type == 2) { { result = [ { _id: "59defa39d205237da05bbc34", contact_number: 9901377433, room_id: "3c5e25b6-acc1-11e7-abc4-cec278b6b50T", room_name: "Conference Name B" } ]; } res.json({ status: 200, callList: result }); // db.collection('calls').find({},{contact_number:1,room_name:1,company_location:1,company_name:1}).toArray((err, result) => { // res.json({"status":200,"callList":result}); // } ) } } catch (err) { throw err; } }); };
// window.onload = function(){ // // Blockly.HSV_SATURATION = 0.80; // // Blockly.HSV_VALUE = 0.90; // } // // const workspace = Blockly.inject( // 'blocklyDiv', // { // toolbox: document.getElementById('toolbox'), // trashcan: true, // }, // ); // // function showCode() { // // Blockly.JavaScript.INFINITE_LOOP_TRAP = null; // const jsCode = document.getElementById('jsCode'); // jsCode.innerHTML = Blockly.JavaScript.workspaceToCode(workspace); // } // // function runCode() { // const code = Blockly.JavaScript.workspaceToCode(workspace); // eval(code); // } // // document.getElementById('showCode').addEventListener('click', showCode, false); // document.getElementById('runCode').addEventListener('click', runCode, false);
import './assets/scss/app.scss'; import $ from 'cash-dom'; export class App { initializeApp() { let self = this; // Validation condition const letters = /^[0-9a-zA-Z \- \_]+$/; const input = document.querySelector('input') input.addEventListener('input', evt => { }) $('.load-username').on('click', function (e) { let userName = $('.username.input').val(); if (typeof userName == 'undefined' || !userName || userName.length === 0 || userName === "") { input.dataset.state = 'invalid' } else { if(userName.match(letters)) { input.dataset.state = 'valid' fetch('https://api.github.com/users/'+userName+'/events/public') .then(resp => resp.json()) .then(resp => { console.log(resp); resp.forEach(user => { self.update_profile(user); }) }) } else { input.dataset.state = 'invalid' } } }) } update_profile(user) { $('#profile-name').text($('.username.input').val()) $('#profile-image').attr('src', user.actor.avatar_url) $('#profile-url').attr('href', user.html).text(user.actor.login) $('#profile-bio').text(user.bio || '(no information)') } }
import React from 'react' // 创建一个全局的上下文对象 const context = React.createContext() export default context
// function mymap(arr,fn){ // const newArray=[]; // for (let i = 0; i < arr.length; i++) { // //newArray[i]=array[i]*2; // newArray.push(fn(arr[i],i)); // } // return newArray; // } // const array=[1,2,3,4]; // // console.log(array.map(element=>element * 2)); // // console.log(mymap(array,element=>element * 2)); // Array.prototype.map = function(item){ // console.log('map called'); // return item; // } // String.prototype.toUpperCase = function (){ // } // const x = array.map('asdas'); // console.log(x);
import React from 'react' import styled from 'styled-components' const Welcome = styled.h1` ` export default () => ( <Welcome> <span id='title'> Code yellow </span> <br/> <span> Lab for code experiments </span> </Welcome> )
const Job = require('../models/job-model'); createJob = (req, res) => { const body = req.body; if (!body) { return res.status(400).json({ success: false, error: 'You must provide a job', }); } body.status = 'Open'; const job = new Job(body); if (!job) { return res.status(400).json({ success: false, error: err }); } job .save() .then(() => { return res.status(201).json({ success: true, id: job._id, message: 'Job created!', }); }) .catch(error => { return res.status(400).json({ error, message: 'Job not created!', }); }); } updateJob = async (req, res) => { const body = req.body if (!body) { return res.status(400).json({ success: false, error: 'You must provide a body to update', }); } Job.findOne({ _id: req.params.id }, (err, job) => { if (err) { return res.status(404).json({ err, message: 'Job not found!', }); } job.status = body.status; job .save() .then(() => { return res.status(200).json({ success: true, id: job._id, message: 'Job updated!', }); }) .catch(error => { return res.status(404).json({ error, message: 'Job not updated!', }); }); }); } deleteJob = async (req, res) => { await Job.findOneAndDelete({ _id: req.params.id }, (err, job) => { if (err) { return res.status(400).json({ success: false, error: err }); } if (!job) { return res .status(404) .json({ success: false, error: `Job not found` }); } return res.status(200).json({ success: true, job }); }).catch(err => console.log(err)); } getJobById = async (req, res) => { await Job.findOne({ _id: req.params.id }, (err, job) => { if (err) { return res.status(400).json({ success: false, error: err }); } if (!job) { return res .status(404) .json({ success: false, error: `Job not found` }); } return res.status(200).json({ success: true, job }); }).catch(err => console.log(err)); } getJobs = async (req, res) => { await Job.find({}, (err, jobs) => { if (err) { return res.status(400).json({ success: false, error: err }); } if (!jobs.length) { return res .status(404) .json({ success: false, error: `Jobs not found` }); } return res.status(200).json({ success: true, jobs }); }).catch(err => console.log(err)); } module.exports = { createJob, updateJob, deleteJob, getJobs, getJobById, }
Layers.HUD = (function() { var LifeSprite = defineLifeSprite(); var M = cc.Layer.extend({ MARGIN: 10, INNER_MARGIN: 5, lifeSprites: [], weaponSprite: null, maxHealth: null, timerLabel: null, init: function(maxHealth) { this._super(); this.maxHealth = maxHealth; var lifeSection = this.createLifeSprites(maxHealth); this.createTimerLabel(); }, update: function(health, weaponSprite, timeLeft) { this.updateLabel(timeLeft); if(health < 0) return; for(var i = 0; i < health; i++) { if(!this.lifeSprites[i].isActive()) this.lifeSprites[i].activate(); } for(var i = health; i < this.maxHealth; i++) { if(this.lifeSprites[i].isActive()) this.lifeSprites[i].deactivate(); } if(this.weaponSprite === null && weaponSprite) { this.weaponSprite = weaponSprite; this.weaponSprite.removeFromParent(); this.addChild(weaponSprite); } else if(this.weaponSprite && !weaponSprite) { this.weaponSprite.removeFromParent(); this.weaponSprite = null; } if(this.weaponSprite) { var weaponPosition = this.getWeaponPosition(this.weaponSprite); this.weaponSprite.update(weaponPosition.x, weaponPosition.y); } }, getWeaponPosition: function(sprite) { return { x: cc.winSize.width/2, y: cc.winSize.height - sprite.size().height/2 } }, createLifeSprites: function() { var size = {width: 0, height: 0}; for(var i = 0; i < this.maxHealth; i++) { var sprite = new LifeSprite(); var x = sprite.size().width/2 + (sprite.size().width + this.INNER_MARGIN)*i + this.MARGIN; var y = cc.winSize.height - sprite.size().height/2 - this.MARGIN; sprite.setPosition({x: x, y: y}); this.addChild(sprite); this.lifeSprites.push(sprite); size.width += sprite.size().width + this.INNER_MARGIN; size.height = Math.max(sprite.size().height, size.height); } size.width += this.MARGIN; size.height += this.MARGIN; return { size: size }; }, createTimerLabel: function() { var label = new Sprites.RegularLabel(30); this.addChild(label); this.timerLabel = label; }, updateLabel: function(timeLeft) { this.timerLabel.setString(timeToString(timeLeft)); var size = this.timerLabel.size(); this.timerLabel.setPosition(cc.winSize.width - this.MARGIN - size.width/2, cc.winSize.height - size.height/2 - this.MARGIN); } }); function timeToString(timeLeft) { var minutes = Math.floor(timeLeft / 60); var seconds = Math.floor(timeLeft % 60); return padding(minutes, 2, "0") + ":" + padding(seconds, 2, "0") } function padding(number, size, fill) { var str = ""+number; while(str.length < size) { str = fill + str; } return str; } function defineLifeSprite() { return cc.Sprite.extend({ activated: null, ctor: function() { this._super(); this.initWithFile(res.horsefish_life_png); this.setScale(0.45); this.activate(); }, activate: function() { this.setOpacity(255); this.activated = true; }, deactivate: function() { this.setOpacity(50); this.activated = false; }, isActive: function() { return this.activated; }, size: function() { return { width: this.width * this.getScaleX(), height: this.height * this.getScaleY() } } }); } return M; }());
'use strict'; export default class db { constructor() { this.data = []; } findOne(id) { if (this.data.hasOwnProperty(id)) return Promise.resolve(this.data[id]); else return Promise.reject(); } save(url) { this.data.push(url); return Promise.resolve(this.data.length - 1); } }
//Function 1 function stringLetters(string) { for (var i=0; i<string.length; i++) { console.log(string[i]) } } stringLetters(" Hello "); //Function 2 function characterPosition(string, character) { var index = string.indexOf(character) if (index < 0) { return "Character Not Found" } else { return index } } console.log(characterPosition("hello", "o")); console.log(characterPosition("hello", "x")); //Function 3 function fortyTwo(array) { for (var i=0; i<array.length; i++) { if (array[i] === 42) { return "42 Has been found" } else if (array.length - 1 === i) { return "42 Has NOT been found" } } } console.log(fortyTwo([2,3,4,5,6,4,3,3,42])) console.log(fortyTwo([2,3,4,5,6,4,3,3,3])) //Function 4 function smallestNum(array) { var min = array[0] for (var i=1; i<array.length; i++) { if (min > array[i]) { min = array[i] } } return min } console.log(smallestNum([2,5,4,78,3,1,3,4,3]));
var mongoose = require('mongoose'); var Task = require('../models/taskModel'); var User = require('../models/userModel'); module.exports = function(app) { app.get('/api/setupTaskUsers', function(req, res){ var user = new User({ _id: new mongoose.Types.ObjectId(), name: 'TestUser' }); user.save(function (err) { if (err) throw err; var task = new Task({ _id: new mongoose.Types.ObjectId(), taskId: 'taskId', name: 'TestTask', description: 'This is Test Task.', status: 'Pending', user: user._id }); task.save(function (err) { if (err) throw err; res.send('Success'); }) }); // // User.create(user, function (err, results) { // if (err) throw err; // // var task = new Task({ // _id: new mongoose.Types.ObjectId(), // name: 'TestTask', // description: 'This is Test Task.', // status: 'Pending', // userId: user._id // }); // var userResult = results; // Task.create(task, function (err, results) { // if (err) throw err; // res.send([userResult,results]); // // }); // // }); }); }
import puppeteer from 'puppeteer'; import childProcces from 'child_process'; const server = childProcces.fork(`${__dirname}/test-server.js`); jest.setTimeout(60000); describe('Items list', () => { let browser = null; let page = null; const baseUrl = 'http://localhost:9000'; beforeAll(async () => { await new Promise((resolve, reject) => { server.on('error', () => { reject(); }); server.on('message', (message) => { if (message === 'ok') { resolve(); } }); }); browser = await puppeteer.launch({ // headless: false, // show gui // slowMo: 50, // devtools: true, // show devTools }); page = await browser.newPage(); }); afterAll(async () => { await browser.close(); server.kill(); }); test('.add button should add new item to the list', async () => { await page.goto(baseUrl); const $add = await page.$('#add'); const $title = await page.$('#title'); const $price = await page.$('#price'); const $submit = await page.$('#submit'); $add.click(); await $title.type('Xiaomi Mi5'); await Promise.all([ await $title.type('Xiaomi Mi5'), await $price.type('15000'), ]); $submit.click(); await page.waitFor(1000); const $items = await page.$$('.goods__item'); expect($items.length).toBe(4); }); test('.del button should remove item from the list', async () => { await page.goto(baseUrl); const $delBtns = await page.$$('.del'); await $delBtns[0].click(); await page.waitFor(1000); const $items = await page.$$('.goods__item'); expect($items.length).toBe(2); }); test('.edit button should edit current item in the list', async () => { await page.goto(baseUrl); const $edit = await page.$('.edit'); const $title = await page.$('#title'); const $price = await page.$('#price'); const $submit = await page.$('#submit'); $edit.click(); await page.click('#title'); await page.keyboard.down('Control'); await page.keyboard.press('KeyA'); await page.keyboard.up('Control'); await page.keyboard.press('Backspace'); await $title.type('Xiaomi Mi5'); await page.click('#price'); await page.keyboard.down('Control'); await page.keyboard.press('KeyA'); await page.keyboard.up('Control'); await page.keyboard.press('Backspace'); await $price.type('15000'); $submit.click(); await page.waitFor(1000); const $firstItemTitle = await page.$('#product__title'); const title = await page.evaluate((element) => element.textContent, $firstItemTitle); const $firstItemPrice = await page.$('#product__price'); const price = await page.evaluate((element) => element.textContent, $firstItemPrice); expect(title).toBe('Xiaomi Mi5'); expect(price).toBe('15000'); }); });
import React from 'react' import Navbar from '../../components/Navbar/Navbar' import Recorder from '../../components/Recorder/Recorder' export default class RecordPage extends React.Component{ componentDidMount(){ } render(){ return( <div> <Navbar/> <Recorder/> </div> ); } }
const express = require("express"); const router = express.Router(); const authUser = require("../middlewares/auth"); const PostsController = require("../Controllers/PostsController"); router .route("/") .get(PostsController.getAllPosts) .post(authUser, PostsController.createPost); router.route("/like/:postId").get(authUser, PostsController.likePost); router.route("/retweet/:postId").get(authUser, PostsController.retweetPost); router.route("/profile/:id").get(PostsController.userProfilePosts); router.route("/reply/:postId").post(authUser, PostsController.replyPost); router.route("/delete/:postId").delete(authUser, PostsController.deletePost); module.exports = router;
/* * Setup nock for test. */ const prepare = require('mocha-prepare') const nock = require('nock') const testData = require('./common/testData') prepare(function (done) { nock(/\.com/) .persist() .filteringPath(function (path) { if (path.startsWith(testData.CHALLENGE_API_PATH)) { return path.substring(testData.CHALLENGE_API_PATH.length) } return path }) .post(testData.AUTH_PATH) .reply((_uri, requestBody) => { if (requestBody.client_id === 'invalid') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.M2MAuth] }) .post(testData.AUTHN_PATH) .reply((_uri, requestBody) => { if (requestBody.username === 'invalid') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.Authv2] }) .post(testData.AUTHZ_PATH) .reply(200, testData.ResponseBody.Authv3) .get(/\/challenges\/.*/) .reply(function (_uri, _requestBody) { return [200, testData.ResponseBody.getChallengeResponse] }) .get(/\/challenges.*/) .reply(function (_uri, _requestBody) { return [200, testData.ResponseBody.searchChallengesResponse] }) .post('/challenges') .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.createChallengeResponse] }) .put(/\/challenges\/.+/) .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.updateChallengeResponse] }) .patch(/\/challenges\/.+/) .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.patchChallengeResponse] }) .get(/\/challengeTypes\/.*/) .reply(function (_uri, _requestBody) { return [200, testData.ResponseBody.getChallengeTypeResponse] }) .get(/\/challengeTypes.*/) .reply(function (_uri, _requestBody) { return [200, testData.ResponseBody.searchChallengeTypesResponse] }) .post('/challengeTypes') .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.createChallengeTypeResponse] }) .put(/\/challengeTypes\/.+/) .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.updateChallengeTypeResponse] }) .patch(/\/challengeTypes\/.+/) .reply(function (_uri, _requestBody) { if (this.req.headers.authorization === 'Bearer invalid_token') { return [400, { message: 'Unkown Error' }] } return [200, testData.ResponseBody.patchChallengeTypeResponse] }) done() }, function (done) { done() })
import Card from "react-bootstrap/Card"; import styled from "styled-components"; export const CardWrapper = styled(Card)` border: 1px solid lightgray; border-radius: 8px; box-shadow: 0 2px 8px rgb(0 0 0 / 10%); & .card-img-top { border-top-left-radius: 8px; border-top-right-radius: 8px; } `;
'use strict' const mongoose = require('mongoose') const router = require('express').Router() const Room = mongoose.model('Room') // Get all rooms router.get('/', (req, res) => { Room.find((err, rooms) => { if (err) return res.status(err.statusCode || 500).json({ error: err.message }) res.json(rooms) }) }) // Save a new room to the database router.post('/', (req, res) => { new Room(req.body).save((err, room) => { if (err) return res.status(err.statusCode || 500).json({ error: err.message }) res.json(room) }) }) // Get a room from the database router.get('/:id', (req, res) => { Room.findById(req.params.id, (err, room) => { if (err) return res.status(err.statusCode || 500).json({ error: err.message }) res.json(room) }) }) // Save room changes to the database router.patch('/:id', (req, res) => { Room.findByIdAndUpdate(req.params.id, req.body, (err, room) => { if (err) return res.status(err.statusCode || 500).json({ error: err.message }) res.json(room) }) }) // Delete a room from the database router.delete('/:id', (req, res) => { Room.findByIdAndRemove(req.params.id, (err, room) => { if (err) return res.status(err.statusCode || 500).json({ error: err.message }) res.json(room) }) }) module.exports = router
import VueAxios from 'vue-axios'; import axios from 'axios'; import VueRouter from 'vue-router'; import routes from './router'; import DataTable from "@andresouzaabreu/vue-data-table"; require("mdbvue/lib/css/mdb.min.css"); require('./bootstrap'); window.Vue = require('vue'); Vue.use(VueAxios, axios); Vue.use(VueRouter); Vue.component("data-table", DataTable); const app = new Vue({ el: '#app', router: new VueRouter(routes) });
import React,{useState} from 'react'; import {Modal,Button} from 'react-bootstrap'; import {firebaseApp} from '../firebaseConfig'; export default function AddStudent ({student,nendo}) { const [show,setShow] = useState(false); const [name,setName] = useState(''); const [furiname,setFuriname] = useState(''); const [callname,setCallname] = useState(''); const [studentId,setStudentId] = useState(''); const [gender,setGender] = useState(''); const [birth,setBirth] = useState(''); const [country,setCountry] = useState(''); const [phone,setPhone] = useState(''); const [address,setAddress] = useState(''); const [image,setImage] = useState(''); const [url,setUrl] = useState(''); const [checkImg,setCheckImg]= useState(true) const handleClose = () => setShow(false); const handleShow = () => setShow(true); const saveData = () => { if(image === ''){ setCheckImg(false) } else { const uploadTask = firebaseApp.storage().ref(`student${nendo}/${image.name}`).put(image); uploadTask.then( ()=>{ firebaseApp.storage() .ref(`student${nendo}`) .child(image.name) .getDownloadURL() .then(url=>{ setUrl(url); const newKeyId = firebaseApp.database().ref().push().key; let student={ name:name, furiname:furiname, callname:callname, studentId:studentId, gender:gender, birth:birth, country:country, phone:phone, address:address, imgurl:url, keyId:newKeyId } let updata ={} updata['studentdata/year'+nendo+'/'+newKeyId]=student; firebaseApp.database().ref().update(updata); setShow(false) }) } ) } } return( <> <Button variant="info" size="sm" onClick={handleShow}>学生追加</Button> <Modal show={show} onHide={handleClose}> <Modal.Header> <h4>{nendo}年度 ― 学生追加</h4> </Modal.Header> <Modal.Body> <div className="container"> <div className="form-group"> <label>名前</label> <input onChange={(e)=>{setName(e.target.value)}} type="text" className="form-control" placeholder="読売 or YOMIURI" /> </div> <div className="form-group"> <label>フリガナ</label> <input onChange={(e)=>{setFuriname(e.target.value)}} type="text" className="form-control" placeholder="ヨミウリ" /> </div> <div className="form-group"> <div className="row"> <div className="col-6"> <label>呼び名前</label> <input onChange={(e)=>{setCallname(e.target.value)}} type="text" className="form-control" placeholder="" /> </div> <div className="col-6"> <label>学生番号</label> <input onChange={(e)=>{setStudentId(e.target.value)}} type="text" className="form-control" placeholder="0000000" /> </div> </div> </div> <div className="form-group"> <div className="row"> <div className="col-6"> <label>性別</label> <select className="form-control" onChange={(e)=>{setGender(e.target.value)}} name="gender"> <option value="null">選択</option> <option value={true}>男性</option> <option value={false}>女性</option> </select> </div> <div className="col-6"> <label>生年月日</label> <input onChange={(e)=>{setBirth(e.target.value)}} type="text" className="form-control" placeholder="0000-00-00" /> </div> </div> </div> <div className="form-group"> <div className="row"> <div className="col-6"> <label>国籍</label> <input onChange={(e)=>{setCountry(e.target.value)}} type="text" className="form-control" placeholder="日本" /> </div> <div className="col-6"> <label>電話番号</label> <input onChange={(e)=>{setPhone(e.target.value)}} type="text" className="form-control" placeholder="" /> </div> </div> </div> <div className="form-group"> <label>住所</label> <input onChange={(e)=>{setAddress(e.target.value)}} type="text" className="form-control" placeholder="" /> </div> <div class="form-group"> <label>写真</label> <input onChange={(e)=>{setImage(e.target.files[0])}} type="file" className="ml-3" placeholder="" /> {checkImg?'':<small className="text-danger">学生の写真をアップロードしてください</small>} </div> <div className="form-group row justify-content-center"> <button className="btn btn-primary" onClick={saveData}>送信</button> <button className="btn btn-outline-dark mx-3" onClick={handleClose}>キャンセル</button> </div> </div> </Modal.Body> </Modal> </> ); }
import React,{Component} from 'react'; import {Link} from 'react-router-dom'; import * as BooksAPI from './BooksAPI' import './App.css' import Book from './Book.js'; class SearchPage extends Component{ state={ query:'', resultBooks:[], books:[], emptySearch:false } componentDidMount(){ BooksAPI.getAll() .then((books) =>{ this.setState(() =>({ books })); }) } updateQuery =(query) =>{ this.setState (() =>({ query: query, })) if(query){ BooksAPI.search(query.trim()) .then(books =>{ if(query===this.state.query){ books.length>0 ? this.setState({resultBooks:books, emptySearch:false}) : this.setState({resultBooks:[], emptySearch:true}) } }); } else { this.setState({resultBooks:[]}); } }; searchChangeShelf = (updatedBook, newShelf) =>{ BooksAPI.update(updatedBook,newShelf) .then(response =>{ updatedBook.shelf = newShelf; this.setState((prevState) =>({ books : prevState.books.filter((b) => b.id !== updatedBook.id).concat([updatedBook]), })) }); } render(){ const {resultBooks,emptySearch,books} = this.state; return( <div> <div className="search-books"> <div className="search-books-bar"> <Link to='/' className="close-search">Close Search </Link> <div className="search-books-input-wrapper"> <input type="text" placeholder="Search by title or author" value={this.state.query} onChange={(event) => this.updateQuery(event.target.value)} /> </div> </div> <div className="search-books-results"> <div> <ol className="books-grid"> {resultBooks.map(book =>( <Book books={books} book={book} key ={book.id} changeShelf={this.searchChangeShelf} shelf={book.shelf}/> ))} </ol> </div> {emptySearch && ( <h4>You do not have any search results. Please try again</h4>)} </div> </div> </div> ); } } export default SearchPage;
angular.module('shortly.links', []) .controller('LinksController', ['$scope', 'Links', function ($scope, Links) { // Your code here $scope.data = {}; $scope.getLinks = function(){ Links.getLinks() .then(function(linkData) { console.log(linkData); $scope.data.links = linkData; }); }; $scope.getLinks(); }]) .directive('ngLink', function() { return { restrict: 'E', template: " <div class='link'><img src='../assets/redirect_icon.png'> <div class='info'> <div class='visits'> <span class='count'> {{link.visits }} </span> Visits </div> <div class ='title'> {{ link.title }}</div> <div class='original'> {{ link.url }}</div> <a href ='{{ link.base_url + \"/api/links/\" + link.code }}'>{{ link.base_url + '/' + link.code }}</a> </div> </div>" }; });
/** * @license * * Copyright IBM Corp. 2020, 2021 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { Provider } from 'react-redux'; import DDSLeavingIbmContainer, { store, } from '@carbon/ibmdotcom-web-components/es/components-react/leaving-ibm/leaving-ibm-container.js'; const App = () => ( <Provider store={store}> <DDSLeavingIbmContainer href="https://www.carbondesignsystem.com/all-about-carbon/what-is-carbon/" open /> </Provider> ); export default App;
import React, { Component } from "react"; import AvatarEditor from "react-avatar-editor"; import { Button } from "semantic-ui-react"; import { Mutation } from "react-apollo"; import minus from "assets/minus-circle-outline.svg"; import plus from "assets/plus-circle-outline.svg"; import reload from "assets/reload-circle-outline.svg"; import { addToGallery } from "api/mutations"; import "./styles.scss"; export default class SimpleAvatarEditor extends Component { state = { scale: [1.5], rotate: 0, }; onClickSave = (uploadImage) => { if (this.editor) { const canvas = this.editor.getImage(); this.props.handleSaveImage(canvas, uploadImage); } }; setEditorRef = (editor) => (this.editor = editor); handleChangeRotate = () => this.setState({ rotate: this.state.rotate + 90 }); render() { const { width, height, borderRadius, image, border } = this.props; const { scale, rotate } = this.state; const value = parseFloat(scale); return ( <div className="avatar-editor-wrapp"> <AvatarEditor ref={this.setEditorRef} image={image || this.props.avatar.image} width={200} height={200} scale={scale} rotate={rotate} borderRadius={borderRadius} crossOrigin="anonymous" /> <div className="text-left" style={{ width: 250, margin: "auto" }}> <p>Zoom and Rotation</p> <div className="d-flex justify-content-between" style={{ paddingTop: "20px" }} > <img src={minus} className="pointer mr-3" onClick={() => this.setState({ scale: value > 1 ? [value - 0.1] : scale, }) } alt="" /> <div style={{ width: 106 }}> <input type="range" className="w-100" min={1} max={3} value={scale} step={0.1} onChange={(e) => this.setState({ scale: e.target.value })} /> </div> <img src={plus} className="pointer ml-3" onClick={() => this.setState({ scale: value < 100 ? [value + 0.1] : scale, }) } alt="" /> <img src={reload} className="ml-3 pointer" onClick={this.handleChangeRotate} alt="" /> </div> <Mutation mutation={addToGallery}> {(uploadImage, { loading }) => { return ( <Button className="primary-button w-100" loading={loading} disabled={loading} onClick={() => this.onClickSave(uploadImage)} style={{ marginTop: 18 }} > Save </Button> ); }} </Mutation> </div> </div> ); } }
"use strict"; var archDevRequire = require("@walmart/electrode-archetype-react-app-dev/require"); var mergeWebpackConfig = archDevRequire("webpack-partial").default; module.exports = function (babel) { return function (config) { return mergeWebpackConfig(config, { module: { loaders: [{ name: "babel", test: /\.jsx?$/, exclude: /(node_modules|\bclient\/vendor\b)/, // NOTE: webpack.config.hot.js inserts "react-hot" into loaders array loader: archDevRequire.resolve("babel-loader"), query: babel }, { name: "json", test: /\.json$/, loader: archDevRequire.resolve("json-loader") }] } }); }; };
module.exports = function(){ var express = require('express'); var router = express.Router(); //Selects all Locations to display to user function getLocations(res, mysql, context, complete){ mysql.pool.query("SELECT Hikes.hikeID, Hikes.hikeName, Locations.locationID as id, Locations.hikeID, Locations.city, Locations.state, Locations.zipCode FROM Locations JOIN Hikes ON Locations.hikeID = Hikes.hikeID", function(error, results, fields){ if(error){ res.write(JSON.stringify(error)); res.end(); } context.locations = results; complete(); }); } //Selects all Hikes to display to user function getHikes(res, mysql, context, complete){ mysql.pool.query("SELECT hikeID, hikeName, distance, elevation, difficulty, averageRating FROM Hikes", function(error, results, fields){ if(error){ res.write(JSON.stringify(error)); res.end(); } context.hikes = results; complete(); }); } //update function getLocation(res, mysql, context, id, complete){ var sql = "SELECT Hikes.hikeID, Hikes.hikeName, Locations.locationID as id, Locations.hikeID, Locations.city, Locations.state, Locations.zipCode FROM Locations JOIN Hikes ON Locations.hikeID = Hikes.hikeID WHERE locationID =?"; var inserts = [id]; mysql.pool.query(sql, inserts, function(error, results, fields){ if(error){ res.write(JSON.stringify(error)); res.end(); } context.locat = results[0]; complete(); }); } //Router to display search page router.get('/', function(req, res){ var callbackCount = 0; var context = {}; context.jsscripts = ["deletelocation.js", "searchhike.js"]; var mysql = req.app.get('mysql'); //Calling select functions getLocations(res, mysql, context, complete); getHikes(res, mysql, context, complete); //Complete function makes sure all select functions have finished before rendering page function complete(){ callbackCount++; if(callbackCount >= 2){ res.render('search', context); } } }); //Router to display search results /*router.post('/', function(req, res) { var mysql = req.app.get('mysql'); var sql = "SELECT hikeName, distance, elevation, difficulty, averageRating FROM Hikes WHERE hikeName LIKE %?%"; var inserts = [req.body.text_search]; sql = mysql.pool.query(sql,inserts,function(error, results, fields){ if(error){ res.write(JSON.stringify(error)); res.end(); }else{ res.redirect('/search'); } }); });*/ router.get('/:id', function(req, res){ callbackCount = 0; var context = {}; context.jsscripts = ["updatelocation.js"]; var mysql = req.app.get('mysql'); getLocation(res, mysql, context, req.params.id, complete); function complete() { callbackCount++; if(callbackCount >= 1){ res.render('update-search', context); } } }); /*update data is sent to in order to update a Locations */ router.put('/:id', function(req, res){ var mysql = req.app.get('mysql'); console.log(req.body) console.log(req.params.id) var sql = "UPDATE Locations SET state=?, city=? zipCode=? locationID=?"; var inserts = [req.body.state, req.body.city, req.body.zipCode, req.params.id]; sql = mysql.pool.query(sql,inserts,function(error, results, fields){ if(error){ res.write(JSON.stringify(error)); res.end(); }else{ res.status(200); res.end(); } }); }); //Insert for a location router.post('/', function(req, res){ var mysql = req.app.get('mysql'); var sql = "INSERT INTO Locations (locationID, hikeID, state, city, zipCode) VALUES (NULL,?,?,?,?)"; var inserts = [req.body.hikeName, req.body.state, req.body.city, req.body.zipCode]; sql = mysql.pool.query(sql,inserts,function(error, results, fields){ if(error){ console.log(JSON.stringify(error)) res.write(JSON.stringify(error)); res.end(); }else{ res.redirect('/search'); } }); }); //Delete a location router.delete('/:id', function(req, res){ var mysql = req.app.get('mysql'); var sql = "DELETE FROM Locations WHERE locationID = ?"; var inserts = [req.params.id]; sql = mysql.pool.query(sql, inserts, function(error, results, fields) { if(error){ console.log(error) res.write(JSON.stringify(error)); res.status(400); res.end(); }else{ res.status(202).end(); } }) }) return router; }();
const {readFile} = require("fs"); const {readdirSync} = require("fs"); let regexp = new RegExp(process.argv[2]); let files = [...process.argv].slice(3); function checkSubDirs(dir) { for (let subfile of readdirSync(dir)) { readFile(dir+"/"+subfile, "utf8", (error, text) => { if (error) { if (error.code = "EISDIR") checkSubDirs(dir+"/"+subfile); else throw errow; } if (regexp.test(text)) console.log(dir+"/"+subfile); }); } } for (let file of files) { readFile(file, "utf8", (error, text) => { if (error) { if (error.code == "EISDIR") { checkSubDirs(file); } else throw error; } if (regexp.test(text)) console.log(file); }); }
function currency(value) { if (isNaN(value)) return value; return numbro(value).formatCurrency('0,0.00'); } function number(value, format) { if (isNaN(value)) return value; return numbro(value).format(format); } function headers(batch) { return _.compact([ batch.hdr_pay_code1, batch.hdr_pay_code2, batch.hdr_pay_code3, batch.hdr_pay_code4, batch.hdr_pay_code5, batch.hdr_pay_code6, batch.hdr_pay_code7, batch.hdr_pay_code8, batch.hdr_pay_code9, batch.hdr_pay_code10, ]) } function date(value) { return moment(value).format('MM/DD/YYYY'); } function period_desc(period) { switch (period) { case 'W': return 'WEEKL'; } }