text
stringlengths
7
3.69M
module.exports = { "content": [{ "id": "5ebb8b347b8a7c11150e6eb2", "image": "https://i1-giaitri.vnecdn.net/2020/05/24/Avatar-1590294287-1673-1590294326.jpg?w=300&h=180&q=100&dpr=2&fit=crop&s=99dGoZVO67kkTfMqnsHHwQ", "internalTitle": "category 1", "lastModified": "2020-05-07T04:09:43.243+0000", "status": "inactive", "created": "2020-05-07T04:09:43.243+0000", "activatedDate": "2020-05-07T04:09:43.243+0000", "creator": "letruongan@gmail.com", "shows": 1 }, { "id": "5ebb8bd4c5a6d91115964ffe", "image": "https://i1-giaitri.vnecdn.net/2020/05/21/settopjusticeleaguebansnydercu-6262-3659-1590042775.jpg?w=300&h=180&q=100&dpr=2&fit=crop&s=5qJpRdiiluSxC7EPZfHsqg", "internalTitle": "category 2", "lastModified": "2020-05-07T04:09:43.243+0000", "status": "activated", "created": "2020-05-07T04:09:43.243+0000", "activatedDate": "2020-05-07T04:09:43.243+0000", "shows": 4, "creator": "tester_create@gmail.com" }, { "id": "5ebb8bd7c5a6d91115965000", "image": "https://i1-giaitri.vnecdn.net/2020/05/26/settopduonghamsinhtu-159047395-1781-1716-1590473995.jpg?w=300&h=180&q=100&dpr=2&fit=crop&s=B4hAuszyBJq5sDa5-QBS_A", "internalTitle": "category 3", "lastModified": "2020-05-07T04:09:43.243+0000", "status": "draft", "created": "2020-05-07T04:09:43.243+0000", "activatedDate": "2020-05-07T04:09:43.243+0000", "shows": 3, "creator": "tester_create@gmail.com" }, { "id": "5ebb8bd7c5a6d91115965000", "image": "https://i1-giaitri.vnecdn.net/2020/05/27/TomCruisetop-1590552355-9891-1590552452.jpg?w=300&h=180&q=100&dpr=2&fit=crop&s=ndEyn5dou9gov6gbOEgOEg", "internalTitle": "cacategory 4", "lastModified": "2020-05-07T04:09:43.243+0000", "status": "updated", "created": "2020-05-07T04:09:43.243+0000", "activatedDate": "2020-05-07T04:09:43.243+0000", "shows": 3, "creator": "tester_create@gmail.com" } ], "totalElements": 4, "totalPages": 1 }; // // time: '2020-05-17T08:41:07.142Z', // // errorCode: '1007', // // internalMessage: 'Bad Request', // // userMessage: 'Invalid Request Error', // // errors: [ // // { // // property: 'name', // // invalidValue: 'null', // // message: 'must not be blank' // // }, // // { // // property: 'rightType', // // invalidValue: 'null', // // message: 'must not be null' // // } // // ] // };
let pessoa = { nome: 'Rodrigo', altura: 1.72, peso: 85, }; const { nome, altura, peso: weight } = pessoa; console.log(weight); let listaCompras = ['pão', 'leite', 'açúcar']; const [item1, item2, item3] = listaCompras; console.log(item2);
// @flow export function removePrefix(property: ?string): ?string { if (property == null) { return null } return property.replace(/^-.*-/, "") }
import React, { Component } from 'react'; import { message, Select } from 'antd'; import CommitteeHeader from './CommitteeHeader.jsx'; import RequirementsTable from './RequirementsTable.jsx'; import MembersTable from './MembersTable.jsx'; import axios from 'axios'; import SearchDropDown from '../common/SearchDropDown.jsx'; const { Option } = Select; export default class App extends Component { constructor(props) { super(props); let value = 1; if (this.props.location.state !== undefined) { value = this.props.location.state.selected; } this.state = { committee: [], committeeId: 1, committeeAssignment: {}, committeeSlots: {}, committees: [], dataLoaded: false, selected: value, }; this.rerenderParentCallback = this.rerenderParentCallback.bind(this); } componentDidMount() { this.fetchCommittees(); } rerenderParentCallback() { this.fetchCommittees(); } fetchCommitteeInfo(id) { axios .get(`/api/committee/info/${id}`) .then(response => { this.setState({ committee: response.data, committeeId: response.data.id, committeeAssignment: response.data['committeeAssignment'], committeeSlots: response.data['committeeSlots'], dataLoaded: true, }); }) .catch(err => { message.error(err); }); } fetchCommittees() { axios .get('/api/committees') .then(firstResponse => { axios .get(`/api/committee/info/${this.state.selected}`) .then(secondResponse => { this.setState({ committees: firstResponse.data, committee: secondResponse.data, committeeId: secondResponse.data.id, defaultCommittee: secondResponse.data.name, committeeAssignment: secondResponse.data['committeeAssignment'], committeeSlots: secondResponse.data['committeeSlots'], dataLoaded: true, }); }); }) .catch(err => { console.debug('Failed to fetch: ', { err }); }); } handleChange = value => { this.setState({ selected: value, }); this.fetchCommitteeInfo(value); }; render() { const options = this.state.committees.map(committees => ( <Option key={committees.committee_id}>{committees.name}</Option> )); return ( <div className="committeeTable"> <div className="table-wrapper"> {this.state.dataLoaded && ( <React.Fragment> <SearchDropDown dataMembers={options} placeholder="Search Committees" onChange={this.handleChange} dividerText="Committee Info" default={this.state.defaultCommittee} showInfo={true} /> <CommitteeHeader data={this.state.committee} committeeId={this.state.committeeId} rerenderParentCallback={this.rerenderParentCallback} /> <MembersTable data={this.state.committeeAssignment} id={this.state.committeeId} rerenderParentCallback={this.rerenderParentCallback} /> <RequirementsTable data={this.state.committeeSlots} committeeId={this.state.committeeId} rerenderParentCallback={this.rerenderParentCallback} /> </React.Fragment> )} </div> </div> ); } }
import React from 'react' const index = (props) => { const progressError = props.progressError const progressValue = props.progressValue return ( <div className='getloader-default-progressBar'> <div className={`progress-value ${progressError}`} style={{ width: `${progressValue}%` }} /> </div> ) } export default index
var request = require('request'); var initLon = null; var initLat = null; function deg2rad(deg) { return deg * (Math.PI / 180); } function hypotenuseDistance(lat1, lon1, lat2, lon2) { var R = 6371000; // Radius of the earth in m var dLat = deg2rad(lat2 - lat1); // deg2rad below var dLon = deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; // Distance in m return d; } function findXDistance(initLat, newLat) { return (newLat - initLat) * 111230; } function square(number) { return number * number; } function findYDistance(hypotenuse, xDistance, initLon, newLon) { var yDistance = Math.sqrt(square(hypotenuse) - square(xDistance)); return (newLon - initLon > 0) ? yDistance : -1 * yDistance; } function checkInit(req) { if (req.body.threejsLat === 0 && req.body.threejsLon === 0) { initLat = req.body.latitude; initLon = req.body.longitude; } } var placesKeyword = { food: 'restaurant', hotel: 'lodging', cafes: 'bakery|cafe', nightlife: 'bar|night_club', shopping: 'clothing_store|department_store|electronics_store|shopping_mall', publicTransit: 'bus_station|subway_station|train_station', bank: 'atm|bank', gasStation: 'gas_station', parking: 'parking', park: 'park', }; function placesFilter(obj) { var filtered = false; var results = []; for (var key in obj) { if (obj[key] === true) { filtered = true; results.push(placesKeyword[key]); } } if (filtered) { return `&type=${results.join('+')}`; } else { return ''; } } function placesSearch(string) { if (string === '' || string === undefined) { return ''; } else { var stringArray = string.split(' '); return `&keyword=${stringArray.join('+')}`; } } function getPlaces(req, res) { checkInit(req); var googleOpenNow = ''; if (req.body.openNow !== undefined) { googleOpenNow = '&opennow'; } var radius = 1000; var apiKey = 'AIzaSyD7aR69bFQ1ao2A3PKTBRGUEp4cSWaxnmw'; var link = `https://maps.googleapis.com/maps/api/place/search/json?location=${req.body.latitude},${req.body.longitude}&radius=${radius}${placesFilter(req.body)}${googleOpenNow}${placesSearch(req.body.placeSearch)}&key=${apiKey}`; return new Promise((resolve, reject) => { request(link, function(error, response, body) { if (!error && response.statusCode === 200) { var placesObj = []; var googleResults = JSON.parse(body); googleResults.results.forEach(function(result, index) { var googleLat = findXDistance(initLat, result.geometry.location.lat); var distanceFromInit = hypotenuseDistance(initLat, initLon, result.geometry.location.lat, result.geometry.location.lng); var googleDistance = hypotenuseDistance(req.body.latitude, req.body.longitude, result.geometry.location.lat, result.geometry.location.lng); var googleLon = findYDistance(distanceFromInit, googleLat, initLon, req.body.longitude); googleDistance = Math.floor(googleDistance * 3.28084); var name = result.name; if (name !== null) { name = result.name.replace(/'/g, ''); } var address = result.vicinity; if (address !== null) { address = result.vicinity.replace(/'/g, ''); } var place = { name: name, googleId: result.place_id, lat: googleLat, lon: googleLon, realLat: result.geometry.location.lat, realLon: result.geometry.location.lng, distance: googleDistance, img: result.icon, address: address, type: 'place', }; placesObj.push(place); }); resolve(res.send(placesObj)); } }); }); } function dateFormat(date) { var day = date.getDate(); if ((date.getDate()) <= 9) { day = `0${date.getDate()}`; } var month = date.getMonth() + 1; if ((date.getMonth() + 1) <= 9) { month = `0${date.getMonth() + 1}`; } return `${date.getFullYear()}${month}${day}00`; } var eventsCategory = { business: 'conference+business', family: 'family_fun_kids', comedy: 'comedy', festivals: 'festivals_parades+food,outdoors_recreation', sports: 'sports', music: 'music', social: 'attractions+community+singles_social', film: 'movies_film', art: 'art+performing_arts', sci_tec: 'science+technology', }; function eventsFilter(obj, string) { var filtered = false; var results = []; for (var key in obj) { if (obj[key] === true) { filtered = true; results.push(eventsCategory[key]); } } if (string !== '' || string !== undefined) { filtered = true; results.push(string); } if (filtered) { return `&q=${results.join('+')}`; } else { return ''; } } function getEvents(req, res) { checkInit(req); var startDate = new Date(); var endDate = new Date(); endDate.setDate(endDate.getDate() + req.body.eventDays - 1); var date = `${dateFormat(startDate)}-${dateFormat(endDate)}`; var eventsApiKey = 'CbNBBV9Qm4wTwMpg'; var radius = 0.5; var eventsApiLink = `http://api.eventful.com/json/events/search?...&location=${req.body.latitude},${req.body.longitude}&within=${radius}&units=miles&date=${date}${eventsFilter(req.body, req.body.eventSearch)}&app_key=${eventsApiKey}`; return new Promise((resolve, reject) => { request(eventsApiLink, function(error, response, body) { if (error) { reject(error); } else { if (!error && response.statusCode === 200) { var eventObj = []; var eventsResults = JSON.parse(body); if (eventsResults.events !== null && eventsResults.events.event[0] !== undefined) { eventsResults.events.event.forEach(function(event) { var eventLat = findXDistance(initLat, event.latitude); var distanceFromInit = hypotenuseDistance(initLat, initLon, event.latitude, event.longitude); var eventDistance = hypotenuseDistance(req.body.latitude, req.body.longitude, event.latitude, event.longitude); var eventLon = findYDistance(distanceFromInit, eventLat, initLon, req.body.longitude); eventDistance = Math.floor(eventDistance * 3.28084); var name = event.title; if (name !== null) { name = event.title.replace(/'/g, ''); name = event.title.replace(/&#39/g, ''); } var venue = event.venue_name; if (venue !== null) { venue = event.venue_name.replace(/'/g, ''); venue = event.venue_name.replace(/&#39/g, ''); } var address = event.venue_address; if (address !== null) { address = event.venue_address.replace(/'/g, ''); venue = event.venue_name.replace(/&#39/g, ''); } var description = event.description; if (description !== null) { description = event.description.replace(/'/g, ''); description = event.description.replace(/&#39/g, ''); } var place = { name: name, venue: venue, address: address, startTime: event.start_time, endTime: event.stop_time, lat: eventLat, lon: eventLon, realLat: event.latitude, realLon: event.longitude, distance: eventDistance, url: event.url, image: event.image, details: event.description, type: 'event' }; eventObj.push(place); }); } resolve(res.send(eventObj)); } } }); }); } function getPhotos(req, res) { var flickrApiKey = '0067ef61b0e0fe17b2d46892a314223b'; var flickrGetPhotosLink = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${flickrApiKey}&text=san+francisco+${req.body.name.replace(' ', '+')}&format=json&nojsoncallback=1`; return new Promise((resolve, reject) => { request(flickrGetPhotosLink, function(error, response, body) { if (error) { reject(error); } else { var results = []; var images = JSON.parse(body); images.photos.photo.forEach(function(item) { var url = `https://farm${item.farm}.staticflickr.com/${item.server}/${item.id}_${item.secret}.jpg`; results.push(url); }); } resolve(res.send(results)); }); }); } function getDirections(req, res) { var ApiDirectionKey = 'AIzaSyD2yLYA4u-MuYGMJrBgrerIF898U2s6MlA'; var getDirectionsLink = `https://maps.googleapis.com/maps/api/directions/json?origin=${req.body.curLat},${req.body.curLon}&destination=${req.body.destLat},${req.body.destLon}&mode=walking&key=${ApiDirectionKey}`; return new Promise((resolve, reject) => { request(getDirectionsLink, function(error, response, body) { if (error) { reject(error); } else { var results = []; var directions = JSON.parse(body); directions.routes[0].legs[0].steps.forEach(function(item) { var newItems = item.html_instructions.replace('<div style="font-size:0.9em">', '. '); results.push(newItems.replace(/<(?:.|\n)*?>/gm, '')); }); } resolve(res.send(results)); }); }); } module.exports = { getPlaces, getEvents, getPhotos, getDirections, };
var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var levelData = (function () { function levelData() { //声明一个数组。用来保存关卡数据 this.items = []; //加载所有数据 this.items = RES.getRes('questions_json'); } levelData.Shared = function () { if (levelData.shared == null) { levelData.shared = new levelData(); } return levelData.shared; }; //通过关卡号获取该关卡的数据 levelData.prototype.getLevel = function (level) { if (level < 0) { level = 0; } if (level >= this.items.length) { level = this.items.length - 1; } //通过数据下标访问数据 return this.items[level]; }; Object.defineProperty(levelData.prototype, "Miletone", { //获取当前游戏最远的进度 get: function () { var miletone = egret.localStorage.getItem('guessWord'); if (miletone == '' || miletone == null) { miletone = '1'; } return parseInt(miletone); }, //设置当前游戏最远的进度 set: function (val) { egret.localStorage.setItem('guessWord', val.toString()); }, enumerable: true, configurable: true }); return levelData; }()); __reflect(levelData.prototype, "levelData"); //每个关卡的model var levelDatas = (function () { function levelDatas() { } return levelDatas; }()); __reflect(levelDatas.prototype, "levelDatas");
window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (window.pageYOffset > 50 && window.innerWidth <= 875) { document.getElementById("navbar").style.height = "50px"; document.getElementById("logo").style.height = "50px"; document.getElementById("header").style.backgroundColor = "#fff"; document.getElementById("nav-text-dropdown").style.top = "50px"; document.getElementById("nav-text-dropdown").style.left = "0px"; document.getElementById("nav-text-dropdown").style.backgroundColor = "#fff"; } else if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) { document.getElementById("navbar").style.height = "50px"; document.getElementById("logo").style.height = "50px"; document.getElementById("header").style.backgroundColor = "#fff"; document.getElementById("nav-text-dropdown").style.top = "50px"; document.getElementById("nav-text-dropdown").style.left = "0px"; document.getElementById("nav-text-dropdown").style.backgroundColor = "#fff"; } else { document.getElementById("navbar").style.height = "100px"; document.getElementById("logo").style.height = "100px"; document.getElementById("header").style.backgroundColor = "#fff"; document.getElementById("nav-text-dropdown").style.top = "100px"; document.getElementById("nav-text-dropdown").style.left = "0px"; document.getElementById("nav-text-dropdown").style.backgroundColor = "#fff"; } }
// @flow weak import React, { Component } from 'react'; import Radio from 'material-ui/Radio'; import { withStyles } from 'material-ui/styles'; import PropTypes from 'prop-types'; const styles = { container: { // maxWidth: 400, // flexGrow: 1, // position: 'absolute', // bottom: '0', // width: '100vw', // maxWidth: '960px', // backgroundColor: 'white' }, // backgroundColor: 'white', }; class DotsMobileStepper extends Component { state = { selectedValue: undefined, }; handleChange = event => { this.setState({ selectedValue: event.currentTarget.value }); }; render() { const { classes } = this.props; return ( <div className={classes.container}> <Radio checked={this.props.position === 0} onChange={this.handleChange} value="a" name="radio button demo" aria-label="A" /> <Radio checked={this.props.position === 1} onChange={this.handleChange} value="b" name="radio button demo" aria-label="B" /> <Radio checked={this.props.position === 2} onChange={this.handleChange} value="c" name="radio button demo" aria-label="C" /> <Radio checked={this.props.position === 3} onChange={this.handleChange} value="c" name="radio button demo" aria-label="C" /> </div> ); } } DotsMobileStepper.propTypes = { classes: PropTypes.object.isRequired } export default withStyles(styles)(DotsMobileStepper); // // ========== BELOW IS THE ORIGINAL ========== // // // import React, { Component } from 'react'; // import PropTypes from 'prop-types'; // import { withStyles } from 'material-ui/styles'; // import MobileStepper from 'material-ui/MobileStepper'; // // const styles = { // root: { // maxWidth: 400, // flexGrow: 1, // }, // backgroundColor: 'white', // position: 'absolute', // bottom: '0', // width: '100vw', // maxWidth: '960px' // // }; // // class DotsMobileStepper extends Component { // state = { // activeStep: 0, // }; // // handleNext = () => { // this.setState({ // activeStep: this.state.activeStep + 1, // }); // }; // // handleBack = () => { // this.setState({ // activeStep: this.state.activeStep - 1, // }); // }; // // render() { // const classes = this.props.classes; // return ( // <MobileStepper // type="dots" // steps={4} // position="static" // activeStep={this.props.position} // disableBack={true} // disableNext={true} // style={styles} // /> // ); // } // } // // DotsMobileStepper.propTypes = { // classes: PropTypes.object.isRequired, // }; // // export default DotsMobileStepper;
import Mock from 'mockjs'; const getTable = Mock.mock(location.origin + '/api/getTable.json', 'get', { 'listData': [ { orderId: '61011727', customerName: '小红', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '73580830', customerName: '小明', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '90506090', customerName: '小明', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '64413424', customerName: '小明', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '73725798', customerName: '小黑', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '91780336', customerName: '小黑', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '91775287', customerName: '小黑', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '38370406', customerName: '小黑', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '18339567', customerName: '小蓝', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '80573291', customerName: '小蓝', placeOrder: '自主下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' }, { orderId: '91635681', customerName: '小红', placeOrder: '代下单', goodsName: '智能机器人', price: '¥199', placeOrderTime: '2018-12-17' } ] }); export { getTable };
import {HtmlView} from "gml-html"; import template from './template.html'; import * as style from './style.scss'; export default async function ({ locale, system, thread }) { const view = HtmlView(template, style, locale.get()); view.style(); rx.connect .partial({ logged: () => system.store.hasLogged, email: () => system.store.email }) .subscribe(function ({logged, email}) { view.get('email').innerHTML = logged ? email : locale.get('menuHeader.userNotLogged'); view.get('logout').style.display = logged ? 'block' : 'none'; view.get('login').style.display = !logged ? 'block' : 'none'; view.get('register').style.display = !logged ? 'block' : 'none'; }); view.get('form').logout = async function () { system.store.loading = true; await thread.execute('user/logout'); system.store.loading = false; system.store.logged = false; system.navigateTo(locale.get('urls.homePage.href')); }; return view; }
//@prepros-append jquery-3.4.1.js //@prepros-append parallax.js //@prepros-append parallax-conf.js
var ShaderProgram = function ( vsSource, fsSource ) { this.programID = gl.createProgram(); this.vertexShaderID = this.loadShader( gl.VERTEX_SHADER, vsSource ); this.fragmentShaderID = this.loadShader( gl.FRAGMENT_SHADER, fsSource ); gl.attachShader( this.programID, this.vertexShaderID ); gl.attachShader( this.programID, this.fragmentShaderID ); this.bindAttributes(); gl.linkProgram( this.programID ); // If creating the shader program failed, alert if ( ! gl.getProgramParameter( this.programID, gl.LINK_STATUS ) ) { var info = gl.getProgramInfoLog( this.programID ); alert( 'Unable to initialize the shader program: ' + info ); } gl.validateProgram( this.programID ); this.getAllUniformLocations(); } ShaderProgram.prototype.getUniformLocation = function ( name ) { return gl.getUniformLocation( this.programID, name ); } ShaderProgram.prototype.getAllUniformLocations = function () { // Defined by child } ShaderProgram.prototype.bindAttribute = function ( index, name ) { gl.bindAttribLocation( this.programID, index, name ); } ShaderProgram.prototype.bindAttributes = function () { // Defined by child } ShaderProgram.prototype.loadFloat = function ( location, value ) { gl.uniform1f( location, value ); } ShaderProgram.prototype.loadVector3 = function ( location, value ) { gl.uniform3f( location, value.x, value.y, value.z ); } ShaderProgram.prototype.loadBoolean = function ( location, value ) { var _value = value ? 1 : 0; gl.uniform1f( location, _value ); } ShaderProgram.prototype.loadMatrix4 = function ( location, matrix ) { gl.uniformMatrix4fv( location, false, matrix ); } ShaderProgram.prototype.start = function () { gl.useProgram( this.programID ); } ShaderProgram.prototype.stop = function () { gl.useProgram( null ); } ShaderProgram.prototype.cleanUp = function () { this.stop(); gl.detachShader( this.programID, this.vertexShaderID ); gl.detachShader( this.programID, this.fragmentShaderID ); gl.deleteShader( this.vertexShaderID ); gl.deleteShader( this.fragmentShaderID ); gl.deleteProgram( this.programID ); } ShaderProgram.prototype.loadShader = function ( type, shaderText ) { var shaderID = gl.createShader( type ); gl.shaderSource( shaderID, shaderText ); gl.compileShader( shaderID ); // See if it compiled successfully if ( ! gl.getShaderParameter( shaderID, gl.COMPILE_STATUS ) ) { var info = gl.getShaderInfoLog( shaderID ); alert( 'An error occurred compiling the shader: ' + info ); gl.deleteShader( shaderID ); return null; } return shaderID; }
$('.shows').hide(); $('.UpdateForm').on('click',function(){ $('.shows').toggle(); })
import React from "react"; import Header from "../components/Post/SearchHeader"; import Results from "../components/Post/SearchResultsContainer"; export default class SearchPage extends React.Component { render() { return ( <div style={{ paddingBottom: "10em" }}> <Header> <Results /> </Header> </div> ); } }
describe('standard.echo.emit', () => { test.todo('Envia uma mensagem com channel e message') })
var BULLET, PLAYER, imageLoader, img, init; var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; PLAYER = 1; BULLET = 2; imageLoader = function() {}; img = []; imageLoader.imageLoaded = function(name) { img[name].loaded = true; imageLoader.imagesLoaded += 1; if (imageLoader.imagesLoaded === imageLoader.imagesToLoad) { return imageLoader.onload(); } }; imageLoader.onload = function() {}; imageLoader.imagesToLoad = 0; imageLoader.imagesLoaded = 0; imageLoader.load = function(name, file) { imageLoader.imagesToLoad += 1; img[name] = new Image(); img[name].loaded = false; img[name].src = './img/' + file; return img[name].onload = function() { return imageLoader.imageLoaded(name); }; }; init = function() { var body, canvas, ctx, livesCounter, newCanvas, objects, objectsData, offscreen, player, rebuildStage, stage, syncObjects; body = document.body; canvas = document.createElement('canvas'); livesCounter = document.getElementById('livesCounter'); canvas.width = document.documentElement.clientWidth; canvas.height = document.documentElement.clientHeight; ctx = canvas.getContext('2d'); offscreen = document.getElementById('offscreen'); ctx.fillStyle = "#111"; ctx.fillRect(0, 0, canvas.width, canvas.height); window.map = new GridMap(10, 20, 32, 32); newCanvas = window.map.getCanvas(); offscreen.appendChild(newCanvas); ctx.drawImage(newCanvas, 0, 0); stage = new Stage(canvas); objects = []; objectsData = []; player = {}; stage.mouseEventsEnabled = true; stage.onPress = __bind(function(mouseEvent) { var pos; pos = window.stageCoordsToMap(mouseEvent.stageX, mouseEvent.stageY); return now.click(pos); }, this); document.onkeydown = __bind(function(event) { if (event.keyCode === 38) { console.log('up'); if (!player.goingUp) { console.log('not'); now.goingUp(true); return player.goingUp = true; } } else if (event.keyCode === 40) { if (!player.goingDown) { now.goingDown(true); return player.goingDown = true; } } else if (event.keyCode === 37) { if (!player.goingLeft) { now.goingLeft(true); return player.goingLeft = true; } } else if (event.keyCode === 39) { if (!player.goingRight) { now.goingRight(true); return player.goingRight = true; } } }, this); document.onkeyup = __bind(function(event) { if (event.keyCode === 38) { if (player.goingUp) { now.goingUp(false); return player.goingUp = false; } } else if (event.keyCode === 40) { if (player.goingDown) { now.goingDown(false); return player.goingDown = false; } } else if (event.keyCode === 37) { if (player.goingLeft) { now.goingLeft(false); return player.goingLeft = false; } } else if (event.keyCode === 39) { if (player.goingRight) { now.goingRight(false); return player.goingRight = false; } } }, this); stage.addChild(new Bitmap(newCanvas)); Ticker.addListener(window); Ticker.setInterval(10); window.tick = function() { var o, _i, _len; for (_i = 0, _len = objects.length; _i < _len; _i++) { o = objects[_i]; o.tick(); } return stage.update(); }; livesCounter.innerHTML = "Connecting..."; body.appendChild(canvas); body.appendChild(livesCounter); now.ready(function() { now.sync = function(data) { objectsData = data; return syncObjects(); }; now.setLives = function(lives) { return livesCounter.innerHTML = lives; }; return now.join("Player"); }); syncObjects = function() { var o, _i, _len, _results; _results = []; for (_i = 0, _len = objectsData.length; _i < _len; _i++) { o = objectsData[_i]; _results.push(objects[_i] != null ? objects[_i].setObjectData(o) : o.type === 1 ? (console.log("player found"), objects[_i] = new Player(o), stage.addChild(new PlayerBitmap(objects[_i]))) : o.type === 2 ? (console.log("bullet found"), objects[_i] = new Bullet(o), stage.addChild(new BulletBitmap(objects[_i]))) : void 0); } return _results; }; rebuildStage = function() { var o, _i, _len, _results; console.log("rebuild"); _results = []; for (_i = 0, _len = objects.length; _i < _len; _i++) { o = objects[_i]; _results.push(stage.addChild(new PlayerBitmap(element))); } return _results; }; return rebuildStage(); }; imageLoader.load('object', 'object.png'); imageLoader.load('monsterARun', 'monsterARun.png'); imageLoader.load('bullet', 'bullet.png'); imageLoader.load('grass', 'grass1.png'); imageLoader.onload = function() { return init(); };
import styled from "styled-components"; import Frame from "../components/Frame"; import axios from "axios"; import React, { useState } from 'react'; import cookies from 'next-cookies' import { useRef } from 'react'; import {ChangePassword} from '../components/ChangePassword'; import {UpdateAddress} from '../components/UpdateAddress'; import { set } from "js-cookie"; import Router from 'next/router' const Background = styled.div` background-color: #e7e7e7; height:auto; padding-top:20px ; padding-bottom:20px ; `; const Block=styled.div` height:auto; width: 60%; background-color:white; margin-left: 20%; border-radius:4px; border:0.5px solid grey; padding-bottom: 40px; margin-top: 20px; margin-bottom: 20px; `; const Tittle=styled.header` height:50px; color: black; font-size:200%; text-align: center; border-bottom: 3px solid black; `; const Detail= styled.div` height:40px; width: 400px; background-color: transparent; margin-top:2px; padding-left:20px; display: flex; `; const Edit= styled.img` height:27px; width: 32px; margin-left:5px; cursor: pointer; `; const Blockk=styled.div` height:400px; width: 100%; background-color: transparent; border-radius:5px; padding-bottom: 40px; margin-top: 20px; margin-bottom: 20px; `; const Table= styled.table` width:100%; height:100%; `; const Avartar=styled.img` width:300px; height:width; border: 3px solid black; margin-top: 47px; `; const Tdd=styled.td` text-align: center; border-bottom: 0.5px solid #dbd8d8; height:40px; `; const Td=styled.td` text-align: center; height:40px; margin:5px; `; const Droper=styled.ul` opacity: 0%; position: absolute; width: auto; list-style: none; display: inline-block; pointer-events: none; `; const Options=styled.li` text-align:center; background-color: #f1f1f1; height:30px; `; const ButtonMoreProd=styled.button` border:0px; background-color: transparent; transition: all 0.2s ease-in-out; height: 100%; &:hover { background-color: #f1f1f1; } &:hover .Drop{ opacity: 100%; transition: opacity 0.4s ease-in-out; transform: translate(-28px,-6px); } `; const getuser = (Id) => { const [re,setre]=useState('loading...'); axios .get( "http://localhost:5035/users/"+Id, { headers: { "Content-Type": "application/json" }, } ) .then(function (response) { console.log(response.data.name); setre(response.data); }) .catch(function (error) { console.log(error); }); return re; }; const GetProducname = (Id) => { const [re,setre]=useState('Loading...'); axios .get( "http://localhost:5035/courses/"+Id, { headers: { "Content-Type": "application/json" }, } ) .then(function (response) { setre(response.data.Name); console.log('e'); }) .catch(function (error) { console.log(error); }); return re; }; // useEffect(() => { // const ourRequest = Axios.CancelToken.source() // <-- 1st step // const [re,setre]=useState('Loading...'); // const GetProducname = async (Id) => { // try { // const response = await Axios.get("http://localhost:5035/courses/"+Id, { // cancelToken: ourRequest.token, // <-- 2nd step // }) // setre(response.data.Name); // setPost(response.data) // setIsLoading(false) // } catch (err) { // console.log('There was a problem or request was cancelled.') // } // return re; // } // fetchPost() // return () => { // ourRequest.cancel() // } // }, []) function Idfilter(arr,id){ // var re=[]; // for(var i=0;i<arr.length;i++){ // if(arr[i].userId==id){ // re.push(arr[i]); // } // console.log(arr[i].userId+' '+id); // } // return re; return arr; } // export const getStaticPaths = async () => { // const res = await fetch("http://localhost:5035/users"); // const data = await res.json(); // const paths = data.map((item) => { // return { // params: { // id: item._id.toString(), // }, // }; // }); // return { // paths, // fallback: false, // }; // }; // export const getStaticProps = async (context) => { // const id = context.params.id; // const res = await fetch("http://localhost:5035/users/" + id); // const data = await res.json(); // return { // props: { // user: data, // }, // }; // }; const EditBar=styled.input` width:200px; height:30px; `; const SaveButton=styled.button` height:30px; width:40px; border-radius: 4px; background-color: #098b3f; border:none; `; export default function UserPage({data}){ function GetDate(fulltime){ const dateTime=new Date(fulltime); return dateTime.toLocaleDateString(); } // const [Dv1,setDv1] = useState(''); // const [Dv2,setDv2] = useState(''); // const [Dv3,setDv3] = useState(''); const Dv = useRef([]); const ShowMode=(title)=>{ return <h6>{title}</h6>; } function UpdateCloud(){ axios .put( "http://localhost:5035/users/"+data[0]._id, {name:(Dv.current)[0],email:(Dv.current)[1],address:(Dv.current)[3]}, { headers: { "Content-Type": "application/json" }, } ) .then(function (response) { console.log('sussces'); }) .catch(function (error) { console.log('error'); console.log(error); }); } const Update=(up)=>{ if(up.name=="name"){ data[0].name=(Dv.current)[0]; setD1([ShowMode((Dv.current)[0])]); UpdateCloud(); }else if(up.name=="email"){ data[0].email=(Dv.current)[1]; setD2([ShowMode('G-mail: '+(Dv.current)[1])]); UpdateCloud(); }else if(up.name=="address"){ data[0].address=(Dv.current)[3]; setD4([ShowMode('Địa chỉ: '+(Dv.current)[3])]); UpdateCloud(); }else if(up.name=="createDate"){ data[0].createDate=(Dv.current)[4]; setD5([ShowMode('Ngày tạo: '+(Dv.current)[4])]); UpdateCloud(); } } const [btnsave,setbtnsave]=useState(null); const btnEdit=(onclick)=>{ return <Edit src='imgs/Edit.jpg' onClick={onclick}></Edit>; } //show modal const [showChangePass,setshowChangePass]=useState(false); const [showChangeaddress,setshowChangeaddress]=useState(false); const [D1,setD1]=useState([ShowMode(data[0].name)]); const [D2,setD2]=useState([ShowMode('G-mail: '+data[0].email)]); const [D3,setD3]=useState([ShowMode('Vai trò: '+data[0].role)]); const [D4,setD4]=useState([ShowMode('Địa chỉ: '+data[0].address)]); const [D5,setD5]=useState([ShowMode('Ngày tạo: '+GetDate(data[0].createDate))]); const [D6,setD6]=useState([ShowMode('Mật khẩu: **********')]); const [E1,setE1]=useState(btnEdit(()=>setD1(EditMode(data[0].name,"name",{value: (Dv.current)[0],name:"name"})))); const [E2,setE2]=useState(btnEdit(()=>setD2(EditMode(data[0].email,"email",{value: (Dv.current)[1],name:"email"})))); const [E3,setE3]=useState(btnEdit(()=>setD3(EditMode(data[0].role,"role",{value: (Dv.current)[2],name:"role"})))); const [E4,setE4]=useState(btnEdit(()=>setshowChangeaddress(true))); const [E6,setE6]=useState(btnEdit(()=>setshowChangePass(true))); //const [E5,setE5]=useState(btnEdit(()=>setD5(EditMode(data[0].createDate,"createDate",{value: (Dv.current)[4],name:"createDate"})))); function D4Do(vv){ setD4(vv); } const HandleChange=()=>(e)=>{ if(e.target.name=="name"){ (Dv.current)[0]=e.target.value; console.log((Dv.current)[0]); setD1(Change(e.target.value,"name",{value: (Dv.current)[0],name:"name"})); }else if(e.target.name=="email"){ (Dv.current)[1]=e.target.value; console.log((Dv.current)[1]); setD2(Change(e.target.value,"email",{value: (Dv.current)[2],name:"email"})); }else if(e.target.name=="address"){ (Dv.current)[3]=e.target.value; console.log((Dv.current)[3]); setD4(Change(e.target.value,"address",{value: (Dv.current)[3],name:"address"})); }else if(e.target.name=="createDate"){ (Dv.current)[4]=e.target.value; console.log((Dv.current)[4]); setD4(Change(e.target.value,"createDate",{value: (Dv.current)[4],name:"createDate"})); } } const Change=(title,name,up)=>{ return [<EditBar value={title} name={name} onChange={HandleChange()}/>,<SaveButton onClick={()=>Update(up)}>Lưu</SaveButton>]; } const EditMode=(title,name,up)=>{ (Dv.current)=([data[0].name,data[0].email,data[0].role,data[0].address,data[0].createDate]); return [<EditBar value={title} name={name} onChange={HandleChange()}/>,<SaveButton onClick={()=>Update(up)}>Lưu</SaveButton>]; } return ( <Frame data={data[0].name}> <ChangePassword show={showChangePass} setShow={setshowChangePass} emaill={data[0].email}/> <UpdateAddress show={showChangeaddress} setShow={setshowChangeaddress} idd={data[0]._id} previusAddress={data[0].address} setStatic={D4Do}></UpdateAddress> <Background> <Block> <Table> <tr> <td> <Blockk> <Tittle> Thông tin cá nhân </Tittle> <Detail> {D1[0]} {E1} {D1[1]} </Detail> <Detail> {D2[0]} {E2} {D2[1]} </Detail> <Detail> {D3[0]} </Detail> <Detail> {D4[0]} {E4} {D4[1]} </Detail> <Detail> {D5[0]} </Detail> <Detail> {D6[0]} {E6} {D6[1]} </Detail> </Blockk> {btnsave} </td> <td> <Blockk> <Avartar src={"http://localhost:5035/upload/images/" + data[0].avatar} /> </Blockk> </td> </tr> </Table> </Block> <Block > <Tittle> Lịch sử mua hàng </Tittle> <Table> <tr> <Tdd><strong>Mã đơn hàng</strong></Tdd> <Tdd><strong>Trạng thái</strong></Tdd> <Tdd><strong>Hàng hóa</strong></Tdd> <Tdd><strong>Giá tổng giá</strong></Tdd> <Tdd><strong>Ngày thanh toán</strong></Tdd> </tr> {(Idfilter(data[1],data[0]._id)).map((item)=>( <tr> <Tdd>{item._id}</Tdd> <Tdd>{item.Status}</Tdd> <Tdd> <ButtonMoreProd>{((item.Products)[0].courseName)} <Droper className='Drop'> {(item.Products).map((iitem)=>( <Options> <Table> <tr> <Td> <strong>Tên:</strong> {(iitem.courseName)} </Td> <Td> <strong>Số lượng:</strong> {iitem.quantity} </Td> <Td> <strong>Giá/1:</strong> {iitem.unitPrice} </Td> </tr> </Table> </Options> ))} </Droper> </ButtonMoreProd> </Tdd> <Tdd>{item.TotalPrice}</Tdd> <Tdd>{item.BillDate}</Tdd> </tr> ))} </Table> </Block> </Background> </Frame> ); } UserPage.getInitialProps = async (ctx) => { const {Acc} =cookies(ctx); const res21 = await fetch("http://localhost:5035/users/"+Acc); var json21 = await res21.json(); const res11 = await fetch("http://localhost:5035/users/"+Acc+"/bills"); var json11 = await res11.json(); for(var i=0;i<json11.length;i++) { for(var j=0;j<(json11[i].Products).length;j++) { var courseId=(json11[i].Products)[j].courseId; if((json11[i].Products)[j].courseId==undefined){ courseId=(json11[i].Products)[j].product.id; } const res21 = await fetch("http://localhost:5035/courses/" +courseId); const json21 = await res21.json(); if(!json21) { (json11[i].Products)[j].courseName="Không tồn tại"; continue; } (json11[i].Products)[j].courseName=json21.Name; } } return { data: [json21,json11] }; };
/*global module */ 'use strict'; module.exports = { name: '../ember-unified-select', };
$(function() { var key = getCookie('key'); if (!key) { window.location.href = WapSiteUrl + '/tmpl/member_system/login.html'; return; } var change_passwd = 0; $('#loginpasswdbtn').click(function() { if (change_passwd) { errorTipsShow("正在处理中,请勿重复点击!"); return false; } var old_passwd = $('#old_passwd').val(); var new_passwd = $('#new_passwd').val(); var passwd_confirm = $('#passwd_confirm').val(); change_passwd = 1; $.ajax({ type: 'post', url: ApiUrl + '/index.php?act=setting&op=changeLoginPasswd', data: { key: key, old_passwd: old_passwd, new_passwd: new_passwd, passwd_confirm: passwd_confirm }, dataType: 'json', success: function(result) { change_passwd = 0; checkLogin(result.login); if (result.datas.error) { errorTipsShow(result.datas.error); return; } delCookie('username'); delCookie('userid'); delCookie('key'); location.href = WapSiteUrl + '/tmpl/member_system/login.html'; return; } }) }); })
(function() { 'use strict'; /** * @ngdoc function * @name app.controller:xmodalCtrl * @description * # xmodalCtrl * Controller of the app */ angular .module('ngdirectives') .controller('XmodalCtrl', Xmodal ); Xmodal.$inject = []; /* * recommend * Using function declarations * and bindable members up top. */ function Xmodal() { /*jshint validthis: true */ var vm = this; } })();
export function invertColor(hex) { let r = parseInt("0x" + hex.substr(1, 2)) let g = parseInt("0x" + hex.substr(3, 2)) let b = parseInt("0x" + hex.substr(5, 2)) let textColor = ((r * 299) + (g * 587) + (b * 114)) / 1000; return textColor >= 128 ? "#000000" : "#FFFFFF" } export function hexToRGBA(hex, alpha) { let r = parseInt("0x" + hex.substr(1, 2)) let g = parseInt("0x" + hex.substr(3, 2)) let b = parseInt("0x" + hex.substr(5, 2)) return "rgba(" + [r, g, b, alpha].join() + ")" }
require('./bootstrap'); // window.Vue = require('vue'); import Vue from 'vue'; import Vuetify from "vuetify"; import Vuelidate from 'vuelidate' import LoteComponent from './components/LoteComponent.vue' import MeusLotesComponent from './components/MeusLotesComponent.vue' import LeilaoComponent from './components/LeilaoComponent.vue' Vue.use(Vuetify); Vue.use(Vuelidate); const app = new Vue({ components: { LoteComponent, LeilaoComponent, MeusLotesComponent, }, el: '#app', mounted: function(){ // alert("OPA App Funcionando"); } });
import { SHOW_LIST, EXPORT_LIST, DELETE_DEVOPS, DELETE_ENGINEERING, UPDATE_DEVOPS, UPDATE_ENGINEERING} from '../constants/types' export const showList = (updates) => { return { type: SHOW_LIST, payload:updates }; } export const updateDevops = (devOps) => { return { type: UPDATE_DEVOPS, payload: devOps }; } export const exportList = (updates) => { return { type: EXPORT_LIST, payload:updates }; } export const updateEngineering = (engineering) => { return { type: UPDATE_ENGINEERING, payload: engineering }; } export const deleteDevops = (devOps) => { return { type: DELETE_DEVOPS, payload: devOps }; } export const deleteEngineering = (engineering) => { return { type: DELETE_ENGINEERING, payload: engineering }; }
import React from "react"; import { Text, View, FlatList, TouchableOpacity } from "react-native"; import Data from "../../common/data"; import Language from "../../common/lang"; import UTILS from "../../common/utils"; import NavigationService from "../../common/nav-service"; import Heading from "../elements/Heading"; import Loading from "../elements/Loading"; import styles from "../../styles/main"; export default class Territories extends React.Component { static navigationOptions = ({ navigation }) => { return { ...UTILS.headerNavOptionsDefault, headerRight: () => <View />, // To center on Andriod headerTitle: Language.translate("All Territories"), }; }; loadingTerritories = false; allTerritories = true; componentDidMount() { if (!Data.user) return; this.loadTerritories(); } loadTerritories() { this.loadingTerritories = true; const filter = !!this.allTerritories ? null : { userId: Data.user.userId }; Data.getApiData( `territories${filter ? "/filter" : ""}`, filter, filter ? "POST" : "" ) .then((data) => { this.loadingTerritories = false; this.setState({ territories: data }); }) .catch(UTILS.logError); } getListings(data = []) { return ( <FlatList contentContainerStyle={styles.listings} data={data.sort(UTILS.sortTerritory)} keyExtractor={(item) => item.territoryId.toString()} renderItem={({ item }) => ( <TouchableOpacity style={styles["listings-item"]} onPress={() => this.viewDetails(item)} > <View style={styles["listings-number"]}> <Text style={styles["listings-number-text"]}>{item.number}</Text> </View> <View style={styles["listings-name"]}> <Text style={styles["listings-name-text"]}> {item.publisher ? item.publisher.firstName + " " + item.publisher.lastName : ""} </Text> </View> <View style={styles["listings-date"]}> <Text style={styles["listings-date-text"]}>{item.date}</Text> </View> </TouchableOpacity> )} /> ); } viewDetails(data) { NavigationService.navigate("TerritoryDetails", { territoryId: data.territoryId, allTerritories: this.allTerritories, }); } render() { const { state, props } = this; // if "id", Load Territory Details if (!!props.id && !this.loadingTerritories) { // return (<Territory {...props} />); } if (!state.territories) return <Loading />; const listings = state.territories.length ? ( this.getListings(state.territories) ) : ( <Heading>{Language.translate("You have no territories")}</Heading> ); return <View style={[styles.section, styles.content]}>{listings}</View>; } }
console.log("Initialize module 2"); var module1 = require("./module1"); module.exports = { module1: module1 }; console.log("End of module 2");
db_query_all_product(function(err, result) { if (err) { console.log("query All fail"); } else { console.log("query All success"); console.log(result); } }); db_insert_product(my_db_data.product, function(err, result) { if (err) { console.log("insert fail"); } else { console.log("insert success"); } }); db_deleteAll_product(function(err, result) { if (err) { console.log("delete All fail"); } else { console.log("delete All success"); } });
var mongoose = require('mongoose') var rutaSchema = new mongoose.Schema({ nombre:{ type: String, require: true, trim: true }, descripcion:{ type: String, require: true, trim: true }, tipoUser:{ type: String, trim: true } }) /******* STATICS *******/ rutaSchema.statics.findByIdu = async function(id){ return await this.findOne( { _id: id }).exec() } rutaSchema.statics.findTypeUser = async function(tipo){ return await this.find( { tipoUser: tipo }).exec() } module.exports = mongoose.model('Ruta', rutaSchema);
/** * Created by xiaojiu on 2017/2/9. */ define(['../../../app', '../../../services/storage/inventory-manage/collectDifferenceConfirmService'], function(app) { var app = angular.module('app'); app.controller('collectDifferenceConfirmCtrl', ['$scope', '$state', '$stateParams', '$sce', 'collectDifferenceConfirm', function($scope, $state, $stateParams, $sce, collectDifferenceConfirm) { //table头 $scope.thHeader = collectDifferenceConfirm.getThead(); // get banner and grid data var pmsBanner = collectDifferenceConfirm.getBanner({ param: { query:{ taskId: $stateParams['taskId'], custTaskId: $stateParams['custTaskId'], } } }); pmsBanner.then(function(data) { $scope.result = data.grid; $scope.banner = data.banner }) // 返回 $scope.goBack = function(){ $state.go('main.goodsDifferenceManage') } $scope.showRemarks=function(){ $("#remarks").modal('show'); } $scope.remarksModel={ remarks:'', } //定义表单模型 $scope.goodsDifferenceModel={ packageDamage:'', damage:'', lost:'', id:'' } //查看差异 $scope.checkDetail=function(i,item){ $scope.goodsDifferenceModel.id=item.id; var opts={}; opts.id=item.id; var sendParams = { param: { query:opts } } var pmsBanner = collectDifferenceConfirm.getDataTableLook(sendParams); pmsBanner.then(function(data) { $scope.goodsDifferenceModel.packageDamage=data.banner.packageDamage; $scope.goodsDifferenceModel.damage=data.banner.damage; $scope.goodsDifferenceModel.lost=data.banner.lost; }) } // 确认差异 $scope.diffConfirm = function(){ var sendParam = { query: $scope.banner } sendParam.query.remarks=$scope.remarksModel.remarks; var diffComfirmPms = collectDifferenceConfirm.getDataTable({ param: sendParam }); diffComfirmPms.then(function(data){ if(data.status.code == "0000"){ $("#remarks").modal('hide'); alert('确认成功',function(){ $state.go('main.goodsDifferenceManage') }); }else { alert(data.status.msg); } }) } //删除备注差异 $scope.deleteRemarks=function(){ $scope.remarksModel={ remarks:'', } } }]) });
function multiply (a, b) { //TODO retun };
import React from "react"; import PropTypes from "prop-types"; export const Customer = ({ name, onClick }) => <li onClick = {onClick}> {name} </li>; Customer.propTypes = { name: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired };
module.exports = [{ fName: "Luke", lName: "Skywalker", isLiving: false, amount: 4000, type: "Jedi", _id: "1" }];
export const housesDataWrangler = housesArray => housesArray.map(house => ({ name: house.name, founded: house.founded, seats: house.seats.join(', '), titles: house.titles, coatOfArms: house.coatOfArms, ancestralWeapons: house.ancestralWeapons.join(', '), words: house.words, swornMembers: house.swornMembers.map(member => member.slice(49)) })); export const swornMembersDataWrangler = membersArray => membersArray.map(member => ({ name: member.name, died: member.died || 'Alive' }));
module.exports = function(app) { var User = require('../db/models/').User; var Stylist = require('../db/models/').Stylist; var Salons = require('../db/models/').Salons; var skillsJobTypeStylists = require('../db/models/').skillsJobTypeStylists; var skills = require('../db/models/').skills; var jobTypeStylists = require('../db/models/').jobTypeStylists; var userTypeUser = require('../db/models/').userTypeUser; var userType = require('../db/models/').userType var jobType = require('../db/models/').jobType var jwt = require('jwt-simple'); app.get('/', function(req,res){ res.send("Hello Kirisanth"); }); const signup = require('../controllers/signupController'); app.post('/signup',signup); const login = require('../controllers/loginController'); app.post('/login', login); //////////////////////////////////// app.post('/simpleSearch',function(req, res){ var name = req.body.name; User.findAll({ where:{firstname:{$like:'%'+name+'%'}} }).then(users => { var userIdArray = users.map(function(user){ return user.id; }); console.log(userIdArray); Stylist.findAll({ where:{stylistId:userIdArray} }).then(stylists=>{ var stylistIdArray = stylists.map(function(stylist){ return stylist.stylistId; }); User.findAll({ where:{id:stylistIdArray} }).then(user=>{ res.json(user); }); console.log(stylistIdArray); }) //res.json(users); }) }); //////////////////////////////////////// app.post('/skills',async function(req, res) { let userId = req.body.userId let data = [] req.body.skills.forEach(jobType => { Object.keys(jobType.skillList).forEach(skill => { data.push({ stylistId: userId, jobTypeId: jobType.jobId, skillId: skill }) }) }) await skillsJobTypeStylists.destroy({ where: { stylistId: userId } }).then(function(task) { }); await skillsJobTypeStylists.bulkCreate(data ).then(skills => { res.json(skills); }) }); app.post('/jobtypePrices',async function(req, res){ let userId = req.body.userId let jobTypeData = [] req.body.jobtypePrices.forEach(jobType => { jobTypeData.push({ stylistId: userId, jobTypeId: jobType.jobtypeId, price: jobType.price }) }) await jobTypeStylists.destroy({ where: { stylistId: userId } }).then(function(task) { }); await jobTypeStylists.bulkCreate(jobTypeData ).then(jobTypes => { res.json(jobTypes); }) }); app.get('/skills',function(req, res){ skills.findAll({ }).then(skills => { res.json(skills); }) }); app.get('/profile',function(req, res, next){ var userId = req.query.id; User.findOne({ where: { id : userId} }).then(user => { res.json(user); }) }); app.get('/stylistDetail',function(req, res, next){ console.log("backend detail reached "); console.log(req.query.id); var userId = req.query.id; Stylist.findOne({ where: { stylistId : userId} }).then(details => { //console.log(details); res.json(details); }) }); app.get('/jobType',function(req, res, next){ jobType.findAll({ }).then(jobTypes => { res.json(jobTypes); }) }); app.get('/skills',function(req, res, next){ skills.findAll({ }).then(skillsItems => { res.json(skillsItems); }) }); app.get('/jobTypeDetail',function(req, res, next){ var userId = req.query.id; jobTypeStylists.findAll({ where: { stylistId : userId} }).then(details => { res.json(details); }) }); app.get('/userType',function(req, res, next){ userType.findAll({ }).then(userTypes => { res.json(userTypes); }) }); app.get('/userTypeUsersDetail',function(req, res, next){ var userId = req.query.id; userTypeUser.findAll({ where: { userId : userId} }).then(details => { res.json(details); }) }); app.get('/SkillsJobTypeUsersDetail',function(req, res, next){ var userId = req.query.id; skillsJobTypeStylists.findAll({ where: { stylistId : userId} }).then(skillsDetails => { res.json(skillsDetails); }) }); // application ------------------------------------------------------------- app.get('/HairB2Bfront/signup.html', function(req, res) { res.sendfile('./HairB2Bfront/signup.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/login.html', function(req, res) { res.sendfile('./HairB2Bfront/login.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/profile.html', function(req, res) { res.sendfile('./HairB2Bfront/profile.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/password.html', function(req, res) { res.sendfile('./HairB2Bfront/password.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/skills.html', function(req, res) { res.sendfile('./HairB2Bfront/skills.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/edit.html', function(req, res) { res.sendfile('./HairB2Bfront/edit.html'); // load the single view file (angular will handle the page changes on the front-end) }); app.get('/HairB2Bfront/headerAndFooter.html', function(req, res) { res.sendfile('./HairB2Bfront/headerAndFooter.html'); // load the single view file (angular will handle the page changes on the front-end) }); }
import React from 'react'; class Footer extends React.Component { render() { return ( <footer className=" mx-auto mt-5 page-footer font-small "> <div className="footer-copyright text-center py-3">© 2019 Copyright: <a className='a' href=""> RAZANAKINIAINA Onisoa Tahina</a> </div> </footer> ); } } export default Footer;
const e = require("express"); const caja = require("../../Models/Seguridad/cajas"); function guardarCaja(req, res) { console.log('Endpoint para crear cajas ejecutado'); const newCaja = new caja(); const { codigo, fecha, descripcion, entrada, restaurante } = req.body; newCaja.codigo = codigo; newCaja.fecha = fecha; newCaja.descripcion = descripcion; newCaja.entrada = entrada; newCaja.restaurante = restaurante; if (codigo == '') { res.status(404).send({ message: "Codigo necesario" }) } else { if (fecha == '') { res.status(404).send({ message: "Fecha necesaria" }) } else { if (descripcion == '') { res.status(404).send({ message: "Descripcion necesaria" }) } else { if (entrada == '') { res.status(404).send({ message: "Entrada necesaria" }) } else { if (restaurante == '') { res.status(404).send({ message: "Restaurante necesario" }) } else { newCaja.save((err, CajaStored) => { if (err) { res.status(500).send({ message: "Error del servidor" }) } else { if (!CajaStored) { res.status(404).send({ message: "Error al guardar caja" }); } else { console.log('Caja creada'); res.status(200).send({ bbH: CajaStored }); } } }); } } } } } } function getCajas(req, res) { Cajas.find().then(cajas => { if (!cajas) { res.status(404).send({ message: "No se ha encontrado ninguna cajas" }); } else { res.status(200).send({ cajas }); } }) } module.exports = { guardarCaja, getCajas };
import React from 'react'; import PropTypes from 'prop-types'; import { observable, computed, toJS } from 'mobx'; import { observer } from 'mobx-react'; import { withStyles } from '@material-ui/core/styles'; import Fuse from 'fuse.js'; import empty from 'is-empty'; import match from 'autosuggest-highlight/match'; import parse from 'autosuggest-highlight/parse'; import { autoCompleteStyles } from '../styles'; import Autosuggest from 'react-autosuggest'; import TextField from '@material-ui/core/TextField'; import Paper from '@material-ui/core/Paper'; import MenuItem from '@material-ui/core/MenuItem'; const InputComponent = ({ classes, inputRef = () => {}, ref, ...other }) => ( <TextField fullWidth InputProps={{ inputRef: node => { ref(node); inputRef(node); }, classes: { input: classes.input, }, }} {...other} /> ); const getSuggestionComponent = key => (suggestion, { query, isHighlighted }) => { const matcheList = match(suggestion[key], query); const partList = parse(suggestion[key], matcheList); return ( <MenuItem selected={isHighlighted} component="div"> <div> { partList.map((part, index) => part.highlight ? ( <strong key={String(index)}> { part.text } </strong> ) : ( <span key={String(index)}> { part.text } </span> ), ) } </div> </MenuItem> ); }; const SuggestionListContainer = ({ containerProps, children }) => ( <Paper {...containerProps} square> { children } </Paper> ); @observer class IntegrationAutosuggest extends React.Component { @observable pageState = {}; @computed get Fuse () { const { dataSource, labelKey } = this.props; const options = { keys: [ labelKey ], threshold: 0.4, }; return new Fuse(toJS(dataSource), options); } constructor (props) { super(props); this.pageState = { suggestionList: [] }; } handleSuggestionListFetch = ({ value }) => { const { suggestionListLimit } = this.props; this.pageState.suggestionList = empty(value) ? [] : this.Fuse.search(value).slice(0, suggestionListLimit); }; handleSuggestionListClear = () => { this.pageState.suggestionList.clear(); }; handleGetSuggestion = suggestion => suggestion; handleGetSuggestionValue = suggestion => { const { labelKey } = this.props; return suggestion[labelKey]; }; handleOnChange = (event, { newValue, method }) => { const { id, name } = this.props; this.props.onChange({ target: { id: id, name: name, suggestion: method == 'type' ? null : newValue, value: method == 'type' ? newValue : this.handleGetSuggestionValue(newValue) } }); }; render() { const { suggestionList } = this.pageState; const { classes, labelKey, id, name, label, value, error, helperText, disabled } = this.props; return ( <Autosuggest renderInputComponent={InputComponent} renderSuggestionsContainer={SuggestionListContainer} renderSuggestion={getSuggestionComponent(labelKey)} onSuggestionsFetchRequested={this.handleSuggestionListFetch} onSuggestionsClearRequested={this.handleSuggestionListClear} getSuggestionValue={this.handleGetSuggestion} inputProps={{ classes, id, name, label, value, onChange: this.handleOnChange, error, helperText, disabled }} theme={{ container: classes.container, suggestionsContainerOpen: classes.suggestionListContainerOpen, suggestionsList: classes.suggestionList, suggestion: classes.suggestion, }} suggestions={suggestionList} /> ); } } IntegrationAutosuggest.propTypes = { classes: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, value: PropTypes.string.isRequired, dataSource: PropTypes.array.isRequired, labelKey: PropTypes.string.isRequired, suggestionListLimit: PropTypes.number.isRequired, error: PropTypes.bool, helperText: PropTypes.string, }; IntegrationAutosuggest.defaultProps = { labelKey: 'label', suggestionListLimit: 5 }; export default withStyles(autoCompleteStyles)(IntegrationAutosuggest);
const objectToParams = payload => { let str = ''; Object.keys(payload).map(key => { if (str !== '') { str += '&'; } return (str += `${key}=${payload[key]}`); }); return str; }; export default objectToParams;
import React, { Fragment, Component } from 'react'; import PropTypes from 'prop-types'; import { Menu, Grid, Segment } from 'semantic-ui-react'; import styles from './Footer.scss'; import { NavLink } from 'react-router-dom'; class Footer extends Component { constructor(props){ super(props) this.state={activeItem:{}} } render() { const {activeItem} = this.state; return ( <Segment as='footer' className={styles.Footer} inverted> <Grid> <Grid.Row> <Grid.Column width={4}> <Menu vertical fluid inverted> <Menu.Item> <Menu.Header className={styles.headings}>Company</Menu.Header> <Menu.Menu> <Menu.Item name="About" content="About" active={this.state.activeItem === 'About'} onClick={this.handleItemClick} as={NavLink} to="/events/venue" /> <Menu.Item name="press" content="Press" active={this.state.activeItem === 'press'} onClick={this.handleItemClick} as={NavLink} to="/press" /> <Menu.Item name="privacypolicy" content="Privacy Policy" active={this.state.activeItem === 'privacypolicy'} onClick={this.handleItemClick} as={NavLink} to="/privacy-policy" /> <Menu.Item name="tos" content="Terms of Service" active={this.state.activeItem === 'tos'} onClick={this.handleItemClick} as={NavLink} to="/terms" /> </Menu.Menu> </Menu.Item> </Menu> </Grid.Column> <Grid.Column width={4}> <Menu vertical fluid inverted> <Menu.Item> <Menu.Header className={styles.headings}>Contact Us</Menu.Header> <Menu.Menu> <Menu.Item name="About" content="About" active={this.state.activeItem === 'About'} onClick={this.handleItemClick} as={NavLink} to="/events/venue" /> <Menu.Item name="press" content="Press" active={this.state.activeItem === 'press'} onClick={this.handleItemClick} as={NavLink} to="/press" /> <Menu.Item name="privacypolicy" content="Privacy Policy" active={this.state.activeItem === 'privacypolicy'} onClick={this.handleItemClick} as={NavLink} to="/privacy-policy" /> <Menu.Item name="tos" content="Terms of Service" active={this.state.activeItem === 'tos'} onClick={this.handleItemClick} as={NavLink} to="/terms" /> </Menu.Menu> </Menu.Item> </Menu> </Grid.Column> <Grid.Column width={4}> <Menu vertical fluid inverted> <Menu.Item> <Menu.Header className={styles.headings}>Social Media</Menu.Header> <Menu.Menu> <Menu.Item name="About" content="About" active={this.state.activeItem === 'About'} onClick={this.handleItemClick} as={NavLink} to="/events/venue" /> <Menu.Item name="press" content="Press" active={this.state.activeItem === 'press'} onClick={this.handleItemClick} as={NavLink} to="/press" /> <Menu.Item name="privacypolicy" content="Privacy Policy" active={this.state.activeItem === 'privacypolicy'} onClick={this.handleItemClick} as={NavLink} to="/privacy-policy" /> <Menu.Item name="tos" content="Terms of Service" active={this.state.activeItem === 'tos'} onClick={this.handleItemClick} as={NavLink} to="/terms" /> </Menu.Menu> </Menu.Item> </Menu> </Grid.Column> <Grid.Column width={4}> <Menu vertical fluid inverted> <Menu.Item> <Menu.Header className={styles.headings}>Street Cred</Menu.Header> <Menu.Menu> <Menu.Item name="starrit" content="STARRIT ENGINEERING" as="a" href="http://www.starrit.io" /> </Menu.Menu> </Menu.Item> </Menu> </Grid.Column> </Grid.Row> </Grid> </Segment> ); } } Footer.propTypes = { }; export default Footer;
function OnNetworkInstantiate(msg : NetworkMessageInfo) { if(networkView.isMine) { var _NetworkRigidBody : NetworkRigidBody = GetComponent("NetworkRigidBody"); _NetworkRigidBody.enabled = false; } else { name += "Remote"; var _NetworkRigidBody2 : NetworkRigidBody = GetComponent("NetworkRigidBody"); _NetworkRigidBody2.enabled = true; } } function Update () { }
const socketController = (socket) => { console.log('Cliente conectado', socket.id ); socket.on('disconnect', () => { console.log('Cliente desconectado', socket.id ); }); socket.on('enviar-mensaje', ( payload, callback ) => { console.log('Mensaje Recibido',payload); const id = 123456789; if (!callback) return; // evitar que ocurra error si mensaje del cliente no se hizo con callback // si el cliente remoto envio mensaje con peticion de confirmacion en 'callback' en parametro 3 entonces: // if (payload.usuario) { // callback({ // resp: 'El mensaje contiene la llave: usuario' // validacion positiva // }); // } else { // callback({ // resp: 'ATENCION!El mensaje NO contiene la llave: usuario' // validacion negativa // }); // } callback( id ); socket.broadcast.emit('enviar-mensaje', payload ); }) } module.exports = { socketController }
;(function (){ 'use strict'; app.Collections.Users = Backbone.Collection.extend({ model: app.Models.User, url: 'http://tiyqpic.herokuapp.com/users' }); }());
import React, { useEffect } from 'react'; import { HashLink as Link } from 'react-router-hash-link'; import classes from './Navbar.module.css'; import clockicon from '../../Assets/Images/Icons/clock.svg'; import phoneicon from '../../Assets/Images/Icons/phone.svg'; import phoneiconblack from '../../Assets/Images/Icons/phone_black.svg'; import locationicon from '../../Assets/Images/Icons/location.svg'; import logo from '../../Assets/Images/Icons/logo.svg'; import { NavLink } from 'react-router-dom'; import Aos from 'aos'; import 'aos/dist/aos.css'; import Burger from './Burger/Burger'; import insta from '../../Assets/Images/Icons/insta.png' const Navbar = (props) => { useEffect(() => { Aos.init({ duration: 100 }); }, []); return( <nav className={classes.main}> <div className={classes.header} data-aos="fade-down" data-aos-duration="900"> <div className={classes.container}> <div className={classes.block}> <img src={clockicon}/> <span>Пн - Пт: с 09:00 до 19:00 Сб: с 09:00 до 18:00</span> </div> <div className={classes.block}> <img src={phoneicon}/> <a href="tel:+380661973904" className={classes.phone}>+38 (066) 197 39 04</a> <a href="tel:+380980380434">+38 (098) 038 04 34</a> </div> <div className={classes.block}> <img src={locationicon}/> <Link to="/#map">Запорожье, ул. Независимой Украины 56</Link> </div> </div> </div> <div className={classes.menu}> <div className={classes.container}> <NavLink to="/"> <img src={logo} data-aos="fade-up" data-aos-duration="1200"/> </NavLink> <div className={classes.links} data-aos="fade-up" data-aos-duration="1200"> <NavLink to="/">ГЛАВНАЯ</NavLink> <NavLink to="/services">УСЛУГИ</NavLink> <NavLink to="/contacts">КОНТАКТЫ</NavLink> </div> <a data-aos="fade-up" data-aos-duration="1200" rel="noreferrer" target="_blank" href="https://www.instagram.com/stobshzpua/" className={classes.insta}> <img src={insta}/> instagram </a> </div> </div> <div className={classes.mobileHeader}> <Burger/> <div className={classes.block}> <a data-aos="fade-up" data-aos-duration="1200" rel="noreferrer" target="_blank" href="https://www.instagram.com/stobshzpua/" className={classes.insta}> <img src={insta}/> instagram </a> <img src={locationicon}/> <Link to="/#map" target="_self">СТО <br/> НА БШ</Link> </div> </div> <div className={classes.mobileMenu}> <img src={phoneiconblack}/> <a href="tel:+380661973904" className={classes.phone}>+38 (066) 197 39 04</a> <a href="tel:+380980380434">+38 (098) 038 04 34</a> </div> </nav> ) } export default Navbar;
var db = require('../../../config/db.config'); db.registration.hasOne(db.candidatemodel,{foreignKey: 'user_id'}); db.candidatemodel.belongsTo(db.work, {foreignKey: 'user_id'}); db.work.belongsTo(db.education, {foreignKey: 'user_id'}); db.registration.hasMany(db.userquestionans, {foreignKey: 'user_id'}); db.registration.hasOne(db.iqtestsubmit, {foreignKey: 'user_id'}); exports.findAll = (req, res) => { db.registration.findOne({ include: [ { where:{user_id: req.body.user_id}, model: db.candidate_bio, }, { model: db.candidatemodel }, { model: db.jobalert } ], }).then(data =>{ res.json({ success:true, data:data }) }).catch(err =>{ res.json({ message: "error " +err }) }) }; exports.findProfileSetting = (req, res) => { console.log(req.body); if(!req.body.user_id){ res.json({ success:false, message:"User Id can not be empty" }) } if(!req.body.role_type){ res.json({ success:false, message:"Role type can not be empty" }) } if(req.body.role_type == 1){ db.registration.findOne({ where:{id: req.body.user_id}, attributes: [ ['id','user_id'], ['profile_pic','company_idcard'], 'email','fullName','company_name','phoneno','role_type','enable_location','profile_visibility','industry','category','recovery_email'], include: [ { model: db.companybio, attributes: [['id','companyBioId'],'profile_pic','bio_info','requirement_video'] }, { model: db.jobalert, attributes: [['id','jobalertId'],['designation','jobalert_designation'], 'qualification','shift','candidate_location', 'candidate_lat', 'candidate_lng', 'typeof_employement','employement_category','industry_category','from_salary_range','to_salary_range'] }, { attributes: ['question_id','answer'], model: db.userquestionans }, { model: db.companyinfo, attributes: [['id','companyId'],'designation','company_type','company_formed_year','company_website','company_location','company_lat','company_lng','company_branches','company_description','company_logo'], include:[ { attributes:[['companyType','companyName']], model: db.companytype, as: "companyType" }, { model: db.memberinfo, attributes: [['id','memberId'], 'member_email_id','member_phoneno','member_name','member_designation','member_specialization'] }, ] }, ], }).then(data =>{ res.json({ success:true, data:data }) }).catch(err =>{ res.json({ success: false, message: "error " +err }) }) } if(req.body.role_type == 2){ db.registration.findOne({ where:{id: req.body.user_id}, order:[ [db.work,'to_date','DESC'] ], attributes: [ ['id','user_id'], 'email','fullName','phoneno','role_type','enable_location','profile_visibility','industry','category','recovery_email'], include: [ { model: db.candidate_bio, attributes: [['id','candidateBioId'], 'profile_pic', 'other_img1', 'other_img2', 'candidate_idcard', 'candidate_info', 'special_telent', 'social_responsiblity', 'sports', 'candidate_resume_video', 'candidate_resume'] }, { attributes: [['id','workId'], 'fresher','name_of_company','designation','total_years_of_experience','from_date','to_date'], model: db.work }, { model: db.education, attributes: [['id','educationId'], 'highest_qualification','name_institution','year_of_passing'] }, { model: db.candidatemodel, attributes: [['id','candidateBasicInfoId'], 'date_of_birth','gender','language_knows','marital_status','height','weight','differently_abled','differently_abled_details','age'] }, { model: db.jobalert, attributes: [['id','jobalertId'],['designation','jobalert_designation'], 'qualification','shift','candidate_location', 'candidate_lat', 'candidate_lng', 'typeof_employement','employement_category','industry_category','from_salary_range','to_salary_range'] }, { attributes: ['question_id','answer'], model: db.userquestionans }, { model: db.iqtestsubmit, attributes: ['resultIqTest'], }, ], }).then(data =>{ res.json({ success:true, data:data }) }).catch(err =>{ res.json({ success: false, message: "error " +err }) }) } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class GroupExpenseUpdate { constructor(model) { if (!model) return; this.userId = model.userId; this.parent = model.parent; this.code = model.code; this.name = model.name; if (model.order) this.order = model.order; this.searchTerm = model.searchTerm; } } Object.seal(GroupExpenseUpdate); exports.default = GroupExpenseUpdate;
const mobile = 375; const tablet = 768; const laptop = 1024; const wide = 1440; module.exports = { mobile, tablet, laptop, wide, customMedia: { "--mobile": `(min-width: ${mobile}px)`, "--tablet": `(min-width: ${tablet}px)`, "--laptop": `(min-width: ${laptop}px)`, "--wide": `(min-width: ${wide}px)`, }, };
import dbFactory from '../../dbFactory'; import { CATEGORY } from './../../../constant/Constant'; const getDbRef = collectionName => { const db = dbFactory.create('firebase'); const ref = db.firestore().collection(collectionName); return ref; }; export const getCategoryFromDB = dispatch => { const db = dbFactory.create('firebase'); db.firestore() .collection('category') .doc('0') .get() .then(function(doc) { if (doc.exists) dispatch({ type: CATEGORY.ACTIONS.GET, category: [doc.data()] }); }) .catch(err => { dispatch({ type: CATEGORY.ACTIONS.ERROR, err }); }); }; export const manageCategoryFromDB = async (dispatch, tree, state) => { const db = dbFactory.create('firebase'); const treeData = await manageTree(tree, state); db.firestore() .collection('category') .doc('0') .set(treeData[0]) .then(() => { dispatch({ type: CATEGORY.ACTIONS.MANAGE, category: treeData }); }) .catch(err => { dispatch({ type: CATEGORY.ACTIONS.ERROR, err }); }); }; const manageTree = async (tree, state) => { if (state.selectedNodeIndex.length === 1) { tree[0].items.push({ text: state[state.categoryType.toLowerCase()], items: [] }); return tree; } await manageNestedTree(tree, state); return tree; }; const manageNestedTree = (tree, state) => { let clonedTree = tree; const itemHierarchicalIndex = splitItem(state.selectedNodeIndex, '_'), len = itemHierarchicalIndex.length; itemHierarchicalIndex.forEach((item, index) => { if ( index === len - 1 && (state.categoryType === CATEGORY.TYPE.EDIT || state.categoryType === CATEGORY.TYPE.DELETE) ) { if (state.categoryType === CATEGORY.TYPE.EDIT) { clonedTree = clonedTree[item]; clonedTree.text = state[state.categoryType.toLowerCase()]; } else if (state.categoryType === CATEGORY.TYPE.DELETE) { clonedTree.splice(item, 1); } } else { clonedTree = clonedTree[item].items; } }); if (state.categoryType === CATEGORY.TYPE.ADD) { clonedTree.push({ text: state[state.categoryType.toLowerCase()], items: [] }); } return tree; }; const splitItem = (item, seprator) => { return item.split(seprator); }; export const getAllCategory = () => { return getDbRef('subject'); };
import React from "react"; import { ReactComponent as Paw } from "../../paw-solid.svg"; function Header() { return ( <> <h1 className="text-center p-5 m-5 header"> <Paw className="m-2 paw" /> Survey Tiger </h1> </> ); } export default Header;
const { Layer, Network }= window.synaptic const inputLayer = new Layer(1); const hiddenLayer = new Layer(2); const outputLayer = new Layer(3); inputLayer.project(hiddenLayer); hiddenLayer.project(outputLayer); const myNetwork = new Network({ input: inputLayer, hiddenLayer, hidden: [hiddenLayer], output: outputLayer }); // train the network const learningRate = .3; for (let i =0; i < 20000; i++) { //0,0 => 0 myNetwork.activate([0,0]); myNetwork.propagate(learningRate, [0]); //0,1 => 1 myNetwork.activate([0,1]); myNetwork.propagate(learningRate, [1]); //1,0 => 1 myNetwork.activate([1,0]); myNetwork.propagate(learningRate, [1]); //1,1 =>0 myNetwork.activate([1,1]); myNetwork.propagate(learningRate, [0]); } //test the network console.log(myNetwork.activate([0,0])); console.log(myNetwork.activate([0,1])); console.log(myNetwork.activate([1,0])); console.log(myNetwork.activate([1,1]));
var comments21; if (window.localStorage.getItem("comment21")) { comments21 = JSON.parse(window.localStorage.getItem("comment21")); } else { comments21 = []; } function storeComm21() { var date = new Date().toLocaleString(); var singleComment = { value: comm21.value, date: date }; comments21.push(singleComment); console.log(comments21); window.localStorage.setItem("comment21", JSON.stringify(comments21)); load(); } function load() { var first = document.getElementById("labels21"); while (first.firstChild) { first.removeChild(first.lastChild); } var comments21 = JSON.parse(window.localStorage.getItem("comment21")); console.log(comments21); if (comments21) { comments21.forEach((element) => { var y = document.createElement("LABEL"); var x = document.createElement("BR"); var p = document.createElement("BR"); var z = document.createElement("LABEL"); var node = document.createTextNode(element.value); var nodeDate = document.createTextNode(element.date); y.style.fontWeight = "bold"; y.appendChild(node); z.appendChild(nodeDate); document.getElementById("labels21").appendChild(y); document.getElementById("labels21").appendChild(x); document.getElementById("labels21").appendChild(p); document.getElementById("labels21").appendChild(z); document.getElementById("labels21").appendChild(x); }); } }
import {SAVED_STATE_MODE, RESTORING_STATE_MODE, STATE_RESTORE_MODE, SEARCH_TERM} from "./constants"; export const defaultFilters = { sortingMethod: 'bestMatch', newlyListed: false, lowestPrice: false, highestPrice: false, highQuality: false, shippingCountries: [], taxonomies: [], globalIds: [], hideDuplicateItems: false, doubleLocaleSearch: false, fixedPrice: false, brandSearch: false, searchQueryFilter: false, }; export const defaultSearchState = { [SAVED_STATE_MODE]: false, [RESTORING_STATE_MODE]: false, [STATE_RESTORE_MODE]: false, }; export const defaultModel = { keyword: null, filters: {}, pagination: { limit: 8, page: 1, }, locale: 'en', internalPagination: { limit: 80, page: 1 }, globalId: null, }; export const state = { // loading state ebaySearchListingLoading: false, preparingProductsLoading: false, translatingProductsLoading: false, ebay404EmptyResult: false, // errors httpRequestFailed: false, ebaySearchListing: { siteInformation: null, items: null }, preparedSearchMetadata: { pagination: {limit: null, page: null}, totalItems: null }, totalListing: [], searchInitialiseEvent: { searchUrl: null, initialised: false, }, savedSearchStateMode: defaultSearchState, listingInitialiseEvent: { initialised: false, }, localeChanged: { value: '', origin: null, }, filtersEvent: defaultFilters, translationsMap: {}, modelWasCreated: defaultModel, modelWasUpdated: { keyword: null, filters: {}, pagination: { limit: 8, page: 1, }, locale: 'en', internalPagination: { limit: 80, page: 1 }, globalId: null, }, };
import ChainLongWeb3Provider from '../src' import * as Web3 from 'web3' describe('ChainLongWeb3Provider', () => { test('create instance', () => { const provider = new ChainLongWeb3Provider({ rpcUrl: 'wss://rinkeby.infura.io/ws' }) expect(provider).toBeInstanceOf(ChainLongWeb3Provider) expect(provider).toBeInstanceOf(Web3.providers.WebsocketProvider) }) })
$(document).ready(function(){ //be yt-nav $(".yt-nav a").click(function(e) { $(".yt-nav a").removeClass('active'); $(".yt-left-but").removeClass('minout'); $(this).addClass('active'); pos=$(".yt-nav a").index(this); var sub2nav=new Array(); //alert(main_nav[pos]['children']); if(main_nav[pos]['children']) sub2nav=main_nav[pos]['children']; //alert(sub2nav.length); subnavhtml=''; if(sub2nav.length==0) { $('.yt-subnav').html(''); $('.yt-subnav').css('display','none'); upiframe($(this).attr('href'),$(this).text()); if($(this).attr('href')=='javascript:void(0)'){ upiframe(ZHL.U($(this).attr('url')),$(this).text()); }else{ upiframe($(this).attr('href'),$(this).text()); } } else { $('.yt-subnav').html('<i class="uk-icon-spinner uk-icon-spin"></i>'); $('.yt-subnav').css('display','table-cell'); for(j=0;j<sub2nav.length;j++){ subnavhtml+="<li class=\'sub2nav\'><a href=\'" + ZHL.U(sub2nav[j]['url']) + "\'>"+ sub2nav[j]['text']+"</a>"; if(sub2nav[j]['children']){ subnavhtml+="<ul>"; sub3nav=sub2nav[j]['children']; for(k=0;k<sub3nav.length;k++){ subnavhtml+="<li class=\'sub3nav\'><a href=\'"+ ZHL.U(sub3nav[k]['url'])+"\'>"+ sub3nav[k]['text']+"</a></li>"; } subnavhtml+="</ul>"; } subnavhtml+="</li>"; } $('.yt-subnav').html(subnavhtml); if(sub2nav[0]['children']){ upiframe(ZHL.U(sub2nav[0]['children'][0]['url']),sub2nav[0]['children'][0]['text']); $(".yt-subnav .sub2nav").eq(0).addClass('active'); $(".yt-subnav .sub2nav").eq(0).find('.sub3nav').eq(0).addClass('active'); }else{ upiframe(ZHL.U(sub2nav[0]['url']),sub2nav[0]['text']); $(".yt-subnav .sub2nav").eq(0).addClass('active'); } } return false; }); $(".yt-subnav").on("click","a",function(e) { if( $(this).parent().find('ul li.sub3nav').size()>0 ){ //alert('dd'); $(this).parent().find('ul').stop(true,false).toggle(); //return false; } else{ $(".yt-subnav li").removeClass('active'); $(this).parent().addClass('active'); if( $(this).parent().parent().parent().hasClass('sub2nav') ) $(this).parent().parent().parent().addClass('active'); //$(this).find('ul').stop(true,false).fadeOut(); } upiframe($(this).attr('href'),$(this).text() ); return false; }); //end yt-nav $(".yt-left-but").on("click",function(e) { //$(".yt-subnav").css("dipaly","block"); // //$(".yt-subnav").toggleClass('uk-animation-slide-left uk-animation-reverse'); //$(".yt-subnav").fadeToggle("slow"); $(".sub2nav").animate({width:'toggle'},"slow"); $(".yt-subnav").animate({width:'toggle'},''); $(".yt-left-but").toggleClass('minout'); }); });//$(document).ready function upiframe(url,title){ if(url!='' || url!='#'){ //if(url=='javascript:void(0)'){url=ZHL.U('oa/staffs/profile');} iframetitle=title; $('#yt-iframe').contents().find("body").html('<i class="uk-icon-spinner uk-icon-spin"></i>'); $('.main-iframe').css('height',200); $('#yt-iframe').attr('src',url); // $('.yt-subnav li.sub2nav').not(".active").find('ul').fadeOut(); //$('.yt-subnav li.sub2nav.active').find('ul').fadeIn(); } } function reinitIframe(){ var iframe = document.getElementById("yt-iframe"); try{ var bHeight = iframe.contentWindow.document.body.scrollHeight; var dHeight = iframe.contentWindow.document.documentElement.scrollHeight; var height = Math.min(bHeight, dHeight); height = Math.max(height, 700); iframe.height = height; $('.main-iframe').css('height',height); // console.log(height); if( $('.yt-subnav').html()!=''){ $(".yt-left-but").show(); }else{ } }catch (ex){} } window.onload = function () { setInterval("reinitIframe()", 500); }; function topCenter(t,m){ $.messager.show({ title:t, msg:m, showType:'slide', border:'thin',cls:'c6', style:{ right:'', top:document.body.scrollTop+document.documentElement.scrollTop, bottom:'' } }); }
import React, { useEffect, useState } from 'react'; import { FlatList, Alert } from 'react-native'; import Geolocation from 'react-native-geolocation-service'; import Styled from 'styled-components/native'; const Container = Styled.SafeAreaView` flex: 1; background-color: #EEE; `; const WeatherContainer = Styled(FlatList)``; const LoadingView = Styled.View` flex: 1; justify-content: center; align-items: center; `; const Loading = Styled.ActivityIndicator` margin-bottom: 16px; `; const LoadingLabel = Styled.Text` font-size: 16px; `; const WeatherItemContainer = Styled.View` height: 100%; justify-content: center; align-items: center; `; const Weather = Styled.Text` margin-bottom: 16px; font-size: 24px; font-weight: bold; `; const Temperature = Styled.Text` font-size: 16px; `; const API_KEY = '6b6bd2c07f4ffce14997c59056aa387f'; const WeatherView = () => { const [ weatherInfo, setWeatherInfo ] = useState({ temperature: undefined, weather: undefined, isLoading: false, }); const getCurrentWeather = () => { setWeatherInfo({ isLoading: false, }); Geolocation.getCurrentPosition( position => { const { latitude, longitude } = position.coords; fetch( `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&APPID=${API_KEY}&units=metric` ) .then(response => response.json()) .then(json => { setWeatherInfo({ temperature: json.main.temp, weather: json.weather[0].main, isLoading: true, }) }) .catch(error => { setWeatherInfo({ isLoading: true, }); showError('Fail to get weatherInfo'); }); }, error => { setWeatherInfo({ isLoading: true, }); showError('Fail to get weatherInfo'); } ) }; const showError = message => { setTimeout(() => { Alert.alert(message); }, 500); }; useEffect(() => { getCurrentWeather(); }, []); let data = []; const { isLoading, weather, temperature } = weatherInfo; if (weather && temperature) { data.push(weatherInfo); } return ( <Container> <WeatherContainer onRefresh={() => getCurrentWeather()} refreshing={!isLoading} data={data} keyExtractor={( item, index ) => { return `Weather-${index}`; }} ListEmptyComponent={ <LoadingView> <Loading size="large" color="#1976D2" /> <LoadingLabel>Loading...</LoadingLabel> </LoadingView> } renderItem={({ item, index }) => ( <WeatherItemContainer> <Weather>{item.weather}</Weather> <Temperature>({item.temperature}`C)</Temperature> </WeatherItemContainer> )} contentContainerStyle={{ flex: 1 }} /> </Container> ); }; export default WeatherView;
import React from 'react'; import { View, Text, ScrollView } from 'react-native'; import { colors } from '../../constants/theme'; const MyRecipes = (props) => { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.white, }}> <Text>MyRecipes!</Text> </View> ); }; export default MyRecipes;
import aAmicoPower from './aAmicoPower' export { aAmicoPower }
import { renderString } from '../../src/index'; describe(`return datetime of beginning of the day`, () => { it('renders correct time', () => { const html = renderString("{{ today() }}"); }); it('plusDays', () => { const html = renderString("{{ today().plusDays(1) }}"); }); });
const mongoose = require('mongoose') const Schema = mongoose.Schema const ArticleSchema = new Schema({ id: String, slug: String, title: String, lang: String, langCode: String, converted: Boolean, published: Boolean, draft: Boolean, editor: String, version: String, wikiSource: String, // The wiki source the artcle was fetched from wikiRevisionId: Number, // the revision id of the article on Wikipedia // media source controls from where does the article get it's media // script: for custom artcles on Wikipedia // user: for all other articles mediaSource: { type: String, enum: ['script', 'user'], default: 'user', }, ns: Number, // the namespace of the article featured: { type: Number, default: 0, }, conversionProgress: { type: Number, default: 0, }, reads: { type: Number, default: 0, index: true, }, image: String, contributors: [String], slides: { type: Array, default: [], }, slidesHtml: { type: Array, default: [], }, sections: { type: Array, default: [], }, referencesList: {}, clonedFrom: { type: Schema.Types.ObjectId, ref: 'Article' }, created_at: { type: Date, default: Date.now, index: true }, updated_at: { type: Date, default: Date.now }, }) ArticleSchema.pre('save', function (next) { const now = new Date() this.updated_at = now if (!this.created_at) { this.created_at = now } next() }) ArticleSchema.statics.isObjectId = (id) => mongoose.Types.ObjectId.isValid(id) ArticleSchema.statics.getObjectId = (id) => mongoose.Types.ObjectId(id) const ArticleModel = mongoose.model('Article', ArticleSchema); module.exports = ArticleModel;
function initDoomWadLevel(context) { /** * Constructor */ var Level = context.DoomWad.Level = function(info, directory, textures, name) { var self = this; // Level lump header (eg MAP01) const levelLump = directory.lumpHeaderFor(name); const header = levelLump.header; const stream = levelLump.stream; // The level lump is empty. It just marks the first lump of the level. // The rest of the lumps should be read in linearly. So go through // each lump after this one. var nextLump = header; // Look for the THINGS lump which contain the interactive objects in the // level var thingsLump = directory.lumpHeaderAfter(header, "THINGS"); if (thingsLump) { self._things = new DoomWad.Things(stream, info, thingsLump); } // Look for the VERTEXES lump which contains the vertex geometry of the // level var vertexesLump = directory.lumpHeaderAfter(header, "VERTEXES"); if (vertexesLump) { self._vertexes = new DoomWad.Vertexes(stream, info, vertexesLump); } // Look for the SECTORS lump which contains the polygon information for the // level var sectorsLump = directory.lumpHeaderAfter(header, "SECTORS"); if (sectorsLump) { self._sectors = new DoomWad.Sectors(stream, info, sectorsLump, textures); } // Look for the SIDEDEFS lump which contains information about texturing // walls of the map. var sideDefsLump = directory.lumpHeaderAfter(header, "SIDEDEFS"); if (sideDefsLump) { self._sideDefs = new DoomWad.SideDefs(stream, info, sideDefsLump, self._sectors, textures); } // Look for the LINEDEFS lump which contains information about lines // between vertices in the level. var lineDefsLump = directory.lumpHeaderAfter(header, "LINEDEFS"); if (lineDefsLump) { self._lineDefs = new DoomWad.LineDefs(stream, info, lineDefsLump, self._vertexes, self._sideDefs); } return self; }; Level.prototype.boundingBox = function() { var minX = this._vertexes.minX(); var maxX = this._vertexes.maxX(); var minZ = this._sectors.minZ(); var maxZ = this._sectors.maxZ(); var width = maxX - minX; var minY = this._vertexes.minY(); var maxY = this._vertexes.maxY(); var height = maxY - minY; return { "x": minX, "y": minY, "width": width, "height": height, "floor": minZ, "ceiling": maxZ, }; }; Level.prototype.vertices = function () { return this._vertexes.vertices(); }; Level.prototype.lineDefs = function () { return this._lineDefs.lineDefs(); }; Level.prototype.sectors = function () { return this._sectors.sectors(); }; }
module.exports = function (app) { var pagamento = app.controllers.pagamento; app.route('/pagamento') .get(pagamento.lista) .post(pagamento.novo); app.route('/pagamento/:id') .get(pagamento.buscaPorId) .put(pagamento.confirma) .delete(pagamento.cancela); };
//--------------------------------------------------; // UTIL; //--------------------------------------------------; //-------------------------; // PACKAGE; //-------------------------; window.service.render = {}; //-------------------------; // FUNCTION; //-------------------------; /** * */ window.service.render.divider = function(){ var div = document.createElement("div"); div.setAttribute("class", "ui section divider"); return div } /** * */ window.service.render.h = function( text, tagOption, attr ){ if( tagOption == null ){ var h = document.createElement( "h4"); }else{ var h = document.createElement( "h" + tagOption ); } if( attr != null ){ var i = 0,iLen = attr.length,io for(;i<iLen;++i){ h.setAttribute( attr[ i ][ 0 ], attr[ i ][ 1 ]); } } h.appendChild(document.createTextNode( text )) return h } /** * */ window.service.render.div = function( text, attr ){ var div = document.createElement("div"); if( attr != null ){ var i = 0,iLen = attr.length,io for(;i<iLen;++i){ div.setAttribute( attr[ i ][ 0 ], attr[ i ][ 1 ]); } } div.appendChild(document.createTextNode( text )) return div } /** * */ window.service.render.table = function( arr0, arr1 ){ var table = document.createElement("table"); table.setAttribute("class", "ui compact celled small stackable table"); table.setAttribute("style", "border-radius : 0 !important;"); if( arr0 != null ){ var thead = document.createElement("thead"); var tr = document.createElement("tr"); for(var i = 0;i < arr0.length;++i){ var th = document.createElement("th"); th.appendChild(document.createTextNode( arr0[i] )) tr.appendChild( th ) } thead.appendChild(tr); table.appendChild(thead) } var tbody = document.createElement("tbody"); for(var i = 0;i < arr1.length;++i){ var tr = document.createElement("tr"); for( var s in arr1[ i ] ){ var td = document.createElement("td"); if( arr1[ i ][ s ][ 0 ] == "{" ){ console.log( arr1[ i ][ s ] ) var text = document.createTextNode( JSON.stringify( JSON.parse( arr1[ i ][ s ] ), null, 4 ) ) var pre = document.createElement("pre"); pre.appendChild( text ) td.appendChild(pre); tr.appendChild(td); }else{ var text = document.createTextNode( arr1[ i ][ s ] ) td.appendChild( text ) tr.appendChild(td); } } tbody.appendChild(tr); } table.appendChild(tbody) return table; } /** * */ window.service.render.table_String = function( arr0, data ){ var table = document.createElement("table"); table.setAttribute("class", "ui compact celled small stackable table"); table.setAttribute("style", "border-radius : 0 !important;"); if( arr0 != null ){ var thead = document.createElement("thead"); var tr = document.createElement("tr"); for(var i = 0;i < arr0.length;++i){ var th = document.createElement("th"); th.appendChild(document.createTextNode( arr0[i] )) tr.appendChild( th ) } thead.appendChild(tr); table.appendChild(thead) } var tbody = document.createElement("tbody"); var tr = document.createElement("tr"); var td = document.createElement("td"); var text = document.createTextNode( data ) var pre = document.createElement("pre"); pre.setAttribute("style", "white-space: pre-wrap;") pre.appendChild( text ) td.appendChild(pre); tr.appendChild(td); tbody.appendChild(tr); table.appendChild(tbody) return table; } window.service.render.table_Object = function( arr0, data ){ var table = document.createElement("table"); table.setAttribute("class", "ui compact celled small stackable table"); table.setAttribute("style", "border-radius : 0 !important;"); if( arr0 != null ){ var thead = document.createElement("thead"); var tr = document.createElement("tr"); for(var i = 0;i < arr0.length;++i){ var th = document.createElement("th"); th.appendChild(document.createTextNode( arr0[i] )) tr.appendChild( th ) } thead.appendChild(tr); table.appendChild(thead) } var tbody = document.createElement("tbody"); var tr = document.createElement("tr"); var td = document.createElement("td"); var __temp = data; var __temp = JSON.stringify( JSON.parse( data ), null, 4 ) var text = document.createTextNode( __temp ) var pre = document.createElement("pre"); pre.appendChild( text ) td.appendChild(pre); tr.appendChild(td); tbody.appendChild(tr); table.appendChild(tbody) return table; } /** * */ window.service.render.a = function( text, href, attr ){ var a = document.createElement("a"); a.setAttribute("href", href); if( attr != null ){ var i = 0,iLen = attr.length,io for(;i<iLen;++i){ a.setAttribute( attr[ i ][ 0 ], attr[ i ][ 1 ]); } } a.appendChild(document.createTextNode( text )) return a } /** * */ window.service.render.span = function( text, attr ){ var span = document.createElement("span"); if( attr != null ){ var i = 0,iLen = attr.length,io for(;i<iLen;++i){ span.setAttribute( attr[ i ][ 0 ], attr[ i ][ 1 ]); } } span.appendChild(document.createTextNode( text )) return span } /** * */ window.service.render.li = function( text, attr ){ var li = document.createElement("li"); if( attr != null ){ for(;i<iLen;++i){ li.setAttribute( attr[ i ][ 0 ], attr[ i ][ 1 ]); } } li.appendChild(document.createTextNode( text )) return li }; /** * */ window.service.render.dimmer = function( txt ){ var div0 = document.createElement("div"); div0.setAttribute("class", "ui dimmer"); div0.setAttribute("style", "display: flex !important;"); var div1 = document.createElement("div"); div1.setAttribute("class","content") var div2 = document.createElement("div"); div2.setAttribute("class","center") var h = document.createElement("h1"); h.setAttribute("class", "ui inverted icon"); h.setAttribute("id", "msg_m"); var i = document.createElement("i"); i.setAttribute("class", "heart outline big icon"); var div3 = document.createElement("div"); div3.setAttribute("class", "sub header"); div3.setAttribute("id", "msg_s"); //var _txt0 = document.createTextNode( "LESS BUT BETTER." ); var _txt1 = document.createTextNode( "Hello! " + txt ); var body = document.getElementsByTagName("body")[ 0 ]; div3.appendChild( _txt1 ); h.appendChild( i ); div2.appendChild( h ); div2.appendChild( div3 ); div1.appendChild( div2 ); div0.appendChild( div1 ); body.appendChild( div0 ) return $('.dimmer').dimmer('show'); } /** * */ window.service.render.detect_scrollHeight = function( d ){ return d.scrollHeight }; /** * */ window.service.render.textarea_html_tag_change = function(str){ //return String(str).replace(/(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g, '') return String(str).replace(/\"/g, "'") .replace(/&quot;/g, "'") //.replace(/^<table.*[">$]/g, '<table class="ui celled compact table">') //.replace(/<table/g, '<table class="ui celled compact table" ') // .replace(/<span >/g, '') // .replace(/<\/span>/g, '') // .replace(/<td >/g, '<td>') .replace(/&nbsp;/g, '') //.replace(/\&/g, '&amp;'); // .replace(//g, '<td>') };
//头部组件 import React from "react"; import {Row,Col,Menu,Icon,Button,Modal,Tabs,Form,Input} from "antd"; import {Link} from "react-router"; import logo from "../images/logo.png" const MenuItem = Menu.Item; const TabPane = Tabs.TabPane; const FormItem = Form.Item; class NewsHeader extends React.Component{ constructor(props){ super(props); this.state={ username:null, selectedKey:"shehui", modalShow:true } } handleClickItem=(event)=>{ this.setState({ // 更新selectKey selectedKey:event.key }); if(event.key==="regist"){ this.setState({ modalShow:true }) } }; // 关闭对话框 handleClose=()=>{ this.setState({ modalShow:false }) }; render(){ const {selectedKey,username,modalShow} = this.state; const userInfo = username ?( <MenuItem key="logout" className="logout"> <Button type="primary">{username}</Button>&nbsp;&nbsp; <Link to="/usercenter"> <Button type="dashed">个人中心</Button>&nbsp;&nbsp; </Link> <Button type="default">退出</Button> </MenuItem> ) :( <MenuItem key="regist" className="regist"> <Icon type="appstore-o"/>登录/注册 </MenuItem> ); const {getFieldDecorator} = this.props.form; return ( <header> <Row> <Col span={1}></Col> <Col span={3}> <a href="/" className="logo"> <img src={logo} alt=""/> <span>ReactNews</span> </a> </Col> <Col span={19}> <div> <Menu mode="horizontal" selectedKeys={[selectedKey]} onClick={this.handleClickItem}> <MenuItem key="top"> <Icon type="appstore-o"/>头条 </MenuItem> <MenuItem key="shehui"> <Icon type="appstore-o"/>社会 </MenuItem> <MenuItem key="guonei"> <Icon type="appstore-o"/>国内 </MenuItem> <MenuItem key="guoji"> <Icon type="appstore-o"/>国际 </MenuItem> <MenuItem key="yule"> <Icon type="appstore-o"/>娱乐 </MenuItem> <MenuItem key="tiyu"> <Icon type="appstore-o"/>体育 </MenuItem> <MenuItem key="keji"> <Icon type="appstore-o"/>科技 </MenuItem> <MenuItem key="shishang"> <Icon type="appstore-o"/>时尚 </MenuItem> {userInfo} </Menu> <Modal title="用户中心" visible={modalShow} onOk={this.handleClose} onCancel={this.handleClose} okText="关闭"> <Tabs type="card"> <TabPane tab="登录" key="1"> <Form> <FormItem label="用户名"> { getFieldDecorator("username")( <Input type="text" placeholder="请输入账号"/> ) } </FormItem> <FormItem label="密码"> { getFieldDecorator("password")( <Input type="text" placeholder="请输入密码"/> ) } </FormItem> <Button type="primary" >登录</Button> </Form> </TabPane> <TabPane tab="注册" key="2"> <Form> <FormItem label="账户"> { getFieldDecorator("r_username")( <Input type="text" placeholder="请输入账号"/> ) } </FormItem> <FormItem label="密码"> { getFieldDecorator("r_password")( <Input type="text" placeholder="请输入密码"/> ) } </FormItem> <FormItem label="确认密码"> { getFieldDecorator("r_confirm_password")( <Input type="text" placeholder="请再次输入您的密码"/> ) } </FormItem> <Button type="primary" >注册</Button> </Form> </TabPane> </Tabs> </Modal> </div> </Col> <Col span={1}></Col> </Row> </header> ) } } // 所有包含<Form>的组件类都需要通过Form来包装一下 /* 结果: this.props.form: getFieldDecorator(): 包装<Input> */ const FormNewsHeader = Form.create()(NewsHeader); export default FormNewsHeader;// 向外暴露的必须是包装后的组件
// var filterFn = require('./mymodule.js') // var dir = process.argv[2] // var filterStr = process.argv[3] // filterFn(dir, filterStr, function (err, list) { // if (err) { // return console.error('There was an error:', err) // } // list.forEach(function (file) { // console.log(file) // }) // }) // var result = 0 // for (var i = 2; i < process.argv.length; i++) { // result += Number(process.argv[i]) // } // console.log(result) // var fs = require('fs') // var contents = fs.readFileSync(process.argv[2]) // var lines = contents.toString().split('\n').length - 1 // console.log(lines) // var fs = require('fs') // var file = process.argv[2] // fs.readFile(file, function (err, contents) { // if (err) { // return console.log(err) // } // // fs.readFile(file, 'utf8', callback) can also be used // var lines = contents.toString().split('\n').length - 1 // console.log(lines) // }) //filtered ls // var fs = require('fs') // var path = require('path') // var folder = process.argv[2] // var ext = '.' + process.argv[3] // fs.readdir(folder, function (err, files) { // if (err) return console.error(err) // files.forEach(function (file) { // if (path.extname(file) === ext) { // console.log(file) // } // }) // }) //http client // var http = require('http') // http.get(process.argv[2], function (response) { // response.setEncoding('utf8') // response.on('data', console.log) // response.on('error', console.error) // }).on('error', console.error) //http collect // var http = require('http') // var bl = require('bl') // http.get(process.argv[2], function (response) { // response.pipe(bl(function (err, data) { // if (err) { // return console.error(err) // } // data = data.toString() // console.log(data.length) // console.log(data) // })) // }) //juging asy var http = require('http') var bl = require('bl') var results = [] var count = 0 function printResults () { for (var i = 0; i < 3; i++) { console.log(results[i]) } } function httpGet (index) { http.get(process.argv[2 + index], function (response) { response.pipe(bl(function (err, data) { if (err) { return console.error(err) } results[index] = data.toString() count++ if (count === 3) { printResults() } })) }) } for (var i = 0; i < 3; i++) { httpGet(i) } //time server // var net = require('net') // function zeroFill (i) { // return (i < 10 ? '0' : '') + i // } // function now () { // var d = new Date() // return d.getFullYear() + '-' + // zeroFill(d.getMonth() + 1) + '-' + // zeroFill(d.getDate()) + ' ' + // zeroFill(d.getHours()) + ':' + // zeroFill(d.getMinutes()) // } // var server = net.createServer(function (socket) { // socket.end(now() + '\n') // }) // server.listen(Number(process.argv[2])) //http file server // var http = require('http') // var fs = require('fs') // var server = http.createServer(function (req, res) { // res.writeHead(200, { 'content-type': 'text/plain' }) // fs.createReadStream(process.argv[3]).pipe(res) // }) // server.listen(Number(process.argv[2])) //http upercase // var http = require('http') // var map = require('through2-map') // var server = http.createServer(function (req, res) { // if (req.method !== 'POST') { // return res.end('send me a POST\n') // } // req.pipe(map(function (chunk) { // return chunk.toString().toUpperCase() // })).pipe(res) // }) // server.listen(Number(process.argv[2])) //http_json_api_server // var http = require('http') // var url = require('url') // function parsetime (time) { // return { // hour: time.getHours(), // minute: time.getMinutes(), // second: time.getSeconds() // } // } // function unixtime (time) { // return { unixtime: time.getTime() } // } // var server = http.createServer(function (req, res) { // var parsedUrl = url.parse(req.url, true) // var time = new Date(parsedUrl.query.iso) // var result // if (/^\/api\/parsetime/.test(req.url)) { // result = parsetime(time) // } else if (/^\/api\/unixtime/.test(req.url)) { // result = unixtime(time) // } // if (result) { // res.writeHead(200, { 'Content-Type': 'application/json' }) // res.end(JSON.stringify(result)) // } else { // res.writeHead(404) // res.end() // } // }) // server.listen(Number(process.argv[2])) //helloworld //console.log('HELLO WORLD') //http collect // var http = require('http') // var bl = require('bl') // http.get(process.argv[2], function (response) { // response.pipe(bl(function (err, data) { // if (err) { // return console.error(err) // } // data = data.toString() // console.log(data.length) // console.log(data) // })) // })
$(document).ready(function(){ var idevent; $(".report").click(function(){ idevent = $(this).val(); $("#dialogreportadv").empty(); /*$("#dialogreportadv").dialog('option', 'position', { my: "left+20 top", at: "left bottom", of: ".report" }); */ $("#dialogreportadv").dialog("open"); var strfilsed = "<fieldset>"; var endfilsed = "</fieldset>"; var label = "<label> Введіть код для звітування </label>"; var inputcode = "<input type='text' name='code' id='hashto'/>"; $("#dialogreportadv").append(strfilsed +label + inputcode + endfilsed); $.ajax({ type: "get", url: "checkreport.html", data: "idevent="+idevent, cache: false, success: function(datas){ var count = parseInt(datas); if(count>0){ $("#report").fadeOut(); $("#editreport").fadeIn(); } else { $("#report").fadeIn(); $("#editreport").fadeOut(); } } }); }); $("#dialogreportadv").dialog({ autoOpen: false, heigh: 235, width: 400, modal: true, buttons: { "report":{ text: "Звітувати", id: "report", click: function(){ $("#dialogreportadv p").empty(); var hashto = $("#dialogreportadv input").val(); $.ajax({ type: "get", url: "checkcode.html", data: "idevent="+idevent+ "&hashcode="+hashto, cach: false, success: function(html){ if(html == 1){ window.location = "report.html?idreport="+idevent+"&hashcode="+hashto; $(this).dialog("close"); } else { $("#dialogreportadv").append('<p style="color:red;"><b>Не правильний код. <br>Код був відправлений на пошту!</b></p>'); } } }); } }, "edit":{ text: "редагувати", id: "editreport", click: function(){ $("#dialogreportadv p").empty(); var hashto = $("#dialogreportadv input").val(); $.ajax({ type: "get", url: "checkcode.html", data: "idevent="+idevent+ "&hashcode="+hashto, cach: false, success: function(html){ if(html == 1){ // alert(1); window.location = "editreport.html?idreport="+idevent+"&hashcode="+hashto; $(this).dialog("close"); } else { $("#dialogreportadv").append('<p style="color:red;"><b>Не правильний код. <br>Код був відправлений на пошту!</b></p>'); } } }); } }, "view":{ text: "перегляд", id: "view", click: function(){ $(this).dialog("close"); } }, "cancel":{ text: "відміна", id: "cancel", click: function(){ $(this).dialog("close"); } } } }); });
$(function(){ $('.header-slider').slick({ arrows: false, vertical: true, dots: true, dotsClass: 'header-dots', autoplay:2000, }); });
import React, { Component } from 'react'; import OfferCard from './OfferCard'; import '../../css/Offer/Offer.css'; import '../../css/Offer/Mobile.css'; class Offer extends Component { constructor(props){ super(props); this.state = { offers: [ { offer_id: "off1", bg: "/img/offers/offer1.jpg", offer_name: "Ngày trái đất 2021", from: "18/4/2021", to: "23/4/2021", content: "Chung tay bảo vệ môi trường vì trái đất thân yêu, vì ngày mai xanh, sạch", }, { offer_id: "off2", bg: "/img/offers/offer2.jpg", offer_name: "Ưu đãi dành cho những con Sen", from: "Ngày mỹ nữ vào làm", to: "Tận thế", content: "Mèo méo meo mèo meo ngoa ngoa ngoa :3", }, { offer_id: "off3", bg: "/img/offers/offer3.jpg", offer_name: "Ưu đãi dành cho mấy đứa thất tình hoặc ế chảy nước", from: "Ngày thành lập công ty", to: "Tận thế", content: "Cho dzừa =))))))))", }, { offer_id: "off4", bg: "/img/offers/offer4.jpg", offer_name: "Khuyến mãi cho thành viên mới", from: "Hôm nay", to: "Ngày mốt", content: "Thành viên mới sẽ được hưởng một số ưu đãi đặc biệt khi mua sản phẩm", }, ] } } componentDidMount = () =>{ } render = () =>{ return ( <React.StrictMode> <div className="products-title" style={{display: "block"}}> <h2>Một vài Offer thú dzỵ nè :></h2> <img src="/img/art.png"/> </div> <div className="offers" style={{minHeight: `${window.innerHeight-100}px`}}> <div className="offers-container"> {this.state.offers.map(o => <OfferCard data={o} /> )} </div> </div> </React.StrictMode> ) } } export default Offer;
{ "version": 1480542008, "fileList": [ "data.js", "c2runtime.js", "jquery-2.1.1.min.js", "images/p1-sheet0.png", "images/p2-sheet0.png", "images/platform-sheet0.png", "images/p1spawn-sheet0.png", "images/p2spawn-sheet0.png", "images/bullet-sheet0.png", "images/ghost-sheet0.png", "images/jumpthrough-sheet0.png", "images/turret-sheet0.png", "images/jello-sheet0.png", "images/jello-sheet1.png", "images/phasebar-sheet0.png", "images/deathblock-sheet0.png", "images/playeronly-sheet0.png", "images/move-sheet0.png", "images/sprite-sheet0.png", "media/0.m4a", "media/0.ogg", "media/1.m4a", "media/1.ogg", "media/10.m4a", "media/10.ogg", "media/11.m4a", "media/11.ogg", "media/12.m4a", "media/12.ogg", "media/13.m4a", "media/13.ogg", "media/14.m4a", "media/14.ogg", "media/2.m4a", "media/2.ogg", "media/3.m4a", "media/3.ogg", "media/4.m4a", "media/4.ogg", "media/5.m4a", "media/5.ogg", "media/6.m4a", "media/6.ogg", "media/7.m4a", "media/7.ogg", "media/8.m4a", "media/8.ogg", "media/9.m4a", "media/9.ogg", "media/dhaka.m4a", "media/dhaka.ogg", "media/plankp-jarg-2.0-entry-music.m4a", "media/plankp-jarg-2.0-entry-music.ogg", "icon-16.png", "icon-32.png", "icon-114.png", "icon-128.png", "icon-256.png", "loading-logo.png" ] }
var botBuilder = require('claudia-bot-builder'), fbTemplate = botBuilder.fbTemplate; var format = text => (text && text.substring(0, 80)); var _ = require('lodash'); var location = require('./location'); var moment = require('moment'); var Promise = require('bluebird'); var doc = require('dynamodb-doc'); var dynamo = Promise.promisifyAll(new doc.DynamoDB()); var ticketTableName = "choozago.ticket"; function book(user){ const generic = new fbTemplate.Generic(); var loc = _.find(location.getLocations(user.company), function(l) { return l.code == user.location; }); if(loc){ var ticketTitle = "(B1-A208) Expires : 10:15AM, 5th Jan 2017"; var ticketDesc = "{status} by {firstName} {lastName} on 08:15AM, 5th Jan 2017"; ticketDesc = ticketDesc.replace("{status}", "Booked") .replace("{firstName}", user.firstName) .replace("{lastName}", user.lastName); var image = loc.booked; generic .addBubble(format(ticketTitle), format(ticketDesc)) .addImage(image) .addButton('Park my vehicle', '#park') .addButton('Cancel ticket', '#cancel'); return generic.get(); } else{ return "Something went wrong, please try again." } } function park(user){ const generic = new fbTemplate.Generic(); var loc = _.find(location.getLocations(user.company), function(l) { return l.code == user.location; }); if(loc){ var ticketTitle = "(B1-A208) Expires : 10:05AM, 5th Jan 2017"; var ticketDesc = "{status} by {firstName} {lastName} on 09:50AM, 5th Jan 2017"; ticketDesc = ticketDesc.replace("{status}", "Parked") .replace("{firstName}", user.firstName) .replace("{lastName}", user.lastName); var image = loc.parked; generic .addBubble(format(ticketTitle), format(ticketDesc)) .addImage(image) .addButton('Exit my vehicle', '#exit'); return generic.get(); } else{ return "Something went wrong, please try again." } } function exit(user){ const generic = new fbTemplate.Generic(); var loc = _.find(location.getLocations(user.company), function(l) { return l.code == user.location; }); if(loc){ var ticketTitle = "(B1-A208) Exited : Slot will be released. Thank you."; var ticketDesc = "{status} by {firstName} {lastName} on 05:00PM, 5th Jan 2017"; ticketDesc = ticketDesc.replace("{status}", "Parked") .replace("{firstName}", user.firstName) .replace("{lastName}", user.lastName); var image = loc.exited; generic .addBubble(format(ticketTitle), format(ticketDesc)) .addImage(image) .addButton('Book again', '#start'); return generic.get(); } else{ return "Something went wrong, please try again." } } module.exports = { book(user) { return book(user); }, show(user) { return book(user); }, park(user){ return park(user); }, exit(user){ return exit(user); } }
//Defines an Alert //This is abstract function Alert(id, p) { this.id = id; this.priority = p; } //Getters Alert.prototype.getID = function() { return this.id; } Alert.prototype.getPriority = function() { return this.priority; } //Information about this error, should be overriden Alert.prototype.toString = function() { throw "This method is abstract"; } //Tips for avoiding this error, should be overriden Alert.prototype.tips = function() { throw "This method is abstract"; } //Defines a Replica Set Alert //This is abstract ReplicaSetAlert.prototype = new Alert(); ReplicaSetAlert.prototype.constructor=ReplicaSetAlert; function ReplicaSetAlert(id, p, rs) { Alert.call(this, id+200, p); this.myReplicaSet= rs; } //Defines a Primary Down Alert PrimaryDownAlert.prototype = new ReplicaSetAlert(); PrimaryDownAlert.prototype.constructor=PrimaryDownAlert; function PrimaryDownAlert(rs) { ReplicaSetAlert.call(this, 0, 230, rs); } PrimaryDownAlert.prototype.toString = function() { return "The primary of replica set " + myReplicaSet.id + " is down."; } PrimaryDownAlert.prototype.tips = function() { return "If the primary is down it means that no new primary could be elected. This probably means that either a majority of your secondaries are down or you have a 2 node replica set without an arbiter. Check for stale or unreachable alerts on your secondary nodes."; } //Defines a Missing Arbiter Alert MissingArbiterAlert.prototype = new ReplicaSetAlert(); MissingArbiterAlert.prototype.constructor=MissingArbiterAlert; function MissingArbiterAlert(rs) { ReplicaSetAlert.call(this, 1, 200, rs); } MissingArbiterAlert.prototype.toString = function() { return "A replica set should not contain 2 nodes. If you wish to have a primary and a single backup please add an arbiter."; } MissingArbiterAlert.prototype.tips = function() { return "A replica set should not contain 2 nodes. If your primary goes down the entire replica set will fail because a single node is not a majority in a group of 2 nodes and cannot elect a primary. If you wish to have a primary and a single secondary please add an arbiter."; } //Defines a StaleSecondaryAlert StaleSecondaryAlert.prototype = new ReplicaSetAlert(); StaleSecondaryAlert.prototype.constructor=StaleSecondaryAlert; function StaleSecondaryAlert(rs) { ReplicaSetAlert.call(this, 2, 150, rs); } StaleSecondaryAlert.prototype.toString = function() { return "Some of the secondaries in this replica set are stale."; } StaleSecondaryAlert.prototype.tips = function() { return "A secondary becomes stale if it falls too far behind the primaries oplog. You may wish to increase the size of your oplog to prevent this in the future. To fix the current problem please perform a manual resynch. To do this check each individual server for errors to see if it is stale. For each stale server you will need to stop the server, delete all data and restart it."; } //Defines a Unreachable Secondary Alert UnreachableSecondaryAlert.prototype = new ReplicaSetAlert(); UnreachableSecondaryAlert.prototype.constructor=UnreachableSecondaryAlert; function UnreachableSecondaryAlert(rs) { ReplicaSetAlert.call(this, 3, 160, rs); } UnreachableSecondaryAlert.prototype.toString = function() { return "Some of the secondaries in this replica set are unreachable or unhealthy."; } UnreachableSecondaryAlert.prototype.tips = function() { return "There are many reasons a server may be unreachable or unhealthy. Check the specific erros on your servers for more detail."; } //Defines a Single Failure Point Alert SingleFailurePointAlert.prototype = new ReplicaSetAlert(); SingleFailurePointAlert.prototype.constructor=SingleFailurePointAlert; function SingleFailurePointAlert(rs) { ReplicaSetAlert.call(this, 4, 215, rs); } SingleFailurePointAlert.prototype.toString = function() { return "If the primary fails the entire replica set will fail."; } SingleFailurePointAlert.prototype.tips = function() { return "This problem is most likely due to some of your secondaries failing. Check your secondary servers for alerts indicating they are unreachable or stale."; } //Defines a PrimaryHostFailurePointAlert PrimaryHostFailurePointAlert.prototype = new ReplicaSetAlert(); PrimaryHostFailurePointAlert.prototype.constructor=PrimaryHostFailurePointAlert; function PrimaryHostFailurePointAlert(rs) { ReplicaSetAlert.call(this, 5, 175, rs); } PrimaryHostFailurePointAlert.prototype.toString = function() { return "If the host the primary is on goes down the entire replica set will go down."; } PrimaryHostFailurePointAlert.prototype.tips = function() { return "It is usually a good idea to store secondaries (backups) on different machines from the primary and each other. This way the data will still be available even if any single machine fails."; } //Defines a Host Alert //This is abstract HostAlert.prototype = new Alert(); HostAlert.prototype.constructor=HostAlert; function HostAlert(id, p, h) { Alert.call(this, id+300, p); this.myHost = h; } //Defines a Unreachable Host Alert UnreachableHostAlert.prototype = new HostAlert(); UnreachableHostAlert.prototype.constructor=UnreachableHostAlert; function UnreachableHostAlert(rs) { HostAlert.call(this, 3, 160, rs); } UnreachableHostAlert.prototype.toString = function() { return "This host is unreachable."; } UnreachableHostAlert.prototype.tips = function() { return "This is most likely due to either a network partition or a physical crash."; } //Defines a Server Alert //This is abstract ServerAlert.prototype = new Alert(); ServerAlert.prototype.constructor=ServerAlert; function ServerAlert(id, p, s) { Alert.call(this, id+400, p); this.myServer = s; } //Defines a Unreachable Server Alert UnreachableServerAlert.prototype = new ServerAlert(); UnreachableServerAlert.prototype.constructor=UnreachableServerAlert; function UnreachableServerAlert(e, s) { ServerAlert.call(this, 0, 255, s); if (e) { this.error = e; } else { this.error = "unkown error"; } } UnreachableServerAlert.prototype.toString = function() { return "Server " + this.myServer.getID() + " could not be contacted."; } UnreachableServerAlert.prototype.tips = function() { return "Error: " + this.error + ". Is the host for this server up?"; } //Defines a Unreplicated Server Alert UnreplicatedServerAlert.prototype = new ServerAlert(); UnreplicatedServerAlert.prototype.constructor=UnreplicatedServerAlert; function UnreplicatedServerAlert(s) { ServerAlert.call(this, 1, 200, s); } UnreplicatedServerAlert.prototype.toString = function() { return "Server is not backed up."; } UnreplicatedServerAlert.prototype.tips = function() { return "If this server goes down you will lose access to the data on it. Consider adding this server to a replica set. The smallest type of replica set contain a primary, a secondary (backup) and an arbiter."; } //Defines a Stale Server Alert StaleServerAlert.prototype = new ServerAlert(); StaleServerAlert.prototype.constructor=StaleServerAlert; function StaleServerAlert(s) { ServerAlert.call(this, 10, 150, s); } StaleServerAlert.prototype.toString = function() { return "Server " + this.myServer.id + " is stale."; } StaleServerAlert.prototype.tips = function() { return "Manually resych this server by shutting it down, deleteing all data and restarting it. In the future you may want to increase the size of your replica set's oplog to prevent this from occurring."; }
import * as firebase from "firebase"; const User = { id: "", name: "", email: "", dataCriacao: (new Date().getTime()) } export default class UserHelper{ static getUser(){ return new Promise(async (resolve,reject)=>{ const currentUser = firebase.auth().currentUser; if(currentUser){ let snap = await firebase.database().ref("Usuarios").child(currentUser.uid).once("value").catch(err=>{console.log(err)}); if(snap){ let user = Object.assign(User, snap.val()); user.id = snap.ref.path.toString().replace(/\/$/gi).split("/").pop(); resolve(user); }else{ reject("Erro na tentativa de buscar o usuário!"); } }else{ firebase.auth().onAuthStateChanged(async (user)=>{ if(user){ let snap = await firebase.database().ref("Usuarios").child(user.uid).once("value").catch(err=>{console.log(err)}); if(snap){ let user = Object.assign(User, snap.val()); user.id = snap.ref.path.toString().replace(/\/$/gi).split("/").pop(); resolve(user); }else{ reject("Erro na tentativa de buscar o usuário!"); } }else{ reject("Erro na tentativa de buscar o usuário!"); } }) } }); } static login(email, password){ return new Promise((resolve, reject)=>{ let validEmail = new RegExp(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/).exec(email); if(!validEmail){ reject("E-mail inválido!"); return; } firebase.auth().signInWithEmailAndPassword(email, password) .then(async (result)=>{ this.getUser().then(resolve).catch(()=>{ this.logout(); }); }) .catch((err)=>{ let errMss = "E-mail ou senha incorretos!"; if(err.code.search("invalid-email") >= 0){ errMss = "E-mail incorreto, tente novamente!"; }else if(err.code.search("wrong-password") >= 0){ errMss = "Senha incorreta, tente novamente!"; }else if(err.code.search("user-disabled") >= 0){ errMss = "Esse e-mail se encontra desativado!"; }else if(err.code.search("user-not-found") >= 0){ errMss = "Esse e-mail não existe, tente novamente!"; } reject(errMss); }); }); } static logout(){ return new Promise(async (resolve,reject)=>{ await firebase.auth().signOut().catch(console.log); resolve(); }); } static criarUsuario(user, password){ return new Promise(async (resolve,reject)=>{ if(!user.email){ reject("E-mail não foi informado corretamente!"); return; } firebase.auth().createUserWithEmailAndPassword(user.email, password).then(userRec=>{ let uid = userRec.user.uid; user.dataCriacao = new Date().getTime(); user.id = uid; firebase.database().ref("Usuarios").child(uid).set(user) .then(async ()=>{ await this.logout(); resolve(user); }) .catch(err=>{ reject("Erro ao salvar dados do usuário."); }) }) .catch(err=>{ reject("Erro ao criar usuário."); }) }); } }
import React from 'react' import { Layout } from '../components' const AboutPage = () => ( <Layout title='About' description='$ whoami'> <p> Hi, my name is Iago Dahlem Lorensini, born in Porto Alegre/RS, with 21 years old, graduating in Computer Science at <a href="http://ulbra.br/canoas/" target="_blank" rel="noopener noreferrer">Ulbra</a>, I'm a Front-end Developer working at <a href="http://codeminer42.com" target="_blank" rel="noopener noreferrer">Codeminer 42</a>, before that my first job as a Developer was in <a href="https://cwi.com.br" target="_blank" rel="noopener noreferrer">CWI Software</a>, where I started my career. I have experience with JavaScript, Ruby, and Java. I'm a Front-end with passion for design and visual things, but I also like to build Back-end and DevOps code. </p> </Layout> ) export default AboutPage
'use strict'; const assert = require('assert'); const path = require('path'); const sep = path.sep; const pm = require('..'); const compare = (a, b) => { a = a.toLowerCase(); b = b.toLowerCase(); return a > b ? 1 : a < b ? -1 : 0; }; const match = (list, pattern, options = {}) => { let isMatch = pm(pattern, options); let matches = new Set(); for (let ele of [].concat(list || [])) { ele = ele.replace(/^\.\//, ''); if (options.unixify !== false) { ele = ele.replace(/\\\\/g, '/'); } if (isMatch(ele)) { matches.add(ele); } } return [...matches]; }; describe('options', () => { beforeEach(() => (path.sep = '\\')); afterEach(() => (path.sep = sep)); after(() => (path.sep = sep)); describe('options.ignore', () => { let negations = ['a/a', 'a/b', 'a/c', 'a/d', 'a/e', 'b/a', 'b/b', 'b/c']; let globs = ['.a', '.a/a', '.a/a/a', '.a/a/a/a', 'a', 'a/.a', 'a/a', 'a/a/.a', 'a/a/a', 'a/a/a/a', 'a/a/a/a/a', 'a/a/b', 'a/b', 'a/b/c', 'a/c', 'a/x', 'b', 'b/b/b', 'b/b/c', 'c/c/c', 'e/f/g', 'h/i/a', 'x/x/x', 'x/y', 'z/z', 'z/z/z']; it('should filter out ignored patterns', () => { let opts = { ignore: ['a/**'] }; let dotOpts = { ...opts, dot: true }; assert.deepEqual(match(globs, '*', opts), ['b']); assert.deepEqual(match(globs, '*', { ignore: '**/a' }), ['b']); assert.deepEqual(match(globs, '*/*', opts), ['x/y', 'z/z']); assert.deepEqual(match(globs, '*/*/*', opts), ['b/b/b', 'b/b/c', 'c/c/c', 'e/f/g', 'h/i/a', 'x/x/x', 'z/z/z']); assert.deepEqual(match(globs, '*/*/*/*', opts), []); assert.deepEqual(match(globs, '*/*/*/*/*', opts), []); assert.deepEqual(match(globs, 'a/*', opts), []); assert.deepEqual(match(globs, '**/*/x', opts), ['x/x/x']); assert.deepEqual(match(globs, '**/*/[b-z]', opts), ['b/b/b', 'b/b/c', 'c/c/c', 'e/f/g', 'x/x/x', 'x/y', 'z/z', 'z/z/z']); assert.deepEqual(match(globs, '*', { ignore: '**/a', dot: true }), ['.a', 'b']); assert.deepEqual(match(globs, '*', dotOpts), ['.a', 'b']); assert.deepEqual(match(globs, '*/*', dotOpts), ['.a/a', 'x/y', 'z/z']); assert.deepEqual(match(globs, '*/*/*', dotOpts), ['.a/a/a', 'b/b/b', 'b/b/c', 'c/c/c', 'e/f/g', 'h/i/a', 'x/x/x', 'z/z/z']); assert.deepEqual(match(globs, '*/*/*/*', dotOpts), ['.a/a/a/a']); assert.deepEqual(match(globs, '*/*/*/*/*', dotOpts), []); assert.deepEqual(match(globs, 'a/*', dotOpts), []); assert.deepEqual(match(globs, '**/*/x', dotOpts), ['x/x/x']); // see https://github.com/jonschlinkert/micromatch/issues/79 assert.deepEqual(match(['foo.js', 'a/foo.js'], '**/foo.js'), ['foo.js', 'a/foo.js']); assert.deepEqual(match(['foo.js', 'a/foo.js'], '**/foo.js', { dot: true }), ['foo.js', 'a/foo.js']); assert.deepEqual(match(negations, '!b/a', opts), ['a/a', 'a/b', 'a/c', 'a/d', 'a/e', 'b/b', 'b/c']); assert.deepEqual(match(negations, '!b/(a)', opts), ['a/a', 'a/b', 'a/c', 'a/d', 'a/e', 'b/b', 'b/c']); assert.deepEqual(match(negations, '!(b/(a))', opts), ['b/b', 'b/c']); assert.deepEqual(match(negations, '!(b/a)', opts), ['b/b', 'b/c']); assert.deepEqual(match(negations, '**'), negations, 'nothing is ignored'); assert.deepEqual(match(negations, '**', { ignore: ['*/b', '*/a'] }), ['a/c', 'a/d', 'a/e', 'b/c']); assert.deepEqual(match(negations, '**', { ignore: ['**'] }), []); }); }); describe('options.matchBase', () => { it('should match the basename of file paths when `options.matchBase` is true', () => { assert.deepEqual(match(['a/b/c/d.md'], '*.md'), [], 'should not match multiple levels'); assert.deepEqual(match(['a/b/c/foo.md'], '*.md'), [], 'should not match multiple levels'); assert.deepEqual(match(['ab', 'acb', 'acb/', 'acb/d/e', 'x/y/acb', 'x/y/acb/d'], 'a?b'), ['acb', 'acb/'], 'should not match multiple levels'); assert.deepEqual(match(['a/b/c/d.md'], '*.md', { matchBase: true }), ['a/b/c/d.md']); assert.deepEqual(match(['a/b/c/foo.md'], '*.md', { matchBase: true }), ['a/b/c/foo.md']); assert.deepEqual(match(['x/y/acb', 'acb/', 'acb/d/e', 'x/y/acb/d'], 'a?b', { matchBase: true }), ['x/y/acb', 'acb/']); }); it('should work with negation patterns', () => { assert(pm.isMatch('./x/y.js', '*.js', { matchBase: true })); assert(!pm.isMatch('./x/y.js', '!*.js', { matchBase: true })); assert(pm.isMatch('./x/y.js', '**/*.js', { matchBase: true })); assert(!pm.isMatch('./x/y.js', '!**/*.js', { matchBase: true })); }); }); describe('options.flags', () => { it('should be case-sensitive by default', () => { assert.deepEqual(match(['a/b/d/e.md'], 'a/b/D/*.md'), [], 'should not match a dirname'); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/*/E.md'), [], 'should not match a basename'); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/C/*.MD'), [], 'should not match a file extension'); }); it('should not be case-sensitive when `i` is set on `options.flags`', () => { assert.deepEqual(match(['a/b/d/e.md'], 'a/b/D/*.md', { flags: 'i' }), ['a/b/d/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/*/E.md', { flags: 'i' }), ['a/b/c/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/C/*.MD', { flags: 'i' }), ['a/b/c/e.md']); }); }); describe('options.nobrace', () => { it('should not expand braces when disabled', () => { assert.deepEqual(match(['a', 'b', 'c'], '{a,b,c,d}'), ['a', 'b', 'c']); assert.deepEqual(match(['a', 'b', 'c'], '{a,b,c,d}', { nobrace: true }), []); assert.deepEqual(match(['1', '2', '3'], '{1..2}', { nobrace: true }), []); }); }); describe('options.nocase', () => { it('should not be case-sensitive when `options.nocase` is true', () => { assert.deepEqual(match(['a/b/c/e.md'], 'A/b/*/E.md', { nocase: true }), ['a/b/c/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/C/*.MD', { nocase: true }), ['a/b/c/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/C/*.md', { nocase: true }), ['a/b/c/e.md']); assert.deepEqual(match(['a/b/d/e.md'], 'a/b/D/*.md', { nocase: true }), ['a/b/d/e.md']); }); it('should not double-set `i` when both `nocase` and the `i` flag are set', () => { let opts = { nocase: true, flags: 'i' }; assert.deepEqual(match(['a/b/d/e.md'], 'a/b/D/*.md', opts), ['a/b/d/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/*/E.md', opts), ['a/b/c/e.md']); assert.deepEqual(match(['a/b/c/e.md'], 'A/b/C/*.MD', opts), ['a/b/c/e.md']); }); }); describe('options.noextglob', () => { it('should match literal parens when noextglob is true (issue #116)', () => { assert(pm.isMatch('a/(dir)', 'a/(dir)', { noextglob: true })); }); it('should not match extglobs when noextglob is true', () => { assert(!pm.isMatch('ax', '?(a*|b)', { noextglob: true })); assert.deepEqual(match(['a.j.js', 'a.md.js'], '*.*(j).js', { noextglob: true }), ['a.j.js']); assert.deepEqual(match(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true }), ['a/!(z)']); assert.deepEqual(match(['a/z', 'a/b'], 'a/!(z)', { noextglob: true }), []); assert.deepEqual(match(['c/a/v'], 'c/!(z)/v', { noextglob: true }), []); assert.deepEqual(match(['c/z/v', 'c/a/v'], 'c/!(z)/v', { noextglob: true }), []); assert.deepEqual(match(['c/z/v', 'c/a/v'], 'c/@(z)/v', { noextglob: true }), []); assert.deepEqual(match(['c/z/v', 'c/a/v'], 'c/+(z)/v', { noextglob: true }), []); assert.deepEqual(match(['c/z/v', 'c/a/v'], 'c/*(z)/v', { noextglob: true }), ['c/z/v']); assert.deepEqual(match(['c/z/v', 'z', 'zf', 'fz'], '?(z)', { noextglob: true }), ['fz']); assert.deepEqual(match(['c/z/v', 'z', 'zf', 'fz'], '+(z)', { noextglob: true }), []); assert.deepEqual(match(['c/z/v', 'z', 'zf', 'fz'], '*(z)', { noextglob: true }), ['z', 'fz']); assert.deepEqual(match(['cz', 'abz', 'az'], 'a@(z)', { noextglob: true }), []); assert.deepEqual(match(['cz', 'abz', 'az'], 'a*@(z)', { noextglob: true }), []); assert.deepEqual(match(['cz', 'abz', 'az'], 'a!(z)', { noextglob: true }), []); assert.deepEqual(match(['cz', 'abz', 'az', 'azz'], 'a?(z)', { noextglob: true }), ['abz', 'azz']); assert.deepEqual(match(['cz', 'abz', 'az', 'azz', 'a+z'], 'a+(z)', { noextglob: true }), ['a+z']); assert.deepEqual(match(['cz', 'abz', 'az'], 'a*(z)', { noextglob: true }), ['abz', 'az']); assert.deepEqual(match(['cz', 'abz', 'az'], 'a**(z)', { noextglob: true }), ['abz', 'az']); assert.deepEqual(match(['cz', 'abz', 'az'], 'a*!(z)', { noextglob: true }), []); }); }); describe('options.nodupes', () => { beforeEach(() => { path.sep = '\\'; }); afterEach(() => { path.sep = sep; }); it('should remove duplicate elements from the result array:', () => { let fixtures = ['.editorconfig', '.git', '.gitignore', '.nyc_output', '.travis.yml', '.verb.md', 'CHANGELOG.md', 'CONTRIBUTING.md', 'LICENSE', 'coverage', 'example.js', 'example.md', 'example.css', 'index.js', 'node_modules', 'package.json', 'test.js', 'utils.js']; assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '/a/b/c', { unixify: false }), ['/a/b/c']); assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '\\a\\b\\c', { unixify: false }), ['\\a\\b\\c']); assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '/a/b/c', { unixify: false, nodupes: true }), ['/a/b/c']); assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '\\a\\b\\c', { unixify: false, nodupes: true }), ['\\a\\b\\c']); assert.deepEqual(match(fixtures, ['example.*', '*.js'], { unixify: false, nodupes: true }), ['example.js', 'example.md', 'example.css', 'index.js', 'test.js', 'utils.js']); }); it('should not remove duplicates', () => { assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '/a/b/c', { nodupes: false }), ['/a/b/c', '\\a\\b\\c']); assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '\\a\\b\\c', { nodupes: false }), ['\\a\\b\\c']); assert.deepEqual(match(['abc', '/a/b/c', '\\a\\b\\c'], '\\a\\b\\c', { unixify: false, nodupes: false }), ['\\a\\b\\c' ]); }); }); describe('options.unescape', () => { it('should remove backslashes in glob patterns:', () => { let fixtures = ['abc', '/a/b/c', '\\a\\b\\c']; assert.deepEqual(match(fixtures, '\\a\\b\\c'), ['\\a\\b\\c']); assert.deepEqual(match(fixtures, '\\a\\b\\c', { nodupes: false }), ['\\a\\b\\c']); assert.deepEqual(match(fixtures, '\\a\\b\\c', { nodupes: false, unescape: false }), ['\\a\\b\\c']); assert.deepEqual(match(fixtures, '\\a\\b\\c', { unescape: true, nodupes: false, unixify: false }), ['\\a\\b\\c']); }); }); describe('options.nonegate', () => { it('should support the `nonegate` option:', () => { assert.deepEqual(match(['a/a/a', 'a/b/a', 'b/b/a', 'c/c/a', 'c/c/b'], '!**/a'), ['c/c/b']); assert.deepEqual(match(['a.md', '!a.md', 'a.txt'], '!*.md', { nonegate: true }), ['!a.md']); assert.deepEqual(match(['!a/a/a', 'a/b/a', 'b/b/a', '!c/c/a'], '!**/a', { nonegate: true }), ['!a/a/a', '!c/c/a']); assert.deepEqual(match(['!*.md', '.dotfile.txt', 'a/b/.dotfile'], '!*.md', { nonegate: true }), ['!*.md']); }); }); describe('options.unixify', () => { it('should unixify file paths by default', () => { assert.deepEqual(match(['a\\b\\c.md'], '**/*.md'), ['a\\b\\c.md']); assert.deepEqual(match(['a\\b\\c.md'], '**/*.md', { unixify: false }), ['a\\b\\c.md']); }); it('should unixify absolute paths', () => { assert.deepEqual(match(['E:\\a\\b\\c.md'], 'E:/**/*.md'), ['E:\\a\\b\\c.md']); assert.deepEqual(match(['E:\\a\\b\\c.md'], 'E:/**/*.md', { unixify: false }), []); }); it('should strip leading `./`', () => { let fixtures = ['./a', './a/a/a', './a/a/a/a', './a/a/a/a/a', './a/b', './a/x', './z/z', 'a', 'a/a', 'a/a/b', 'a/c', 'b', 'x/y']; assert.deepEqual(match(fixtures, '*'), ['a', 'b']); assert.deepEqual(match(fixtures, '**/a/**'), ['a', 'a/a/a', 'a/a/a/a', 'a/a/a/a/a', 'a/b', 'a/x', 'a/a', 'a/a/b', 'a/c']); assert.deepEqual(match(fixtures, '*/*'), ['a/b', 'a/x', 'z/z', 'a/a', 'a/c', 'x/y']); assert.deepEqual(match(fixtures, '*/*/*'), ['a/a/a', 'a/a/b']); assert.deepEqual(match(fixtures, '*/*/*/*'), ['a/a/a/a']); assert.deepEqual(match(fixtures, '*/*/*/*/*'), ['a/a/a/a/a']); assert.deepEqual(match(fixtures, './*'), ['a', 'b']); assert.deepEqual(match(fixtures, './**/a/**'), ['a', 'a/a/a', 'a/a/a/a', 'a/a/a/a/a', 'a/b', 'a/x', 'a/a', 'a/a/b', 'a/c']); assert.deepEqual(match(fixtures, './a/*/a'), ['a/a/a']); assert.deepEqual(match(fixtures, 'a/*'), ['a/b', 'a/x', 'a/a', 'a/c']); assert.deepEqual(match(fixtures, 'a/*/*'), ['a/a/a', 'a/a/b']); assert.deepEqual(match(fixtures, 'a/*/*/*'), ['a/a/a/a']); assert.deepEqual(match(fixtures, 'a/*/*/*/*'), ['a/a/a/a/a']); assert.deepEqual(match(fixtures, 'a/*/a'), ['a/a/a']); assert.deepEqual(match(fixtures, '*', { unixify: false }), ['a', 'b']); assert.deepEqual(match(fixtures, '**/a/**', { unixify: false }), ['a', 'a/a/a', 'a/a/a/a', 'a/a/a/a/a', 'a/b', 'a/x', 'a/a', 'a/a/b', 'a/c']); assert.deepEqual(match(fixtures, '*/*', { unixify: false }), ['a/b', 'a/x', 'z/z', 'a/a', 'a/c', 'x/y']); assert.deepEqual(match(fixtures, '*/*/*', { unixify: false }), ['a/a/a', 'a/a/b']); assert.deepEqual(match(fixtures, '*/*/*/*', { unixify: false }), ['a/a/a/a']); assert.deepEqual(match(fixtures, '*/*/*/*/*', { unixify: false }), ['a/a/a/a/a']); assert.deepEqual(match(fixtures, './*', { unixify: false }), ['a', 'b']); assert.deepEqual(match(fixtures, './**/a/**', { unixify: false }), ['a', 'a/a/a', 'a/a/a/a', 'a/a/a/a/a', 'a/b', 'a/x', 'a/a', 'a/a/b', 'a/c']); assert.deepEqual(match(fixtures, './a/*/a', { unixify: false }), ['a/a/a']); assert.deepEqual(match(fixtures, 'a/*', { unixify: false }), ['a/b', 'a/x', 'a/a', 'a/c']); assert.deepEqual(match(fixtures, 'a/*/*', { unixify: false }), ['a/a/a', 'a/a/b']); assert.deepEqual(match(fixtures, 'a/*/*/*', { unixify: false }), ['a/a/a/a']); assert.deepEqual(match(fixtures, 'a/*/*/*/*', { unixify: false }), ['a/a/a/a/a']); assert.deepEqual(match(fixtures, 'a/*/a', { unixify: false }), ['a/a/a']); }); }); describe('options.dot', () => { describe('when `dot` or `dotfile` is NOT true:', () => { it('should not match dotfiles by default:', () => { assert.deepEqual(match(['.dotfile'], '*'), []); assert.deepEqual(match(['.dotfile'], '**'), []); assert.deepEqual(match(['a/b/c/.dotfile.md'], '*.md'), []); assert.deepEqual(match(['a/b', 'a/.b', '.a/b', '.a/.b'], '**'), ['a/b']); assert.deepEqual(match(['a/b/c/.dotfile'], '*.*'), []); // https://github.com/isaacs/minimatch/issues/30 assert.deepEqual(match(['foo/bar.js'], '**/foo/**'), ['foo/bar.js']); assert.deepEqual(match(['./foo/bar.js'], './**/foo/**'), ['foo/bar.js']); assert.deepEqual(match(['./foo/bar.js'], './**/foo/**', { unixify: false }), ['foo/bar.js']); assert.deepEqual(match(['./foo/bar.js'], '**/foo/**'), ['foo/bar.js']); assert.deepEqual(match(['./foo/bar.js'], '**/foo/**', { unixify: false }), ['foo/bar.js']); }); it('should match dotfiles when a leading dot is defined in the path:', () => { assert.deepEqual(match(['a/b/c/.dotfile.md'], '**/.*'), ['a/b/c/.dotfile.md']); assert.deepEqual(match(['a/b/c/.dotfile.md'], '**/.*.md'), ['a/b/c/.dotfile.md']); }); it('should use negation patterns on dotfiles:', () => { assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!.*'), ['c', 'c.md']); assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!.b'), ['.a', 'c', 'c.md']); }); }); describe('when `dot` or `dotfile` is true:', () => { it('should match dotfiles when there is a leading dot:', () => { let opts = { dot: true }; assert.deepEqual(match(['.dotfile'], '*', opts), ['.dotfile']); assert.deepEqual(match(['.dotfile'], '**', opts), ['.dotfile']); assert.deepEqual(match(['a/b', 'a/.b', '.a/b', '.a/.b'], '**', opts), ['a/b', 'a/.b', '.a/b', '.a/.b']); assert.deepEqual(match(['a/b', 'a/.b', 'a/.b', '.a/.b'], 'a/{.*,**}', opts), ['a/b', 'a/.b']); assert.deepEqual(match(['a/b', 'a/.b', 'a/.b', '.a/.b'], '{.*,**}', {}), ['a/b']); assert.deepEqual(match(['a/b', 'a/.b', 'a/.b', '.a/.b'], '{.*,**}', opts), ['a/b', 'a/.b', '.a/.b']); assert.deepEqual(match(['.dotfile'], '.dotfile', opts), ['.dotfile']); assert.deepEqual(match(['.dotfile.md'], '.*.md', opts), ['.dotfile.md']); }); it('should match dotfiles when there is not a leading dot:', () => { let opts = { dot: true }; assert.deepEqual(match(['.dotfile'], '*.*', opts), ['.dotfile']); assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '*.*', opts), ['.a', '.b', 'c.md']); assert.deepEqual(match(['.dotfile'], '*.md', opts), []); assert.deepEqual(match(['.verb.txt'], '*.md', opts), []); assert.deepEqual(match(['a/b/c/.dotfile'], '*.md', opts), []); assert.deepEqual(match(['a/b/c/.dotfile.md'], '*.md', opts), []); assert.deepEqual(match(['a/b/c/.verb.md'], '**/*.md', opts), ['a/b/c/.verb.md']); assert.deepEqual(match(['foo.md'], '*.md', opts), ['foo.md']); }); it('should use negation patterns on dotfiles:', () => { assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!.*'), ['c', 'c.md']); assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!(.*)'), ['c', 'c.md']); assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!(.*)*'), ['c', 'c.md']); assert.deepEqual(match(['.a', '.b', 'c', 'c.md'], '!*.*'), ['.a', '.b', 'c']); }); it('should match dotfiles when `options.dot` is true:', () => { assert.deepEqual(match(['a/./b', 'a/../b', 'a/c/b', 'a/.d/b'], 'a/.*/b', { dot: true }), ['a/./b', 'a/../b', 'a/.d/b']); assert.deepEqual(match(['a/./b', 'a/../b', 'a/c/b', 'a/.d/b'], 'a/.*/b', { dot: false }), ['a/./b', 'a/../b', 'a/.d/b']); assert.deepEqual(match(['a/./b', 'a/../b', 'a/c/b', 'a/.d/b'], 'a/*/b', { dot: true }), ['a/c/b', 'a/.d/b']); assert.deepEqual(match(['.dotfile'], '*.*', { dot: true }), ['.dotfile']); assert.deepEqual(match(['.dotfile'], '*.md', { dot: true }), []); assert.deepEqual(match(['.dotfile'], '.dotfile', { dot: true }), ['.dotfile']); assert.deepEqual(match(['.dotfile.md'], '.*.md', { dot: true }), ['.dotfile.md']); assert.deepEqual(match(['.verb.txt'], '*.md', { dot: true }), []); assert.deepEqual(match(['.verb.txt'], '*.md', { dot: true }), []); assert.deepEqual(match(['a/b/c/.dotfile'], '*.md', { dot: true }), []); assert.deepEqual(match(['a/b/c/.dotfile.md'], '**/*.md', { dot: true }), ['a/b/c/.dotfile.md']); assert.deepEqual(match(['a/b/c/.dotfile.md'], '**/.*', { dot: false }), ['a/b/c/.dotfile.md']); assert.deepEqual(match(['a/b/c/.dotfile.md'], '**/.*.md', { dot: false }), ['a/b/c/.dotfile.md']); assert.deepEqual(match(['a/b/c/.dotfile.md'], '*.md', { dot: false }), []); assert.deepEqual(match(['a/b/c/.dotfile.md'], '*.md', { dot: true }), []); assert.deepEqual(match(['a/b/c/.verb.md'], '**/*.md', { dot: true }), ['a/b/c/.verb.md']); assert.deepEqual(match(['d.md'], '*.md', { dot: true }), ['d.md']); }); }); }); describe('windows', () => { it('should unixify file paths', () => { assert.deepEqual(match(['a\\b\\c.md'], '**/*.md'), ['a\\b\\c.md']); assert.deepEqual(match(['a\\b\\c.md'], '**/*.md', { unixify: false }), ['a\\b\\c.md']); }); it('should unixify absolute paths', () => { assert.deepEqual(match(['E:\\a\\b\\c.md'], 'E:/**/*.md'), ['E:\\a\\b\\c.md']); assert.deepEqual(match(['E:\\a\\b\\c.md'], 'E:/**/*.md', { unixify: false }), []); }); }); });
'use strict'; module.exports = function (UploadedFile) { //destroyAll UploadedFile.aminoDestroyAll = function (cb) { UploadedFile.destroyAll((err, info) => { cb(err, info); }); }; UploadedFile.remoteMethod('aminoDestroyAll', { accepts: [], returns: [ { arg: 'info', type: 'object', root: true, description: 'DestroyAll info' } ], http: {path: '/aminoDestroyAll', verb: 'post'} } ); //ingestUploadedJsonFile UploadedFile.ingestUploadedJsonFile = function (uploadedFile, cb) { const DS = UploadedFile.app.models.DataSet; DS.create({ name: 'Goony Byrd' }, (err, result) => { cb(new Error('sorry, man')); //cb(err, result); }); }; UploadedFile.remoteMethod('ingestUploadedJsonFile', { accepts: [ { arg: 'uploadedFile', type: 'UploadedFile', required: true, description: 'Uploaded file model to ingest', http: {source: 'body'} } ], returns: [ { arg: 'dataSet', type: 'DataSet', root: true, description: 'DataSet created by JSON file ingest' } ], http: {path: '/ingestUploadedJsonFile', verb: 'post'} } ); };
// CREATE BUDGET import React, {useState, useEffect} from 'react'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import {getCategory} from '../redux/reducer'; import axios from 'axios'; const CreateBudget = (props) => { const[form, toggleForm] = useState(false); const[name, setName] = useState(''); const[amount, setAmount] = useState(0); const[type, setType] = useState('Dollar'); const[showMore, toggleShowMore] = useState(false); useEffect(() => { getCategory() console.log(props)}, []) const getCategory = () => { axios .get('/api/category') .then((res) => { props.getCategory(res.data) console.log(props.category) }) .catch(() => console.log('did not get categories')) } const remove = id => { axios .delete(`/api/category/${id}`) .then(() => { getCategory() console.log(id) }) .catch(() => console.log('cannot delete')) } const submit = () => { axios .post('/api/category', {name, amount, type}) .then((res) => { setName(''); setAmount(0); props.getCategory(res.data) getCategory(); toggleForm(); }) .catch(()=>console.log('did not get category')) } return( <div id='cb-main'> <h1 id='cb-text'>[Total money] </h1> <div id='cb-categories'> {props.category.map((element, index)=>{ return( <div> <div onClick={()=>{remove(element.category_id)}} id='cb-doll-cat' key={index}> <h1>{element.category_name}</h1> <h1>${element.category_value}</h1> <div id='cb-temp-circ' onClick={()=>{toggleShowMore(true)}}/> </div> {showMore ? <div id='cb-doll-cat-extra'> Edit Delete </div> : null}</div> ) })} </div> {form ? <div id='cb-inputs'> <span> Category </span> <input className='auth-input' value={name} onChange={(e)=>setName(e.target.value)}/> <span> Amount </span> <input className='auth-input' value={amount} onChange={(e)=>setAmount(e.target.value)}/> <span> Type </span> <div id='cb-form-buttons'> <button className='cb-form-button' onClick={()=>setType('Dollar')}> Dollar</button> <button className='cb-form-button' onClick={()=>setType('Percentage')}> Percentage</button> </div> <div id='cb-form-buttons'> <button className='cb-form-button' onClick={()=>submit()}> Add</button> <button className='cb-form-button' onClick={()=>toggleForm(false)}> Cancel</button> </div> <div id='cb-keyboard'/> </div> : <button id='cb-add-new' onClick={()=>toggleForm(true)}> + Add another category </button>} <Link to='budget'>Cancel</Link> </div> ) } const mapStateToProps = (reduxState) => { return reduxState } export default connect(mapStateToProps, {getCategory})(CreateBudget);
import React, { Component } from "react"; import { Text, View, FlatList, StyleSheet, AppRegistry, Image, ActivityIndicator } from "react-native"; import { colors, metrics, fonts } from "../themes"; import Items from "../components/Item"; export default class Item extends Component { constructor() { super(); this.state = { datasource: [], isloading: true }; } renderItem = ({ item }) => { return ( <View> <Items datasource={item} /> </View> ); }; componentDidMount() { fetch("https://jsonplaceholder.typicode.com/todos") .then(function(response) { return response.json(); }) .then(res => { this.setState({ datasource: res, isloading: false }); }) .catch(e => { console.log("error"); }); } render() { return this.state.isloading ? ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <ActivityIndicator size="large" color={colors.green} animating /> </View> ) : ( <View> <Text style={{ textAlign: "center", fontSize: 18 }}>TODO LIST</Text> <FlatList style={{ backgroundColor: colors.grey2 }} data={this.state.datasource} renderItem={this.renderItem} /> </View> ); } }
// Realizzare una todolist con Vue. La lista deve essere già popolata con alcuni elementi e si deve dare la possibilità di aggiungere nuovi item e di cancellarli. // Bonus 1): permettere ai file cancellati di finire in un'area 'cestino' dove possono essere eliminati del tutto oppure ripristinati. // Bonus 2): Dare la possibilità di eliminare tutti i file dal cestino var app = new Vue({ el: '#list', data: { impegni: ['Andare al lavoro','Fare la spesa', 'Andare in piscina', 'Comprare nuovi vestiti', 'Guardarsi un film'], impegniEliminati: [], nuovoImpegno: '', cambia: '' }, methods: { // Area dove inseriamo i dati aggiungiImpegno(){ var primaLettera = this.nuovoImpegno.charAt(0).toUpperCase(); var restoParola = this.nuovoImpegno.substring(1).toLowerCase(); this.nuovoImpegno = primaLettera + restoParola; if (this.nuovoImpegno.length > 4) { this.impegni.push(this.nuovoImpegno); } else { alert('Hai inserito una parola troppo corta. La lunghezza deve superare i 4 caratteri.'); } this.nuovoImpegno = ''; }, // Lista degli elementi modificaImpegno(index){ this.cambia = prompt('Modifica ciò che hai inserito.', this.impegni[index]); var primaLettera = this.cambia.charAt(0).toUpperCase(); var restoParola = this.cambia.substring(1).toLowerCase(); this.cambia = primaLettera + restoParola; this.impegni.splice(index, 1, this.cambia); }, cestinaImpegno (index){ this.impegniEliminati.push(this.impegni[index]); // console.log(this.impegniEliminati); this.impegni.splice(index, 1); }, cestinaTutto(){ this.impegniEliminati.push(...this.impegni); this.impegni = []; }, // Lista degli elementi eliminati ripristinaImpegno(index){ this.impegni.push(this.impegniEliminati[index]); this.impegniEliminati.splice(index, 1); }, ripristinaTutto(){ this.impegni.push(...this.impegniEliminati); this.impegniEliminati = []; }, cancellaImpegno(index){ this.impegniEliminati.splice(index, 1); }, cancellaTutto(){ this.impegniEliminati.splice(0); } } }); // Implementazioni // (1) inserire il nuovo todo; // (2) modificare un todo; // (3) spostare il todo nel cestino; // (4) pulsante per spostare tutti i todo nel cestino; // (5) ripristinare dal cestino un todo; // (6) eliminare definitivamente un todo dal cestino; // (7) pulsante per eliminare tutti i todo del cestino.
'use strict'; describe('Accordion Combined Test',function(){ it('展开accordion并且能够点击combo下面的basic_select控件',function(){ browser.get("test/e2e/testee/accordion/web/combined.html"); browser.sleep(2000); element(by.css(".combo .rdk-accordion-module .theme")).click(); var combo_input=element(by.css(".combo .rdk-accordion-module .rdk-combo-select-module .form-control")); combo_input.click(); var options=element.all(by.css(".combo .rdk-accordion-module .rdk-combo-select-module .rdk-selector-module .selector li")); options.get(0).click() .then(function(){ expect(combo_input.getAttribute("title")).toBe("南京"); }); }); it('展开accordion能够展现panel 并且获取内容',function(){ element(by.css(".panel .rdk-accordion-module .theme")).click(); var panel_content=element(by.css(".panel .rdk-accordion-module .rdk-panel-content p")); expect(panel_content.getText()).toBe("这是一段文字"); }); it("展开accordion可以展现scroller内部图片点击播放",function(){ element(by.css(".scroller .rdk-accordion-module .theme")).click(); var img=element(by.css(".scroller .rdk-accordion-module .slide .context img")); expect(img.getAttribute("ng-src")).toBe('./images/Chrysanthemum.jpg'); //每次点击切换都输出切换后的src element(by.css(".scroller .rdk-accordion-module .slider .arrows .right_arrow i")).click(). then(function(){ expect(img.getAttribute("ng-src")).toBe('./images/Hydrangeas.jpg'); }); }); it('展开accordion展现Tab控件 选择tab3的呈现basic_select控件',function(){ var ele=element(by.css(".tab .rdk-accordion-module .theme")); ele.click(); var tab_title=element.all(by.css(".tab .rdk-accordion-module .rdk-tab-module .tabs ul>li")); tab_title.get(2).element(by.css("a")).click();//展现basic_select //点击选择项 element.all(by.css(".tab .rdk-accordion-module .rdk-tab-module .tabs .rdk-selector-module .selector li")).get(0).click(); expect(element(by.model('currentVal')).getAttribute("value")).toBe("南京"); element.all(by.css(".tab .rdk-accordion-module .rdk-tab-module .tabs .rdk-selector-module .selector li")).get(1).click(); expect(element(by.model('currentVal')).getAttribute("value")).toBe("上海"); }); });
import React from "react" import Layout from "../components/layout" import RightFeature from "../components/rightFeature" import LeftFeature from "../components/leftFeature" import featureStyles from "./features.module.css" import metricsScreen from "../assets/metrics_mock.png" import overviewScreen from "../assets/overview_mock.png" import scheduleScreen from "../assets/schedule_mock.png" import presetScreen from '../assets/preset_mock.png' export default () => ( <Layout> <div style={{height: 100}}></div> {/*just for extra spacing*/} <div className={featureStyles.titleText}>Features</div> <RightFeature title="Live updates on your plant" content="See the current status of your plant's environment." image={overviewScreen} /> {/* pic of the app homepage*/} <LeftFeature title="Statistics over time" content="Track status of your plant over time in beautiful, easy-to-read charts." image={metricsScreen} /> {/*Metrics Screen*/} <RightFeature title="Set it and forget it" content="You'll never have to remember to water your plants ever again. Set up a schedule with the app and watch your plant prosper." image={scheduleScreen} /> {/*Scheduling screen*/} <LeftFeature title="Don't know where to start? " content="From leafy greens to chili peppers, we've got you covered. Choose from any of the given presets of plant settings and we'll take care of the rest." image={presetScreen} /> {/*Set up screen*/} <div style={{height: 100}}></div> {/*just for extra spacing*/} </Layout> )
/** * Description: ie6 7 8 9 placeholder fixed * Author: jiangfeng (jiangfeng@tomstaff.com) * Update: 2013-05-24 16:45 */ (function($){ if (!$ || !window.JEND) return; JEND.namespace('JEND.placeholder'); JEND.placeholder.init = function(id, tagid){ alert(111); }; })(jQuery);
const os = require('os'); // console.log("CPU", os.cpus()); // console.log('IP address: ', os.networkInterfaces().en0.map(i => i.address)); // console.log(os.freemem()); // console.log(os.type()); // console.log('OS version', os.release()); console.log(os.userInfo());
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.command === "collectHTMLData") { metaCSP = ""; document.querySelectorAll('meta').forEach(function(node) { if (node.getAttribute('http-equiv') !== null && node.getAttribute('http-equiv').toUpperCase() === 'CONTENT-SECURITY-POLICY') { metaCSP = node.getAttribute('content'); flag = true; return; // Only the first CSP definition is effective } }); sendResponse({"protocol": document.URL.split("://")[0], "metaCSP": metaCSP}); } } );
import produce from 'immer' export const INITIAL_STATE = { counter: 0, } export default (state = INITIAL_STATE, action) => produce(state, draft => { switch (action.type) { case 'INCREMENT': draft.counter += 1 break case 'DECREMENT': draft.counter -= 1 break case 'RESET': draft.counter = 0 break default: return state } })
$(document).ready(function() { // config việc hiển thị message error setValidationForInCareers($("#table4Sub3DataForm")); // config cấu hình rule và message validate cho các item setValidationForInputInCareers($("#table4Sub3DataForm")); $(".changeAny").change(function() { // Tổng số cuối kỳ 12 tháng // Nam (Kỹ thuật viên khoa học vật lý và kỹ thuật) $("input[name='dataTable4DtoList[1].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male1]"))); // Nữ (Kỹ thuật viên khoa học vật lý và kỹ thuật) $("input[name='dataTable4DtoList[1].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female1]"))); // Nam (Giám sát viên khai thác mỏ, chế biến và xây dựng) $("input[name='dataTable4DtoList[2].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male2]"))); // Nữ (Giám sát viên khai thác mỏ, chế biến và xây dựng) $("input[name='dataTable4DtoList[2].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female2]"))); // Nam (Kỹ thuật viên điều khiển quy trình) $("input[name='dataTable4DtoList[3].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male3]"))); // Nữ (Kỹ thuật viên điều khiển quy trình) $("input[name='dataTable4DtoList[3].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female3]"))); // Nam (Kỹ thuật viên kiểm soát, vận hành và điều khiển quy trình) $("input[name='dataTable4DtoList[4].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male4]"))); // Nữ (Kỹ thuật viên kiểm soát, vận hành và điều khiển quy trình) $("input[name='dataTable4DtoList[4].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female4]"))); // Nam (Kỹ thuật viên và kiểm soát viên tàu thuỷ và phương tiện bay) $("input[name='dataTable4DtoList[5].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male5]"))); // Nữ (Kỹ thuật viên và kiểm soát viên tàu thuỷ và phương tiện bay) $("input[name='dataTable4DtoList[5].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female5]"))); // Nam (Kỹ thuật viên y tế và dược) $("input[name='dataTable4DtoList[7].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male7]"))); // Nữ (Kỹ thuật viên y tế và dược) $("input[name='dataTable4DtoList[7].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female7]"))); // Nam (Y tá, kỹ thuật viên chăm sóc bệnh nhân và hộ sinh) $("input[name='dataTable4DtoList[8].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male8]"))); // Nữ (Y tá, kỹ thuật viên chăm sóc bệnh nhân và hộ sinh) $("input[name='dataTable4DtoList[8].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female8]"))); // Nam (Kỹ thuật viên y học cổ truyền và bổ trợ) $("input[name='dataTable4DtoList[9].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male9]"))); // Nữ (Kỹ thuật viên y học cổ truyền và bổ trợ) $("input[name='dataTable4DtoList[9].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female9]"))); // Nam (Kỹ thuật viên thú y và phụ tá) $("input[name='dataTable4DtoList[10].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male10]"))); // Nữ (Kỹ thuật viên thú y và phụ tá) $("input[name='dataTable4DtoList[10].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female10]"))); // Nam (Kỹ thuật viên sức khỏe khác) $("input[name='dataTable4DtoList[11].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male11]"))); // Nữ (Kỹ thuật viên sức khỏe khác) $("input[name='dataTable4DtoList[11].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female11]"))); // Nam (Kỹ thuật viên về toán ứng dụng và tài chính) $("input[name='dataTable4DtoList[13].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male13]"))); // Nữ (Kỹ thuật viên về toán ứng dụng và tài chính) $("input[name='dataTable4DtoList[13].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female13]"))); // Nam (Nhà đại lý và môi giới bán hàng và mua, bán) $("input[name='dataTable4DtoList[14].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male14]"))); // Nữ (Nhà đại lý và môi giới bán hàng và mua, bán) $("input[name='dataTable4DtoList[14].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female14]"))); // Nam (Nhân viên/đại lý dịch vụ kinh doanh) $("input[name='dataTable4DtoList[15].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male15]"))); // Nữ (Nhân viên/đại lý dịch vụ kinh doanh) $("input[name='dataTable4DtoList[15].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female15]"))); // Nam (Thư ký hành chính và nhân viên chuyên môn khác) $("input[name='dataTable4DtoList[16].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male16]"))); // Nữ (Thư ký hành chính và nhân viên chuyên môn khác) $("input[name='dataTable4DtoList[16].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female16]"))); // Nam (Kỹ thuật viên điều tiết của Chính phủ) $("input[name='dataTable4DtoList[17].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male17]"))); // Nữ (Kỹ thuật viên điều tiết của Chính phủ) $("input[name='dataTable4DtoList[17].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female17]"))); // Nam (Nhà chuyên môn cấp trung về luật pháp, xã hội và tôn giáo) $("input[name='dataTable4DtoList[19].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male19]"))); // Nữ (Nhà chuyên môn cấp trung về luật pháp, xã hội và tôn giáo) $("input[name='dataTable4DtoList[19].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female19]"))); // Nam (Người làm trong lĩnh vực thể thao và tập luyện) $("input[name='dataTable4DtoList[20].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male20]"))); // Nữ (Người làm trong lĩnh vực thể thao và tập luyện) $("input[name='dataTable4DtoList[20].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female20]"))); // Nam (Nhà chuyên môn cấp trung về mỹ thuật, văn hóa và nấu ăn) $("input[name='dataTable4DtoList[21].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male21]"))); // Nữ (Nhà chuyên môn cấp trung về mỹ thuật, văn hóa và nấu ăn) $("input[name='dataTable4DtoList[21].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female21]"))); // Nam (Kỹ thuật viên hỗ trợ người sử dụng và vận hành công nghệ thông tin và truyền thông) $("input[name='dataTable4DtoList[23].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male23]"))); // Nữ (Kỹ thuật viên hỗ trợ người sử dụng và vận hành công nghệ thông tin và truyền thông) $("input[name='dataTable4DtoList[23].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female23]"))); // Nam (Nhà chuyên môn về phân tích và phát triển phần mềm và các ứng dụng) $("input[name='dataTable4DtoList[24].tableMale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=male24]"))); // Nữ (Nhà chuyên môn về phân tích và phát triển phần mềm và các ứng dụng) $("input[name='dataTable4DtoList[24].tableFemale.totalEnd12m']").val(calTotal($("[rowtable4Sub3=female24]"))); // Kỹ thuật viên khoa học và kỹ thuật // Nam (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[0].tableMale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=maleFullTimeIndefinite31]"))); // Nam (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[0].tableMale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=maleFullTimeFixedTerm31]"))); // Nam (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[0].tableMale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=malePartTimeIndefinite31]"))); // Nam (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[0].tableMale.totalEnd12m']").val(calTotal($("[coltable4Sub3=maleTotalEnd12m31]"))); // Nữ (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[0].tableFemale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=femaleFullTimeIndefinite31]"))); // Nữ (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[0].tableFemale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=femaleFullTimeFixedTerm31]"))); // Nữ (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[0].tableFemale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=femalePartTimeIndefinite31]"))); // Nữ (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[0].tableFemale.totalEnd12m']").val(calTotal($("[coltable4Sub3=femaleTotalEnd12m31]"))); // Kỹ thuật viên sức khỏe // Nam (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[6].tableMale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=maleFullTimeIndefinite32]"))); // Nam (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[6].tableMale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=maleFullTimeFixedTerm32]"))); // Nam (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[6].tableMale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=malePartTimeIndefinite32]"))); // Nam (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[6].tableMale.totalEnd12m']").val(calTotal($("[coltable4Sub3=maleTotalEnd12m32]"))); // Nữ (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[6].tableFemale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=femaleFullTimeIndefinite32]"))); // Nữ (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[6].tableFemale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=femaleFullTimeFixedTerm32]"))); // Nữ (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[6].tableFemale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=femalePartTimeIndefinite32]"))); // Nữ (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[6].tableFemale.totalEnd12m']").val(calTotal($("[coltable4Sub3=femaleTotalEnd12m32]"))); // Kỹ thuật viên về kinh doanh và quản lý // Nam (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[12].tableMale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=maleFullTimeIndefinite33]"))); // Nam (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[12].tableMale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=maleFullTimeFixedTerm33]"))); // Nam (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[12].tableMale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=malePartTimeIndefinite33]"))); // Nam (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[12].tableMale.totalEnd12m']").val(calTotal($("[coltable4Sub3=maleTotalEnd12m33]"))); // Nữ (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[12].tableFemale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=femaleFullTimeIndefinite33]"))); // Nữ (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[12].tableFemale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=femaleFullTimeFixedTerm33]"))); // Nữ (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[12].tableFemale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=femalePartTimeIndefinite33]"))); // Nữ (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[12].tableFemale.totalEnd12m']").val(calTotal($("[coltable4Sub3=femaleTotalEnd12m33]"))); // Nhà chuyên môn cấp trung về luật pháp, văn hóa, xã hội // Nam (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[18].tableMale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=maleFullTimeIndefinite34]"))); // Nam (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[18].tableMale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=maleFullTimeFixedTerm34]"))); // Nam (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[18].tableMale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=malePartTimeIndefinite34]"))); // Nam (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[18].tableMale.totalEnd12m']").val(calTotal($("[coltable4Sub3=maleTotalEnd12m34]"))); // Nữ (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[18].tableFemale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=femaleFullTimeIndefinite34]"))); // Nữ (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[18].tableFemale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=femaleFullTimeFixedTerm34]"))); // Nữ (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[18].tableFemale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=femalePartTimeIndefinite34]"))); // Nữ (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[18].tableFemale.totalEnd12m']").val(calTotal($("[coltable4Sub3=femaleTotalEnd12m34]"))); // Kỹ thuật viên thông tin và truyền thông // Nam (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[22].tableMale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=maleFullTimeIndefinite35]"))); // Nam (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[22].tableMale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=maleFullTimeFixedTerm35]"))); // Nam (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[22].tableMale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=malePartTimeIndefinite35]"))); // Nam (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[22].tableMale.totalEnd12m']").val(calTotal($("[coltable4Sub3=maleTotalEnd12m35]"))); // Nữ (Toàn thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[22].tableFemale.fullTimeIndefinite']").val(calTotal($("[coltable4Sub3=femaleFullTimeIndefinite35]"))); // Nữ (Toàn thời gian, có xác định thời hạn) $("input[name='dataTable4DtoList[22].tableFemale.fullTimeFixedTerm']").val(calTotal($("[coltable4Sub3=femaleFullTimeFixedTerm35]"))); // Nữ (Bán thời gian, không xác định thời hạn) $("input[name='dataTable4DtoList[22].tableFemale.partTimeIndefinite']").val(calTotal($("[coltable4Sub3=femalePartTimeIndefinite35]"))); // Nữ (Tổng số cuối kỳ 12 tháng) $("input[name='dataTable4DtoList[22].tableFemale.totalEnd12m']").val(calTotal($("[coltable4Sub3=femaleTotalEnd12m35]"))); }); // tự động save setInterval(function() { let statusSave = $("#statusSave").val(); let statusInCarrer = $("#statusInCarrer").val(); if (statusSave == '' && statusInCarrer != '1') { let formScreen = $("#table4Sub3DataForm"); formScreen.attr('action', './save'); formScreen.submit(); } }, $("#autosaveInterval").val()); });
app.factory('userFactory',['$http','env',($http,env)=>{ const getUser = () =>{ return $http({ url :env.SERVICE_URL+'/getUser', method :'GET' }).then((result) => { return result.data; }).catch((err) => { console.log(err); }); }; return { getUser } }]);
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsEndpointsDisconnected = { name: 'endpoints_disconnected', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2.39 4.93l6.08 6.08H3.01v2H7V18H6v4h3.99v-4h-1v-4.99h1.48l8.65 8.65 1.28-1.28L3.67 3.66 2.39 4.93zM17.01 11.01v-5h1v-4h-4v4h1v5h-1.44l2 2h5.44v-2h-4z"/></svg>` };
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, Button, ScrollView, TextInput, KeyboardAvoidingView, Picker, TouchableOpacity, Dimensions, } from 'react-native'; import {connect} from 'react-redux'; import {bindActionCreators } from 'redux'; import navigateTo from '../../actions/NavigationAction'; import { Container, Content, Form, Item, Input } from 'native-base'; import uStyles from '../../styles'; import Icon from 'react-native-vector-icons/Ionicons'; import {List, ListItem, Left, Body, Right, Thumbnail} from 'native-base'; import createCommentAction from '../../actions/comment/createCommentAction'; import LoaderComponent from '../LoaderComponent'; import moment from 'moment'; const {height,width}=Dimensions.get('window'); class CommentComponent extends React.Component{ constructor(){ super(); this.state={ comment:'', showLoader:false, count:0 }; this.submitComment=this.submitComment.bind(this); } static navigationOptions = ({ navigation }) => ({ headerTitle:'Comments', headerTintColor: '#fff', headerStyle: { backgroundColor: '#0D47A1'}, }); componentWillMount(){ this.count=0; this.props.commentReducer.filter((x)=>{ if(x.user_id === this.props.userData[0].id){ this.count ++; } }); this.setState({ count:this.count }); } submitComment(){ this.setState({ showLoader:true }); let data={ headline_id:this.props.selectedHeadline.id, user_id:this.props.userData[0].id, comment:this.state.comment }; /* let data={ headline_id:1, user_id:1, comment:this.state.comment };*/ this.props.createCommentAction(data).then((x)=>{ this.setState({ showLoader:false }); if(x){ this.setState({ comment:'', count:this.state.count + 1 }); } }); } render(){ const showLoader=()=>{ if(this.state.showLoader){ return( <LoaderComponent/> ) } }; const canComment=()=>{ console.log('comments',this.state.count); if(this.props.userData[0].user_group_name!=='SystemAdmin' && this.props.userData[0].user_group_name!=='SuperAdmin' && this.props.userData[0].user_group_name!=='Employee') { if(this.state.count < 3){ return( <View style={uStyles.row}> <View style={localStyles.textInputContainer}> <View style={[localStyles.textInput,uStyles.textInput]}> <TextInput placeholder="Comment" underlineColorAndroid="#fff" value={this.state.comment} onChange={(event) => this.setState({comment:event.nativeEvent.text})} /> </View> </View> {submitButton()} </View> ) } } }; const submitButton=()=>{ if(this.state.showLoader){ return( <View style={localStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <View style={uStyles.dashBoardbutton}> <Text style={uStyles.dashBoardButtonText}>Submitting..</Text> </View> </View> </View> ) }else { return( <View style={localStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <TouchableOpacity style={uStyles.dashBoardbutton} onPress={()=>this.submitComment()}> <Text style={uStyles.dashBoardButtonText}>Submit</Text> </TouchableOpacity> </View> </View> ) } }; const comments=()=>{ if (this.props.commentReducer!==null){ return this.props.commentReducer.map((x,index)=>{ //if employee see all comments from your published headline if(this.props.userData[0].user_group_name === 'Employee'){ if(this.props.selectedHeadline.user_id === this.props.userData[0].id){ return( <List key={index}> <ListItem avatar> <Left> <Icon name="ios-person" size={30} color="#546E7A" /> </Left> <Body> <Text style={localStyles.name}>{x.fname + ' '+ x.lname}</Text> <Text note>{x.comment}</Text> </Body> <Right> <Text note>{moment(x.created_at).fromNow()}</Text> </Right> </ListItem> </List> ) } }else { if(x.user_id===this.props.userData[0].id){ return( <List key={index}> <ListItem avatar> <Left> <Icon name="ios-person" size={30} color="#546E7A" /> </Left> <Body> <Text style={localStyles.name}>{x.fname + ' '+ x.lname}</Text> <Text note>{x.comment}</Text> </Body> <Right> <Text note>{moment(x.created_at).fromNow()}</Text> </Right> </ListItem> </List> ) } } }); } }; return( <ScrollView style={[uStyles.mainView,localStyles.mainView]} keyboardShouldPersistTaps="always"> <View style={[uStyles.container,localStyles.container]}> {comments()} {showLoader()} {canComment()} </View> </ScrollView> ) } } const localStyles=StyleSheet.create({ mainView:{ backgroundColor:'#fff' }, container:{ }, logoContainer:{ }, textInput:{ }, name:{ fontWeight:'700' }, textInputContainer:{ flex:3, marginTop:25 }, buttonContainer:{ flex:1, marginLeft:5, marginTop:25 }, }); function mapStateToProps(state) { return { selectedHeadline:state.selectedHeadline, userData:state.userDataReducer, commentReducer:state.commentReducer } } function mapDispatchToProps(dispatch) { return bindActionCreators( { navigateTo:navigateTo, createCommentAction:createCommentAction },dispatch) } export default connect(mapStateToProps,mapDispatchToProps)(CommentComponent)
import React from 'react'; import { Link } from 'react-router-dom'; import '../styles/Navbar.scss'; export const Navbar = () => { return ( <nav className="navbar"> <Link to="/home/1"> <li className="fas fa-home"></li> </Link> <Link to="/search"> <li className="fas fa-search"></li> </Link> <Link to="/genres"> <li className="fas fa-film"></li> </Link> <Link to="/profile"> <li className="fas fa-user-circle"></li> </Link> </nav> ); };
const EspacosController = require('../controllers/espaco-controller') module.exports = (app)=>{ const espacoController = new EspacosController (app.datasource.models.espacos, app.datasource.sequelize) app.route('/espacos') .all(app.auth.authenticate()) .get(async(req, res)=>{ try{ var data = await espacoController.getAll() res.send(data) }catch(e){ console.log(e) res.status(400) } }) .post(async (req, res)=>{ try { let espaco = await espacoController.espaco(req.body.nome) if(espaco){ return res.send('Espaco já cadastrado') }else{ var rs = await espacoController.post(req.body) res.send(true).status(201) } }catch(e){ console.log(e) res.status(422) } }) app.route('/espacos/:id') .all(app.auth.authenticate()) .get(async(req, res)=>{ try{ var data = await espacoController.getById(req.params.id) res.send(data) }catch(e){ console.log(e) res.status(400) } }) .put(async (req, res)=>{ try{ var rs = await espacoController.put(req.body, req.params.id) res.send(true).status(200) }catch(e){ console.log(e) res.status(400) } }) .delete(async (req, res)=>{ try{ var rs = await espacoController.delete(req.params.id) res.send(true).status(204) }catch(e){ console.log(e) res.status(400) } }) app.route('/labsDisponiveis') .all(app.auth.authenticate()) .get(async(req, res)=>{ try{ var data = await espacoController.getLabs(req.body) res.send(data) }catch(e){ console.log(e) res.status(400) } }) app.route('/getIdEspaco/:id') .get(async(req, res)=>{ try{ var data = await espacoController.getIdLab(req.params.id) res.send(data) }catch(e){ console.log(e) res.status(400) } }) }
//Requiere de myUbication.js en el head //colocar este codigo al final del body //requiere los input para la latitud y longitud //requiere de el div id="map-canvas" para el mapa //requiere de <input type="text" id="searchmap"> para busquedas varLatitud=Number(localStorage.getItem('varLatitud')); varLongitud=Number(localStorage.getItem('varLongitud')); $( document ).ready(function() { $('#txtLatitud').val(varLatitud); $('#txtLongitud').val(varLongitud); }); var map = new google.maps.Map(document.getElementById('map-canvas'),{ center:{ lat: varLatitud, lng: varLongitud }, zoom:15 }); var image = { url: '/images/home-pointer-icon2.png', // This marker is 20 pixels wide by 32 pixels high. size: new google.maps.Size(48, 48), // The origin for this image is (0, 0). origin: new google.maps.Point(0, 0), // The anchor for this image is the base of the flagpole at (0, 32). anchor: new google.maps.Point(23, 49) }; //var image = '/images/home-pointer-icon.png'; var marker = new google.maps.Marker({ position: { lat: varLatitud, lng: varLongitud }, map: map, icon:image, draggable: true }); var searchBox = new google.maps.places.SearchBox(document.getElementById('searchmap')); google.maps.event.addListener(searchBox,'places_changed',function(){ var places = searchBox.getPlaces(); var bounds = new google.maps.LatLngBounds(); var i, place; for(i=0; place=places[i];i++){ bounds.extend(place.geometry.location); marker.setPosition(place.geometry.location); //set marker position new... } map.fitBounds(bounds); map.setZoom(15); }); google.maps.event.addListener(marker,'position_changed',function(){ var lat = marker.getPosition().lat(); var lng = marker.getPosition().lng(); $('#txtLatitud').val(lat); $('#txtLongitud').val(lng); });
const EC = require('elliptic').ec; const SHA256 = require('crypto-js/sha256'); const uuidV1 = require('uuid/v1'); const ec = new EC('secp256k1'); class ChainUtil { static id() { return uuidV1(); } static genKeyPair() { return ec.genKeyPair(); } static hash(data) { return SHA256(JSON.stringify(data)).toString(); } static verifySignature(publicKey, signature, dataHash) { return ec.keyFromPublic(publicKey, 'hex').verify(dataHash, signature); } } module.exports = ChainUtil; /*sec stands for standards of efficient cryptography. The p stands for prime, and 256 for 256 bits. In the elliptic-based algorithm itself, a key component is a prime number to generate the curve, and this prime number will be 256 bits, or 32 bytes/characters. K stands for Koblitz which is the name of a notable mathematician in the field of cryptography. And 1 stands for this being the first implementation of the curve algorithm in this standard. */
import React, {useState, useEffect } from 'react'; //import logo from 'logo.svg'; import './App.css'; function App(){ //хуки позаоляют делать внутреннее состояние без классовых компонентов. Функция возвращает массив const [count, setCount] = useState(0);//в скобкахх передаётся начальное состояние const [data, refreshData] = useState([{name:'Ivan' , sex: 'Male'}]); useEffect(()=>{ //выполняется при перересовке дом дерева(после первой отрисовки и после каждого последующего обновления компонента) console.log(Math.random()); let timerId = setInterval(console.log('dfsfs', 15000)); return () => { //иммитация componentWillUnmount(при удалении компонента) clearInterval(timerId); } }); return( <div> <p> вы кликнули {count} раз </p> <button onClick={() => setCount(count+1)}>Клик</button> <div>Name: {data[0].name}, sex: {data[0].sex}</div> {data.map(item => { return ( <div>Name: {item.name}, sex: {item.sex}</div> ); })} <button onClick={() => refreshData(data => ([...data,/*иммутабельность*/ {name: 'Alex' , sex: 'Male'}]))}> Добавить данные </button> </div> ); } export default App;
const logging = require('../../../../../shared/logging'); const commands = require('../../../schema').commands; const table = 'mobiledoc_revisions'; const message1 = 'Adding table: ' + table; const message2 = 'Dropping table: ' + table; module.exports.up = (options) => { const connection = options.connection; return connection.schema.hasTable(table) .then(function (exists) { if (exists) { logging.warn(message1); return; } logging.info(message1); return commands.createTable(table, connection); }); }; module.exports.down = (options) => { const connection = options.connection; return connection.schema.hasTable(table) .then(function (exists) { if (!exists) { logging.warn(message2); return; } logging.info(message2); return commands.deleteTable(table, connection); }); };
import dialogPolyfill from "dialog-polyfill"; import Handsontable from "handsontable"; import JSZip from "jszip"; export default class TaguchiDesigner { constructor(viewmanager) { this.__viewManagerDelegate = viewmanager; this.__numberOfParameters = 0; this.__numberOfLevels = 0; this.__orthogonalArray = null; this.__parameterHeaders = []; //Setup the Dialog this.__dialog = document.getElementById("doe_dialog"); this.__doeFileInput = document.getElementById("doe_input"); if (!this.__dialog.showModal) { dialogPolyfill.registerDialog(this.__dialog); } let ref = this; this.__dialog.querySelector(".close").addEventListener("click", function() { ref.__dialog.close(); }); //Setup the tableview this.__tablecontainer = document.getElementById("taguchi-table"); if (this.__tablecontainer === null || this.__tablecontainer === undefined) { throw new Error("Cannot find table element"); } this.__generateDesignsButton = document.getElementById("download-doe-button"); this.__generateDesignsButton.addEventListener("click", function(el, ev) { ref.generateAndDownloadTaguchiDesigns(); }); this.__handsonTableObject = null; let reader = new FileReader(); reader.onload = function(e) { //console.log(reader.result); ref.loadCSVData(reader.result); }; if (this.__doeFileInput) { this.__doeFileInput.addEventListener( "change", function() { let file = this.files[0]; reader.readAsText(file); }, false ); } } openDialog(componentName) { let component = this.__viewManagerDelegate.currentDevice.getComponentByName(componentName); this.__selectedComponent = component; this.__dialog.showModal(); } loadCSVData(text) { //Initialize the table based on the data in the CSV this.parseCSV(text); //Initialize the params table UI so that the user can input the DOE parameters this.__initializeTable(); } parseCSV(text) { let lines = text.split("\n"); let headers = lines[0].split(","); this.__parameterHeaders = headers; this.__numberOfParameters = headers.length; // console.log(headers); let max = 0; //Find the highest value for the parameter values for (let i in lines) { let line = lines[i]; let items = line.split(","); for (let ii in items) { let val = parseInt(items[ii]); if (val > max) { max = val; } } } this.__numberOfLevels = max; // console.log("Max number of values = ", max); //Number of parameters // console.log("# parameters", headers.length); this.__orthogonalArray = []; lines = lines.splice(1, lines.length - 1); for (let i in lines) { let line = lines[i]; this.__orthogonalArray.push(line.split(",")); } } __initializeTable() { let heritables = this.__selectedComponent.getParams().heritable; let paramoptions = []; for (let key in heritables) { paramoptions.push(key); } let blank_column_format = { type: "numeric" }; let data = []; let rowdata; //fill out blank data for (let y = 0; y < this.__numberOfParameters; y++) { rowdata = []; rowdata.push(paramoptions[y]); for (let x = 0; x < this.__numberOfLevels; x++) { rowdata.push(0); } data.push(rowdata); } let selectionboxcell = { editor: "select", selectOptions: paramoptions }; let column_data = []; column_data.push(selectionboxcell); let col_header = ["Parameter"]; for (let i = 0; i < this.__numberOfLevels; i++) { column_data.push(blank_column_format); col_header.push(i + 1); } this.__handsonTableObject = new Handsontable(this.__tablecontainer, { data: data, colHeaders: col_header, rowHeaders: this.__parameterHeaders, columns: column_data, minSpareCols: 0, colWidths: 150 }); } generateAndDownloadTaguchiDesigns() { let paramdata = this.__handsonTableObject; let jsons = []; //Go through each design for (let i in this.__orthogonalArray) { let iteration = this.__generateOrthogonalDesign(this.__orthogonalArray[i], paramdata); jsons.push(iteration); } //Create a Zip let zipper = new JSZip(); for (let i = 0; i < jsons.length; i++) { zipper.file(this.__viewManagerDelegate.currentDevice.getName() + "_" + i + ".json", jsons[i]); } let content = zipper.generate({ type: "blob" }); saveAs(content, "Taguchi_DOE.zip"); } __generateOrthogonalDesign(orthogonalArrayElement, paramdata) { //Read the orthogonal array for each experiment let paramMap = {}; // console.log("ORthogonal array", orthogonalArrayElement); for (let i = 0; i < orthogonalArrayElement.length; i++) { let columnindex = parseInt(orthogonalArrayElement[i]); // console.log(i, columnindex); paramMap[paramdata.getDataAtCell(i, 0)] = paramdata.getDataAtCell(i, columnindex); } //TODO: Update the component and then download the design // console.log(paramMap); for (let key in paramMap) { this.__selectedComponent.updateParameter(key, paramMap[key]); } //Serialize each design let json = JSON.stringify(this.__viewManagerDelegate.currentDevice.toInterchangeV1()); return json; } }
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt var QuadHotspotDEFAULTDEPTH = 0.125 var QuadHotspotclassName = "QuadHotspot" function QuadHotspot(quads,depth,name,debug) { this.quads = quads ; this.name = name || "NONAME" ; this.depth = depth || QuadHotspotDEFAULTDEPTH ; this.className = QuadHotspotclassName ; this.debug = debug ; this._Init() } function stringformat() { return arguments ; } function _subtractv(v1,v2) { var answ = Vector4.Create() answ.Subtract(v1,v2) return answ ; } function _Dot2(v1,v2) { // Dot2 takes x && z components of 2 Vector4's to produce 2D dot product return v1.X()*v2.X() + v1.Z()*v2.Z() ; } QuadHotspot.Create = function(quads,depth,name,debug) { return new QuadHotspot(quads,depth,name,debug) ; } // Build Regular QHS QuadHotspot.Build2DPoly = function(tx,tz,radius,phase,name,debug) { var polypoints = new Array() ; var points = 4 ; var angle = 2*Math.PI/points ; var qrtpi = 2*Math.PI/4 ; for (var i=1 ; i <= points ; i++) { var x = radius*Math.cos(angle*(i-1)-qrtpi+(phase || 0)) ; var z = radius*Math.sin(angle*(i-1)-qrtpi+(phase || 0)) ; polypoints.push(Vector4.Create(tx+x,0,tz+z)) ; } var qhs = QuadHotspot.Create(polypoints,0.5,name,debug) // qhs.cenx,qhs.cenz = tx,tz return qhs } QuadHotspot.prototype = { constructor: QuadHotspot, _Init: function() { // Find Equation of plane - Normal // Make sure we have our own copies of vectors. var quads = this.quads var nquads = [Vector4.Create(quads[0]), Vector4.Create(quads[1]), Vector4.Create(quads[2]), Vector4.Create(quads[3])] this.quads = nquads // Work out normal to plane this.normal = Vector4.Create() this.Enormal1 = Vector4.Create() this.Enormal2 = Vector4.Create() this.Enormal3 = Vector4.Create() this.Enormal4 = Vector4.Create() // this.normal2 = Vector4.Create() // this.normal3 = Vector4.Create() // this.normal4 = Vector4.Create() Vector4.Cross(this.normal,_subtractv(nquads[2], nquads[0]),_subtractv(nquads[1] , nquads[0])) Vector4.Normalize3(this.normal) this.D = -Vector4.Dot3(this.normal,nquads[0]) // Now recalculate Y coord of 4th point // Make all our points are on the same plane! var rY = -(this.D + this.normal.X()*nquads[3].X() + this.normal.Z()*nquads[3].Z())/this.normal.Y() nquads[3].SetY(rY) var eps = 0.001 assert(Math.abs(Vector4.Dot3(this.normal,nquads[0]) + this.D) <= eps,"SHOULD BE 0") assert(Math.abs(Vector4.Dot3(this.normal,nquads[1]) + this.D) <= eps,"SHOULD BE 0") assert(Math.abs(Vector4.Dot3(this.normal,nquads[2]) + this.D) <= eps,"SHOULD BE 0") assert(Math.abs(Vector4.Dot3(this.normal,nquads[3]) + this.D) <= eps,"SHOULD BE 0") // Calculate Edge Normals Vector4.Cross(this.Enormal1,this.normal,_subtractv(nquads[1] , nquads[0])) Vector4.Cross(this.Enormal2,this.normal,_subtractv(nquads[2] , nquads[1])) Vector4.Cross(this.Enormal3,this.normal,_subtractv(nquads[3] , nquads[2])) Vector4.Cross(this.Enormal4,this.normal,_subtractv(nquads[0] , nquads[3])) Vector4.Normalize3(this.Enormal1) Vector4.Normalize3(this.Enormal2) Vector4.Normalize3(this.Enormal3) Vector4.Normalize3(this.Enormal4) this.centre = this._GetCentre() assert(this.IsPointInside(Vector4.Create(this.centre.x,this.centre.y,this.centre.z)),'CENTRE NOT IN HOTSPOT - SEE A CODE DOCTOR') }, _GetCentre: function(quadhotspot) { var quads = this.quads ; var x = 0,y = 0, z = 0 ; for (var idx in quads) { var v = quads[idx] ; x = x + v.X() y = y + v.Y() z = z + v.Z() } return {x:x/4,y:y/4,z:z/4} ; }, // function Polygon.BuildPolyIreg(radius,angles,colour) { // // var polypoints = {} // var points = #angles // var rad = Math.rad // for i=1,points do // var angle = rad(angles[i]-90) // var x = radius*Math.cos(angle) // var y = radius*Math.sin(angle) // table.insert(polypoints,{x = x,y = y}) // } // // var poly = Polygon.Create(polypoints,radius) // poly.radius = radius // poly.colour = colour || Polygon.DEFAULTCOLOUR // return poly // }, SetName: function(name) { this.name = name }, GetRawQuads: function(quadhotspot) { return this.quads }, GetName: function(name) { return this.name }, IsPointInside: function(point,somedepth) { // Logger.lprint("QuadHotspot.IsPointInside"..point:X()..","..point:Y()..","..point:Z()) var dpth = somedepth || this.depth var quads = this.quads // Ignore Y! - becareful now - watch GC!! var v1 = _Dot2(this.Enormal1,_subtractv(point,quads[0])) var v2 = _Dot2(this.Enormal2,_subtractv(point,quads[1])) var v3 = _Dot2(this.Enormal3,_subtractv(point,quads[2])) var v4 = _Dot2(this.Enormal4,_subtractv(point,quads[3])) this.debug = {v1: v1, v2: v2, v3: v3, v4: v4, pdist: this.DistanceFromPlane(point)} //if ( (v1 < 0) && (v2 < 0) && (v3 < 0) && (v4 < 0) && this.DistanceFromPlane(point) <= dpth) //{ // console.log("INSIDE "+this.name) //} return (v1 < 0) && (v2 < 0) && (v3 < 0) && (v4 < 0) && this.DistanceFromPlane(point) <= dpth }, DistanceFromPlane: function(point) { return Math.abs(Vector4.Dot3(point,this.normal) + this.D) ; }, RenderDebug: function(renderHelper,point,x,y) { var defaultCol = [255,255,0,64] var insideCol = [255,0,0,255] if (point) { var inside = this.IsPointInside(point) if (this.debug) { var dbg = this.debug var col = inside && insideCol || defaultCol renderHelper.drawText( stringformat( this.GetName(), dbg.v1, dbg.v2, dbg.v3, dbg.v4, dbg.pdist),x,y,col,{horizontal:"left",vertical:"top"}) } } else { renderHelper.drawText(stringformat(this.GetName()),x,y,col,{horizontal:"left",vertical:"top"}) ; } }, Render: function(renderHelper,col) { this.Render2D(renderHelper,col) // this.Render3D(renderHelper,col) }, Render3D: function(renderHelper,col) { assert(this.className && this.className == QuadHotspotclassName,'NOT A QUADHOTSPOT!') var dcol = col || Vector4.Create( 1, 0, 1, 1 ) var qquad = this.GetRawQuads() // Debug.DrawQuad3d(qquad[1],qquad[2],qquad[3],qquad[4],dcol,true) }, Render2D: function(renderHelper,col) { var dcol = col || [255,255,0,255] var qquad = this.GetRawQuads() var x1 = qquad[0].X(),y1 = qquad[0].Z() ; var x2 = qquad[1].X(),y2 = qquad[1].Z() ; var x3 = qquad[2].X(),y3 = qquad[2].Z() ; var x4 = qquad[3].X(),y4= qquad[3].Z() ; renderHelper.drawLine(x1,y1,x2,y2,dcol) ; renderHelper.drawLine(x2,y2,x3,y3,dcol) ; renderHelper.drawLine(x3,y3,x4,y4,dcol) ; renderHelper.drawLine(x4,y4,x1,y1,dcol) ; renderHelper.drawText(this.name,this.centre.x,this.centre.z) ; }, toString: function() { return "QuadHotspot" ; } }
import React from 'react'; export default function Cloc(props) { return ( <div> <h1>CLOC Homepage</h1> <p>Add some content</p> </div> ); };
import mongoose from "mongoose"; const Schema = mongoose.Schema; const trackSchema = new Schema({ title: String, id: { type: Number, unique: true }, release_date: String, duration: Number, artist: { id: Number, name: String, picture: String }, album: Object, user: { type: Schema.Types.ObjectId, ref: "User" } }); export default mongoose.model("Track", trackSchema);
let as_nav_h2 = "Bag" let as_nav_h3 = "" let as_nav_list = [ {name:"Home",href:"#home"}, {name:"Feature",href:"#feature"}, {name:"About",href:"#about"}, {name:"Product",href:"#product"}, {name:"Shop Now",href:"#shop-btn"} ] let bags = [ {bg:"#FFE1E8",img:'bag1'}, {bg:"#FFE1E8",img:'bag2'}, {bg:"#F9DCFF",img:'bag3'}, {bg:"#FFDEE7",img:'bag4'}, {bg:"#ECF1FF",img:'bag5'}, {bg:"#FADADE",img:'bag6'}, {bg:"#D9E6FE",img:'bag7'}, {bg:"#EBF4BF",img:'bag8'} ] for(bag of bags){ document.querySelector(".sec3_bags").innerHTML+=`<div class="bag" style="background:${bag.bg};"><img src="./img/product/${bag.img}.png" alt=""></div>` }
try{ pastigagal(); } catch(e){ console.log('ini di baris 12:',e); } finally{ console.log('pada finally semua harus lewat sini'); }
import React from "react"; import {ActivityIndicator, StyleSheet, View} from "react-native"; import { VERDE, FUNDO_CINZA_CLARO } from "../../assets/estilos/estilos"; export default Loading = (props) => { return props.bolAtivo ? <View style={styles.loading}> <ActivityIndicator size="large" color={VERDE}/> </View> : null } const styles= StyleSheet.create({ loading: { flex : 1, // backgroundColor: FUNDO_CINZA_CLARO, justifyContent: 'center', alignItems: 'center' } })
function syncCanvasData (canvasData, aDocument) { // initializating position variables let computedStyle = aDocument.defaultView.getComputedStyle(canvasData.canvas, null) canvasData.stylePaddingLeft = parseInt(computedStyle['paddingLeft'], 10) || 0 canvasData.stylePaddingTop = parseInt(computedStyle['paddingTop'], 10) || 0 canvasData.styleBorderLeft = parseInt(computedStyle['borderLeftWidth'], 10) || 0 canvasData.styleBorderTop = parseInt(computedStyle['borderTopWidth'], 10) || 0 // Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page // They will mess up mouse coordinates and this fixes that let html = aDocument.body.parentNode canvasData.htmlTop = html.offsetTop canvasData.htmlLeft = html.offsetLeft return canvasData } function undrawCell (cellDefinition, canvasData, context) { let calculatedContext = context || canvasData.canvas.getContext('2d') calculatedContext.clearRect(cellDefinition.gridPosition.x, cellDefinition.gridPosition.y, canvasData.resolution, canvasData.resolution) } function drawCell (cellDefinition, canvasData, context) { let calculatedContext = context || canvasData.canvas.getContext('2d') calculatedContext.fillStyle = cellDefinition.getUserColor.apply() calculatedContext.strokeStyle = calculatedContext.fillStyle calculatedContext.fillRect(cellDefinition.gridPosition.x, cellDefinition.gridPosition.y, canvasData.resolution, canvasData.resolution) } function drawCanvas (canvasData, context) { let calculatedContext = context || canvasData.canvas.getContext('2d') console.log(`painting with canvasData = ${JSON.stringify(canvasData)}`) calculatedContext.clearRect(0, 0, canvasData.canvas.width, canvasData.canvas.height) for (let x in canvasData.cells) { for (let y in canvasData.cells[x]) { let color = canvasData.cells[x][y].color canvasData.cells[x][y].getUserColor = () => color drawCell(canvasData.cells[x][y], canvasData, calculatedContext) } } } /** * This will normalize the given coordinates to they possible positions in the grid, to allow the client to draw the cell * in that position as the server allegedly will do */ function normalizeGridPosition (position, resolution) { return { x: Math.round((position.x - (resolution / 2)) / resolution) * resolution, y: Math.round((position.y - (resolution / 2)) / resolution) * resolution } } this.syncCanvasData = syncCanvasData this.undrawCell = undrawCell this.drawCell = drawCell this.drawCanvas = drawCanvas this.normalizeGridPosition = normalizeGridPosition